body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>From times to times I stumble over the following situation:</p> <p>I have got a class with a property that's only used if another property has a particular value, for instance:</p> <pre><code>public enum enum_ConnectionType { Local, Server } public class Session { private enum_ConnectionType _connectionType; private string _serverName; // It only makes sense if _connectionType == enum_ConnectionType.Server public Session(enum_ConnectionType connectionType, string serverName) { _connectionType = connectionType; _serverName = serverName; } } </code></pre> <p>There's something that does not feel right to me. What is your common approach on this kind of situations?</p> <p><strong>EDIT</strong></p> <p>I think both Jeff and Leonid answers are valid depending on the situation.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:33:21.877", "Id": "32438", "Score": "0", "body": "What language are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:35:13.393", "Id": "32439", "Score": "0", "body": "C#, I just updated the tags, but I believe this is a common situation for most of the oop languages." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:49:10.570", "Id": "32441", "Score": "0", "body": "I'd just change the line `_serverName = serverName;` to be `_serverName = _connectionType == enum_ConnectionType.Server ? serverName : null;` . So an instance of `Session` is internally consistent." } ]
[ { "body": "<p>I would do this using an interface and polymorphism to represent this:</p>\n\n<pre><code>public interface ISession\n{\n void DoSomething();\n\n // Add your properties / method definitions\n}\n\npublic class ServerSession : ISession\n{\n private readonly string _serverName;\n\n public ServerSession(string serverName)\n {\n _serverName = serverName;\n }\n\n public void DoSomething()\n {\n // Some Code\n }\n\n // Implement interface contracts\n}\n\npublic class OtherSession : ISession\n{\n\n public void DoSomething()\n {\n // Some Code\n }\n\n // Implement interface contracts\n}\n</code></pre>\n\n<p>Then you would use it something like this:</p>\n\n<pre><code>public DoSomethingWithSession(ISession session)\n{\n session.DoSomething();\n}\n\nfoo.DoSomethingWithSession(new ServerSession());\n</code></pre>\n\n<p>If there is commonality between ISession implementations, you could base class that out, then inherit from that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:50:11.767", "Id": "32442", "Score": "0", "body": "This was my initial thought, thanks for posting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:32:46.730", "Id": "32444", "Score": "4", "body": "Did you really use “base class” as a verb? :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:48:21.647", "Id": "32450", "Score": "0", "body": "lol...guess I did :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:28:14.673", "Id": "32470", "Score": "0", "body": "While this is valid, depending on what the class is doing it may also be over-engineering." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T07:39:16.140", "Id": "32509", "Score": "3", "body": "This is not over-engineering. It's paying your technical debt upfront.\n\nSession class, as it is, doesn't have any public behavior.\nYou either put `doSomething()`s on it, or `getSomething()`.\n\nIf you go `doSomething` route your Session class is peppered with `if(connectionType==LOCAL)` conditionals.\nIf you go `getSomething` route, it is worse; everywhere `Session` class is used is polluted with the said conditionals.\n\nMoreover, each time you forget the conditional you get a `NullReferenceException` or what's its name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T07:52:09.227", "Id": "32510", "Score": "0", "body": "Only case you can cleanly ignore this is a case where you set `serverName` to some default value, say `localhost` and everything just works. (As in *Substitution Principle*)\nOf course, in that case, having a `ConnectionType` type-code is also over-engineering." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:55:32.580", "Id": "32544", "Score": "0", "body": "@abuzittin gillifirca, my answer is different from this one (and it is a good thing) and I admit that there is no perfect answer for \"it depends\" (on what you are doing). To address your concern for having ugly code - there is a way to factor out the commonly used logic into a helper function such that the probability of a bug goes down. If my project was small, I would probably start as simple as possible. Once a class can no longer cope with everything that is demanded from it, I think it is a good time to modify the class hierarchy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:04:06.977", "Id": "32545", "Score": "0", "body": "Helper functions drive me nuts. They totally undermine the power of OOD and OOP. Even in a small project, extract classes to remove if/then/else is worth way more for readability and simplicity than helper functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:52:11.220", "Id": "32565", "Score": "1", "body": "@abuzittingillifirca I disagree that its not overengineered. The problems you are worrying about in your solution may never become problems because the class may never become as complex as you're anticipating. The other answer to this question is perfectly acceptable if there are only minor and easily implemented differences between a local and remote connection." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:47:37.943", "Id": "20286", "ParentId": "20280", "Score": "13" } }, { "body": "<p>From a memory perspective I wouldn't worry. A few extra machine words in your class is unlikely to make a difference, and allocators out there tend to pad upwards anyway.</p>\n\n<p>From an OO perspective, you can always make a subclass to add the field.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:51:20.477", "Id": "20287", "ParentId": "20280", "Score": "2" } }, { "body": "<p>There is a different way, supplemented by documentation. One can say that it goes against OOP, one can also say that it keeps things simple and favors composition over inheritance. Here <code>serverName = null</code> is a convention for local connection. This approach condenses the entire state to a single string value. </p>\n\n<p>This is not the only way. Sometimes this is a bad approach, sometimes a good one - depends on how big your architecture is and what your use cases are.</p>\n\n<pre><code>public class Session\n{\n private readonly string serverName;\n\n /// Document me! \n public Session() : this(null)\n {\n }\n\n /// Document me!\n public Session(string serverName)\n {\n // Assert serverName is not null or whitespace\n this.serverName = serverName;\n }\n\n /// Document me! \n public bool IsLocalConnection\n {\n // Make sure that it is not whitespace\n return this.ServerName == null;\n }\n\n /// Document me!\n public string ServerName\n {\n get\n {\n return this.serverName;\n }\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:29:33.663", "Id": "32471", "Score": "0", "body": "Why not just have two CreateSession methods, one which takes a string the other which takes nothing? Seems like the Session itself is the only thing that should care if its local or not. Otherwise I think this is the best answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T23:26:28.233", "Id": "32477", "Score": "0", "body": "@Andy, you are right. I took your feedback and simplified my code, albeit in a slightly different way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:30:39.673", "Id": "20290", "ParentId": "20280", "Score": "5" } } ]
{ "AcceptedAnswerId": "20286", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:01:30.727", "Id": "20280", "Score": "8", "Tags": [ "c#", "object-oriented", "classes", "properties" ], "Title": "Class with a sometimes unused property" }
20280
<p>I have been working on a php driven template engine. This is fairly light weight, and fast from all of my testing, but I was hoping to get some feed back on it. First I would like to show you an example usages before I show the actual library. For full documentation and more examples: <a href="http://plater.phpsnips.com/" rel="nofollow">http://plater.phpsnips.com/</a></p> <p>This first part is a example users homepage</p> <p><strong>templates/user.tpl</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;User Home Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Welcome, $session.first.ucfirst();&lt;/h2&gt; &lt;p&gt; Here is where you will find the last 5 images that you have uploaded. &lt;/p&gt; $each("myimages"): &lt;div style="border: solid 1px activeborder;margin-bottom: 5px;"&gt; &lt;p&gt; &lt;img src="images/$image;" /&gt; &lt;/p&gt; &lt;p&gt; $description; &lt;/p&gt; &lt;/div&gt; $endeach; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This next section is the php part for the above template.</p> <p><strong>user.php</strong></p> <pre><code>&lt;?php session_start(); require_once "Plater.php"; require_once "db.php"; $tpl = new Plater(); // Query a database $user_id = (int)$_SESSION["user_id"]; $sql = mysql_query("select * from images where user_id = $user_id order by date desc limit 5"); $images = []; // put into the array while($row = mysql_fetch_assoc($sql)){ $images[] = ["image" =&gt; $row["filename"], "description" =&gt; $row["descr"]]; } // replacemet $tpl-&gt;assign("myimages", $images); // show $tpl-&gt;show("templates/user.tpl"); </code></pre> <p>That was just a little taste of the template system. Here are some of the current features that it has so far:</p> <ul> <li>Import templates within the template</li> <li>Run PHP functions</li> <li>Run Custom functions</li> <li>Tidy</li> <li>Import css (decreases http requests)</li> <li>Loops</li> <li>globals <ul> <li>$get</li> <li>$post</li> <li>$session</li> <li>$cookie</li> <li>$server</li> </ul></li> <li>Template comments (Won't display in html output) <ul> <li>Multi line: /$ Multiline comment $/</li> <li>Single line: $$ Single line comment</li> </ul></li> <li>Remove empty tags after all replacements are done</li> </ul> <p>And finally, here is the main library:</p> <pre><code>&lt;?php /** * @author php Snips &lt;hi@phpsnips.com&gt; * @copyright (c) 2012, php Snips * @version 0.0.1 * @see http://plater.phpsnips.com/docs/ */ class Plater{ protected $template = "", $replacements = array(), $cssFiles = array(), $disableTidy = false; public function __construct(){ } public function show($filename){ try{ $this-&gt;template = $this-&gt;import($filename); $this-&gt;format(); echo $this-&gt;template; }catch(Exception $e){ echo $e-&gt;getMessage(); } } public function attachCSS($filename = null){ $tmp = $this-&gt;template; if(empty($filename)){ $matches = array(); preg_match_all("/\\\$attachCSS\((\"|')(.+)(\"|')\);/U", $tmp, $matches); $tmp = preg_replace("/\\\$attachCSS\((\"|')(.+)(\"|')\);/U", "", $tmp); foreach($matches[2] as $filename){ $this-&gt;cssFiles[] = $this-&gt;import($filename); } $this-&gt;template = $tmp; }else{ $this-&gt;cssFiles[] = $this-&gt;import($filename); } } public function import($filename){ if(!is_file($filename)){ throw new Exception("Could not find \"&lt;b&gt;$filename&lt;/b&gt;\" it does not exist."); } return file_get_contents($filename); } public function assign($key, $value){ $this-&gt;replacements[$key] = $value; } public function disableTidy($boolean){ $this-&gt;disableTidy = (bool)$boolean; } private function format(){ $this-&gt;loadIncludes(); $this-&gt;get(); $this-&gt;post(); $this-&gt;session(); $this-&gt;server(); $this-&gt;cookie(); $this-&gt;template = $this-&gt;removeComments(); $this-&gt;runWhileLoops(); $this-&gt;template = $this-&gt;replaceTags(); $this-&gt;loadIncludes(); $this-&gt;template = $this-&gt;replaceTags(); $this-&gt;template = $this-&gt;removeEmptyTags(); $this-&gt;attachCSS(); $this-&gt;template = $this-&gt;replaceCSS(); if(!$this-&gt;disableTidy){ $this-&gt;template = $this-&gt;tidy(); } } private function tidy(){ if(class_exists("tidy")){ $tmp = $this-&gt;template; $tidy = new \tidy(); $config = array( "indent" =&gt; true, "indent-spaces" =&gt; 4, "clean" =&gt; true, "wrap" =&gt; 200, "doctype" =&gt; "html5" ); $tidy-&gt;parseString($tmp, $config, 'utf8'); $tidy-&gt;cleanRepair(); $string = $tidy; } return $string; } private function get(){ foreach($_GET as $k =&gt; $v){ $this-&gt;replacements["get." . $k] = $v; } } private function post(){ foreach($_POST as $k =&gt; $v){ $this-&gt;replacements["post." . $k] = $v; } } private function server(){ foreach($_SERVER as $k =&gt; $v){ $this-&gt;replacements["server." . $k] = $v; } } private function session(){ if(isset($_SESSION)){ foreach($_SESSION as $k =&gt; $v){ $this-&gt;replacements["session." . $k] = $v; } } } private function cookie(){ foreach($_COOKIE as $k =&gt; $v){ $this-&gt;replacements["cookie." . $k] = $v; } } private function loadIncludes(){ $tmp = $this-&gt;template; $matches = array(); preg_match_all('/(\\$import\(("|\')(.+?)("|\')\).*;)/i', $tmp, $matches); //print_r($matches); $files = $matches[3]; $replace = 0; foreach($files as $key =&gt; $file){ $command = preg_replace("/\\\$import\((\"|').+?(\"|')\)/", "", $matches[0][$key]); $string = $this-&gt;import($file); $string = $this-&gt;runFunctions($string, "blah" . $command); $f = preg_quote($file, "/"); $tmp = preg_replace('/\\$import\(("|\')' . $f . '("|\')\).*;/i', $string, $tmp); $replace++; } $this-&gt;template = $tmp; if($replace &gt; 0){ $this-&gt;loadIncludes(); } } private function runWhileLoops(){ $tmp = $this-&gt;template; $matches = array(); preg_match_all("/\\\$each\((\"|')(.+)(\"|')\):(.+)\\\$endeach;/isU", $tmp, $matches); if(isset($matches[4]) &amp;&amp; !empty($matches[4])){ foreach($matches[4] as $id =&gt; $match){ $new = ""; $match = ""; $name = $matches[2][$id]; $ntmp = $matches[4][$id]; if(isset($this-&gt;replacements[$name])){ foreach($this-&gt;replacements[$name] as $val){ $new .= $this-&gt;replaceTags($val, $ntmp); } } $name = preg_quote($name); $tmp = preg_replace("/\\\$each\((\"|')$name(\"|')\):(.+)\\\$endeach;/isU", $new, $tmp); } } $this-&gt;template = $tmp; } private function replaceCSS(){ $tmp = $this-&gt;template; $css = "&lt;style&gt;\n"; foreach($this-&gt;cssFiles as $cssStr){ $css .= "$cssStr\n"; } $css .= "&lt;/style&gt;\n"; if(preg_match("/&lt;\/head&gt;/i", $tmp)){ $tmp = preg_replace("/&lt;\/head&gt;/i", "$css&lt;/head&gt;", $tmp, 1); }else{ $tmp .= $css; } return $tmp; } private function replaceTags($keys = null, $tmp = null){ if(empty($tmp)){ $tmp = $this-&gt;template; } if(!empty($keys)){ $replacements = $keys; }else{ $replacements = $this-&gt;replacements; } foreach($replacements as $key =&gt; $value){ if(is_array($value)){ continue; } $matches = array(); preg_match_all('/\\$' . $key . '\..+?;/', $tmp, $matches); if(!empty($matches[0])){ foreach($matches[0] as $match){ $result = $this-&gt;runFunctions($value, $match); $m = preg_quote($match); $tmp = preg_replace('/' . $m . '/', "$result", $tmp); } } if(!is_array($value)){ $tmp = str_replace('$' . $key . ';', $value, $tmp); } } return $tmp; } private function runFunctions($value, $functions){ $functions = explode(".", $functions); array_shift($functions); foreach($functions as $func){ $func = trim($func, "$();"); if(function_exists($func)){ $value = $func($value); /* if(empty($value)){ throw new Exception("Invalid parameter for &lt;b&gt;$func&lt;/b&gt; received \"&lt;b&gt;$v&lt;/b&gt;\" within template."); } */ } } return $value; } private function removeEmptyTags(){ $tmp = $this-&gt;template; $tmp = preg_replace("/\\$[^\"' ]+?;/", "", $tmp); return $tmp; } private function removeComments(){ $tmp = $this-&gt;template; $tmp = preg_replace("/\/\\$.*\\$\//isU", "", $tmp); $tmp = preg_replace("/.*\\$\\$.+(\n|$)/iU", "", $tmp); return $tmp; } } </code></pre> <p>So, after review, what are your thoughts on this library?</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T01:38:05.373", "Id": "32482", "Score": "0", "body": "Have you compared your template engine with Smarty (which is licensed under the LGPL)? http://www.smarty.net/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:26:09.090", "Id": "32492", "Score": "0", "body": "I have. Mine doesn't all the features of smarty, but some of smarty's features seem a little unnecessary any way. I have added features that I felt were needed, and I am willing to add more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T06:56:14.577", "Id": "34541", "Score": "1", "body": "The PHP it self is a template engine. I see no reason to create an overhead. Creating some helper functions/methods are okay but $each(\"myimages\"); --- $endeach; syntax is horrible." } ]
[ { "body": "<p><strong>Disclaimer:</strong></p>\n\n<p>If you are just doing this for experience that's fine, but there are already many popular templating engines out there. Trying to compete with them isn't going to be easy or even probable. Sorry to be so blunt about it, but its the truth. Don't expect this to \"make it big\" or anything. That being said, have you profiled your engine and compared it to others on the market? If not, you should consider it. That will let you know if you really want to continue development, or if you need to go back to the drawing board.</p>\n\n<p><strong>Some General Considerations</strong></p>\n\n<p>Your class lacks an API. There is no interface for others to extend from, making it hard for anyone to know how to use it. There is also no documentation/doccomments, which makes it harder to use. At the very least you need some doccomments for your public scoped methods to make integration easier.</p>\n\n<p>You are continuously scraping your HTML with regex. If you could find some way to do it once, then you would probably notice some immediate improvements in performance. Since, most, if not all, of your templating language begins with a dollar sign <code>$</code>, you could probably scrape for that and get everything into an array. Then you could loop over said array to determine what methods you will need to run.</p>\n\n<p>Regex is sometimes slower than other options, especially with HTML. Have you considered loading your HTML into DOM to manipulate it? I'd give it a shot and profile it to check for any differences. I'd be willing to bet you'd see some improvements, and not just in speed, but in legibility as well. Regex is really bad on the eyes.</p>\n\n<p>If you aren't going to do anything with your constructor, there is no need to have one. You can remove it. That being said, you <strong>can</strong> probably find something to do with it. Rarely ever, unless using a base class to be extended from (usually an interface or abstract class), will you not need a constructor. I've already given a couple of suggestions.</p>\n\n<p><strong>About Your Code</strong></p>\n\n<p>You should generally avoid outputting text directly. This makes your code less reusable. Let the application using your class determine what it wants to do with its data. Change those echos to returns.</p>\n\n<pre><code> return $this-&gt;template;\n}catch(Exception $e){\n return $e-&gt;getMessage();\n</code></pre>\n\n<p>A NULL value is essentially the same as not being set. This means that a default value of NULL isn't really necessary, an <code>isset()</code> check will determine this for us. Empty, on the other hand, is sometimes useful for callbacks when checking FALSE values (FALSE, NULL, etc..), but is more commonly used for determining if an array is empty. So, to check if a string is NULL we could use <code>isset()</code> or <code>is_null</code>, or we could just query the variable directly without needing to use a function at all. The benefit of not using a function is that the code is a little more efficient (slightly faster, though negligible), and is a little cleaner (less parenthesis to clutter the statement).</p>\n\n<pre><code>public function attachCSS( $filename ) {//default NULL is unnecessary\n\nif( ! $filename ) {\n</code></pre>\n\n<p>I really don't know the proper procedure here. There are only a few functions in PHP that use references to automatically populate variables provided to them via their arguments, but I don't really use that many of them. Typically, when I see these functions being used, this referenced variable is not declared beforehand. I don't think there is anything wrong with it really, it just confused me at first. So, I'm not saying this needs to be changed, just letting you know its unnecessary to declare the <code>$matches</code> array beforehand.</p>\n\n<pre><code>$matches = array();//unnecessary\npreg_match_all(\"/\\\\\\$attachCSS\\((\\\"|')(.+)(\\\"|')\\);/U\", $tmp, $matches);\n</code></pre>\n\n<p>Accessing an array's elements \"magically\" (<code>$matches[ 2 ]</code>) is really confusing. I for one have no idea how you came to the decision to use \"2\" here, nor why you chose to use \"4\" later. This might be a familiar formula for the regex functions, I don't really know because I never use them, but to the regular user, they probably aren't going to know what's going on. There are a few ways you can fix this to make it easier. One is to use <code>list()</code> to label each element of your array. Another is to use more general array functions, such as <code>array_shift()</code> and <code>array_pop()</code> to abstract the desired elements. And the final way, assuming the array is an associative one, you can use <code>extract()</code> to dump the array into the local variable scope so that each of its keys corresponds to a new variable. The latter obviously wont work here, but either of the first two might.</p>\n\n<pre><code>//list\narray_pad( $matches, 2, array() );//padding to ensure length\nlist( $label1, $match );\nlist( , $match );//also works\n\n//array functions\n$match = array_pop( $matches );//assuming its the last element\n\n//then you can loop\nforeach( $match AS $filename ) {\n</code></pre>\n\n<p>Inline CSS/JS is slow. By using <code>file_get_contents()</code> to dump these files directly into your HTML you are forcing your browser to load all those styles and scripts every time the page loads. This is why its strongly urged for people to use external scripts and styles, so that the browser can cache them. Instead of reading the file, you should just verify that it exists, and then use the external script and style tags to include them.</p>\n\n<pre><code>&lt;script src=\"path/to/script.js\"&gt;&lt;/script&gt;\n&lt;link rel=\"stylesheet\" href=\"path/to/style.css\" /&gt;\n</code></pre>\n\n<p>If you aren't going to use the value portion of the foreach loop, you can just loop over the array keys. There's no need to NULL out the value. Additionally, what is <code>$ntmp</code>? Don't use acronyms or obscure references for your variables/functions unless they are extremely common (PHP, HTML, etc...). Doing so will make your code harder to read. Strive for self-documenting code. This sort of goes along with that advice I gave about magically accessing arrays too.</p>\n\n<pre><code>$match = array_keys( $matches[ 4 ] );\nforeach( $match AS $id ) {\n</code></pre>\n\n<p>My biggest problem with your code, asides from the regex, is the inconsistencies in how the <code>$template</code> property is set. In the following snippet that property is changed three times, yet, it only looks like it happens twice. Either way is fine, but it should be consistent. I don't think there is a right or wrong here, except in maybe that the first way is more reusable, sort of like the situation with echo and return earlier.</p>\n\n<pre><code>$this-&gt;template = $this-&gt;removeComments();\n$this-&gt;runWhileLoops();\n$this-&gt;template = $this-&gt;replaceTags();\n</code></pre>\n\n<p>Your <code>tidy()</code> method has an error. If the tidy class doesn't exist, then you still attempt to return <code>$string</code>, which hasn't been set. An appropriate move here is to either return early with the default string, or to throw an error.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T02:26:50.633", "Id": "32611", "Score": "0", "body": "`public function attachCSS( $filename ) {//default NULL is unnecessary` is at best misleading and at worst blatantly wrong. `function g($x = null) {}` `function f($x) {}`. `g()` is a valid call. `f()` is not. The default value **is** necessary if he wants to call it without a parameter (at least without issuing a warning)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:04:12.753", "Id": "32630", "Score": "0", "body": "@Corbin: I'll have to take your word for that until I can test it. I don't ever remember having such an error, and I work with error reporting all the way on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:49:22.627", "Id": "32640", "Score": "0", "body": "do you work with strict php on? you would get a warning somewhat like this: `Warning: Missing argument 1 for func_name()...` for a function that looks like this: `func_name($thing){return $thing;}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:57:56.547", "Id": "32645", "Score": "0", "body": "Some comments: **1)** Defining variables before use is good practice. **2)** I don't want to use a return for `show` I could make another function though such as `render` which could return instead. **3)** Why pad to ensure length, when I could just check to see if it exists and then go off that. **4)** Inline css isn't as slow as making multiple http requests. Thanks for the input, I did like a few things, which I did change (or I'm in the process of changing)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:33:05.477", "Id": "20355", "ParentId": "20281", "Score": "1" } }, { "body": "<blockquote>\n<p><sub><a href=\"http://bit.ly/phpmsql\" rel=\"nofollow noreferrer\"><strong>Please, don't use <code>mysql_*</code> functions in new code</strong></a>. They are no longer maintained <a href=\"https://wiki.php.net/rfc/mysql_deprecation\" rel=\"nofollow noreferrer\">and are officially deprecated</a>. See the <a href=\"http://j.mp/Te9zIL\" rel=\"nofollow noreferrer\"><strong>red box</strong></a>? Learn about <a href=\"http://j.mp/T9hLWi\" rel=\"nofollow noreferrer\"><em>prepared statements</em></a> instead, and use <a href=\"http://php.net/pdo\" rel=\"nofollow noreferrer\">PDO</a> or <a href=\"http://php.net/mysqli\" rel=\"nofollow noreferrer\">MySQLi</a> - <a href=\"http://j.mp/QEx8IB\" rel=\"nofollow noreferrer\">this article</a> will help you decide which. If you choose PDO, <a href=\"http://j.mp/PoWehJ\" rel=\"nofollow noreferrer\">here is a good tutorial</a>.</sub></p>\n</blockquote>\n<p>PHP itself already is a templating language, so my first thought would be - <strong>this is completely pointless.</strong> And no, <em>&quot;designers do not know PHP&quot;</em> is not an argument for making such templates, since those same developer would have to learn how to use your <em>miracle</em> instead.</p>\n<h3>About the code ..</h3>\n<ul>\n<li><p>There is only one way to render you template:</p>\n<pre><code>public function show($filename){\n try{\n $this-&gt;template = $this-&gt;import($filename);\n $this-&gt;format();\n echo $this-&gt;template;\n }catch(Exception $e){\n echo $e-&gt;getMessage();\n }\n}\n</code></pre>\n<p>The problem is that this approach severely limits the ability to cache the rendered templates (you could use <code>ob_*</code>, that would be extremely hack'ish).</p>\n</li>\n<li><p>The <code>public function attachCSS($filename = null)</code> should be refactored. It's basically two different methods.</p>\n</li>\n<li><p>You have replaces the PHP built in templating functionality with <code>preg_*</code>, which seems quite silly.</p>\n</li>\n<li><p>These kind of templates will most likely conflict with JS libraries</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T02:12:12.377", "Id": "34584", "Score": "3", "body": "Having a template engine that works four times slower than *normal* PHP in order to have `{var}` instead of `<?=$var?>` is not worth it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:54:08.980", "Id": "21512", "ParentId": "20281", "Score": "4" } }, { "body": "<p>so I have played around with it a bit and added what I call a pseudo if statement -- so within the loop you can have something like {if name == 'bob'} out put some html\nSo in the .tpl you can have something like:</p>\n\n<pre><code>$each(\"myimages\"):\n\n {if size &lt; 600 }\n &lt;div style=\"border: solid 1px activeborder;margin-bottom: 5px;\"&gt;\n &lt;p&gt;&lt;h3&gt;[@size]&lt;/h3&gt;&lt;/p&gt;\n &lt;p&gt;\n &lt;img src=\"images/$image;\" /&gt;\n &lt;/p&gt;\n &lt;p&gt;\n $description;\n &lt;/p&gt;\n &lt;/div&gt;\n {else}\n &lt;h3&gt;Sorry Image size too Big!!!&lt;/h3&gt;\n {endif}\n$endeach;\n</code></pre>\n\n<p>and in the array which I have just created manually for now I have added a size element if it is over 600 bytes is shows the message \"Sorry Image size too Big!!! . The If statement is fairly basic as in it does not allow for things like nested if's ... I guess you would need some kind of parser or tree structure for that.\nHere is the manualy array passed in:</p>\n\n<pre><code>$images=array(\n array('image'=&gt;'a1.png' , 'description'=&gt;'image 1' , 'size'=&gt;2343),\n array('image'=&gt;'a2.png' , 'description'=&gt;'image 1' , 'size'=&gt;12),\n array('image'=&gt;'a1.png' , 'description'=&gt;'image 1' , 'size'=&gt;231),\n array('image'=&gt;'a1.png' , 'description'=&gt;'image 1' , 'size'=&gt;8342),\n array('image'=&gt;'a1.png' , 'description'=&gt;'image 1' , 'size'=&gt;632) \n);\n</code></pre>\n\n<p>and finally you class with the IF statement bit added:</p>\n\n<pre><code>class Plater{\n\n protected\n $template = \"\",\n $replacements = array(),\n $cssFiles = array(),\n $disableTidy = false;\n\n public function __construct(){\n\n }\n\n public function show($filename){\n try{\n $this-&gt;template = $this-&gt;import($filename);\n $this-&gt;format();\n echo $this-&gt;template;\n }catch(Exception $e){\n echo $e-&gt;getMessage();\n }\n }\n\n public function attachCSS($filename = null){\n $tmp = $this-&gt;template;\n if(empty($filename)){\n $matches = array();\n preg_match_all(\"/\\\\\\$attachCSS\\((\\\"|')(.+)(\\\"|')\\);/U\", $tmp, $matches);\n $tmp = preg_replace(\"/\\\\\\$attachCSS\\((\\\"|')(.+)(\\\"|')\\);/U\", \"\", $tmp);\n foreach($matches[2] as $filename){\n $this-&gt;cssFiles[] = $this-&gt;import($filename);\n }\n $this-&gt;template = $tmp;\n }else{\n $this-&gt;cssFiles[] = $this-&gt;import($filename);\n }\n }\n\n public function import($filename){\n if(!is_file($filename)){\n throw new Exception(\"Could not find \\\"&lt;b&gt;$filename&lt;/b&gt;\\\" it does not exist.\");\n }\n return file_get_contents($filename);\n }\n\n public function assign($key, $value){\n $this-&gt;replacements[$key] = $value;\n }\n\n public function disableTidy($boolean){\n $this-&gt;disableTidy = (bool)$boolean;\n }\n\n private function format(){\n $this-&gt;loadIncludes();\n $this-&gt;get();\n $this-&gt;post();\n $this-&gt;session();\n $this-&gt;server();\n $this-&gt;cookie();\n $this-&gt;template = $this-&gt;removeComments();\n $this-&gt;runWhileLoops();\n $this-&gt;template = $this-&gt;replaceTags();\n $this-&gt;loadIncludes();\n $this-&gt;template = $this-&gt;replaceTags();\n $this-&gt;template = $this-&gt;removeEmptyTags();\n $this-&gt;attachCSS();\n $this-&gt;template = $this-&gt;replaceCSS();\n// if(!$this-&gt;disableTidy){\n // $this-&gt;template = $this-&gt;tidy();\n // }\n }\n\n private function tidy(){\n if(class_exists(\"tidy\")){\n $tmp = $this-&gt;template;\n $tidy = new \\tidy();\n $config = array(\n \"indent\" =&gt; true,\n \"indent-spaces\" =&gt; 4,\n \"clean\" =&gt; true,\n \"wrap\" =&gt; 200,\n \"doctype\" =&gt; \"html5\"\n );\n $tidy-&gt;parseString($tmp, $config, 'utf8');\n $tidy-&gt;cleanRepair();\n $string = $tidy;\n }\n return $string;\n }\n\n private function get(){\n foreach($_GET as $k =&gt; $v){\n $this-&gt;replacements[\"get.\" . $k] = $v;\n }\n }\n\n private function post(){\n foreach($_POST as $k =&gt; $v){\n $this-&gt;replacements[\"post.\" . $k] = $v;\n }\n }\n\n private function server(){\n foreach($_SERVER as $k =&gt; $v){\n $this-&gt;replacements[\"server.\" . $k] = $v;\n }\n }\n\n private function session(){\n if(isset($_SESSION)){\n foreach($_SESSION as $k =&gt; $v){\n $this-&gt;replacements[\"session.\" . $k] = $v;\n }\n }\n }\n\n private function cookie(){\n foreach($_COOKIE as $k =&gt; $v){\n $this-&gt;replacements[\"cookie.\" . $k] = $v;\n }\n }\n\n private function loadIncludes(){\n $tmp = $this-&gt;template;\n $matches = array();\n preg_match_all('/(\\\\$import\\((\"|\\')(.+?)(\"|\\')\\).*;)/i', $tmp, $matches);\n //print_r($matches);\n $files = $matches[3];\n $replace = 0;\n foreach($files as $key =&gt; $file){\n $command = preg_replace(\"/\\\\\\$import\\((\\\"|').+?(\\\"|')\\)/\", \"\", $matches[0][$key]);\n $string = $this-&gt;import($file);\n $string = $this-&gt;runFunctions($string, \"blah\" . $command);\n $f = preg_quote($file, \"/\");\n $tmp = preg_replace('/\\\\$import\\((\"|\\')' . $f . '(\"|\\')\\).*;/i', $string, $tmp);\n $replace++;\n }\n $this-&gt;template = $tmp;\n if($replace &gt; 0){\n $this-&gt;loadIncludes();\n }\n }\n\n private function runWhileLoops(){\n $tmp = $this-&gt;template;\n $matches = array();\n preg_match_all(\"/\\\\\\$each\\((\\\"|')(.+)(\\\"|')\\):(.+)\\\\\\$endeach;/isU\", $tmp, $matches);\n if(isset($matches[4]) &amp;&amp; !empty($matches[4])) {\n // Loop over all $each found.\n foreach($matches[4] as $id =&gt; $match){\n $new = \"\";\n $match = \"\";\n $name = $matches[2][$id]; // $each variable - e.g. $each('images') --&gt; images.\n $ntmp = $matches[4][$id]; // the HTML between the $each AND $endeach.\n // is name in array?\n if(isset($this-&gt;replacements[$name])){\n // if so loop over all occurances of it.\n foreach($this-&gt;replacements[$name] as $val){\n $t = $this-&gt;replaceTags ( $val , $ntmp);\n $xif = $this-&gt;if_conditions( $t , $val );\n $new .= $xif;\n }\n }\n $name = preg_quote($name);\n $tmp = preg_replace(\"/\\\\\\$each\\((\\\"|')$name(\\\"|')\\):(.+)\\\\\\$endeach;/isU\", $new, $tmp);\n }\n }\n $this-&gt;template = $tmp;\n }\n\n private function replaceCSS(){\n $tmp = $this-&gt;template;\n $css = \"&lt;style&gt;\\n\";\n foreach($this-&gt;cssFiles as $cssStr){\n $css .= \"$cssStr\\n\";\n }\n $css .= \"&lt;/style&gt;\\n\";\n if(preg_match(\"/&lt;\\/head&gt;/i\", $tmp)){\n $tmp = preg_replace(\"/&lt;\\/head&gt;/i\", \"$css&lt;/head&gt;\", $tmp, 1);\n }else{\n $tmp .= $css;\n }\n return $tmp;\n }\n\n private function replaceTags($keys = null, $tmp = null){\n if(empty($tmp)){\n $tmp = $this-&gt;template;\n }\n\n if(!empty($keys)){\n $replacements = $keys;\n }else{\n $replacements = $this-&gt;replacements;\n }\n\n $i=0;\n $xif='';\n $tmp1='';\n foreach($replacements as $key =&gt; $value){\n if(is_array($value)){\n continue;\n }\n $matches = array();\n preg_match_all('/\\\\$' . $key . '\\..+?;/', $tmp, $matches);\n if(!empty($matches[0])){\n foreach($matches[0] as $match){\n $result = $this-&gt;runFunctions($value, $match);\n $m = preg_quote($match);\n $tmp = preg_replace('/' . $m . '/', \"$result\", $tmp); \n }\n }\n if(!is_array($value)){\n $tmp = str_replace('$' . $key . ';', $value, $tmp);\n }\n }\n return $tmp;\n }\n\n private function runFunctions($value, $functions){\n $functions = explode(\".\", $functions);\n array_shift($functions);\n foreach($functions as $func){\n $func = trim($func, \"$();\");\n if(function_exists($func)){\n $value = $func($value);\n /* if(empty($value)){\n throw new Exception(\"Invalid parameter for &lt;b&gt;$func&lt;/b&gt; received \\\"&lt;b&gt;$v&lt;/b&gt;\\\" within template.\");\n } */\n }\n }\n return $value;\n }\n\n private function removeEmptyTags(){\n $tmp = $this-&gt;template;\n $tmp = preg_replace(\"/\\\\$[^\\\"' ]+?;/\", \"\", $tmp);\n return $tmp;\n }\n\n private function removeComments(){\n $tmp = $this-&gt;template;\n $tmp = preg_replace(\"/\\/\\\\$.*\\\\$\\//isU\", \"\", $tmp);\n $tmp = preg_replace(\"/.*\\\\$\\\\$.+(\\n|$)/iU\", \"\", $tmp);\n return $tmp;\n }\n\n\n\n\n private function if_conditions($html,$ar) {\n if($html=='') { return null; }\n // find ALL occurances of if..else..endif in current layer.\n $template = preg_match_all('/\\{if\\s+(.*?)\\}\\s+(.*?)\\s+(?:\\{else\\}\\s+(.*?)\\s+)?\\{endif\\}/s', $html , $M , PREG_SET_ORDER );\n // check for matches..\n if(!empty($M)){\n $i=0;\n //LOOP over if..else..endif matches.\n foreach ($M as $mm){\n // get the array of if..else..endif\n $condition=$mm[1];\n $cond = $this-&gt;_if_in_template($condition);\n if(!empty($cond)) {\n $if_variable = $cond[0]; // if part\n $if_comparison = $cond[1]; // == != &lt; &gt; etc..\n $if_value = $cond[2]; // value\n if(isset($ar[ $if_variable ])){\n $val = $ar[ $if_variable ]; // actual val.\n } else {\n $val=null;\n }\n // $left_side: value from TEMPLATE.\n // $right_side: value from DATA.\n $left_side = $val;\n $right_side = $if_value;\n $if_result = $this-&gt;_if_compare_values( $left_side , $right_side , $if_comparison );\n if( $if_result == true ) {\n if(isset($mm[3])) {\n $html = str_replace( $mm[3] , '' , $html );\n }\n } else {\n // IF statement is FALSE so remove Second part.\n if(isset($mm[2] )){\n $html = str_replace( $mm[2] , '', $html );\n }\n }\n }\n $i++;\n } // end of FOREACH\n }\n $ret = $html;\n /*\n * STRIP OUT ALL {if} {else} {endif}\n */\n //$template = preg_match_all('/\\{if\\s+(.*?)\\}\\s+(.*?)\\s+(?:\\{else\\}\\s+(.*?)\\s+)?\\{endif\\}/s', $html , $M , PREG_SET_ORDER ); \n $ret = preg_replace(\"/\\{if\\s+(.*?)\\}/\" , \"\" , $ret );\n $ret = preg_replace(\"/\\{endif}/\" , \"\" , $ret ); \n $ret = preg_replace(\"/\\{else}/\" , \"\" , $ret ); \n\n\n\n return $ret;\n }\n\n\n\n private function _if_compare_values( $left_side,$right_side, $if_comparison){\n $first = false;\n switch ( $if_comparison){\n case '==':\n if($left_side==$right_side) { $first=true; }\n break;\n case '&gt;':\n if($left_side&gt;$right_side) { $first=true; } \n break;\n case '&lt;':\n if($left_side&lt;$right_side) { $first=true; } \n break;\n case '!=':\n if($left_side!=$right_side) { $first=true; }\n break;\n case '&gt;=':\n if($left_side&gt;=$right_side) { $first=true; } \n break;\n case '&lt;=':\n if($left_side&lt;=$right_side) { $first=true; } \n break;\n }\n\n\n return $first;\n }\n\n\n\n private function _if_in_template($condition){\n if(strlen($condition)!=0) {\n $cond = explode(\" \" , $condition);\n if(!empty($cond)){\n return $cond;\n } else {\n return array();\n }\n }\n }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-09T12:27:28.753", "Id": "177518", "ParentId": "20281", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:09:49.160", "Id": "20281", "Score": "4", "Tags": [ "php", "html", "template" ], "Title": "PHP Template Engine" }
20281
<p>It currently takes about 10 minutes to process ~16k teams and ~81k games. I could soon have ~17k teams with ~160k, and multiple sports. I run this as a cron job overnight and store the results in a serialized gzipped array which is processed upon each pageload to sort teams by states for displaying and actually calculate the RPI (add WP, OWP and OOWP together) which works well for speed for displaying purposes. I'm only concerned with trying to speed up this calculation:</p> <p>If you need more information about what the RPI (Ratings Percentage Index) is, <a href="http://www.collegerpi.com/rpifaq.html" rel="nofollow">this is a good primer</a>. Please note, I have modified from this formula to include a weighting factor (function reduction_factor() ) so it is slightly different that that page states.</p> <p>Here is my base function:</p> <pre><code>// ********************************************************************************************************************************* // function to calculate RPI given a sportid and year, optional cutoff date // ********************************************************************************************************************************* function rpi($sportid, $year, $date = FALSE, $my_db, $sport_array){ //figure out if this is a year-spanning sport $year_display = $year; $date_start = $year.$sport_array[$sportid]['start_date']; $date_end = $year.$sport_array[$sportid]['end_date']; if ($sport_array[$sportid]['end_year_plus']){ $year_display = $year.'-'.($year+1); $date_end = ($year+1).$sport_array[$sportid]['end_date']; } if ($date) $date_end = $date; elseif ($date_end &gt; date("Y-m-d")) $date_end = date("Y-m-d"); $rpiteamarray = array(); $results = $my_db-&gt;query("SELECT `teamid` FROM `team` WHERE `jv` = '0' AND `teamid` &gt; 0;"); while ($row = $results-&gt;fetchRow(MDB2_FETCHMODE_ASSOC)){ $teamid = $row['teamid']; if (!array_key_exists($teamid, $rpiteamarray)) $rpiteamarray[$teamid] = new rpiteam($teamid, $sportid, $year, $my_db, $date_start, $date_end); if ($rpiteamarray[$teamid]-&gt;total_games() == 0) continue; $rpi[$teamid]['numgames'] = $rpiteamarray[$teamid]-&gt;total_games(); } unset($results, $row); foreach ($rpi as $teamid =&gt; $value){ $rpi[$teamid]['wp'] = $rpiteamarray[$teamid]-&gt;wp(); $rpi[$teamid]['owp'] = $rpiteamarray[$teamid]-&gt;owp($rpiteamarray); $rpi[$teamid]['oowp'] = $rpiteamarray[$teamid]-&gt;oowp($rpiteamarray); } return $rpi; } </code></pre> <p>Here is my rpiteam class:</p> <pre><code>&lt;?php class rpiteam { protected $sportid, $levelid, $levelid_state, $year, $wins, $loss, $tie, $total, $wp, $db, $opponentsarray, $date_start, $date_end; function __construct($teamid, $sportid, $year, $db, $date_start, $date_end) { if ($teamid == '') return null; if ($year == '') return null; if ($sportid == '') return null; $this-&gt;db = $db; $this-&gt;sportid = $sportid; $this-&gt;teamid = $teamid; $this-&gt;year = $year; $this-&gt;date_start = $date_start; $this-&gt;date_end = $date_end; $row = $this-&gt;db-&gt;query("SELECT `levelid`,`levelid_state` FROM `team_class` WHERE `teamid` = $teamid AND `sportid` = $sportid AND `year` = $year;")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC); $this-&gt;levelid = $row['levelid']; $this-&gt;levelid_state = $row['levelid_state']; $this-&gt;opponentsarray = array(); } public function wins(){ if ($this-&gt;wins) return $this-&gt;wins; $this-&gt;wins = $this-&gt;db-&gt;query("SELECT COUNT(`winner`) FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` = $this-&gt;teamid AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end';")-&gt;fetchOne(); return $this-&gt;wins; } public function loss(){ if ($this-&gt;loss) return $this-&gt;loss; $this-&gt;loss = ($this-&gt;total_games())-($this-&gt;wins()); return $this-&gt;loss; } public function total_games(){ if ($this-&gt;total) return $this-&gt;total; //echo "SELECT COUNT(`winner`) FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` IS NOT NULL AND (`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end';"; $this-&gt;total = $this-&gt;db-&gt;query("SELECT COUNT(`winner`) FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` IS NOT NULL AND (`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end';")-&gt;fetchOne(); return $this-&gt;total; } public function get_opponentsarray(){ if ($this-&gt;opponentsarray) return $this-&gt;opponentsarray; $opponentsarray = array(); $result = $this-&gt;db-&gt;query("SELECT `hometeam`,`awayteam`,`winner` FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` IS NOT NULL AND (`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end' ORDER BY `date` ASC;"); while ($row = $result-&gt;fetchRow(MDB2_FETCHMODE_ASSOC)){ if ($row['hometeam'] == $this-&gt;teamid){ if ($row['winner'] == $this-&gt;teamid) $opponentsarray[$row['awayteam']] = 'W'; elseif ($row['winner'] == 0) $opponentsarray[$row['hometeam']] = 'T'; else $opponentsarray[$row['awayteam']] = 'L'; } elseif ($row['awayteam'] == $this-&gt;teamid){ if ($row['winner'] == $this-&gt;teamid) $opponentsarray[$row['hometeam']] = 'W'; elseif ($row['winner'] == 0) $opponentsarray[$row['hometeam']] = 'T'; else $opponentsarray[$row['hometeam']] = 'L'; } } $this-&gt;opponentsarray = $opponentsarray; return $this-&gt;opponentsarray; } public static function reduction_factor($levelid){ switch ($levelid){ case 66: return 1.00; case 55: return 1.00; case 44: return 0.90; case 33: return 0.75; case 22: return 0.60; case 11: return 0.45; case 9: return 0.40; case 8: return 0.35; case 7: return 0.30; case 6: return 0.15; default: return 1.00; } } // ********************************************************************************************************************************* // Calculate WP (winning percentage) // ********************************************************************************************************************************* public function wp(){ if ($this-&gt;wp) return $this-&gt;wp; if ($this-&gt;total_games() == 0) { $this-&gt;wp = 0; return $this-&gt;wp; } $reduce = $this-&gt;reduction_factor($this-&gt;levelid_state); $this-&gt;wp = round($this-&gt;wins()/$this-&gt;total_games() * $reduce, 4); return $this-&gt;wp; } // ********************************************************************************************************************************* // Calculate WP (winning percentage) with exclusion // ********************************************************************************************************************************* public function wp_exclude($team_excluding, $rpiteamarray){ $opponentsarray = $this-&gt;get_opponentsarray(); $wins = 0; $total = 0; foreach ($opponentsarray as $key =&gt; $value){ if ($key == $team_excluding) continue; ++$total; if ($value == 'W') ++$wins; elseif ($value == 'T') $wins = $wins + 0.5; } if ($total == 0) return 0; return round($wins/$total * $this-&gt;reduction_factor($this-&gt;levelid_state), 4); } // ********************************************************************************************************************************* // Calculate OWP (opponents winning percentage) // ********************************************************************************************************************************* public function owp($rpiteamarray){ $opponentsarray = $this-&gt;get_opponentsarray(); $owp = 0; $total = 0; foreach ($opponentsarray as $key =&gt; $value){ ++$total; $owp += $rpiteamarray[$key]-&gt;wp_exclude($this-&gt;teamid, $rpiteamarray); } if ($total == 0) return 0; return round($owp/$total, 4); } // ********************************************************************************************************************************* // Calculate OWP (opponents winning percentage) // ********************************************************************************************************************************* public function oowp($rpiteamarray){ $opponentsarray = $this-&gt;get_opponentsarray(); $oowp = 0; $total = 0; foreach ($opponentsarray as $key =&gt; $value){ $owp_opponentsarray = $rpiteamarray[$key]-&gt;get_opponentsarray(); foreach ($owp_opponentsarray as $owp_key =&gt; $owp_value){ ++$total; $oowp += $rpiteamarray[$owp_key]-&gt;wp(); } } if ($total == 0) return 0; return round($oowp/$total, 4); } } </code></pre> <p>I use PHP with PEAR MDB2.</p> <p>Is there a good way to prepare the queries used in the class? That is, can I prepare the queries once somehow, so when they are called ~16k times each it helps?</p> <p>I haven't run the numbers, but I think it's querying the database 4x(num teams) or ~64k times.</p> <p>Any other improvements possible?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:04:45.150", "Id": "32598", "Score": "0", "body": "Sorry if this is a stupid question, I haven't read over your question fully yet, but why are you checking all this data every time? Does it change? If, once its stored, its static, then you can check it once then cache the results, then each subsequent check can use the cached results instead. I'm currently looking over your code, but I may not be able to upload my answer until tomorrow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T23:56:24.987", "Id": "32605", "Score": "0", "body": "Can you explain a bit about why you first iterate over the recordset, store an array and then iterate again over the array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:09:12.667", "Id": "32664", "Score": "0", "body": "@mseancole The data can change with the addition of new results, and rarely the change of past results (errors, corrections). I do currently store as a file and run this calculation daily, but I'd like to increase the speed so it could be updated several times a day without hampering the rest of the website." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:13:17.597", "Id": "32668", "Score": "0", "body": "@RobApodaca The rpi() function flow is as follows: Get a list of all teams. Create the objects from the list of teams. If the team hasn't played any games, their values (WP, OWP and OOWP) will all be 0.0000 so I've chosen to just not display them at all so I remove them from the $rpi array. Then I run through the array to actually calculate the RPI values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T14:28:54.887", "Id": "43416", "Score": "0", "body": "@jsanc623 @RobApodaca As it turns out, the query(s) that had `(`hometeam` = $this->teamid OR `awayteam` = $this->teamid)` were the biggest hit to performance. Each of these queries took 0.5 to 1.1 seconds. Changing this query http://dba.stackexchange.com/questions/45219/how-can-i-speed-up-this-slow-simple-query makes it now take <0.002 seconds, so total execution went from 900 minutes to 2 minutes." } ]
[ { "body": "<p>Not quite a lot that can be done performance-wise...you have a lot of data to pour over (<code>16,000 * 81,000 = 1,296,000,000 records</code> and with the new data <code>17,000 * 160,000 = 2,720,000,000 records)</code>. You could possibly think of moving over to a faster database (Redis? Cassandra?). </p>\n\n<p>Anyways, I made a few <strong>minor</strong> changes to your code - added empty() checks rather than empty string checks, shortened a few if statements, etc. </p>\n\n<pre><code>&lt;?php\n\n/**\n * Function to calculate RPI given a sportid and year, optional cutoff date\n */\n\nfunction rpi($sportid, $year, $date = FALSE, $my_db, $sport_array){\n # figure out if this is a year-spanning sport\n $year_display = $year;\n $date_start = $year . $sport_array[$sportid]['start_date'];\n $date_end = $year . $sport_array[$sportid]['end_date'];\n $today = date(\"Y-m-d\");\n $rpiteamarray = array();\n\n if($sport_array[$sportid]['end_year_plus']){\n $year_display = $year . '-' . ( $year + 1 );\n $date_end = ( $year + 1 ) . $sport_array[$sportid]['end_date'];\n }\n\n if($date){\n $date_end = $date;\n } else if ($date_end &gt; $today){\n $date_end = $today;\n }\n\n $results = $my_db-&gt;query(\"SELECT `teamid` FROM `team` WHERE `jv` = '0' AND `teamid` &gt; 0;\");\n\n while ($row = $results-&gt;fetchRow(MDB2_FETCHMODE_ASSOC)){\n $teamid = $row['teamid'];\n\n if(!array_key_exists($teamid, $rpiteamarray)){\n $rpiteamarray[$teamid] = new rpiteam($teamid, $sportid, $year, $my_db, $date_start, $date_end);\n }\n if($rpiteamarray[$teamid]-&gt;total_games() == 0){\n continue; \n }\n $rpi[$teamid]['numgames'] = $rpiteamarray[$teamid]-&gt;total_games();\n }\n unset($results, $row);\n\n foreach($rpi as $teamid =&gt; $value){\n $rpi[$teamid]['wp'] = $rpiteamarray[$teamid]-&gt;wp();\n $rpi[$teamid]['owp'] = $rpiteamarray[$teamid]-&gt;owp($rpiteamarray);\n $rpi[$teamid]['oowp'] = $rpiteamarray[$teamid]-&gt;oowp($rpiteamarray);\n }\n\n return $rpi;\n}\n?&gt;\n</code></pre>\n\n<p>and the class:</p>\n\n<pre><code>&lt;?php\n\nclass rpiteam {\n protected $sportid, $levelid, $levelid_state, $year,\n $wins, $loss, $tie, $total, $wp, $db,\n $opponentsarray, $date_start, $date_end;\n\n function __construct($teamid, $sportid, $year, $db, $date_start, $date_end){\n # You had three If statements here...just replace it with one\n if (empty($teamid) || empty($year) || empty($sportid)){\n return null;\n }\n\n $this-&gt;db = $db;\n $this-&gt;sportid = $sportid;\n $this-&gt;teamid = $teamid;\n $this-&gt;year = $year;\n $this-&gt;date_start = $date_start;\n $this-&gt;date_end = $date_end;\n\n $row = $this-&gt;db-&gt;query(\"SELECT `levelid`,`levelid_state` FROM `team_class` WHERE `teamid` = $teamid AND `sportid` = $sportid AND `year` = $year;\")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC);\n $this-&gt;levelid = $row['levelid'];\n $this-&gt;levelid_state = $row['levelid_state'];\n $this-&gt;opponentsarray = array();\n }\n\n public function wins(){\n if (!empty($this-&gt;wins)){\n return $this-&gt;wins;\n }\n\n $this-&gt;wins = $this-&gt;db-&gt;query(\"SELECT COUNT(`winner`) FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` = $this-&gt;teamid AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end';\")-&gt;fetchOne();\n return $this-&gt;wins;\n }\n\n public function loss(){\n if (!empty($this-&gt;loss)){\n return $this-&gt;loss;\n }\n $this-&gt;loss = ($this-&gt;total_games())-($this-&gt;wins());\n return $this-&gt;loss;\n }\n\n public function total_games(){\n if (!empty($this-&gt;total)){\n return $this-&gt;total;\n }\n $this-&gt;total = $this-&gt;db-&gt;query(\"SELECT COUNT(`winner`) FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` IS NOT NULL AND (`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end';\")-&gt;fetchOne();\n return $this-&gt;total;\n }\n\n public function get_opponentsarray(){\n if (!empty($this-&gt;opponentsarray)){\n return $this-&gt;opponentsarray;\n }\n\n $result = $this-&gt;db-&gt;query(\"SELECT `hometeam`,`awayteam`,`winner` FROM `game` WHERE `sportid` = $this-&gt;sportid AND `winner` IS NOT NULL AND (`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) AND `date` BETWEEN '$this-&gt;date_start' AND '$this-&gt;date_end' ORDER BY `date` ASC;\");\n while ($row = $result-&gt;fetchRow(MDB2_FETCHMODE_ASSOC)){\n if ($row['hometeam'] == $this-&gt;teamid){\n if ($row['winner'] == $this-&gt;teamid) $this-&gt;opponentsarray[$row['awayteam']] = 'W';\n elseif ($row['winner'] == 0) $this-&gt;opponentsarray[$row['hometeam']] = 'T';\n else $this-&gt;opponentsarray[$row['awayteam']] = 'L';\n } elseif ($row['awayteam'] == $this-&gt;teamid){\n if ($row['winner'] == $this-&gt;teamid) $this-&gt;opponentsarray[$row['hometeam']] = 'W';\n elseif ($row['winner'] == 0) $this-&gt;opponentsarray[$row['hometeam']] = 'T';\n else $this-&gt;opponentsarray[$row['hometeam']] = 'L';\n }\n }\n return $this-&gt;opponentsarray;\n }\n\n public static function reduction_factor($levelid){\n switch ($levelid){\n case 66: return 1.00;\n case 55: return 1.00;\n case 44: return 0.90;\n case 33: return 0.75;\n case 22: return 0.60;\n case 11: return 0.45;\n case 9: return 0.40;\n case 8: return 0.35;\n case 7: return 0.30;\n case 6: return 0.15;\n default: return 1.00;\n }\n }\n\n /*\n * Calculate WP (winning percentage)\n */\n public function wp(){\n if (!empty($this-&gt;wp)){\n return $this-&gt;wp;\n }\n\n if ($this-&gt;total_games() == 0) {\n $this-&gt;wp = 0;\n return $this-&gt;wp;\n }\n\n $reduce = $this-&gt;reduction_factor($this-&gt;levelid_state);\n\n $this-&gt;wp = round($this-&gt;wins() / $this-&gt;total_games() * $reduce, 4);\n return $this-&gt;wp;\n }\n\n /*\n * Calculate WP (winning percentage) with exclusion\n */\n public function wp_exclude($team_excluding, $rpiteamarray){\n $opponentsarray = $this-&gt;get_opponentsarray();\n\n $wins = 0;\n $total = 0;\n\n foreach ($opponentsarray as $key =&gt; $value){\n if ($key == $team_excluding) continue;\n ++$total;\n if ($value == 'W') ++$wins;\n elseif ($value == 'T') $wins = $wins + 0.5;\n }\n\n if ($total == 0) return 0;\n return round($wins / $total * $this-&gt;reduction_factor($this-&gt;levelid_state), 4);\n }\n\n /*\n * Calculate OWP (opponents winning percentage)\n */\n public function owp($rpiteamarray){\n $opponentsarray = $this-&gt;get_opponentsarray();\n\n $owp = 0;\n $total = 0;\n\n foreach ($opponentsarray as $key =&gt; $value){\n ++$total;\n $owp += $rpiteamarray[$key]-&gt;wp_exclude($this-&gt;teamid, $rpiteamarray);\n }\n if ($total == 0) return 0;\n return round($owp / $total, 4);\n }\n\n /*\n * Calculate OWP (opponents winning percentage)\n */\n public function oowp($rpiteamarray){\n $opponentsarray = $this-&gt;get_opponentsarray();\n\n $oowp = 0;\n $total = 0;\n\n foreach ($opponentsarray as $key =&gt; $value){\n $owp_opponentsarray = $rpiteamarray[$key]-&gt;get_opponentsarray();\n\n foreach ($owp_opponentsarray as $owp_key =&gt; $owp_value){\n ++$total;\n $oowp += $rpiteamarray[$owp_key]-&gt;wp();\n }\n\n }\n if ($total == 0) return 0;\n return round($oowp/$total, 4);\n }\n}\n?&gt;\n</code></pre>\n\n<p>Like I said - very little to do with code from my POV - perhaps someone can skim through it and add their ideas on how to optimize it further. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:46:32.317", "Id": "32447", "Score": "1", "body": "The games don't multiply by the teams; that is, each team doesn't play 81k games. So, 81k of records/rows in the table, each game has 2 teams as a part of it. Thanks for the tip on empty()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T19:01:56.163", "Id": "32455", "Score": "0", "body": "Ahh...my apologies on the misunderstanding. Sure thing!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:42:02.570", "Id": "20291", "ParentId": "20282", "Score": "3" } }, { "body": "<p>I think there are two main areas you can focus on:</p>\n\n<p><strong>n+1 queries</strong>\nYou have 1 query to select all of the teamid's and n additional queries, where n is the total number of games per team. Actually, the problem is more severe than that because you call <code>get_opponentsarray()</code> from <code>owp()</code>, <code>oowp()</code>, and <code>wp_exclude()</code>. And, <code>wp_exclude()</code> is also called from <code>owp()</code>. All of these queries and redundant queries are probably chewing up the most time. Work on creating one query (or fewer) with joins to the games table as necessary. Make sure that columns are indexed appropriately.</p>\n\n<p><strong>Serialize, gzip</strong>\nYou mention that you are taking all of the results and storing in a serialized, gzipped array. Not sure where you are persisting that (file system?) but, I think you would be better off storing the results in a <a href=\"http://en.wikipedia.org/wiki/Denormalization\" rel=\"nofollow\">denormalized table</a>. If fact, if you take my advice and use just one query, you could <code>select into</code> your results from that one query into the denormalized table.</p>\n\n<p>Personally, I'd reconsider the whole approach here. Surely you are not displaying ~17k teams in a single web page. If you are, don't. If you only display ~20 teams per page, you could easily run some aggregate queries against the games table and run your rpi calculation for each. Not only would this cut out the cron/batch process, your users would always have up-to-date data displayed.</p>\n\n<p><em>Edit</em>:\nTo display only a few teams per page, pass the limit and offset in the url. For example, to display teams 10 through 30, use a url like:</p>\n\n<pre><code>/teams?offset=10&amp;limit=20\n</code></pre>\n\n<p>The result set should contain all data needed for the page (including the rpi calculation).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T14:07:01.687", "Id": "32849", "Score": "0", "body": "I might not understand how it works, but I think I'm \"caching\" the get_opponentsarray() query by storing the array as an property of the object. So the query runs the first time it needs it, then after that, it already has the array so it just returns that array. Is it not \"caching\" the array and operating like I think it does?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T14:09:33.133", "Id": "32850", "Score": "0", "body": "The file storing part was not part of the code shown above, but yes, stored in a file. I am not displaying ~17k teams on one page, but I do show an entire state's teams, which for some states, is in the thousands. I then use jQuery datatables to help display smartly, but, if someone isn't using javascript, they would get a single table of perhaps thousands of teams. But that is an interesting thought: Only display ~25 teams at a time which would certainly cut down on the calculation time. The trouble is: How do you know which top 25 to display, without calculating at least an entire state?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T00:20:07.217", "Id": "33144", "Score": "0", "body": "@MECU ok, yeah I guess I missed the results storage in the array." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T14:18:38.513", "Id": "20460", "ParentId": "20282", "Score": "3" } }, { "body": "<p>Changing the query that contains </p>\n\n<pre><code>(`hometeam` = $this-&gt;teamid OR `awayteam` = $this-&gt;teamid) \n</code></pre>\n\n<p>To one without the OR makes that query go from 0.5-1.1 seconds to &lt;0.002 seconds each. *20,000 occurances (or more) is a huge time delta.</p>\n\n<p>See <a href=\"https://dba.stackexchange.com/questions/45219/how-can-i-speed-up-this-slow-simple-query\">https://dba.stackexchange.com/questions/45219/how-can-i-speed-up-this-slow-simple-query</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T14:30:58.800", "Id": "27849", "ParentId": "20282", "Score": "3" } } ]
{ "AcceptedAnswerId": "27849", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:14:32.600", "Id": "20282", "Score": "4", "Tags": [ "php", "mysqli" ], "Title": "Improve Speed of RPI Calculation" }
20282
<p>Just a small PHP exercise to write some simple reports, I thought I'd do it without a framework for fun and profit. I'm particularly concerned about the potential for SQL injection, since the user could pass their own values to <code>$_GET['status']</code>.</p> <p>I also understand that <code>mysql_connect()</code> et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.</p> <pre><code>&lt;?php $server = "deleted"; $username = "deleted"; $password = "deleted"; $database = "deleted"; $conn = mysql_connect($server, $username, $password); if (!$conn) { die('Could not connect: ' . mysql_error()); } mysql_select_db($database, $conn); // Get the status from the last form submission, otherwise use default. $choice = isset($_GET['status']) ? $_GET['status'] : '7'; // Get all the current statuses to populate the drop down list. $options = mysql_query("SELECT name, id FROM issue_statuses", $conn); // Get all the results for issues matching the chosen status id. $result = mysql_query("SELECT id, subject FROM issues WHERE status_id = " . $choice, $conn); // Get the name of the chosen status. $chosen_status = mysql_query("SELECT name FROM issue_statuses WHERE id = " . $choice, $conn); $status_name = mysql_fetch_array($chosen_status, MYSQL_ASSOC); if (!$options || !$result || !$chosen_status) { echo("&lt;p&gt;Error performing query: " . mysql_error() . "&lt;/p&gt;"); exit(); } mysql_close($conn); ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;RM Rep&lt;/title&gt; &lt;style&gt; body { font-family: Arial, sans-serif; } td { padding: 0px 5px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="status_choice" action="index.php" method="get"&gt; &lt;select name="status"&gt; &lt;?php // Load all the statuses into a select list. while ($row = mysql_fetch_array($options, MYSQL_ASSOC)) { echo('&lt;option value="' . $row['id'] . '"&gt;' . $row['name'] . '&lt;/option&gt;'); } ?&gt; &lt;/select&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;h1&gt;&lt;?php echo($status_name['name']); ?&gt;&lt;/h1&gt; &lt;span&gt;&lt;?php echo(mysql_num_rows($result) . " results"); ?&gt;&lt;/span&gt; &lt;hr&gt; &lt;table&gt; &lt;?php // Print results. while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo("&lt;tr&gt;"); echo("&lt;td&gt;" . $row['id'] . "&lt;/td&gt;"); echo("&lt;td&gt;" . $row['subject'] . "&lt;/td&gt;"); echo("&lt;/tr&gt;"); } ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:37:04.140", "Id": "32440", "Score": "2", "body": "\"Better equivalents\" do not work the same way, they are better. Using a PDO system will help prevent SQL injection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:34:44.137", "Id": "32586", "Score": "0", "body": "Instead of hard-coding `mysql_` everywhere, consider writing wrapper functions. Implement `db_query` that simply calls `mysql_query`. Switching to Oracle or PostgreSQL then requires changing only a single file. Better is to use PDO, which avoids the issue altogether." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:36:46.170", "Id": "32587", "Score": "0", "body": "MySQLi is also another option, but PDO seems to be the most popular choice. Haven't really used either one personally, but in my experiences in reviewing code written for the two, PDO is by far my favorite." } ]
[ { "body": "<blockquote>\n <p>I also understand that mysql_connect() et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.</p>\n</blockquote>\n\n<p>Sort of. MySQLi can work a lot like the the mysql extension, but personally I prefer PDO. Whereas MySQLi has both an OO and a procedural API, PDO has only an OO one. PDO can interact with more than just MySQL though.</p>\n\n<p>Due to differences in SQL dialects, it's rare for it to be possible to just change out the driver and have everything work. It is a lot closer to cross compatibility than a specific RDBMS's API. Also, you can use your knowledge of the PDO API across multiple database systems. Whether it's MySQL, sqlite, SQL Server, etc, the general API is the same.</p>\n\n<p>Anyway, whether you choose MySQLi or PDO, you should definitely stop using ext/mysql.</p>\n\n<hr>\n\n<p>As for SQL injection: your code is basically a poster child for it.</p>\n\n<pre><code>$choice = isset($_GET['status']) ? $_GET['status'] : '7';\n$result = mysql_query(\"SELECT id, subject FROM issues WHERE status_id = \" . $choice, $conn);\n</code></pre>\n\n<p>What if I go to <code>page.php?status=0 OR 1=1</code>? The query becomes:</p>\n\n<pre><code>SELECT id, subject FROM issues WHERE status_id = 0 OR 1=1\n</code></pre>\n\n<p>This is a fairly benevolent example since all this will do is ignore the status filter. I've seen some very clever exploits though. Given enough time and determination, this small exploit could be ripped open into horrible, horrible things.</p>\n\n<p>The easiest solution to SQL injection is to always stay aware that SQL is a language like any other (well, not on a technical level, but on a superficial level).</p>\n\n<p>In particular, just remember to either escape content if it's being put into the query as a string, or cast it if it's being put in as something else.</p>\n\n<p>For example:</p>\n\n<pre><code>$choice = isset($_GET['status']) ? (int) $_GET['status'] : 7;\n</code></pre>\n\n<p><code>$choice</code> is now safe to put into an SQL statement.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php\">This</a> StackOverflow thread gives tons of options for properly handling SQL queries. </p>\n\n<hr>\n\n<pre><code>if (!$options || !$result || !$chosen_status)\n{\n echo(\"&lt;p&gt;Error performing query: \" . mysql_error() . \"&lt;/p&gt;\");\n exit();\n}\n</code></pre>\n\n<p>If more than one query fails, this will only output the error for the last one. Additionally, using <code>exit</code> for rendering errors is bad practice. In a file this simple, there's really not much of a better option without going way out of your way. What I tend to do in larger applications though is let uncaught exceptions (in other words, either the ones that I expect to never happen or the ones that are fatal) bubble up to the top at which point the request is transparently piped to an error controller (basically, I've copied the approach of most PHP MVC frameworks). If you wanted to use a similar approach, you could basically wrap exceptions over the MySQL API. That get's ugly fast though.</p>\n\n<p>Oh, also, the mysql_error should be passed through htmlspecialchars. I'll add more to this note in a minute.</p>\n\n<hr>\n\n<p>I'm not sure if it's technically valid to close a MySQL connection and then read the result sets. I suspect that this is not valid, and that if it works, it's just by luck.</p>\n\n<hr>\n\n<p>Even when not going full-blown MVC, it can be very beneficial to separate logic or manipulation from the view. In particular, all of the mysql calls in the HTML parts, I would put in the PHP parts. If your view is only looping over an array, the source of the array can be changed without the view having to know about it. (Side note: depending on how strictly we're using terminology, the HTML part is probably better not called a view.)</p>\n\n<hr>\n\n<pre><code>while ($row = mysql_fetch_array($options, MYSQL_ASSOC))\n</code></pre>\n\n<p>You might as well us mysql_fetch_assoc.</p>\n\n<hr>\n\n<pre><code>echo('&lt;option value=\"' . $row['id'] . '\"&gt;' . $row['name'] . '&lt;/option&gt;');\n</code></pre>\n\n<p>Anything being put into HTML needs to be run through htmlspecialchars. This comes back to being aware of context. It's just the rules of HTML. Certain things must be escaped in the same way that things in SQL or PHP must be escaped.</p>\n\n<p>(I'm also not a fan of the <code>echo()</code> form of <code>echo</code>, but that's mostly opinion.)</p>\n\n<pre><code>echo '&lt;option value=\"' . htmlspecialchars($row['id']) . '\"&gt;' . htmlspecialchars($row['name']) . '&lt;/option&gt;';\n</code></pre>\n\n<p>A lot of people will say that the htmlspecialchars on the id is pointless since it's going to be an int. While that's true, that's only <em>for now</em>. With a primary key column it's not likely to happen (in fact it probably shouldn't happen), but I've been in situations before where an int column has been changed to a varchar and we've had problems with the HTML escaping after that. Considering the overhead of htmlspecialchars is tiny, might as well call it on everything being put into HTML.</p>\n\n<hr>\n\n<p>There's a few more comments and suggestions I have. I was originally going to add them as comments to the code, but I got a bit carried away and decided to rewrite it with PDO.</p>\n\n<pre><code>&lt;?php\n\n$db = new PDO('mysql:host=localhost;dbname=somedatabase', 'username', 'password', array(\n PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION\n));\n\n//The error mode being exception means that exceptions will be thrown if a query fails \n//(or some other kind of error happens). This tends to be more convenient since you don't\n//have to explicitly check for unexpected errors -- either everything executes fine, or the script\n//crashes and burns (which might not be desired behavior in a lot of cases).\n//Anyway, there is one little catch. PDOException instances will sometimes include with them\n//the DSN (the 'mysql:host=...' string), the username, and the password. This means that you must be\n//very careful about never letting an end user see a PDOException. In particular, you can either have\n//a just-in-case top level try {} catch {} that can catch any unexpected errors, log them, and render \n//them in a pretty page (what I like to do in any kind of sizable application), or at the very least,\n//you can ensure that display_errors of Off on production servers (which it should be anyway). That way\n//the exception will still be logged, but it won't be displayed.\n\n//$options is a bad name. What kind of options?\n$issueStatusesStmt = $db-&gt;query(\"SELECT name, id FROM issue_statuses\");\n\n//This is done in a weird way, but it has a reason.\n//In particular, you can now check if a provided status id exists (isset($issueStatuses[$idToCheck])).\n//And, you no longer need your name query since you can pull the name with $issueStatuses[$id]['name'].\n$issueStatuses = array();\nwhile ($is = $issueStatusesStmt-&gt;fetch(PDO::FETCH_ASSOC)) {\n $issueStatuses[$is['id']] = $is;\n}\n\n//This handles the isset check and validates that the provided value is an integer.\n//If the value fails the integer check, $statusId will be false. If no status param is\n//provided in the URL, $statusId will be null. There is of course a lot more\n//information about this at http://php.net/filter_input\n$statusId = filter_input(INPUT_GET, 'status', FILTER_VALIDATE_INT);\n\n if (!isset($issueStatuses[$statusId]) {\n //This is what's called a magic constant. They tend to lead to problems.\n //In particular, what is this magical status 7? Someone not intimately familiar\n //with your DB data will have no idea.\n $statusId = 7;\n}\n\n//This prepares a statement with a placeholder for status_id.\n$issuesStmt = $db-&gt;prepare(\"SELECT id, subject FROM issues WHERE status_id = :statusId\");\n$issuesStmt-&gt;execute(array('statusId' =&gt; $statusId));\n/*\n * You could also do it like:\n $issuesStmt = $db-&gt;prepare(\"SELECT id, subject FROM issues WHERE status_id = ?\");\n $issuesStmt-&gt;execute(array($statusId));\n * I prefer to stick with named fillers though. It's significantly less confusing if you have \n * to revisit a complicated query a month later.\n*/\n\n//You could make this an associative array like earlier, but really there's no reason to at this point.\n$issues = $issuesStmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n\n//Note: if $statusId default to 7 and 7 somehow doesn't exist in the database,\n//this will issue a notice and $statusName will be null.\n$statusName = $issueStatuses[$statusId]['name'];\n\n//PHP will only eat one new line. The doctype is supposed to be the very top line (unless I've imagined that requirement).\n//This means it need to be on the line directly after the closing tag.\n?&gt;\n&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;RM Rep&lt;/title&gt;\n &lt;style&gt;\n body { font-family: Arial, sans-serif; }\n td { padding: 0px 5px; }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form name=\"status_choice\" action=\"index.php\" method=\"get\"&gt;\n &lt;select name=\"status\"&gt;\n &lt;?php foreach ($issueStatuses as $is) { ?&gt;\n &lt;option value=\"&lt;?php echo htmlspecialchars($is['id']); ?&gt;\"&gt;&lt;?php echo htmlspecialchars($is['name']); ?&gt;&lt;/option&gt;\n &lt;?php } ?&gt;\n &lt;/select&gt;\n &lt;input type=\"submit\" value=\"Submit\"&gt;\n &lt;/form&gt;\n\n &lt;h1&gt;&lt;?php echo htmlspecialchars($statusName); ?&gt;&lt;/h1&gt;\n &lt;span&gt;&lt;?php echo count($issues) . ' results'; ?&gt;&lt;/span&gt;\n &lt;hr&gt;\n\n &lt;?php \n /*\n If no entries are found, you will emit broken HTML in your current code.\n (At least I think an empty table is invalid HTML -- can't remember.)\n (Oh and also, I'm abusing PHP comments right now...)\n */\n ?&gt;\n\n &lt;?php if (!empty($issues)) { ?&gt;\n\n &lt;table&gt;\n &lt;?php foreach ($issues as $issue) { ?&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($row['id']); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($row['subject']); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php } ?&gt;\n &lt;/table&gt;\n\n &lt;?php } else { ?&gt;\n &lt;div&gt;\n No entries matched the given status.\n &lt;/div&gt;\n &lt;?php } ?&gt;\n\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T10:58:41.497", "Id": "32523", "Score": "0", "body": "Thanks for this thoughtful reply, lots of things to look into!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:12:15.383", "Id": "32524", "Score": "0", "body": "@DesmondWolf Glad to help :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T00:06:00.457", "Id": "20306", "ParentId": "20283", "Score": "3" } } ]
{ "AcceptedAnswerId": "20306", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:16:43.770", "Id": "20283", "Score": "3", "Tags": [ "php", "mysql", "form" ], "Title": "Database report in PHP" }
20283
<p><strong>Introduction</strong></p> <p>In my Java application, I need to represent the result of an operation. This can either be OK or ERROR + an error message.</p> <hr> <p><strong>Background</strong></p> <p>I have a class to verify the integrity of a directory (e.g. to check that a few conditions hold). If it finds out the directory is corrupted, it should return a description of the error, such as:</p> <ul> <li>Unexpected file - [filename].</li> <li>Unexpected number of files - expected [X], actual [Y].</li> </ul> <p>The callers of the class don't know anything about the directory and the conditions. They are only interested to know if the directory is OK or not, and in that case, to get an appropriate error message.</p> <p>The Result class was intended as a way to transmit the results of the verification. </p> <p>I chose not to throw exceptions as (to me) that seemed more convenient for reporting errors in the verification process. It seemed inappropriate to intermix those two situations (e.g. the directory was found invalid vs. an error occurred while verifying the directory). </p> <hr> <p><strong>The current solution</strong></p> <p>I have so far been able to come up with the following class.</p> <pre><code>public class Result { private static enum State { OK, ERROR }; private State state; private String errorMessage; private Result(State state, String errorMessage) { this.state = state; this.errorMessage = errorMessage; } public static Result ok() { return new Result(State.OK, null); } public static Result error(String errorMessage) { return new Result(State.ERROR, errorMessage); } public boolean isOK() { return (this.state == State.OK); } public String getErrorMessage() { return errorMessage; } } </code></pre> <p>The client code then looks like this:</p> <pre><code>Result result = Result.ok(); Result result = Result.error("Could not ..."); if (result.isOK()) ... else { String errorMessage = result.getErrorMessage(); ... } </code></pre> <p>This has the benefit that when creating a result, the client only has to deal with error messages in case of an error.</p> <p>On the other hand, the API does not prevent the client code to ask for an error message in case of an OK result. That does not feel right.</p> <p>I also don't like the way the information about valid states (OK/ERROR) gets dupplicated into:</p> <ul> <li>the internal enumeration,</li> <li>the public static methods.</li> </ul> <hr> <p><strong>What do you think about my implementation? How would you design the class?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:30:51.817", "Id": "32472", "Score": "2", "body": "Are you sure you even need such a class? Why not stick with exceptions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:33:33.807", "Id": "32518", "Score": "0", "body": "I added some background information and elaborated more on that decision. I'm not that sure about it anymore, though. Firstly, I'm not sure that the verification process itself might (in my specific case) fail. Secondly, I could use two different exception types to mark the distinction (and catch and process them separately). But I have a feeling that those two (e.g. verification failure vs. a negative response) are different concepts and should be handled differently. I mean, it is not an error in the verification process if a directory is found invalid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T10:12:19.897", "Id": "32522", "Score": "0", "body": "Thanks for the clarifying edit, that makes a lot of sense to me." } ]
[ { "body": "<p>I do not know the exact requirements, but two simple approaches would be:</p>\n\n<ul>\n<li><p>Just return a String as result. This can either be null or empty (if everything is ok) or the error message (if something is wrong).</p></li>\n<li><p>Throw an exception</p></li>\n</ul>\n\n<p>(Other then that: I would try to find a better name for the factory methods. The meaning of the current names is not really clear.)</p>\n\n<hr>\n\n<p>edit after original post was changed:</p>\n\n<p>If you do not need a general solution or anything special, I would keep the simple way and return a String. KISS principle.</p>\n\n<p>If you want to make it fancy, I would continue with your approach, only slightly modified:</p>\n\n<pre><code>public class DirectoryChecker\n{\n private String errorMessage;\n //or private List&lt;String/anything else&gt; errors;\n\n public static Result ok()\n {\n return new Result(State.OK, null);\n }\n\n public boolean isThereAnyProblem()\n {\n // check if everything is ok. Set error if not.\n // if the check should be done only once, add a member variable to keep the state\n }\n\n public String /* or anything else */ getErrorMessage/*s*/()\n {\n return errorMessage /*or anything else*/;\n }\n}\n</code></pre>\n\n<p>Explanations:</p>\n\n<ul>\n<li>Some factory method will create an instance of this class. The caller can do: <code>if(directoryChecker.isThereAnyProblem()) { get and handle error }</code></li>\n<li>I do not think you need the enum. It represents a state of the internal state. And you only need ok/not ok as far as I got it.</li>\n<li>As you see this is hardly the same as the String approach, you just wrap an additional class around it.</li>\n</ul>\n\n<p>Side note: You could name the check method isEverythingOk, but personally I prefer this flow of code:</p>\n\n<pre><code>if (something happened)\n { handle it }\ngo on with normal flow\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (everything is ok)\n { do normal things }\nelse\n { handle it }\ngo on with normal(?) code or other code(?)\n</code></pre>\n\n<p>About exceptions: I would not use them in this case, it makes life only more complex.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:19:17.020", "Id": "32513", "Score": "0", "body": "I updated the question and described why I did not choose exceptions to transmit the error message." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:55:01.083", "Id": "32525", "Score": "0", "body": "@DušanRychnovský I have updated my post to reflect your changes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T13:58:42.460", "Id": "32530", "Score": "0", "body": "@tb- I don't think that simply returning a string would be a great idea. I feel better when the domain concepts have their own class and I don't have to guess what is the meaning of a string" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T18:21:59.557", "Id": "20289", "ParentId": "20285", "Score": "1" } }, { "body": "<p>I'd change your enum State, like this:</p>\n\n<pre><code>enum State\n{\n OK(null),\n COULDNT_LOAD(\"Error: Could not load file: %s.\"),\n COULDNT_PARSE(\"Error: Could not parse contents of file %s.\"),\n UNEXPECTED_NUM_FILES(\"Error: Unexpected number of files - expected %d, actual %d.\");\n\n String message;\n\n State(String message)\n {\n this.message = message;\n }\n\n void setReplacements(Object... replacements)\n {\n if(this.message != null)\n {\n this.message = new Formatter().format(this.message, replacements).toString();\n }\n }\n}\n</code></pre>\n\n<p>Then you can have your validation method return a state, and you can do your checking block after, like this:</p>\n\n<pre><code>File fileITriedToLoad = new File(\"/usr/file.java\");\nState result = State.COULDNT_LOAD;\nresult.setReplacements(fileITriedToLoad.getAbsolutePath());\n\nif(result != State.OK)\n{\n System.out.println(result.message);\n}\n</code></pre>\n\n<p>And you can delete the rest of your <code>Result</code> class.</p>\n\n<p><strong>Edit:</strong> Using the new <code>setReplacements()</code> method would then allow you to add pieces of text at the specified points in your message, so your validation method that returns a State would use it as follows:</p>\n\n<pre><code>State state = State.UNEXPECTED_NUM_FILES;\nstate.setReplacements(1, 3);\n</code></pre>\n\n<p>And then printing the <code>state.message</code> will produce:</p>\n\n<p><code>Error: Unexpected number of files - expected 1, actual 3.</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T20:52:14.810", "Id": "32463", "Score": "0", "body": "It seems that in this case, the error message would always be like \"Okay\" or \"Error\". That's not what I need. I need it to be either undefined (if the state is OK), or a custom error message, like \"Could not open file XXX.\" (if the state is ERROR). Moreover, multiple error messages should be expressible (e.g. \"Could not open file XXX.\", \"Could not parse contents of file XXX.\", etc.)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T20:58:32.477", "Id": "32464", "Score": "0", "body": "@DušanRychnovský Well then, if you know what file they tried to load, see my edits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:06:13.947", "Id": "32465", "Score": "0", "body": "@DušanRychnovský And to pre-empt the next question: if you don't know the file, wrap the file and Status into a `ValidatedFile` class with a `getState()` and `getFile()` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:17:49.750", "Id": "32512", "Score": "0", "body": "I need a more general solution. I updated the question to make this more apparent. I admit I have not made it clear in my previous comment that not all error messages are related to a single file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T13:04:46.153", "Id": "32526", "Score": "0", "body": "@DušanRychnovský Edited accordingly :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T20:08:28.643", "Id": "20296", "ParentId": "20285", "Score": "1" } }, { "body": "<p>If you don't want to use exceptions you should know that in OOP there is a lot of ways to implement the fact that some object belongs to some specific class. It can be either some enum that enumerates all possible domains or in case of OOP languages it can be class.</p>\n\n<p>So in case of Java (again if you don't want exceptions by some reason) you can use:</p>\n\n<pre><code>class Result\n{\n public static final Result ok = new Result(); // I'm not sure this is correct in terms of Java\n}\n\nclass Failure extends Result\n{\n public final String errorMessage;\n public Faliure(String message)\n { this.errorMessage = message; }\n}\n\nif (result instanceof Failure)\n{\n // do something\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:22:45.570", "Id": "32514", "Score": "0", "body": "I like this idea. The only (subtle) drawback I see is that you have to explicitly cast the result to a Failure in order to obtain the error message. You also have to know the implementation details (e.g. that there is a class hierarchy) to be able to distinguish between an OK and an ERROR state." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T10:01:48.280", "Id": "32520", "Score": "0", "body": "@DušanRychnovský, you need to know that as well in case of `enum` and others. You can tear off need of hierarchy by using interfaces. You can add [continuation behavior](http://en.wikipedia.org/wiki/Continuation-passing_style) and make `Result` to provide `Result RunWithSuccess(/* some action representation */)` which will do nothing but return `this` for `Failure` and result of action execution for `ok`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T13:57:06.827", "Id": "32528", "Score": "0", "body": "@DušanRychnovský if you don't have a hierarchy like that you are going to have an ok result coming with an error message and that does not make too much sense to me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T14:33:29.070", "Id": "32531", "Score": "0", "body": "@mariosangiorgio exactly - that's one of the drawbacks I see with my own solution and one of the reasons why I like this one." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:52:34.547", "Id": "20301", "ParentId": "20285", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T17:39:55.217", "Id": "20285", "Score": "7", "Tags": [ "java" ], "Title": "Java - How to represent the result of an operation" }
20285
<p>I'm just wondering if you see any ways I could simplify the following code without making it too difficult for a newbie to understand what I'm trying to do:</p> <pre><code> if (trim($this-&gt;uri-&gt;segment(5)) == 1) { if ( $this-&gt;my_model-&gt;functionA($this-&gt;uri-&gt;segment(8),$this-&gt;uri-&gt;segment(4)) ) { $data['light'] = $this-&gt;my_model-&gt;data(); } else { show_error($this-&gt;my_model-&gt;errormessage()); } } elseif (trim($this-&gt;uri-&gt;segment(5)) == 0) { if ( $this-&gt;my_model-&gt;functionB($this-&gt;uri-&gt;segment(8),$this-&gt;uri-&gt;segment(4)) ) { $data['light'] = $this-&gt;my_model-&gt;data(); } else { show_error($this-&gt;my_model-&gt;errormessage()); } } elseif (trim($this-&gt;uri-&gt;segment(5)) == 2) { if ( $this-&gt;my_model-&gt;functionC($this-&gt;uri-&gt;segment(8),$this-&gt;uri-&gt;segment(4)) ) { $data['light'] = $this-&gt;my_model-&gt;data(); } else { show_error($this-&gt;my_model-&gt;errormessage()); } } </code></pre> <p>I guess I could use a switch statement but i would still need to check the results of each function call. Would it still be beneficial to use switch? if so, can you explain why? </p> <p>Any suggestions would be appreciated. thanks. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-04T23:33:25.367", "Id": "181558", "Score": "1", "body": "The title of your post should be the function/purpose of your code." } ]
[ { "body": "<p>Don't call the same function over and over with the same parameters, you won't get different results so why call it again and again? Also I would use a switch.</p>\n\n<pre><code>&lt;?php\n\n$seg5 = trim($this-&gt;uri-&gt;segment(5));\n$seg8 = $this-&gt;uri-&gt;segment(8);\n$seg4 = $this-&gt;uri-&gt;segment(4);\n\nswitch($seg5){\n case 0:\n if($this-&gt;my_model-&gt;functionB($seg8, $seg4)){\n $data['light'] = $this-&gt;my_model-&gt;data();\n }else{\n show_error($this-&gt;my_model-&gt;errormessage());\n }\n break;\n case 1:\n if($this-&gt;my_model-&gt;functionA($seg8, $seg4)){\n $data['light'] = $this-&gt;my_model-&gt;data();\n }else{\n show_error($this-&gt;my_model-&gt;errormessage());\n }\n break;\n case 2:\n if($this-&gt;my_model-&gt;functionC($seg8, $seg4)){\n $data['light'] = $this-&gt;my_model-&gt;data();\n }else{\n show_error($this-&gt;my_model-&gt;errormessage());\n }\n break;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T13:57:47.107", "Id": "32529", "Score": "0", "body": "Thanks. I'll implement that suggestion too. But as far as really simplifying the code, I think MrLore's answer is what I was after." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:51:11.363", "Id": "32591", "Score": "0", "body": "My only suggestion to this answer would be to move that repeated else statement out of the switch. After the switch you can check if `$data[ 'light' ]` has been set and use that as your else statement. I especially like that you abstracted those segments. It removes the complexity from the statements." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:40:06.393", "Id": "20298", "ParentId": "20297", "Score": "2" } }, { "body": "<p>I haven't been able to test it, but I'm fairly sure this will work:</p>\n\n<pre><code>$functionName = 'function';\nswitch(trim($this-&gt;uri-&gt;segment(5)))\n{\n case 1: $functionName .= 'A'; break;\n case 0: $functionName .= 'B'; break;\n case 2: $functionName .= 'C'; break;\n}\nif($this-&gt;my_model-&gt;$functionName($this-&gt;uri-&gt;segment(8), $this-&gt;uri-&gt;segment(4)))\n{\n $data['light'] = $this-&gt;my_model-&gt;data();\n}\nelse\n{\n show_error($this-&gt;my_model-&gt;errormessage());\n}\n</code></pre>\n\n<p>For more information, see the PHP page on <a href=\"http://php.net/manual/en/functions.variable-functions.php\" rel=\"nofollow\">Variable Functions</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:50:43.890", "Id": "32590", "Score": "0", "body": "@dot: The problem with this solution is the use of variable-functions. These are frowned upon for their lack of clarity. Not only will \"newbies\" have problems with this code, seasoned programmers will as well. There is no way to know which functions are being called without having to track it down manually. You can't even rely on your IDE to help you out. My advice: stay clear of variable-functions and variable-variables. While this looks clever and clean, its a nightmare to debug. No offense to MrLore, but I'd lean more towards Ryan's answer simply for clarity's sake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:02:52.437", "Id": "32597", "Score": "0", "body": "@mseancole There is nothing wrong with variable functions. They are easier than reflection for basic and efficient tasks, and if your code is complex as a result of using them, I recommend commenting your code for yourself and others. That is what 'seasoned programmers' do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:31:42.453", "Id": "32600", "Score": "0", "body": "There is everything wrong with variable-functions. As I already explained they subtract from your code's legibility and are potential debugging nightmares. Adding inline comments to try and cover it up just adds clutter. Better to expand it, as Ryan did, or better yet, leave it up to the method to decide what to do. I have no idea what the difference between `functionA(), *B(), and *C()` are, but they are likely so similar that they could be combined and a new parameter passed to distinguish them. `functionX( $seg8, $seg4, $diff )`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:34:04.367", "Id": "32601", "Score": "0", "body": "@mseancole That is a problem with function and variable naming, not the methodology. Edit: And I had assumed they were placeholders to obscure the source." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:51:24.207", "Id": "20299", "ParentId": "20297", "Score": "3" } } ]
{ "AcceptedAnswerId": "20299", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:35:26.850", "Id": "20297", "Score": "0", "Tags": [ "php" ], "Title": "how to simplify this code" }
20297
<p>This is my code to partition a list into two parts according to a value. I.e. nodes smaller than value <code>x</code> should precede nodes larger than the value <code>x</code>.<br> It seems correct. Any corner cases I am overseeing or corrections are highly appreciated. </p> <pre><code>public Node partition(Node head, int x){ if(head == null) return head; Node prev = null; Node current = head; while(current != null){ if(current.data &gt; x || current == head){ prev = current; current = current.next; } else{ Node next = current.next; current.next = head; if(prev != null) { prev.next = next; } head = current; current = next; } } return head; } </code></pre>
[]
[ { "body": "<p>I just have a point on naming of your function. You named it <code>partition</code> but you're just rearranging the elements and returning the head pointer! If you want to partition, you may want to return pointers to heads of partitions (the <code>head</code> you already return and another pointer to start of bigger than <code>x</code> partition), this way someone using your function doesn't need to iterate over linked-list to find start of next partition, and this pointer can be easily recorded in <code>if</code> statement in your <code>while</code> loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:29:47.607", "Id": "20302", "ParentId": "20300", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T21:52:02.797", "Id": "20300", "Score": "1", "Tags": [ "java", "algorithm", "linked-list" ], "Title": "Partition a linked list arround an element" }
20300
<p>I have a system that needs to be able to reboot a different piece of hardware partway through a script that programs it. It used to wait for me to come and reboot the hardware halfway through, but I've since automated that. I use <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a> python script to control a USB Net Power 8800. </p> <p>I have two setups to show you: First is a system that I'm sure is secure, but is pretty annoying to maintain; I'm sure the second is insecure.</p> <h2>First:</h2> <h3>/usr/bin/power (not set-uid)</h3> <pre><code>#!/bin/sh if [ -e /opt/usbnetpower/_powerwrapper_$1 ] ; then /opt/usbnetpower/_powerwrapper_$1 else /opt/usbnetpower/_powerwrapper_ fi </code></pre> <h3>/opt/usbnetpower/_powerwrapper_reboot.c (The source code to one of six almost identical set-uid programs)</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid( 0 ); system( "/usr/bin/python /opt/usbnetpower/usbnetpower8800.py reboot" ); return 0; } </code></pre> <p>The reason why there are six is that I didn't trust myself to write correct sanitization code in C that wasn't vulnerable to buffer overflows and the like. </p> <h3>/opt/usbnetpower/usbnetpower8800.py (not set-uid)</h3> <p>Essentially <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a>, but modified to add a <code>reboot</code> command.</p> <p>This setup is what I am currently using.</p> <h2>Second:</h2> <h3>/opt/usbnetpower/usbnetpower8800.py (set-uid)</h3> <p>Much simpler, but I'm concerned that a vulnerability like this would apply. Also, suid python programs appear to be disabled on my system. (CentOS 6)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T22:37:27.413", "Id": "41046", "Score": "1", "body": "Personally I gradually abandon all set-uid things in my system. I primarily use daemons listening UNIX sockets which nonprivileged programs can connect to and ask commands. That way you control what exactly is being used (instead of just all user environment by default). I've developed [a program](https://vi-server.org/vi/dive) to start other programs over UNIX sockets in controlled way." } ]
[ { "body": "<p>Both of your programs are insecure. The problem is that I can set <code>PYTHONPATH</code> to anything I like before executing the program. I can set it to something so that it loads my own <code>usb</code> module which can execute whatever code I like. At that point, I'm executing code as the root user and can do whatever I please. That's why set-uid doesn't work on scripts, and your binary C program wrapper doesn't change that at all.</p>\n\n<p>For more information see: <a href=\"https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts\">https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts</a></p>\n\n<p>In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. That way you don't need to run the script as another user. That's what this portion of the script you are using is referring to:</p>\n\n<pre><code># If you have a permission error using the script and udev is used on your\n# system, it can be used to apply the correct permissions. Example:\n# $ cat /etc/udev/rules.d/51-usbpower.rules\n# SUBSYSTEM==\"usb\", ATTR{idVendor}==\"067b\", MODE=\"0666\", GROUP=\"plugdev\"\n</code></pre>\n\n<p>Discussion of how to adjust your system to give you permission to access the USB device is out of scope for this site. I'm also not really an expert on that. So you may need to ask elsewhere for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T00:48:52.037", "Id": "38010", "Score": "0", "body": "`In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. ` This is what I ended up doing; [I open-sourced my changes](https://github.com/nickodell/usbnetpower)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T00:35:28.513", "Id": "20307", "ParentId": "20304", "Score": "3" } } ]
{ "AcceptedAnswerId": "20307", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T23:16:59.930", "Id": "20304", "Score": "2", "Tags": [ "python", "c", "security", "linux" ], "Title": "Are these set-uid scripts/binaries secure?" }
20304
<p>I wrote a JavaScript that takes 2 fractions and finds the common denominator for both. If the user inputs 2/6 and 1/2 --- the script outputs 2/6 + 3/6. I'm interested in feedback on possibly simplifying it or improving it. Thanks.</p> <p>JS Bin: <a href="http://jsbin.com/omelen/1/edit" rel="nofollow">http://jsbin.com/omelen/1/edit</a></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script&gt; window.onload = function() { // Finds the highest common factor of 2 numbers function highestCommonFactor(a, b) { if (b == 0) { return a; } return highestCommonFactor(b, (a % b)); } // Input fractions to add //////////////////////////////// // Fraction 1 = 2/6 var fraction1Numerator = 2; var fraction1Denominator = 6; // Fraction 2 = 1/2 var fraction2Numerator = 1; var fraction2Denominator = 2; //////////////////////////////////////////////////////////////// // Find the highest common factor of both denominators var factor = highestCommonFactor(fraction1Denominator, fraction2Denominator); // 2 if (factor &gt; 1) { // There's a common factor greater than 1 if (fraction1Denominator &gt; fraction2Denominator) { // Find out how many times the factor goes into bigger denominator var temp = fraction1Denominator / factor; fraction2Numerator = fraction2Numerator * temp; fraction2Denominator = fraction2Denominator * temp; } else { // Find out how many times the factor goes into bigger denominator var temp = fraction2Denominator / factor; fraction1Numerator = fraction1Numerator * temp; fraction1Denominator = fraction1Denominator * temp; } } else { // There's no common factor greater than 1 so we need to multiple each fraction by each others denominators // Temp values var fraction1NumeratorTemp = fraction1Numerator; var fraction1DenominatorTemp = fraction1Denominator; fraction1Numerator = fraction1Numerator * fraction2Denominator; fraction1Denominator = fraction1Denominator * fraction2Denominator; fraction2Numerator = fraction2Numerator * fraction1DenominatorTemp; fraction2Denominator = fraction2Denominator * fraction1DenominatorTemp; } // Display solution document.getElementById("divSolution").innerText = fraction1Numerator + "/" + fraction1Denominator + " + " + fraction2Numerator + "/" + fraction2Denominator; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="divSolution"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Here's my attempt to help you.</p>\n\n<ul>\n<li>As a general rule, keep everything as general as you can and don't split your code into different cases unless you have to. From the <code>if (factor &gt;1)</code> part, I knew things could be improved</li>\n<li>At the end, the denominators will be the Least Common Multiple of the two initial fractions.</li>\n<li>Then, you just need to multiply the numerators by the same amount used to multiply the denominators</li>\n</ul>\n\n<p>Here's the corresponding code.</p>\n\n<pre><code>// Finds the highest common factor of 2 numbers\nfunction highestCommonFactor(a, b) {\n if (b == 0) {\n return a;\n }\n return highestCommonFactor(b, a%b);\n}\nfunction leastCommonMultiple(a,b) {\n return a*b/(highestCommonFactor(a,b));\n}\n\n// Input fractions to add ////////////////////////////////\n// Fraction 1 = 2/6\nvar fraction1Numerator = 2;\nvar fraction1Denominator = 6;\n\n// Fraction 2 = 1/2\nvar fraction2Numerator = 1;\nvar fraction2Denominator = 2;\n////////////////////////////////////////////////////////////////\n\n// Find the highest common factor of both denominators\nvar commonMultiple = leastCommonMultiple(fraction1Denominator, fraction2Denominator); \n\nfraction1Numerator *= (commonMultiple / fraction1Denominator);\nfraction2Numerator *= (commonMultiple / fraction2Denominator);\n\n// Display solution\ndocument.getElementById(\"divSolution\").innerText = fraction1Numerator + \"/\" + commonMultiple + \" + \" + fraction2Numerator + \"/\" + commonMultiple;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T05:21:48.227", "Id": "32494", "Score": "0", "body": "Thanks for taking a look at my code. I tried your revised code but had some issues... I inputted the following fractions and got the following incorrect results...Fraction 1 = 1/2 --> 1/6\nFraction 2 = 2/6 --> 6/6;\n\nFraction 1 = 2/12 --> 2/36\nFraction 2 = 1/18 --> 6/36;\n\nFraction 1 = 1/18 --> 1/36\nFraction 2 = 2/12 --> 12/26." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T05:24:24.263", "Id": "32495", "Score": "0", "body": "I changed the following 2 lines of your code: fraction2Numerator *= (commonMultiple / fraction1Denominator);\nfraction2Numerator *= (commonMultiple / fraction2Denominator); --- TO ---> numeratorMultipler1 = commonMultiple / fraction1Denominator;\nnumeratorMultipler2 = commonMultiple / fraction2Denominator;\n\nfraction1Numerator = numeratorMultipler1 * fraction1Numerator;\nfraction2Numerator = numeratorMultipler2 * fraction2Numerator; And that fixed the issue. Let me know what you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T06:01:16.383", "Id": "32497", "Score": "0", "body": "Actually, you just need to change :\nfraction2Numerator *= (commonMultiple / fraction1Denominator);\nfor\nfraction1Numerator *= (commonMultiple / fraction1Denominator);\n(one character is to be changed)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T06:25:37.310", "Id": "32498", "Score": "0", "body": "Also, I think before programming anything, you should try to do your calculation with a pen and paper and try to figure out what you are doing. Then, once everything's clear, you can open your favorite text editor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T07:20:47.507", "Id": "32504", "Score": "0", "body": "I see it now. Thanks. I started learning JavaScript a few months ago, I appreciate your feedback, especially on how I can make my code clearer and more efficient. I plan on posting a few more similar fraction/decimal codes for review and would like your feedback if you have time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T07:31:51.157", "Id": "32506", "Score": "0", "body": "I'm ready when you are ;-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T02:32:10.930", "Id": "20309", "ParentId": "20308", "Score": "2" } } ]
{ "AcceptedAnswerId": "20309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T01:25:38.240", "Id": "20308", "Score": "2", "Tags": [ "javascript" ], "Title": "Find Common Denominator for 2 Fractions with JavaScript - Simplify & Improve" }
20308
<p>I've developed program, which may work with graphs and its edges (connections between vertices):</p> <p><a href="http://ideone.com/FDCtT0" rel="nofollow">http://ideone.com/FDCtT0</a></p> <pre><code>/* Oleg Orlov, 2012(c), generating randomly adjacency matrix and graph connections */ using System; using System.Collections.Generic; class Graph { internal int id; private int value; internal Graph[] links; public Graph(int inc_id, int inc_value) { this.id = inc_id; this.value = inc_value; links = new Graph[Program.random_generator.Next(0, 4)]; } } class Program { private const int graphs_count = 10; private static List&lt;Graph&gt; list; public static Random random_generator; private static void Init() { random_generator = new Random(); list = new List&lt;Graph&gt;(graphs_count); for (int i = 0; i &lt; list.Capacity; i++) { list.Add(new Graph(i, random_generator.Next(100, 255) * i + random_generator.Next(0, 32))); } } private static void InitGraphs() { for (int i = 0; i &lt; list.Count; i++) { Graph graph = list[i] as Graph; graph.links = new Graph[random_generator.Next(1, 4)]; for (int j = 0; j &lt; graph.links.Length; j++) { graph.links[j] = list[random_generator.Next(0, 10)]; } list[i] = graph; } } private static bool[,] ParseAdjectiveMatrix() { bool[,] matrix = new bool[list.Count, list.Count]; foreach (Graph graph in list) { int[] links = new int[graph.links.Length]; for (int i = 0; i &lt; links.Length; i++) { links[i] = graph.links[i].id; matrix[graph.id, links[i]] = matrix[links[i], graph.id] = true; } } return matrix; } private static void PrintMatrix(ref bool[,] matrix) { for (int i = 0; i &lt; list.Count; i++) { Console.Write("{0} | [ ", i); for (int j = 0; j &lt; list.Count; j++) { Console.Write(" {0},", Convert.ToInt32(matrix[i, j])); } Console.Write(" ]\r\n"); } Console.Write("{0}", new string(' ', 7)); for (int i = 0; i &lt; list.Count; i++) { Console.Write("---"); } Console.Write("\r\n{0}", new string(' ', 7)); for (int i = 0; i &lt; list.Count; i++) { Console.Write("{0} ", i); } Console.Write("\r\n"); } private static void PrintGraphs() { foreach (Graph graph in list) { Console.Write("\r\nGraph id: {0}. It references to the graphs: ", graph.id); for (int i = 0; i &lt; graph.links.Length; i++) { Console.Write(" {0}", graph.links[i].id); } } } [STAThread] static void Main() { try { Init(); InitGraphs(); bool[,] matrix = ParseAdjectiveMatrix(); PrintMatrix(ref matrix); PrintGraphs(); } catch (Exception exc) { Console.WriteLine(exc.Message); } Console.Write("\r\n\r\nPress enter to exit this program..."); Console.ReadLine(); } } </code></pre> <p>The example there is using the <code>const</code> value, but you could erase <code>const</code> and fill <code>Random int</code>.</p> <p>At the ideone as you see the result is ok and are able to see the generated matrix (result):</p> <blockquote> <pre class="lang-none prettyprint-override"><code>0 | [ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, ] 1 | [ 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, ] 2 | [ 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, ] 3 | [ 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, ] 4 | [ 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, ] 5 | [ 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, ] 6 | [ 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, ] 7 | [ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, ] 8 | [ 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, ] 9 | [ 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, ] ------------------------------ 0 1 2 3 4 5 6 7 8 9 Graph id: 0. It references to the graphs: 8 Graph id: 1. It references to the graphs: 4 8 Graph id: 2. It references to the graphs: 4 2 4 Graph id: 3. It references to the graphs: 1 0 1 Graph id: 4. It references to the graphs: 7 5 Graph id: 5. It references to the graphs: 9 7 Graph id: 6. It references to the graphs: 6 9 Graph id: 7. It references to the graphs: 3 6 Graph id: 8. It references to the graphs: 5 2 5 Graph id: 9. It references to the graphs: 2 0 9 Press enter to exit this program... </code></pre> </blockquote>
[]
[ { "body": "<pre><code>class Graph\n</code></pre>\n\n<p>What this class represents is not a whole <a href=\"http://en.wikipedia.org/wiki/Graph_%28mathematics%29\" rel=\"nofollow\">graph</a>, it's a single <a href=\"http://en.wikipedia.org/wiki/Vertex_%28graph_theory%29\" rel=\"nofollow\">vertex</a> (or node). Because of that, you should rename this class to either <code>Vertex</code> or <code>Node</code>.</p>\n\n<pre><code>internal int id;\n</code></pre>\n\n<p>You shouldn't have non-private fields, use properties for that. For more information about reasons, read Jon Skeet's article <a href=\"http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx\" rel=\"nofollow\"><em>Why properties matter</em></a>.</p>\n\n<p>Also, I don't understand why are you marking fields <code>internal</code>, since the whole class is already <code>internal</code> (that's the default for top-level classes). You should mark them <code>public</code>, so that if you decide to make the class <code>public</code> in the future, you don't have to change the fields (or rather properties, see previous point) too.</p>\n\n<p>One more thing: you should also change the name to <code>Id</code>, that's the naming convention used for non-private members.</p>\n\n<pre><code>class Program\n</code></pre>\n\n<p>All methods of this class are <code>static</code>, so you should make the whole class <code>static</code>. Although it might also make sense to put all the graph-related code into a separate (non-<code>static</code> class). A good name for this new class might be <code>Graph</code>.</p>\n\n<pre><code>private const int graphs_count = 10;\n</code></pre>\n\n<p>This should be <code>static readonly</code>, rather than <code>const</code>. <code>const</code> fields should be used only for values that you know will never change. This is most important if you're writing a library, but it's a good habit to get used to it everywhere.</p>\n\n<pre><code>private static List&lt;Graph&gt; list;\n</code></pre>\n\n<p><code>list</code> is a very unclear name, a better name would be something like <code>graphs</code> (or <code>nodes</code> after you fix the name of the class <code>Graph</code>).</p>\n\n<pre><code>public static Random random_generator;\n</code></pre>\n\n<p>Again, the naming convention for non-private members is something like <code>RandomGenerator</code>, you should change that. And again, public fields should be changed to public properties.</p>\n\n<pre><code>private static void Init()\nprivate static void InitGraphs()\n</code></pre>\n\n<p>Having methods that have to be called before a class can be used is a sign of bad design. You should use constructor for that.</p>\n\n<pre><code>Graph graph = list[i] as Graph;\n</code></pre>\n\n<p>There is no need for the <code>as</code> here, the type if <code>list[i]</code> is already <code>Graph</code>.</p>\n\n<pre><code>list[i] = graph;\n</code></pre>\n\n<p>This line doesn't do anything, you should remove it. In C#, <code>class</code>es are reference types, so if you change members of the local variable <code>graph</code> here, <code>list[i]</code> will be also changed (because it refers to the same object).</p>\n\n<pre><code>private static bool[,] ParseAdjectiveMatrix()\n</code></pre>\n\n<p>This is again a very confusing name. There is no such thing as “adjective matrix”, it's called <a href=\"http://en.wikipedia.org/wiki/Adjacency_matrix\" rel=\"nofollow\">adjacency matrix</a>, so you should rename this method. Also, “parsing” usually means reading some string. A better name for this method would then be <code>CreateAdjacencyMatrix</code>.</p>\n\n<pre><code>int[] links = new int[graph.links.Length];\n</code></pre>\n\n<p>There doesn't seem to be any reason for this array, you could simplify your code to:</p>\n\n<pre><code>for (int i = 0; i &lt; graph.links.Length; i++)\n{\n int linkedId = graph.links[i].id;\n matrix[graph.id, linkedId] = matrix[linkedId, graph.id] = true;\n}\n</code></pre>\n\n<p>Or even better, use <code>foreach</code>:</p>\n\n<pre><code>foreach (var linked in graph.links)\n{\n matrix[graph.id, linked.id] = matrix[linked.id, graph.id] = true;\n}\n</code></pre>\n\n\n\n<pre><code>private static void PrintMatrix(ref bool[,] matrix)\n</code></pre>\n\n<p>You should get rid of the <code>ref</code> here. <code>ref</code> is useful if you want to change some variable of the caller (and not just its contents) or in very rare cases when you want to avoid copying a large value type. But <code>matrix</code> is an array, which is a reference type, and you don't change it, so the <code>ref</code> has no use here.</p>\n\n<pre><code>Console.Write(\" ]\\r\\n\");\n</code></pre>\n\n<p>You should use <code>Console.WriteLine(\" ]\")</code> here instead. This applies to other places in your code where you use <code>\\r\\n</code> too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T15:20:31.547", "Id": "20326", "ParentId": "20310", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T02:43:35.617", "Id": "20310", "Score": "1", "Tags": [ "c#", "matrix", "graph" ], "Title": "Generating adjacency matrix on random cout of graphs with output the matrix" }
20310
<p>I'm writing a WCF service for validating password and getting company ID for the clients that requests the services. The service runs on a server locally as a windows service, which sends queries to the database and returns the appropriate info back to the client.</p> <p>I'd first like some comments on how the overall design looks like as I'm going to be adding more operations but wanted to avoid any situations where I have to rewrite them all just in case if I'm headed the wrong direction.</p> <p>I have a specific question regarding the stability of this service. In case if the operation somehow fails on the server's end, such as an exception being thrown because the server couldn't connect to a database.</p> <ul> <li>Where should I handle the exception? Should I wrap my methods in try catch statements on the service methods or where the call is being made (client)?</li> <li>What can I do to increase the stability of this service? Under any circumstances, I cannot allow the service to shut down aside from the user intentionally doing so.</li> </ul> <p>These are probably trivial questions but I'd like some guidance on this matter. Thank you.</p> <pre><code>namespace TopwareOutlookSyncService { [ServiceContract] public interface ITopwareOutlookSyncService { [OperationContract] bool IsPasswordValid(string password); [OperationContract] string GetCompanyID(string userID); } public class TopwareOutlookSyncService : ITopwareOutlookSyncService { private SqlConnection con; public void ConnectDB() { if (!IsDBConnected()) { con = new SqlConnection("user id=nexol;" + "password=;server=666.666.666.666;" + "database=hell; " + "connection timeout=15"); con.Open(); } } public bool IsDBConnected() { return (con != null &amp;&amp; con.State == ConnectionState.Open); } public bool IsPasswordValid(string userID, string password) { if (!IsDBConnected()) ConnectDB(); bool isPasswordValid = false; string sql = "SELECT USER_PW FROM HELL.GRP_USER WHERE USER_ID = '" + userID + "'"; string encryptedPassword = PasswordTable.GetEncryptedString(password); SqlCommand command = new SqlCommand(sql, con); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { if (reader["USER_PW"].ToString() == encryptedPassword) { isPasswordValid = true; break; } } reader.Close(); con.Close(); return isPasswordValid; } public string GetCompanyID(string userID) { if (!IsDBConnected()) ConnectDB(); string companyID = String.Empty; string sql = "SELECT COM_CD FROM HELL.GRP_USER WHERE USER_ID = '" + userID + "'"; SqlCommand command = new SqlCommand(sql, con); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { companyID = reader["COM_CD"].ToString(); } reader.Close(); con.Close(); return companyID; } } } </code></pre>
[]
[ { "body": "<p>You should never generate dynamic SQL by concatenating incoming values into an SQL string that is executed later. This type of code leads to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL injection</a> vulnerability, and by using your service as it is now it's very easy to get access to any user account without knowing its password.</p>\n\n<p>If you plan to develop your service further take your time to learn one of the ORM frameworks (Entity Framework, NHibernate, or maybe one of the NoSQLs like MongoDB or RavenDB) and get rid of low-level DB management code from your service. Alternatively (if you prefer inventing a wheel :)) move DB-related code to separated class and name it \"DB repository\" so that your service doesn't have too many responsibilities (currently it has business logic responsibilities combined with DB access management).</p>\n\n<p>About exception handling - here is a <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229005%28v=vs.100%29.aspx\" rel=\"nofollow\">good article</a> that describes what you should and should not do. Basically you should only catch specific exceptions, and only if you know how to recover from that exception in a meaningful way, that doesn't leave your application in an inconsistent state. In case when WCF service has no way to return a meaningful response (e.g. when response is based on DB data and database is not available) you should pass exception to the client. </p>\n\n<p>And finally, store your connection strings in the configuration files rather than hardcoded.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:11:25.393", "Id": "20359", "ParentId": "20312", "Score": "1" } } ]
{ "AcceptedAnswerId": "20359", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T05:19:33.367", "Id": "20312", "Score": "1", "Tags": [ "sql", "database", "wcf" ], "Title": "How to write a stable WCF service" }
20312
<p>I'd like this reviewed.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define SWITCH(S) char *_S = S; if (0) #define CASE(S) } else if (strcmp(_S, S) == 0) {switch(1) { case 1 #define BREAK } #define DEFAULT } else {switch(1) { case 1 int main() { char buf[256]; printf("\nString - Enter your string: "); scanf ("%s", buf); SWITCH (buf) { CASE ("abcdef"): printf ("B1!\n"); BREAK; CASE ("ghijkl"): printf ("C1!\n"); BREAK; DEFAULT: printf ("D1!\n"); BREAK; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T15:56:28.143", "Id": "32534", "Score": "8", "body": "If you want a different syntax, use a different language. Don't try to bend C to your taste by misusing the preprocessor. It will just cause problems." } ]
[ { "body": "<p>I do like the idea but I'm not sure to really get the benefit of your code compared to (my C is a bit rusty so the code might not be correct) : </p>\n\n<pre><code> if (strcmp(buf,\"abcdef\") == 0) {\n printf (\"B1!\\n\");\n if (strcmp(buf,\"ghijkl\") == 0) {\n printf (\"C1!\\n\");\n } else {\n printf (\"D1!\\n\");\n }\n</code></pre>\n\n<p>\n\n<p>Indeed, the code doesn't really seem easier to read but it's definitly harder to check when something wrong's happening.\nOn top of that, the way you use brackets impose the fact that we have one BREAK per CASE/DEFAULT and this limits the expressiveness of your syntax. For instance, we don't have the following cool structures possible with a real switch :</p>\n\n<pre><code>// The fall-through (1)\ncase 0:\ncase 1: do_stuff_for1_and_2(); break\n\n// The fall-through (1)\ncase 0: do_stuff_for_only1();\ncase 1: do_stuff_for1_and_2(); break\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// The early return\ncase 0 : return FOO;\ncase 1 : return BAR;\ndefault: return FOO_BAR;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// The normal-case with no break in the default\ncase 0: do_stuff(); break;\ndefault: do_nothing();\n</code></pre>\n\n<p>I'm not quite sure about the kind of feedback you expected so I hope this answers your question.</p>\n\n<p>As a side note, I'd choose a different variable name, maybe using <code>__COUNTER__</code> (I've never used it) to generate unique name if you ever plan to nest the switches.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:03:53.013", "Id": "20318", "ParentId": "20314", "Score": "3" } }, { "body": "<p><code>switch</code> is usually assumed to have nearly <code>O(1)</code>. I'm suggesting to introduce additional level for parsing. It is known as lexical analysis. You parse you fixed set of cases to <code>enum</code> values and then switch as you want.</p>\n\n<pre><code>enum { B1, C1, D1 } token_t;\n\ntoken_t lexer(const char *s)\n{\n // TODO: consider hash table here\n static struct entry_s {\n const char *key;\n token_t token;\n } token_table[] = {\n { \"abcdef\", B1 },\n { \"ghijkl\", C1 },\n { NULL, D1 },\n };\n struct entry_s *p = token_table;\n for(; p-&gt;key != NULL &amp;&amp; strcmp(p-&gt;key, s) != 0; ++p);\n return p-&gt;token;\n}\n\nint main()\n{\n char buf[256];\n\n printf(\"\\nString - Enter your string: \");\n scanf (\"%s\", buf);\n\n switch(lexer(buf)) {\n case B1:\n printf (\"B1!\\n\");\n break;\n case C1:\n printf (\"C1!\\n\");\n break;\n case D1:\n printf (\"D1!\\n\");\n break;\n }\n}\n</code></pre>\n\n<p>Note that your <code>SWITCH(S)</code> will work only in C++ since C doesn't allow variables definition in the middle of blocks. Usually such macro uses something like:</p>\n\n<pre><code>#define BEGIN_SEPARATION(S, T) { const char *_tail = (T), *_sep = (S); \\\n size_t _sep_len = strlen(_token); \\\n for(const char *_next = strstr(_tail); _tail != NULL; _tail = (_next != NULL) ? _next + _sep_len : NULL) {\n#define SEPARATION_TOKEN() (_next == NULL ? strdup(_tail) : strndup(_tail, _next - _tail))\n#define END_SEPARATION } }\n</code></pre>\n\n<p>And as far as I know it's common practice to wrap macro arguments (i.e <code>_S = (S);</code>). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T07:43:43.837", "Id": "32687", "Score": "2", "body": "The code will compile just fine in standard C, which allows variable definitions anywhere. To me, it sounds like you are following the 23 year old, obsolete C90 standard." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:18:17.367", "Id": "20320", "ParentId": "20314", "Score": "7" } }, { "body": "<p>As others have pointed, out never try to re-invent the C language. It makes the code less readable and more error-prone, for no obvious benefits. Function-like macros in general are incredibly error-prone and dangerous (and a pain to debug), <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/PRE00-C.+Prefer+inline+or+static+functions+to+function-like+macros\" rel=\"nofollow\">they should be avoided</a>.</p>\n\n<p>If you for some reason need to use function-like macros, <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/PRE12-C.+Do+not+define+unsafe+macros\" rel=\"nofollow\">you need to make them safe</a>, properly encapsulate them with braces and parenthesis.</p>\n\n<p>In addition, doing strcmp after strcmp in sequence like this, is very slow and inefficient, growing more inefficient with each \"case\" you add. This is unacceptable if program speed and random access are important.</p>\n\n<p>So as for code review, I'd strongly recommend to forget this whole program as quickly as possible, nothing good will come out of it.</p>\n\n<p>The proper way to write an algorithm that stores unknown, initially unsorted and completely random input strings, is to use a <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow\">hash table</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T07:52:44.943", "Id": "20409", "ParentId": "20314", "Score": "2" } }, { "body": "<p>I'd add another vote for \"don't do this\", you (or another) will suffer having to reread/debug it.</p>\n\n<p>I'd try something along the lines of:</p>\n\n<pre><code>char* options[] = { \"abcdef\", \"ghijkl\", /* etc */ NULL };\nswitch ( index_of( options, buf ) )\n{\n case 0: // abcdef\n break;\n case 1: // ghijkl\n break;\n /* etc */\n}\n</code></pre>\n\n<p>Which is just another version of <em>ony</em>'s answer. Slightly simpler (maybe), but either version will need keeping in step.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T11:41:10.650", "Id": "20413", "ParentId": "20314", "Score": "1" } }, { "body": "<p>Though your code works, it doesn't handle fall-through and won't be convertible to a jump table.</p>\n\n<p>Since the strings must be constants anyhow, it would make sense to just alphabetize them and use a binary search (O(log n)) instead of an else-if tree (O(n))</p>\n\n<pre><code>#define MAGIC_DATA \\\n MAP(abcdef) \\\n MAP(ghijkl) \\\n MAP(nopqrs) \\\n MAP(tuvwxy)\n\n#define MAP(x) ENUM_##x,\nenum myenums { MAGIC_DATA };\n#undef MAP\n#define MAP(x) #x,\nconst char * mystrings[] = { MAGIC_DATA };\n#undef MAP\n#undef MAGIC_DATA\n\n//different than standard bsearch - not void* and returns index\nlong my_bsearch(const char *key, const char **base, size_t nmemb){\n for (long bot=0, top=nmemb, i=top/2; bot&lt;=top ; i=(bot+top)/2){\n int cmp=strcmp(key,base[i]);\n if (! cmp) return i; //match found\n else if (cmp&gt;0) bot=i+1;\n else top=i-1;\n }\n return -1;\n}\n</code></pre>\n\n<p>Now you can use them in a switch case like this: </p>\n\n<pre><code>int main(int argc, char **argv) {\n switch (my_bsearch(argv[1], mystrings, sizeof(mystrings)/sizeof(mystrings[0]))){\n case ENUM_abcdef : printf (\"A1!\\n\"); break;\n case ENUM_ghijkl : printf (\"B1!\\n\"); break;\n case ENUM_nopqrs : //fallthrough\n case ENUM_tuvwxy : printf (\"D1!\\n\"); break;\n default : printf (\"*!\\n\");\n }\n\n //or you can vectorize the result\n long i = my_bsearch(argv[1], mystrings, sizeof(mystrings)/sizeof(mystrings[0]));\n printf(\"%c1!\\n\",(i==-1)?'*':\"ABDD\"[i]);\n return 0;\n}\n</code></pre>\n\n<p>This example only used strings without spaces, if you have spaces in the strings its only slightly different</p>\n\n<pre><code>#define MAGIC_DATA \\\n MAP(abcdef, \"a b c d e f\", extra) \\\n MAP(ghijkl, \"g h i h k l\", extra, more) \\\n MAP(nopqrs, \"m n o p q r\", more) \\\n MAP(tuvwxy, \"s t u v w x\", lots, of, random, things)\n\n#define MAP(x,y,...) ENUM_##x,\nenum myenums { MAGIC_DATA };\n#undef MAP\n#define MAP(x,y,...) y,\nconst char * mystrings[] = { MAGIC_DATA };\n#undef MAP\n//do similar stuff with __VA_ARGS__ here:\n#undef MAGIC_DATA\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T00:17:39.493", "Id": "121845", "ParentId": "20314", "Score": "2" } }, { "body": "<p>With C++, you can use <code>constexpr</code> functions in your <code>case</code> statements to (effectively) <code>switch</code> on (certain) strings.</p>\n<p>I believe you will need at least C++11 to do this. You might need an even newer version of C++ (not sure about that).</p>\n<p>Here is an example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nconstexpr unsigned long s2n ( const char * s ) { return s[0]; }\n\nvoid ape ( const char * s ) {\n switch ( s2n(s) ) {\n case s2n(&quot;bat&quot;): printf ( &quot;ape bat\\n&quot; ); break;\n case s2n(&quot;cat&quot;): printf ( &quot;ape cat\\n&quot; ); break; } }\n\nint main () {\n ape ( &quot;bat&quot; );\n ape ( &quot;cat&quot; );\n return 0; }\n</code></pre>\n<p>Expected output:</p>\n<pre><code>ape bat\nape cat\n</code></pre>\n<p>You probably want a more sophisticated (and safer) <code>s2n()</code> function than the trivial one I use above.</p>\n<p>You can fit 8 bytes into a 64 bit integer.</p>\n<p>Some platforms may have 128 bit integers, which would allow up to 16 bytes in your strings.</p>\n<p>For a much more sophisticated example, one that apparently uses a sophisticated 128 bit hash function, please see:<br />\n<a href=\"https://github.com/xroche/stringswitch\" rel=\"nofollow noreferrer\">https://github.com/xroche/stringswitch</a></p>\n<p><strong>Update</strong></p>\n<p>Fyi: I looked into the above mentioned <code>xroche/stringswitch</code> source code. There is an additional C++11 feature called &quot;user defined literals&quot;. Using this feature might result in a further improvement to the readability of the code.</p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/user_literal\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/user_literal</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T01:23:00.387", "Id": "528012", "Score": "6", "body": "Note: Post/code is tagged as C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T06:28:32.630", "Id": "528027", "Score": "0", "body": "@chux - I found the page via a web search and, consequently, overlooked the `C` tag. I was looking for a way to switch on strings. I did read the OP's question (all four words of it) to see if C++ was explicitly excluded. I did see another poster claim (probably incorrectly, as it turns out) that the OP's code would only compile in C++. For my particular project, I am willing to switch from C to C++ to be able to switch on (short) strings." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T22:36:55.090", "Id": "267772", "ParentId": "20314", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T08:34:42.363", "Id": "20314", "Score": "6", "Tags": [ "c", "strings" ], "Title": "Using case and switch macros for strings" }
20314
<p>For example I have 2 dates (year and month) like :</p> <pre><code>2013-03 2013-01 &lt;-- Jan. current month. 2012-10 </code></pre> <p>So my code is :</p> <pre><code>// Get current month and year $m = date('m'); $y = date('Y'); // So I do something to get highest date so result is.. $highest = "2013-03"; // Current month and year $current = $y."-".$m; // So I do something to get lowest date so result is.. $lowest = "2012-10"; // My idea is get lower month from variables function do_lower($date){ $date = explode("-",$date); $y = $date[0]; $m = $date[1]; if($m != "01") { $m = $m-1; $m = sprintf('%02d',$m); return $y."-".$m; } else { return ($y-1)."-12"; } } // This is my simple function to get result between high and low function different($h,$l) { global $data; $h = do_lower($h); if($h!=$l){ $data[] = $h; different($h,$l); } } </code></pre> <p>Then .. to do all functions like.. (JSON)</p> <pre><code>$data[] = $highest; different($highest,$current); $data[] = $current; different($current,$lowest); $data[] = $lowest; </code></pre> <p>So my result is correct</p> <pre><code>["2013-03","2013-02","2013-01","2012-12","2012-11","2012-10"] </code></pre> <p>Anyone can review my code ?</p> <p><strong>Thanks so much</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:24:20.187", "Id": "32515", "Score": "0", "body": "I'm confused. What's your end goal? Are you trying to list, in descending order, all dates between two given dates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:27:26.053", "Id": "32517", "Score": "0", "body": "Yes you think right , Edited my code @Corbin" } ]
[ { "body": "<p>There's not really much to review here since it's such a short snippet, but a few things:</p>\n\n<hr>\n\n<p>I tend to avoid manipulating dates as strings. With just a year-month format it's actually fine since there's no odd rules. It's generally a lot safer to use DateTime though (or even strtotime/date). The problem with dates and times are that they are not simple units. There are complex, ever-changing 'business rules' (of sorts) that surround dates and times and cause huge headaches.</p>\n\n<p>As said though, you're fine with <code>year-date</code> format since there's no gotcha's.</p>\n\n<p>Just for consistency sake though, I would work with a standardized date format and use a date-time specific API.</p>\n\n<p>For example:</p>\n\n<pre><code>$start = new DateTime(date('Y-m')); //First of this month\n$end = new DateTime('2013-03'); //March 1st\n$oneDay = new DateInterval('P1D');\n$dates = array();\nfor (; $end &gt;= $start; $end-&gt;sub($oneDay)) {\n $dates[] = $end-&gt;format('Y-m');\n}\n</code></pre>\n\n<p><code>$dates</code> is then an array in the format you want. This code is quite ugly, but unfortunately I've never been able to figure out a way to manipulate dates in PHP that isn't ugly.</p>\n\n<hr>\n\n<p>Here's a strtotime/date based version:</p>\n\n<pre><code>$start = strtotime(date('Y-m'));\n$end = strtotime('2013-03');\n$dates = array();\nwhile ($end &gt;= $start) {\n $dates[] = date('Y-m', $end);\n $end = strtotime(date('Y-m-d', $end) . ' +1 day');\n}\n</code></pre>\n\n<p>Rather than the strtotime call, you could just use 864000 seconds. I'd have to think for a few minutes to make sure that won't have any DST mistakes though. Once again, a situation where I like to keep date operations as abstracted away as possible. 864000 is a lie since not all days have 24 hours (at least not in places that observe DST).</p>\n\n<hr>\n\n<p>If I were to go with a string approach, your do_lower function is basically what I'd use. It's named rather poorly though since it has no mention of what it's 'lowering' or what 'lowering' even means. Also, I would probably use a strict comparison against <code>01</code>.</p>\n\n<p>The problem with a purely string based approach is that it's not very reusable. Your function has a very specific input format and a very specific output format. Anything else and it breaks.</p>\n\n<p>If you pass around DateTime's instead, dates are no longer represented as a string. They're represented as a type that is much more appropriate for such a complicated system. They're represented as a type that is aware that they are a date.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T10:00:02.633", "Id": "32519", "Score": "0", "body": "Oh ! Nice answer , I will try your in my code :D thanks so much" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T10:02:11.250", "Id": "32521", "Score": "1", "body": "@l2aelba Glad to help :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:54:38.787", "Id": "20316", "ParentId": "20315", "Score": "3" } } ]
{ "AcceptedAnswerId": "20316", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T09:09:07.067", "Id": "20315", "Score": "1", "Tags": [ "php", "datetime" ], "Title": "Between dates : from highest -> current -> lowest" }
20315
<p>The below code does Read csv files and process it to do some sort of cacluations.This is more of small picture code , to introduce big picture. The csv file contains information of seeds of crop which have some information in number depending upon the numbers the calcuation have to be done.There are different types of calucations based on traits types. The csv file will contains hybrid numbers followed by the traits . I have recorded observations for 6 traits, now at first i will read traits used in the applicaitons some traits may have 2 ,3 or n enteries.This is stored in db so i will pull inforamtion from there , once i read traits then i will read each hybrid number and trait values once i read trait values of particular trait i will either avgerage or do some more processing for som e trait the value depends on other triats.</p> <p>Please have a look at it and let me know if it has to be improveed from design/implementation point of view.</p> <pre><code>Hybrid PLTHT01 PLTHT02 Avg YLDTH01 YLDTH01 YLD TLSSG01 TLSSG02 TLSSG03 TLSSV HH01 24 42 23 33 42 34 22 HH02 26 40 27 37 42 34 22 HH03 28 38 31 41 42 34 22 HH04 30 36 35 45 42 34 22 HH05 32 34 39 49 42 34 22 HH06 34 32 43 53 42 34 22 HH07 36 30 47 57 42 34 22 HH08 38 28 51 61 42 34 22 HH09 40 26 55 65 42 34 22 HH10 42 24 59 69 42 34 22 </code></pre> <p>I have even entered values for TLSSG01 TLSSG02 TLSSG03 but they are not visible ,</p> <p>Below is the Code:</p> <pre><code>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HybridDataProcessor { public static void main(String[] args) { BufferedReader br = null; try { // holds currentline vlues String sCurrentLine; Map&lt;String, HashMap&lt;String,Float&gt;&gt; hybridTraitValues = new HashMap&lt;String,HashMap&lt;String, Float&gt;&gt;(); // a mapping to traitName and no of columns it will have HashMap&lt;String, Integer&gt; listDataPointMap = new HashMap&lt;String, Integer&gt;(); listDataPointMap.put("PLTHT",2); listDataPointMap.put("YLDTH",2); listDataPointMap.put("YLD",1); listDataPointMap.put("TLSSG",3); listDataPointMap.put("TLSSV",1); List&lt;String&gt; traitList = new ArrayList&lt;String&gt;(); // HashMap&lt;String, Float&gt; traitValues = new HashMap&lt;String, Float&gt;(); br = new BufferedReader(new FileReader("C:\\testing.csv")); int lineNumber = 0; while ((sCurrentLine = br.readLine()) != null) { lineNumber++; String[] itemValues = sCurrentLine.split(","); // if line number then we need to get all the tratis used in csv file if (lineNumber == 1) { for (int j = 1; j &lt; itemValues.length; j++) { String traits = itemValues[j]; // if column name is avg do not consider it as trait if(traits.equalsIgnoreCase("avg")){ continue; } // since yld is special trait and it does not have 01 attached to it we will add it directly if(traits.equalsIgnoreCase("YLD")){ traitList.add(traits); continue; } // since TLSSV is special trait and it does not have 01 attached to it we will add it directly if(traits.equalsIgnoreCase("TLSSV")){ traitList.add(traits); continue; } traits=traits.substring(0,traits.length()-2); if(!traitList.contains(traits)) traitList.add(traits); } } else { String hybridName = itemValues[0]; int datPts=0; int currentPosition = 1; for (String traits : traitList) { // calcutes the vlalue of each trait with respective hybrid if(traits.equalsIgnoreCase("YLD")){ float avg =getYLD(hybridTraitValues.get(hybridName).get("YLDTH")); update(hybridTraitValues, hybridName, avg, traits); currentPosition=currentPosition+1; } else if(traits.equalsIgnoreCase("TLSSV")){ float avg =gettlssv(hybridTraitValues.get(hybridName).get("TLSSG")); update(hybridTraitValues, hybridName, avg, traits); currentPosition=currentPosition+1; } else { datPts=listDataPointMap.get(traits); float avg =getAvg(itemValues, datPts, currentPosition); update(hybridTraitValues, hybridName, avg, traits); if(traits.equalsIgnoreCase("PLTHT")){ currentPosition=currentPosition+datPts+1; }else{ currentPosition=currentPosition+datPts; } } } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static float getAvg(String[] itemValues,int dataPts,int currentPosition){ float avg=0; for (int j = currentPosition; j &lt; (currentPosition + dataPts); j++) { avg+=Float.parseFloat(itemValues[j]); } return avg=avg/2; } public static float getYLD(float avg){ return avg=avg/10; } public static float gettlssv(float avg){ return avg=avg/10; } public static void update(Map&lt;String, HashMap&lt;String,Float&gt;&gt; hybridTraitValues,String hybridName,float avg,String traitName){ HashMap&lt;String, Float&gt; traitValues= hybridTraitValues.get(hybridName); if(traitValues==null){ traitValues = new HashMap&lt;String, Float&gt;(); } traitValues.put(traitName, avg); hybridTraitValues.put(hybridName, traitValues); } } </code></pre> <p>Now what if no of traits increases let if i add 10 more traits with different calcuations, how will i maintain the code please help.Does this look like oo code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:01:15.223", "Id": "32562", "Score": "0", "body": "Don't reinvent the wheel. http://opencsv.sourceforge.net/" } ]
[ { "body": "<ul>\n<li>The path to the CSV file can be a parameter, it should not be hard coded, the path separator is available.</li>\n<li>Depending on the file size there are more modern options to read files. (Guava &amp; File NIO )</li>\n<li>Checking for null values before parsing. </li>\n<li>Method names are camel case \"gettlssv\" can be \"getLSSV\" ?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:50:32.943", "Id": "20334", "ParentId": "20321", "Score": "1" } }, { "body": "<p>I'm sorry to say, it doesn't really look like oo code.</p>\n\n<p>You didn't follow the following base principles of object oriented design: (just some of them listed here)</p>\n\n<ul>\n<li>Encapsulation / Separation of concerns: logical blocks of function should be grouped together and hide their implementation details. e.g. The class that calculates some values, then it should not implement the reading of a CSV file, as this could be encapsulated in another class. So the change of one class doesn't affect the other.</li>\n<li>Objects - actually you don't really use objects. All the code is in one big class, which has the invocation code - the main method - in it.</li>\n<li>Decoupling - everything in one class/method is the highest coupling out there.</li>\n<li>Reuse - no code of this class can be reused, as it is all coded in this class.</li>\n<li>Extensibility - all methods are static, so they can't be mocked out by clients or overriden by subclasses.</li>\n</ul>\n\n<p>You should use common libraries for the CSV parsing, as this is an error prone task. The implementation in this code is in many ways an incomplete CSV parser.</p>\n\n<p>I see the following components/classes in your system:</p>\n\n<ul>\n<li><code>CliClient</code> - the client code with the main method</li>\n<li><code>CsvReader</code> - encapsulates the CSV reading</li>\n<li><code>CalculationHandler(s)</code> - I dont fully see what you're doing, so this can result in more than one object </li>\n<li>Domain objects - this are meaningful objects, that represent your <code>Map</code> - if they can be represented.</li>\n</ul>\n\n<p>So I think you need to think more about the objects in your system. Which are needed? What are they doing? How do the objects relate and collaborate with each other?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T05:41:15.010", "Id": "32614", "Score": "0", "body": "THanks burna this is the sort of comment i was looking for , but i could learn if you could provide me ur version code for the above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T05:42:29.207", "Id": "32615", "Score": "0", "body": "Please explain \"Domain objects - this are meaningful objects, that represent your Map - if they can be represented.\" and why do we need encapsulate csv reading" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:36:22.027", "Id": "20349", "ParentId": "20321", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:26:35.980", "Id": "20321", "Score": "1", "Tags": [ "java", "optimization", "design-patterns" ], "Title": "Review code for optimization and implementation" }
20321
<p>This is a script to access the Stack Exchange API for the genealogy site and create a list of user dictionaries. It contains a snippet at end to validate. The data obtained is stored in YAML format in a file for use by other programs to analyze the data.</p> <pre><code>''' This is a script to access the stackexchange api for the genealogy site and create a list of user dictionaries ''' # use requests module # - see http://docs.python-requests.org/en/latest/user/install/#install import requests # use YAML to store output for use by other programs # see http://pyyaml.org/wiki/PyYAML import yaml OUTFILENAME = "users.yaml" # use se api and access genealogy site # see https://api.stackexchange.com/docs/users for api info URL ='https://api.stackexchange.com/2.1/users' url_params = { 'site' : 'genealogy', 'pagesize' : 100, 'order' : 'desc', 'sort' : 'reputation', } page = 1 not_done = True user_list = [] # replies are paginated so loop thru until none left while not_done: url_params['page'] = page # get next page of users api_response = requests.get(URL,params=url_params) json_data = api_response.json() # pull the list of users out of the json answer user_list.extend( json_data['items'] ) # show progress each time thru loop print api_response.url #note only so many queries allowed per day print '\tquota remaining: %s' % json_data['quota_remaining'] print "\t%s users after page %s" % (len(user_list),page) # prepare for next iteration if needed page += 1 not_done = json_data['has_more'] # output list of users to a file in yaml, a format easily readable by humans and parsed # note safe_dump is used for security reasons # since dump allows executable python code # Sidebenefit of safe_dump is cleaner text outFile = open(OUTFILENAME,"w") yaml.safe_dump(user_list, outFile) outFile.close() # validate it wrote correctly # note this shows example of how to read infile = open(OUTFILENAME) readList = yaml.safe_load(infile) infile.close() print 'wrote list of %d users as yaml file %s' % (len(readList),OUTFILENAME) </code></pre> <p>I wrote this code because I wanted the data it gets from the genealogy site but also:</p> <ul> <li>to learn APIs in general</li> <li>to learn the Stack Exchange API</li> <li>to get back into programming which I hadn't done much lately</li> <li>I thought I'd try YAML</li> </ul> <p>Since it's such a simple script I didn't bother with objects, but I would be interested in how it could be remade in the functional programming paradigm which I'm not as familiar with.</p>
[]
[ { "body": "<pre><code>'''\nThis is a script to access the stackexchange api\n for the genealogy site \n and create a list of user dictionaries\n'''\n\n# use requests module - see http://docs.python-requests.org/en/latest/user/install/#install\nimport requests\n\n# use pretty print for output\n</code></pre>\n\n<p>That's a pretty useless comment. It doesn't really tell me anything I didn't already know from the import</p>\n\n<pre><code>import pprint\n\n\n\n# save output in file in format compatable with eval\n# I didn't use json or yaml since my intent is to continue on using \n# the parsed output so saves a parse step\n</code></pre>\n\n<p><code>eval</code> also has a parse step. So you aren't saving anything by avoiding json.</p>\n\n<pre><code>pytFilename = \"users.pyt\"\n</code></pre>\n\n<p>python convention is for constants to be in ALL_CAPS</p>\n\n<pre><code># use se api and access genealogy site\n# see https://api.stackexchange.com/docs/users for api info\nurl='https://api.stackexchange.com/2.1/users'\nsite = 'genealogy'\n\nurlParams = {}\nurlParams['site'] = site\nurlParams['pagesize'] = 100\nurlParams['order'] = 'desc'\nurlParams['sort'] = 'reputation'\n</code></pre>\n\n<p>Why not put all these parameters into a single dict literal?</p>\n\n<pre><code>page = 1\nnotDone = True\nuserList = []\n</code></pre>\n\n<p>Python convention is for local variables to be mixed_case_with_underscores.</p>\n\n<pre><code># replies are paginated so loop thru until none left\nwhile notDone:\n urlParams['page'] = page\n # get next page of users\n r = requests.get(url,params=urlParams)\n</code></pre>\n\n<p>avoid single letter variable names. It makes it harder to figure out what you are doing. </p>\n\n<pre><code> # pull the list of users out of the json answer\n userList += r.json()['items']\n</code></pre>\n\n<p>I'd use <code>userList.extend( r.json()['items']). Also given the number of times you access the json, I'd have a</code>json = r.json()` line and access the json data through that.</p>\n\n<pre><code> # show progress each time thru loop, note only so many queries allowed per day\n print r.url\n print '\\tquota remaining: %s' % r.json()['quota_remaining'] \n print \"\\t%s users after page %s\" % (len(userList),page)\n\n # prepare for next iteration if needed\n page += 1\n notDone = r.json()['has_more']\n</code></pre>\n\n<p>I'd do: </p>\n\n<pre><code>json = {'has_more' : True}\nwhile json['has_more']:\n ...\n json = r.json()\n ...\n</code></pre>\n\n<p>As I think it's easier to follow then a boolean flag. </p>\n\n<pre><code># output list of users to a file in a format readable by eval\nopen(pytFilename,\"w\").write( pprint.pformat(userList) )\n</code></pre>\n\n<p>This isn't recommended practice. In CPython this will close the file, but it won't if you are using one of the other pythons. Instead, it's recommend to do:</p>\n\n<pre><code>with open(pytFilename, 'w') as output:\n output.write( pprint.pformat(userList) )\n</code></pre>\n\n<p>And that will close the file in all implementations of python.</p>\n\n<pre><code># validate it wrote correctly \n# note this shoasw example of how to read \nreadList = eval( open(pytFilename,\"r\").read() )\n\n\nprint 'wrote %s as python evaluatable list of users' % pytFilename\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:55:37.477", "Id": "20335", "ParentId": "20323", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T12:43:43.470", "Id": "20323", "Score": "0", "Tags": [ "python", "stackexchange" ], "Title": "Script to access genealogy API for list of users and attributes" }
20323
<p>I designed this object for a "bread formula". They use a concept known as <a href="http://en.wikipedia.org/wiki/Baker_percentage" rel="nofollow noreferrer">baker's percentages</a>, but you don't need to understand the math to help with the object design.</p> <p>I designed it as an object (of type <code>Formula</code>) that contains objects (of type <code>Ingredient</code>).</p> <p><img src="https://i.stack.imgur.com/CKDhx.jpg" alt=""></p> <p>Both classes have nullable properties. C# demarcates nullable types using a <code>?</code> after the type, like so: </p> <blockquote> <pre><code>public decimal? Weight { get; set; } </code></pre> </blockquote> <p><strong>The reason I declare them as nullable types is because I don't know their values (when I create an instance of them) until I calculate them later</strong>, as which point I update the null value with a calculated value.</p> <p>The calculations are just basic methods, like <code>CalculateSum()</code> or <code>CalculateWeight()</code>.</p> <p>Is there a better way to design this object? It works, but I feel like it's the wrong way to do things. I feel like I'm trying to force-fit inline/declarative style programming into an OOP design, but I don't know how else to do it, being so new to OOP.</p> <p>My thinking is that this object has this property. I won't know its value when I create an instance of it, so I must declare it as nullable. Once I calculate its value using a method that's also internal to the class, I assign/set its value. Then it will no longer be null.</p> <p>The calculation methods are basic calculations:</p> <blockquote> <pre><code>public type Method(input,input,...){calc; return calc;}. </code></pre> </blockquote> <hr> <pre><code> class Ingredient { public string Name { get; set; } public decimal Percentage { get; set; } public bool IsFlour { get; set; } public decimal? Weight { get; set; } public Ingredient(string _Name, decimal _Percent, bool _IsFlour, decimal? _Weight) { this.Name = _Name; this.Percentage = _Percent; this.IsFlour = _IsFlour; this.Weight = _Weight; } } class Formula { public decimal Weight_Total_Dough { get; set; } public ArrayList Ingredients { get; set; } public int NumberOfIngredients { get; set; } public decimal? SumPercentages { get; set; } public decimal? SumWeights { get; set; } public decimal? SumWeightTotalFlour { get; set; } public Formula(decimal _Weight_Total_Dough, ArrayList _Ingredients, int _NumberOfIngredients, decimal? _SumPercentages, decimal? _SumWeights, decimal? _SumWeightTotalFlour) { this.Weight_Total_Dough = _Weight_Total_Dough; this.Ingredients = _Ingredients; this.NumberOfIngredients = _NumberOfIngredients; this.SumPercentages = _SumPercentages; this.SumWeights = _SumWeights; } } </code></pre> <p>Here's the code for calculating <code>Formula.SumPercentages</code>, which was declared as nullable, but is now assigned a value:</p> <pre><code>public void SumPercentages(Formula f) { //Interate through Formula object, which contains an ArrayList of INGREDIENT objects. //Extract the precentages for each ingredient. //Add them up. //Return the summation as SumOfPercentages. decimal SumOfPercentages; SumOfPercentages = 0; foreach (object x in f.Ingredients) //for each INGREDIENT object in the FORMULA object { Ingredient ig = (Ingredient)x; //get the INGREDIENT.Percentage SumOfPercentages += ig.Percentage; //add it to the other INGREDIENT.Percentages } f.SumPercentages = SumOfPercentages; //SumOfPercentages was null before, but now we assign a value (SumOfPercentages) to it. </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:08:52.350", "Id": "32554", "Score": "1", "body": "If you are always setting a field in the constructor, it doesn't need to be nullable. If you're never setting it to a useful value, it shouldn't be a parameter to the constructor. And if it can be derived entirely from other properties on the same object, it should be set by that object rather than calling a function to perform calculations on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:59:49.210", "Id": "32568", "Score": "0", "body": "@Bobson By derived, do you mean calculated? I can (and do) calculate values from other properties and set those values (to replace) the nulls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:11:36.030", "Id": "32571", "Score": "1", "body": "I do mean calculated, but my point was that if you have all the information already, you don't need them to be nullable - just do the calculation in the constructor. There's no need for a separate function call to do the math later. And if you don't have all the information at first, then you should reconsider whether those values belong on the object - see my answer for another way to do it." } ]
[ { "body": "<p>Here's my humble opinion, it generally looks OK, here are some basic tips:</p>\n\n<ol>\n<li>Use generic collections if you can, <code>List&lt;Ingredient&gt;</code> instead of <code>ArrayList</code>, you won't have to cast it later on</li>\n<li>You can use LINQ for summing/counting/filtering/projections etc. All kinds of collection-related operations.</li>\n</ol>\n\n<p>The nullable part is not really <em>needed</em>, but it can work. If '0' is a valid value for 'no weight', then you can use regular <code>decimal</code> which will be initialized to 0. If you really want a <code>null</code> value for something special, you can leave it. Right now I'll be working under the assumption that the properties are still nullable.</p>\n\n<p>Considering that, I'd just make a few changes:</p>\n\n<pre><code>public class Formula\n{\n public IList&lt;Ingredient&gt; Ingredients { get; private set; }\n public decimal? SumPercentages { get; private set; }\n public decimal? SumWeights { get; private set; }\n public decimal? SumWeightTotalFlour { get; private set; }\n public decimal? WeightTotalDough {get;private set;}\n public int NumberOfIngredients {get;private set}\n\n public Formula(IEnumerable&lt;Ingredient&gt; ingredients, decimal? weightTotalDough)\n {\n Ingredients = new List&lt;Ingredient&gt;(ingredients);\n SumWeights = Ingredients.Sum(x =&gt; (x.Weight ?? 0));\n SumWeightTotalFlour = Ingredients.Where(x =&gt; x.IsFlour).Sum(x =&gt; (x.Weight ?? 0))\n SumPercentages = Ingredients.Sum(x =&gt; x.Percentage);\n WeightTotalDough = weightTotalDough;\n NumberOfIngredients = Ingredients.Count;\n }\n\n}\n</code></pre>\n\n<p>I'm not quite sure what the <code>WeightTotalDough</code> is and where it comes from, but there it is.\nI don't know if you have to expose the <code>Ingredients</code> collection or do you just want to have the fields calculated. If it's the latter, make the <code>List</code> private and just expose the properties. Also I assume you won't pass <code>null</code> collection inside the <code>Formula</code>. After initialization, you can just get the values:</p>\n\n<pre><code>var formula = new Formula(yourIngredients, weightTotalDough);\nvar percentageSumValue = formula.SumPercentages;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:28:56.873", "Id": "32538", "Score": "0", "body": "Very helpful. Thank you. If those LINQ queries work as you've written them, that's about 100 lines of code I can rid myself of. Really need to get LINQ into my system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:51:42.510", "Id": "32542", "Score": "1", "body": "@Thomas No problem, feel free to ask if you have any other questions. :) LINQ is good to know since it can be *hugely* helpful and make your code more readable. Of course unless you go too far... ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:50:30.593", "Id": "32552", "Score": "0", "body": "re:WeightTotalDough. That's an aspect of the Baker's Percentages math. You add up all the percentages of a formula (100%, 70%, 5%, 2%) = 175%. Flour (or total flours) is always 100%. It's the baseline. So a recipe with sum of percentages = 175% just means there are 175 \"parts\" and 100 of those parts are flour. That's where WeightTotalDough comes in. If you want to make 10000 grams (weight) total dough for 177% formula, you know flour weight will be (100 parts/177 parts)*WeightTotalDough or (100/177)*10000=5650g flour. Other ingredients are calculated same way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:14:17.043", "Id": "32572", "Score": "1", "body": "@Thomas oh, OK, makes sense. My curiosity has been satiated. ;) I guess you might freely leave that property there in such case..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:54:28.193", "Id": "32578", "Score": "0", "body": "I've tried and failed to covert fellow cooks to using Baker's Math, not just for baking, but for everything. It's almost too useful. If you want to use it, for example, to make meatloaf, your main ingredient becomes the \"100%\". 100% ground beef, 10% onions, 5% bread crumbs, 1% salt = 116% total formula. Then you can scale it up and down as you please. Make 1/3 a meatloaf for you or 100 meatloaves for an army. :D The great part about baker's math is how it allows you to tweak proportions. Too much onion, reduce to 9% onion, etc. It's a very useful system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:55:26.090", "Id": "32594", "Score": "1", "body": "@Thomas isn't \"Baker's math\" just a special case of \"N parts\" ingredient listing, with one of the ingredients being \"100 parts\" instead of e.g. saying \"10 parts meat, 1 part onions\"? Part of the reason I'm asking this is because it means that flour doesn't need to be \"special\" at all - the only thing distinguishing it from the other ingredients in the math is the fact that its quantity is 100. (or that two different kinds of flour are 65 and 35). Although, there might be some recipes you can't do this with - scaling isn't always a matter of multiplying everything equally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T23:43:47.340", "Id": "32604", "Score": "0", "body": "@Random832 That's exactly right. It's just N parts." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:16:10.103", "Id": "20329", "ParentId": "20328", "Score": "7" } }, { "body": "<p>I'm a fan of <a href=\"http://blogs.msdn.com/b/ericlippert/archive/tags/immutability/\" rel=\"nofollow noreferrer\">immutable objects</a> for their various benefits. Below is an example of how to make your <code>Ingredient</code> class immutable. Similar techniques can be made to your <code>Formula</code> class. I also highly recommend not using <code>ArrayList</code> in favor of a generic <code>List&lt;Ingredient&gt;</code> as <a href=\"https://codereview.stackexchange.com/users/20868/trust-me-im-a-doctor\">Trust me - I'm a Doctor</a> <a href=\"https://codereview.stackexchange.com/a/20329/6172\">recommends</a>.</p>\n\n<pre><code>sealed class Ingredient\n{\n private readonly string name;\n private readonly decimal percentage;\n private readonly bool isFlour;\n private readonly decimal? weight;\n\n public string Name { get { return this.name; } }\n public decimal Percentage { get { return this.percentage; } }\n public bool IsFlour { get { return this.isFlour; } }\n public decimal? Weight { get { return this.weight; } }\n\n public Ingredient(string _Name, decimal _Percent, bool _IsFlour, decimal? _Weight)\n {\n this.name = _Name;\n this.percentage = _Percent;\n this.isFlour = _IsFlour;\n this.weight = _Weight;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:39:51.610", "Id": "32539", "Score": "0", "body": "Thank you, Jesse. I need to read up on immutability before I understand what your changes mean. I might have questions in a bit. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:48:44.143", "Id": "32540", "Score": "1", "body": "I agree that immutability is great, but I don't like that you left the nullable weight. How can you modify it if it is immutable? Are you going to create a new object?\n\nCheck my answer for an alternate design" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:42:35.600", "Id": "32551", "Score": "1", "body": "@mariosangiorgio you DON'T modify it. You pass in the weight (or lack thereof) during construction. Nullable doesn't mean necessarily it's going to need to change during the variable's lifetime. I read it as being fixed to either an actual weight or `null` (no weight needed) when an ingredient is constructed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:54:24.727", "Id": "32566", "Score": "1", "body": "I don't think you can make the object immutable based on my understanding of baker's percentages. Since you have to calculate the weight of non-flour ingredients based on the weight of the flour, and presuming this code is a way to do that, you'll need to be able to modify the ingredient weights based on changes to the flour weight." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:23:44.247", "Id": "20331", "ParentId": "20328", "Score": "7" } }, { "body": "<p>There are several points that is possible to improve.</p>\n\n<p>If you are working at least with <a href=\"http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29\" rel=\"nofollow\">C#</a> 2.0 (as I expect because you mentioned <code>Nullable&lt;decimal&gt;</code>), you could replace <code>ArrayList</code> with <code>List&lt;Ingredient&gt;</code> or even <code>IEnumerable&lt;Ingredient&gt;</code>. This will make it more intuitive, and later you could remove type casting from <code>SumPercentages</code>.</p>\n\n<pre><code>foreach (Ingredient ig in f.Ingredients)\n{\n SumOfPercentages += ig.Percentage;\n}\n</code></pre>\n\n<p>Then, if you are working at least with C# 3.0 you could, rewrite <code>SumPercentages</code> using LINQ:</p>\n\n<pre><code>public void SumPercentages(Formula f)\n{\n f.SumPercentages = f.Ingredients.Select(ig =&gt; ig.Percentage).Sum();\n}\n</code></pre>\n\n<p>Last point, to implement <code>ICloneable</code> for both <code>Formula</code> and <code>Ingredient</code>, then replace </p>\n\n<pre><code>this.Ingredients = _Ingredients;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>this.Ingredients = Ingredients.Select(ig =&gt; ig.Clone()).ToList();\n</code></pre>\n\n<p>So <code>Ingredients</code> will be a copy of the initial array. This will prevent a situation when you unwittingly change the list of ingredients after you have created <code>Formula</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:51:54.193", "Id": "32553", "Score": "0", "body": "My C# is a bit dated and it's very deficient in LINQ. I'm rather glad you guys have pointed this out, as I'm about to start looking for a development job and better get my C# updated and LINQ learned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:27:31.560", "Id": "20332", "ParentId": "20328", "Score": "2" } }, { "body": "<p>I usually don't like too much nullable and I propose an alternative design to your problem.</p>\n\n<p>I think that you should separate the ingredients as specified in the recipe, which contains only the percentages with the actual quantities you need.</p>\n\n<p>I'd go for a class <code>Ingredient</code> describing an ingredient and its percentage, another class <code>Quantity</code> that represent the actual quantity of each ingredient and finally a <code>Recipe</code> class.</p>\n\n<p>The <code>Recipe</code> class should contain the list of ingredients needed and it should have a method <code>List&lt;Quantity&gt; computeQuantities(decimal totalDoughWeight)</code> that computes the quantities of each ingredient you need.</p>\n\n<p>In this way you clearly separate the recipe and the quantities needed in a particular time.</p>\n\n<p>I think that this design is closer to the domain you want to model (In which recipes and actual quantities are separate entities) and it is cleaner because it does not require you to introduce any nullable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:35:08.893", "Id": "32549", "Score": "0", "body": "That's basically what I've done, isn't it? The Formula class (what you call the Recipe class) contains an array (a list) of ingredients and has methods to compute quantities. Maybe I don't understand, but your suggestion is that I should have three classes instead of two: Recipe > Ingredient > Quantity? So instead of quantity being a property of Ingredient, it's a subclass? Let me think on this some more. I see how this would eliminate the nullable type in Ingredient. This might actually be better. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:43:31.860", "Id": "32638", "Score": "1", "body": "No, it isn't. My suggestion was more or less the same thing @Bobson suggested. Quantity should not be a subclass of ingredient, but they should represent two different things. Ingredients are the abstract entities you have in recipes, while with quantities you know the actual amount needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:38:29.593", "Id": "20333", "ParentId": "20328", "Score": "3" } }, { "body": "<p>Everyone has had good ideas, but since you're asking about OOP, I'd suggest refactoring it altogether.</p>\n\n<pre><code>void Main()\n{\n var formula = new Formula(new[] {\n new Ingredient(\"Flour, AP\", 100m, true),\n new Ingredient(\"Water, Warm\", 70.15m, false),\n new Ingredient(\"Salt\", 3.04m, false),\n new Ingredient(\"Yeast\", .24m, false),\n new Ingredient(\"Pate fermentee\", 2.53m, false)\n });\n var weights = formula.GetWeights(10000m);\n}\n\nclass Ingredient\n{\n public string Name { get; private set; }\n public decimal Percentage { get; private set; }\n public bool IsFlour { get; private set; }\n\n public Ingredient(string _Name, decimal _Percent, bool _IsFlour)\n {\n this.Name = _Name;\n this.Percentage = _Percent;\n this.IsFlour = _IsFlour;\n }\n}\n\nclass Formula\n{\n private IEnumerable&lt;Ingredient&gt; Ingredients { get; set; }\n public decimal SumPercentages { get; private set; }\n\n public Formula(IEnumerable&lt;Ingredient&gt; _Ingredients)\n {\n this.Ingredients = _Ingredients;\n this.SumPercentages = _Ingredients.Sum(x =&gt; x.Percentage);\n }\n\n public Dictionary&lt;Ingredient, decimal&gt; GetWeights(decimal weightTotalDough)\n {\n return Ingredients.ToDictionary(k =&gt; k, v =&gt; (v.Percentage / this.SumPercentages) * weightTotalDough);\n }\n}\n</code></pre>\n\n<p>By doing it this way, you separate the formula (which is basically just Ingredient/Percentage pairs) from each application of it. You can use the same <code>Formula</code> object to calculate the weights for 10000g of dough or 50000g of dough - simply call <code>GetWeights()</code> with a different value.</p>\n\n<p>Notice how many fewer properties you need on each class, and the question of \"late setting\" of some of them is entirely irrelevant. Effectively, weight is not an intrinsic property of an ingredient, because it varies based on the total weight, so <code>Weight</code> shouldn't be a property of <code>Ingredient</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:17:44.557", "Id": "32573", "Score": "0", "body": "This is magnitude more elegant than my attempt, if I understand what you've done. I don't entirely, but I'm working on it now and might have questions later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:22:12.857", "Id": "32574", "Score": "3", "body": "Ask away! I'll be glad to explain anything you need me to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T00:56:04.763", "Id": "32610", "Score": "2", "body": "I would probably make some of the properties readonly (or remove the setters) too, so that consumers of the formula can't change it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:35:41.667", "Id": "32632", "Score": "1", "body": "Huh. I did that for `Formula`, and forgot to do it for `Ingredient`. Good catch. Edited." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:58:46.723", "Id": "20347", "ParentId": "20328", "Score": "17" } }, { "body": "<p>Mutability is very often the source of pain for developers and I suggest you to avoid it as much as possible, by breaking into two parts your logic: object construction and object usage. </p>\n\n<p>If the properties of your class are not available all from the beginning, the right approach for me is to to use a builder, which is mutable, but express clearly the fact that there is no object created yet. When you have all the properties set, you can call <code>builder.build</code> to create an instance of the object, and in case the properties are not all set, you will throw an <strong>exception</strong> here. </p>\n\n<p>As a result, all the clients of the class (meaning those parts of the code which use an instance of that class) could rely on the fact that the instance is in correct state and you can use your object for an infinite amount of time without having to check if that property is null or not. The <em>single point of failure</em> is now the creation of the object, which can throw an exception if you didn't provide on the builder all the required properties.</p>\n\n<p>Separating object construction from object itself is a great way to express your intention, make your code readable and avoid tedious bugs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:09:01.670", "Id": "32570", "Score": "1", "body": "I believe this exactly what I need to do, because the mutability of these objects is what's causing me so much pain. I did not know about Builder until you mentioned it, so I'm essentially \"reinventing the wheel\", manually \"building\" this object and using nullables for the pieces of the object I don't yet have. I think you may have helped me tremendously here, as I often find myself deal with object construction vs. object usage issues. Thank you. I may have more questions later. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:05:56.813", "Id": "20348", "ParentId": "20328", "Score": "3" } }, { "body": "<p>Not sure I have a whole lot to add here, but based on the business requirement of representing baker's percentages, I think the object model should be changed to reflect the domain better. As in:</p>\n\n<pre><code>class Ingredient\n{\n public string Name { get; set; }\n public decimal Percentage { get; set; }\n // I don't think you want to be able to have multiple flour ingredients\n // so this isn't appropriate in the ingredient object\n //public bool IsFlour { get; set; }\n // Likewise, the weight is calculated in relation to the flour weight, which\n // I believe should be in the domain of the Formula object\n //public decimal? Weight { get; set; }\n\n public Ingredient(string _Name, decimal _Percent) //, bool _IsFlour, decimal? _Weight)\n {\n this.Name = _Name;\n this.Percentage = _Percent;\n // this.IsFlour = _IsFlour;\n //this.Weight = _Weight;\n }\n}\n\nclass Formula\n{\n // This can't be nullable since it's the key to baker's percentages.\n // It's in the formula since it's a key property of the formula, more than an ingredient\n public decimal FlourWeight { get; set; }\n // In baker's percentages flour is always 100%, isn't it?\n public decimal FlourPercentage\n {\n get { return 100m; }\n }\n\n // This should be a method, since it's a function of the ingredients\n //public decimal Weight_Total_Dough { get; set; }\n public decimal GetTotalDoughWeight()\n {\n // Cycle through ingredients and return the weight based on\n // the ingredient percentage and the flour weight.\n }\n\n // Or you can instantiate in the constructor\n private List&lt;Ingredient&gt; _ingredients = new List&lt;Ingredient&gt;();\n public List&lt;Ingredient&gt; Ingredients \n { \n get { return _ingredients; }\n set { _ingredients = value; }\n }\n\n public int NumberOfIngredients()\n { \n // I agree with other posters that this could be pulled from the list directly\n return _ingredients.Count();\n }\n\n // All of these can be done on the list directly or via linq\n public decimal GetSumPercentages()\n {\n return _ingredients.Sum(i =&gt; i.Percentage);\n }\n\n // This is where the formula class does its work\n public decimal SumWeights \n {\n // I assume you want flour in here, too\n return _ingredients.Sum(i =&gt; i.Percentage * FlourWeight) + FlourWeight;\n }\n\n // This is the only part I'm not comfortable with...I think you'll need it but\n // it doesn't feel right here. I might override IEnumerable and do a custom collection for ingredients\n public decimal GetIngredientWeight(Ingredient ingredient)\n {\n return ingredient.Percentage * FlourWeight;\n }\n\n // Again, I think this should be unnecessary based on how I understand the domain\n //public decimal? SumWeightTotalFlour { get; set; }\n\n public Formula(decimal flourWeight, List&lt;Ingredient&gt; ingredients)\n {\n this.FlourWeight = flourWeight;\n this.Ingredients = ingredients;\n }\n}\n</code></pre>\n\n<p>Granted, I'm taking more of a DDD approach here, but it makes more sense to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T00:29:50.070", "Id": "32609", "Score": "0", "body": "The IsFlour bool is important, but that's domain knowledge. You wouldn't know it otherwise. In short, 100 parts of any recipe is flour. That can be one flour (100%), four flours (25%, 25%, 25%, 25%) or any other combination. Hence the isFlour bool. I see what you mean about the weight calculation belonging in formula. Others suggested that as well. Will move it. Still looking at your other comments. They seem to be related to domain knowledge areas that I left unexplained. Thanks for all of the above. Much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:11:17.717", "Id": "20350", "ParentId": "20328", "Score": "1" } } ]
{ "AcceptedAnswerId": "20347", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T15:58:29.523", "Id": "20328", "Score": "14", "Tags": [ "c#", "object-oriented" ], "Title": "Bread formula object" }
20328
<p>I've designed an algorithm to find the longest common subsequence.</p> <p>These are steps: </p> <ul> <li><p>Pick the first letter in the first string.</p></li> <li><p>Look for it in the second string and if its found, Add that letter to <code>common_subsequence</code> and store its position in <code>index</code>, Otherwise compare the length of <code>common_subsequence</code> with the length of <code>lcs</code> and if its greater, asign its value to <code>lcs</code>.</p></li> <li><p>Return to the first string and pick the next letter and repeat the previous step again, But this time start searching from <code>index</code>th letter</p></li> <li><p>Repeat this process until there is no letter in the first string to pick. At the end the value of <code>lcs</code> is the Longest Common Subsequence.</p></li> </ul> <p>This is an example:</p> <pre><code>X=A, B, C, B, D, A, B‬‬ ‫‪Y=B, D, C, A, B, A‬‬ </code></pre> <ol> <li>Pick <code>A</code> in the first string. </li> <li>Look for <code>A</code> in <code>Y</code>. </li> <li>Now that there is an <code>A</code> in the second string, append it to <code>common_subsequence</code>. </li> <li>Return to the first string and pick the next letter that is <code>B</code>.</li> <li>Look for <code>B</code> in the second string this time starting from the position of <code>A</code>. </li> <li>There is a <code>B</code> after <code>A</code> so append B to <code>common_subsequence</code>. </li> <li>Now pick the next letter in the first string that is <code>C</code>. There isn't a <code>C</code> next to <code>B</code> in the second string. So assign the value of common_subsequence to <code>lcs</code> because its length is greater than the length of <code>lcs</code>.</li> </ol> <p>Repeat the previous steps until reaching the end of the first string. In the end the value of <code>lcs</code> is the Longest Common Subsequence.</p> <p>The complexity of this algorithm is \$\theta(n*m)\$.</p> <p>I implemented it on two methods. The second one is using a hash table, but after implementation I found it's much slower compared to the first algorithm. I can't understand why.</p> <p>The first algorithm:</p> <pre><code>import time def lcs(xstr, ystr): if not (xstr and ystr): return # if string is empty lcs = [''] # longest common subsequence lcslen = 0 # length of longest common subsequence so far for i in xrange(len(xstr)): cs = '' # common subsequence start = 0 # start position in ystr for item in xstr[i:]: index = ystr.find(item, start) # position at the common letter if index != -1: # if common letter is found cs += item # add common letter to the cs start = index + 1 if index == len(ystr) - 1: break # if reached to the end of ystr # updates lcs and lcslen if found better cs if len(cs) &gt; lcslen: lcs, lcslen = [cs], len(cs) elif len(cs) == lcslen: lcs.append(cs) return lcs file1 = open('/home/saji/file1') file2 = open('/home/saji/file2') xstr = file1.read() ystr = file2.read() start = time.time() lcss = lcs(xstr, ystr) elapsed = (time.time() - start) print elapsed </code></pre> <p>The second one using hash table:</p> <pre><code>import time from collections import defaultdict def lcs(xstr, ystr): if not (xstr and ystr): return # if strings are empty lcs = [''] # longest common subsequence lcslen = 0 # length of longest common subsequence so far location = defaultdict(list) # keeps track of items in the ystr i = 0 for k in ystr: location[k].append(i) i += 1 for i in xrange(len(xstr)): cs = '' # common subsequence index = -1 reached_index = defaultdict(int) for item in xstr[i:]: for new_index in location[item][reached_index[item]:]: reached_index[item] += 1 if index &lt; new_index: cs += item # add item to the cs index = new_index break if index == len(ystr) - 1: break # if reached to the end of ystr # update lcs and lcslen if found better cs if len(cs) &gt; lcslen: lcs, lcslen = [cs], len(cs) elif len(cs) == lcslen: lcs.append(cs) return lcs file1 = open('/home/saji/file1') file2 = open('/home/saji/file2') xstr = file1.read() ystr = file2.read() start = time.time() lcss = lcs(xstr, ystr) elapsed = (time.time() - start) print elapsed </code></pre>
[]
[ { "body": "<p>Firstly, your algorithm is incorrect try:</p>\n\n<p><code>lcs(\"AAAABCC\",\"AAAACCB\")</code>, the LCS should be <code>\"AAAACC\"</code>, but your algorithm finds <code>\"AAAAB\"</code>.</p>\n\n<p>Secondly your algorithm is <code>O(n^2*m)</code> not <code>O(n*m)</code>. Since you don't elaborate as to why you think your algorithm is <code>theta(n*m)</code> I can't really guess where your analysis has gone wrong.</p>\n\n<p>Your second version attempts to optimize the process of searching through the string by using a list of pre-calculated positions. This means you don't have to scan through all the positions in the string with different characters. However, you lose the ability to skip all the position before your starting index. For long strings with few distinct characters, you end up losing out. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T13:46:51.347", "Id": "32622", "Score": "0", "body": "I made a little changes to my algorithm. now it passes your test case. i uploaded it here: http://pastebin.com/030Uhpcr .the only change that i made is that it calls the function two time. first lcs(xstr, ystr) and second lcs(ystr, xstr). but i still think that its complexity is theta(n*m). because it loops through second string n times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:14:15.710", "Id": "32631", "Score": "0", "body": "@Rastegar, your algorithm is still incorrect, try: \"AAAABCCD\" and \"AAAADCCB\". As for complexity, `ystr.find` is called `n*(n/2)` times, or `O(n^2)`. The complexity of `ystr.find` is `O(m)`, thus the cost is `O(n^2*m)`. It doesn't loop through the second string `m` times, because you've got two nested for loops there, not one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:55:36.903", "Id": "32644", "Score": "0", "body": "Ok, It seems that my program certainly made fail. but it's complexity was `theta(n*m)` becuase `ystr.find(item, start)` doesn't start searching from the beginning of the list but it starts from `start` where it found the common letter in the last searching. and after getting the end of `ystr`, exits from the second loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T18:11:24.933", "Id": "32648", "Score": "0", "body": "@Rastegar, ok I missed a subtlety in your algorithm. I thought `start` was being reset more then it was. So yes it appears to be `theta(n*m)` but that's all moot because it doesn't work." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T20:31:38.980", "Id": "20352", "ParentId": "20337", "Score": "3" } } ]
{ "AcceptedAnswerId": "20352", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T17:13:23.143", "Id": "20337", "Score": "3", "Tags": [ "python", "algorithm" ], "Title": "Find the longest common subsequence algorithm - low speed" }
20337
<p>I want to ask whether my following implementation is good in the view of good practice and performance. I have an app where I have to show another page or template html in an iframe. I get that template html via ajax and render it in the iframe. Iframe must be used because the template must be isolated.I am now storing that template html in a javscript variable</p> <pre><code>var tmp; $.get('/template/1', function(data){ tmp = $(data); }); // tmp = '&lt;html&gt;&lt;body&gt;....etc...&lt;/body&gt;&lt;/html'; holds whole template </code></pre> <p>and then I have my div container in that template where I use mustache for changing content.</p> <pre><code>var render = tmp.find('#container').html(); var rendered = Mustache.to_html(render, some_data); //then tmp.find('#container').html(rendered); // and add tmp to iframe </code></pre> <p>I am storing whole html in tmp so that it can be used later also and when my some_data change I again process tmp and re-render template in iframe. I may need re-render template many times later so I am storing in in variable. Is it good to store whole template html in javascript variable like that or it's better use other ways...if there are other ways what are they...</p>
[]
[ { "body": "<p>I don't think this will cause you any problems; it may offer superior performance in many scenarios, especially over re-rendering the template. The only other option that comes to mind is to keep this invisibly in the DOM somewhere and use JQuery's <code>clone()</code> to re-render it as needed. I use this latter technique especially if the original template is pre-rendered from another source. Just bear in mind that if you do use <code>clone()</code> JQuery also clones element IDs if you have any, which may cause your selectors on those IDs to behave unexpectedly if you don't change them after the clone (or refactor the source template).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:41:25.447", "Id": "32556", "Score": "0", "body": "If it's a complex element with many nested children clone(deep) works well, however creating individual elements should be faster than cloning the same element over and over again. Doesn't look like that is what the OP is doing, but I thought this was important side note. :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:45:43.977", "Id": "32557", "Score": "0", "body": "@rlemon good point and agreed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:51:44.510", "Id": "32558", "Score": "0", "body": "first of all thank your discussions. It would be too long to explain my whole scenario here but I wanted to know storing whole page html string like that in a var is good for health or not !!\nfor eg:\n `$.get('/template/hello.html', function(data){ tmp = $(data); });`\n\nhello.html is a full web page" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:58:38.380", "Id": "32560", "Score": "2", "body": "@roxxypoxxy well in that case it is not stored in the string, jQuery has created a 'fake' documentFragment (iirc). Basically it's now a HTML Collection wrapped in a jQuery object. If you interact with the contents of this collection a few times they yes, hold it. Reaching into the DOM for multiple updates would be more costly than holding it in memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T19:11:23.130", "Id": "32563", "Score": "0", "body": "hmm..that's interesting." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:38:40.667", "Id": "20346", "ParentId": "20340", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:31:53.350", "Id": "20340", "Score": "4", "Tags": [ "javascript", "jquery", "ajax", "template", "mustache" ], "Title": "Rendering and re-rendering a Mustache template" }
20340
<p>I have designed couple of aspects using PostSharp for different projects, but there is a design flaw in many of them: <strong>dependency management</strong>.</p> <p><strong>This is a question about injection of dependencies into aspects, not about dependency injection using aspects</strong></p> <p>Due to nature of PostSharp post-compilation there are <strong>several limitations</strong> applied to aspects</p> <ol> <li><em>Constructor injection</em> is not applicable. <a href="http://doc.sharpcrafters.com/postsharp-2.1/Default.aspx##PostSharp-2.1.chm/html/7480ca54-61c0-46c5-9914-60a58c3033e8.htm">Constructor will be executed once during post-compilation, then object will be serialized and later deserialized multiple times at runtime</a>. There is a method for <a href="http://doc.sharpcrafters.com/postsharp-2.1/Default.aspx##PostSharp-2.1.chm/html/1568d7bf-91b2-4475-919d-c2810c1fc2fb.htm">runtime initialization</a> <a href="http://doc.sharpcrafters.com/postsharp-2.1/Default.aspx##PostSharp-2.1.chm/html/M_PostSharp_Aspects_IEventLevelAspect_RuntimeInitialize.htm"><code>IEventLevelAspect.RuntimeInitialize</code></a>.</li> <li>Neither property injection is possible to do : properties will be initialized before runtime, and IL weaver will rewrite code, so decoration with some kind of <code>[Injection]</code> attribute will be not possible also</li> <li>Neither <em>Ambient context</em> nor <em>Service Locator</em> are not suitable because they will break unit testing isolation</li> <li><p>It's only possible to provide values of value types known during compilation and <code>System.Type</code> next to aspect decoration:</p> <p><code>[MyAspect(integerValue = 1, providedType = typeof(Type))]</code></p></li> </ol> <p>After all those limitations, there is only one approach (known to me): provide <code>System.Type</code> of <em>abstract factory</em> or class with <em>factory method</em>, so aspect could creates its instance during runtime initialization and resolves dependency using it.</p> <h2>PostSharp aspect that has dependency injection</h2> <p>Here is an example of <em>trivial</em> tracing aspect, that has dependency injection</p> <pre><code>[Serializable] public class TracingAspectAttribute : OnMethodBoundaryAspect { // Question #1: Is there any better way to design aspect // and to inject dependency into it? public Type AbstractFactoryType { get; set; } private ILogger Logger { get; set; } // Compile time validation. // Question #2: Better approach to ensure during post-compile time // that abstract factory could be created at runtime using Activator.CreateInstance public override bool CompileTimeValidate(MethodBase method) { var result = true; var methodInfo = method as MethodInfo; // check that AbstractFactoryType contains proper System.Type if (AbstractFactoryType == null) // check that AbstractFactoryType is provided { // break build with following message Message.Write(methodInfo, SeverityType.Error, "999", "AbstractFactoryType is null"); result = false; } else if (!(typeof(IAbstractFactory&lt;ILogger&gt;).IsAssignableFrom(AbstractFactoryType))) // check that AbstractFactoryType is proper type { // break build with following message Message.Write(methodInfo, SeverityType.Error, "999", "Only abstract facory derived from IAbstractFactory&lt;ILogger&gt; allowed"); result = false; } else if (AbstractFactoryType.IsAbstract || AbstractFactoryType.IsInterface) // check that instance of AbstractFactoryType could be created { // break build with following message Message.Write(methodInfo, SeverityType.Error, "999", "Only concrete facory derived from IAbstractFactory&lt;ILogger&gt; allowed"); result = false; } return result; } // Initializes the current aspect at runtime public override void RuntimeInitialize(MethodBase method) { // create instance of Abstract Factory var abstractFactory = Activator.CreateInstance(AbstractFactoryType); // create an instance of dependency, only instances of IAbstractFactory&lt;ILogger&gt; could be here // proven by CompileTimeValidate method Logger = ((IAbstractFactory&lt;ILogger&gt;)abstractFactory).CreateInstance(); } // Method executed before the body of methods to which this aspect is applied. public override void OnEntry(MethodExecutionArgs args) { Logger.Log(string.Format("OnEntry {0}.{1}(...)", args.Method.DeclaringType.FullName, args.Method.Name)); } // Method executed after the body of methods to which this aspect is applied public override void OnExit(MethodExecutionArgs args) { Logger.Log(string.Format("OnExit {0}.{1}(...)", args.Method.DeclaringType.FullName, args.Method.Name)); } } </code></pre> <p>Sample code is available at <a href="https://gist.github.com/4495440">gist</a> and full example is at <a href="https://github.com/akimboyko/AOP.Hydra/blob/master/AOP.Hydra/AOP.Hydra.PostSharp/TracingAspectAttribute.cs">github</a></p> <h2>Example of usage</h2> <pre><code>[TracingAspect(AbstractFactoryType = typeof(FakeLoggerFactory))] public class FakeService { public int Process(int n, int m) { return n * m; } } </code></pre> <p>More samples could be found at <a href="https://github.com/akimboyko/AOP.Hydra/blob/master/AOP.Hydra/AOP.Hydra.PostSharp.UnitTests/TracingAspectTests.cs">github</a></p> <h2>My questions are following</h2> <ol> <li>Is there any better way to design aspect and to inject dependency into it?</li> <li>Better approach to ensure during post-compile time that <em>abstract factory</em> could be created at runtime using <code>Activator.CreateInstance</code></li> </ol> <h2>Comment from SharpCrafter support</h2> <blockquote> <p>The best way is to use a global singleton service locator, called from method RuntimeInitialize.</p> <p>If you need the ability to change the DI container dynamically (for testing, presumably), you have to write some C# code to handle this concern. For instance, you may maintain a static collection of all aspects in your AppDomain and set the dependencies from the test.</p> <p>Note that most aspects have static lifetime, so it does not fit well with the dependency container framework.</p> </blockquote> <p><a href="http://support.sharpcrafters.com/discussions/questions/52-postsharp-atributes-and-dependency-injection">Postsharp Atributes and Dependency Injection @ SharpCrafters support</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:43:37.737", "Id": "49112", "Score": "0", "body": "The PostSharp documentation proposes several strategies to cope with the issue of consuming dependencies from an aspect: http://doc.postsharp.net/postsharp-3.0/Content.aspx/PostSharp-3.0.chm/html/b57d32e9-f760-4fd2-9a2c-af41a1f00430.htm" } ]
[ { "body": "<p>I've not used PostSharp in a number of years, but have often used the following pattern to get around life-cycle issues with DI on attributes. It's a little manual, so should be seen as the exception rather than the rule, but it's easy to follow.</p>\n\n<p>In your aspect, define a static factory method specifically designed to create your dependency . Define it as a Func and during execution of the aspect, call that func to get an instance of your dependency in the current context.</p>\n\n<p>For example:</p>\n\n<pre><code>public class SomeDependency\n{\n public void DoSomething()\n {\n }\n}\n\npublic class ContainerRegistrationCode\n{\n public void RegisterTypesInContainer()\n {\n SomeAspect.CreateSomeDependency = () =&gt; new SomeDependency(); \n\n // Probably something like\n // SomeAspect.GetDependency = () =&gt; Kernel.GetService&lt;SomeDependency&gt;();\n // goes here\n }\n}\n\npublic class SomeAspect\n{\n public static Func&lt;SomeDependency&gt; CreateSomeDependency { get; set; }\n\n public void OnExecute()\n {\n //Some behavior\n var dependencyINeed = CreateSomeDependency();\n dependencyINeed.DoSomething();\n }\n}\n</code></pre>\n\n<p>This allows you to declaratively bind up your dependencies (unfortunately manually, though I'm sure you could work out some convention for auto-binding), and ensures that your container gives you the correct object on each execution.</p>\n\n<p>I'm not sure if PostSharps IL weaving would interfere with this, but it's simple, clear and effective. We initially started using it to control the life-cycle of injected components that required access to NHibernate ISessions in ASP.NET MVC attributes.</p>\n\n<p>If you intend to wireup many of these types of dependencies, you could likely just use reflection to find any properties on your attributes following a naming convention, and bind them to your container.</p>\n\n<p>This obviously works fine for testability, as you just wire up the Func on your test setup. Obviously, buyer beware if you're running your tests concurrently because of the static.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T14:46:36.543", "Id": "32787", "Score": "0", "body": "Thx David, I'm going to try this idea with PostSharp to unveil questions regarding aspect's lifetime and IL weaver. Anyway this approach contains design flaw: as long as `CreateSomeDependency` is `static`, it will add unnecessary complexity while testing of aspect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T12:12:37.577", "Id": "33348", "Score": "0", "body": "I gave a try to this approach in both with static and instance scope of PostSharp aspect. It works fine, but ` public static Func<SomeDependency> CreateSomeDependency { get; set; }` makes it **hard to unittest in parallel**. Thx anyway. Here is a [code snippet](https://gist.github.com/4594189)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T14:39:25.660", "Id": "33406", "Score": "0", "body": "I'd suggest if it's an acceptable solution apart from that, that you serialize the tests around your aspects. I agree that it's not *ideal* for this reason, but it's not too different than any unit test that requires a [SetUp] ending up a the lesser of the evils ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T15:03:01.177", "Id": "33407", "Score": "0", "body": "Same issue will appear at multi-threaded environment, when different dependencies will be injected into different instances of aspect" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T20:40:06.310", "Id": "33479", "Score": "0", "body": "That depends on your container configuration. It's also why we actually call the Func during OnExecute rather than calling it and caching the output. If you use your DI container to scope your injected dependencies to a suitable unit of work, you'll always get the \"currently scoped\" instance during execution. This works well in a very high transaction website for injecting ISessions, which are request scoped as every time the attribute executes, it calls the container to ask for the current instance." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:49:04.183", "Id": "20422", "ParentId": "20341", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:36:12.040", "Id": "20341", "Score": "13", "Tags": [ "c#", "reflection", "dependency-injection", "postsharp", "aspect-oriented" ], "Title": "Inject dependency into PostSharp aspect" }
20341
<p>From the <a href="https://www.postsharp.net/product" rel="nofollow">PostSharp product page</a>:</p> <blockquote> <p>PostSharp automates the implementation of patterns so they don't turn into boilerplate.</p> <p>It allows developers to eradicate boilerplate by offloading repeating work from humans to machines. PostSharp contains ready-made implementations of the most common patterns and gives you the tools to build automation for your own patterns.</p> <p>Developers usually think in terms of design patterns, but with conventional programming languages, they end up writing boilerplate code. PostSharp extends the C# and VB languages with a notion of pattern. The result: shorter, cleaner code that’s easier to write and understand, contains fewer defects and is less expensive to maintain.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:37:14.427", "Id": "20342", "Score": "0", "Tags": null, "Title": null }
20342
PostSharp is aspect oriented programming for .NET using attributes that encapsulate aspects
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T18:37:14.427", "Id": "20343", "Score": "0", "Tags": null, "Title": null }
20343
Aspect oriented refers to the expression of event-driven programming through the use of callback functions or other means to respond to a local event that has global consequences without going through repetitive conditional checks or creating unnecessary dependencies between objects or subroutines.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-09T18:37:57.390", "Id": "20345", "Score": "0", "Tags": null, "Title": null }
20345
<p>I'm trying to think of ways to separate things out. I'm open to ideas, or if you see anything blatantly wrong, I'd like to know that too.</p> <p>Generally, I'm happy with this, but the sheer size of the class seems like a code smell.</p> <p><a href="https://bitbucket.org/jgrigonis/baseball_simulator/src" rel="nofollow">Original Source</a> </p> <pre><code>'''The Game class.''' import game_exceptions from bases import Bases from count import Count from inning import Inning from team import Team # pylint: disable=R0902 # pylint complains about the number of instance attributes. class Game(object): '''Maintain the state of the game. Includes methods to carry out various game related events. ''' def __init__(self, home, away, league="league.db", innings_per_game=9): '''Set up a new game. home and away are the team_id pointing to a team in the league. The league variable is used to play games in different leagues. innings_per_game is the number of innings in a standard game, it can be changed if you want to represent a little league game, or some type of exhibition game. ''' self.count = Count() self.home = Team(league=league, team_id=home) self.away = Team(league=league, team_id=away) self.inning = Inning(innings_per_game) self.bases = Bases() self.winner = None self.game_over = False self.bat_team = self.away self.pitch_team = self.home self.pitch_team_stats = self.pitch_team.stats.pitching self.current_pitcher = self.pitch_team.pitcher().stats.pitching self.bat_team_stats = self.bat_team.stats.batting self.current_batter = self.bat_team.current_batter().stats.batting def __str__(self): '''Output the important game information as a string.''' if self.game_over: return self.__str_finished_game() else: return self.__str_game_in_progress() def __str_finished_game(self): '''Output a finished game as a string.''' output = 'The game is over.\n' output += 'The %s team won.\n' % (self.winner) output += 'The final score was:\n' output += '%s to %s' % (self.home.score, self.away.score) output += '\n' if self.inning.number != self.inning.innings_per_game: output += 'The game took %s innings.\n' % (self.inning.number) return output def __str_game_in_progress(self): '''Output a game in progress as a string.''' if self.inning.top: half = "top" else: half = "bottom" output = "It's the %s of %s\n" % (half, self.inning.number) output += 'The score is:\n' output += '%s to %s' % (self.home.score, self.away.score) output += '\n' output += "%s is at bat." % (self.bat_team.current_batter()) output += '\nThe count is:\n' output += str(self.count) output += '\nWith %s outs.\n' % (self.inning.outs) output += str(self.bases) + '\n' return output def strike(self): '''Pitcher throws a strike. If there are 2 strikes, call the __strike_out method. Otherwise, just increment the strike count. ''' if self.count.strikes == 2: self.__strike_out() else: self.count.strike() def ball(self): '''Pitcher throws a ball. If there are 3 balls, call the __walk method, otherwise just increment the ball count. ''' if self.count.balls == 3: self.__walk() else: self.count.ball() def foul_ball(self): '''Batter hits a foul. If there are less than 2 strikes, increment the strike count. ''' if self.count.strikes != 2: self.count.strike() def hit_by_pitch(self): '''Batter is hit by pitch. Call the __stats_hbp method to update the stats. Then call the __walk method with hbp set to True, so it knows not to also call the __stats_walk method. We don't want to track it as a walk, we just want to perform the same game functions. ''' self.__stats_hbp() self.__walk(hbp=True) def steal(self, base): '''Runner steals a base. base - the base that is stolen (second, third, home) If the base to be stolen is not empty, or the base they are stealing from is not occupied, an error is assumed to have occured, and an exception will raise. ''' if base == "home": if self.bases[2] != 0: self.__score_run(self.bases[2]) self.__stats_steal(self.bases[2]) self.bases.clear(2) return base_num = self.__base_number(base) if self.bases[base_num - 1] != 0 and self.bases[base_num] == 0: self.__stats_steal(self.bases[base_num - 1]) self.bases.advance(base_num - 1) return raise game_exceptions.InvalidSteal() def caught_stealing(self, base): '''Runner caught stealing a base. base - the base that is attempted to be stolen (second, third, home) If the base to be stolen is not empty, or the base they are stealing from is not occupied, an error is assumed to have occured, and an exception will raise. ''' b_num = self.__base_number(base) if b_num == "home": if self.bases[2] != 0: self.__stats_caught_stealing(self.bases[2]) self.bases.clear([2]) self.__put_out() else: raise game_exceptions.InvalidSteal() elif b_num in [0, 1, 2]: if self.bases[b_num - 1] != 0 and self.bases[b_num] == 0: self.__stats_caught_stealing(self.bases[b_num - 1]) self.bases.clear([b_num - 1]) self.__put_out() else: raise game_exceptions.InvalidSteal() else: raise game_exceptions.InvalidSteal() def picked_off(self, base): '''Runner picked off from a base. base - the base that the runner was on (first, second, third) or (0, 1, 2) If base comes as a string, the __base_number function will translate it to an int. If the base is empty, an error is assumed to have occured, and an exception will raise. ''' base_number = self.__base_number(base) if self.bases[base_number] != 0: self.bases.clear([0]) self.__stats_pick_off() self.__put_out() else: raise game_exceptions.InvalidPickOff() def ground_out(self): '''Batter grounds out.''' self.__stats_atbat() self.__next_batter() self.__put_out() def fly_out(self): '''Batter flies out.''' self.__stats_atbat() self.__next_batter() self.__put_out() def balk(self): '''Pitcher performs a balk. If no baserunners are on, a balk has no effect. If runners are on base, they will all be advanced one base, and possibly scored, if there is a runner on third. ''' if not self.bases.men_on(): return scorer = self.bases.advance_all() if scorer: self.__score_run(scorer) def hit(self, num=1, advances="default"): '''Batter gets a base hit. 1 = single 2 = double 3 = triple 4 = home run By default, the hit is a single, and all runners advance one base. The advances are a list of tuples, there should be one tuple for each runner who advances on the play. It should specify the from and to bases that the runner moved from and to. 0 = first 1 = second 2 = third 3+ = home In the case where the baserunners didn't advance, advances should be passed in as None. ''' scorers = [] if advances == "default": advances = [] for abase in range(3): if not self.bases.empty_base(abase): advances.append((abase, abase + num)) if advances: if self.bases.men_on(): scorers = self.bases.advances(advances) for scorer in scorers: self.__stats_rbi() self.__score_run(scorer) if num == 4: self.__stats_rbi() self.__stats_home_run() self.__score_run(self.bat_team.batter) else: if num == 2: self.__stats_double() elif num == 3: self.__stats_triple() self.bases[num - 1] = self.bat_team.batter # put the batter on base. self.__stats_atbat() self.__stats_hit() self.__next_batter() def double_play(self, base1="second", base2="first", gdp=True): '''Batter hits into a double play. base1 - base where first out is made, assume force out. base2 - base where second out is made. gdp - True if it was a grounder into a double. ''' if self.bases.men_on() == 0: raise game_exceptions.NotEnoughRunnersOnBase() if self.inning.outs == 2: raise game_exceptions.TooManyOuts() self.__stats_atbat() if gdp: self.__stats_gdp() self.__next_batter() self.bases[base1] = 0 self.__put_out() self.bases[base2] = 0 self.__put_out() def triple_play(self, gtp=True): '''Batter hits into a triple play. gtp should be set to True if it was a grounder into a triple play. ''' if self.bases.men_on() &lt; 2: raise game_exceptions.NotEnoughRunnersOnBase() if self.inning.outs != 0: raise game_exceptions.TooManyOuts() self.__stats_atbat() if gtp: self.__stats_gtp() self.pitch_team_stats.out(3) self.current_pitcher.out(3) self.__next_batter() self.__side_retired() def fielders_choice(self, base="second"): '''Batter hits into a fielder's choice. A fielder's choice is when a runner is on base, the batter hits the ball such that the runner is put out, but the batter is then able to get on base. base - base where the out is made, assume force out. It defaults to second, as that is the most common fielder's choice. ''' self.__stats_atbat() self.__next_batter() self.bases[base] = 0 self.__put_out() def error(self, batter_on_base=False, advances=None): '''Fielder makes an error. By default nothing happens other than to take note of the error. batter_on_base determines if the batter got on base during this error. If True, the batter will occupy first base. If the batter were to get multiple bases, the batter_on_base can be set to 1 for "second", 2 for "third", and in some really weird circumstances, 3 for "home" for an error based home run. advances is a list of tuples to advance runners from and to. ''' scorers = [] if advances: if self.bases.men_on(): scorers = self.bases.advances(advances) else: raise game_exceptions.NoRunnerToAdvance() for scorer in scorers: self.__score_run(scorer) if batter_on_base: if batter_on_base == True: batter_base = 0 elif isinstance(batter_on_base, str): batter_base = self.__base_number(batter_on_base) if not self.bases.empty_base(batter_base): raise game_exceptions.InvalidAdvance() self.bases[batter_base] = self.bat_team.batter self.__stats_atbat() self.__next_batter() def sacrifice(self, advances=None): '''Batter performs a sacrifice bunt or fly out. By default all baserunners advance one base. It wouldn't make sense to have a sacrifice and have no one advance. advances is a list of tuples to advance runners from and to. ''' if self.bases.men_on() == 0: raise game_exceptions.NotEnoughRunnersOnBase() if self.inning.outs == 2: raise game_exceptions.BadSacrifice() if not advances: scored = self.bases.advance_all() if scored: self.__stats_rbi() self.__score_run(scored) else: if isinstance(advances, tuple): advances = [advances] for adv in advances: if self.bases[adv[0]] == 0: raise game_exceptions.NoRunnerToAdvance() scorers = self.bases.advances(advances) for scorer in scorers: self.__stats_rbi() self.__score_run(scorer) self.__stats_sacrifice() self.pitch_team_stats.out() self.current_pitcher.out() self.inning.out() self.__next_batter() def end_game(self): '''Game is over, winner is declared, unless tied. When would we ever have a tie? Apparently, this can happen even in MLB, and we may want to simulate other levels of play as well. ''' if self.home.score &gt; self.away.score: self.winner = "home" self.home.wins += 1 self.away.losses += 1 elif self.away.score &gt; self.home.score: self.winner = "away" self.away.wins += 1 self.home.losses += 1 else: # Tie self.winner = None self.home.ties += 1 self.away.ties += 1 self.game_over = True self.home.save() self.away.save() return @staticmethod def __base_number(base): '''Returns the base number, which is an index to the bases list.''' if base == "first": return 0 if base == "second": return 1 if base == "third": return 2 return base def __new_inning(self): '''Start a fresh inning. Clear the bases, reset the count, change sides. TODO: Append to the inning scores list. So we can track runs by inning. ''' self.bases.clear() self.count.reset_count() self.inning.reset_outs() if self.bat_team == self.away: self.bat_team = self.home self.pitch_team = self.away else: self.bat_team = self.away self.pitch_team = self.home self.bat_team_stats = self.bat_team.stats.batting self.current_batter = self.bat_team.current_batter().stats.batting self.pitch_team_stats = self.pitch_team.stats.pitching self.current_pitcher = self.pitch_team.pitcher().stats.pitching def __side_retired(self): '''Three outs, time to switch sides, or end the game.''' if self.inning.number &gt;= self.inning.innings_per_game: if self.inning.top: if self.home.score &gt; self.away.score: self.end_game() self.__new_inning() return else: # top if self.home.score != self.away.score: self.end_game() self.__new_inning() return self.inning.increment() self.__new_inning() def __strike_out(self): '''Batter strikes out.''' self.__stats_atbat() self.__stats_strike_out() self.__next_batter() self.__put_out() def __put_out(self): '''Runner is put out.''' self.current_pitcher.out() self.pitch_team_stats.out() if self.inning.outs == 2: self.__side_retired() else: self.inning.out() def __next_batter(self): '''Next batter is up in the lineup.''' self.bat_team.next_batter() self.current_batter = \ self.bat_team.current_batter().stats.batting self.count.reset_count() def __score_run(self, scorer): '''Score a run. TODO: We currently count all runs as earned. Needs to be fixed. TODO: We should add to the inning scores for home or away. ''' self.__stats_run(scorer) self.current_pitcher.earned_run() self.pitch_team_stats.earned_run() self.bat_team.score_run() if self.inning.number &gt;= self.inning.innings_per_game: if not self.inning.top: if self.home.score &gt; self.away.score: self.end_game() def __walk(self, hbp=False): '''Walk the batter. If hbp is True, the batter was hit by pitch, so we don't call the __stats_walk method. ''' if not hbp: self.__stats_walk() if self.bases[0] != 0: if self.bases[1] != 0: if self.bases[2] != 0: self.__score_run(self.bases[2]) self.__stats_rbi() else: self.bases[2] = self.bases[1] else: self.bases[1] = self.bases[0] else: self.bases[0] = self.bat_team.batter self.__next_batter() def __stats_plate_app(self): '''Batter gets a plate Appearance.''' self.bat_team_stats.plate_app() self.current_batter.plate_app() def __stats_hbp(self): '''Hit by pitch.''' self.bat_team_stats.hbp() self.current_batter.hbp() self.__stats_plate_app() self.current_pitcher.hit_batter() self.pitch_team_stats.hit_batter() def __stats_steal(self, runner): '''Steal.''' self.bat_team_stats.steal() self.bat_team.lineup[runner].stats.batting.steal() def __stats_caught_stealing(self, runner): '''Caught stealing.''' self.bat_team_stats.caught_stealing() self.bat_team.lineup[runner].stats.batting.caught_stealing() def __stats_atbat(self): '''Batter gets an at bat.''' self.bat_team_stats.atbat() self.current_batter.atbat() self.__stats_plate_app() self.current_pitcher.atbat() self.pitch_team_stats.atbat() def __stats_pick_off(self): '''Pitcher picks off a baserunner.''' self.current_pitcher.pick_off() self.pitch_team_stats.pick_off() def __stats_walk(self): '''Walk.''' self.bat_team_stats.walk() self.current_batter.walk() self.__stats_plate_app() self.current_pitcher.walk() self.pitch_team_stats.walk() def __stats_rbi(self): '''Run batted in.''' self.bat_team_stats.rbi() self.current_batter.rbi() def __stats_home_run(self): '''Home Run.''' self.bat_team_stats.home_run() self.current_batter.home_run() self.current_pitcher.home_run() self.pitch_team_stats.home_run() def __stats_double(self): '''Double.''' self.bat_team_stats.double() self.current_batter.double() def __stats_triple(self): '''Triple.''' self.bat_team_stats.triple() self.current_batter.triple() def __stats_hit(self): '''Hit.''' self.bat_team_stats.hit() self.current_batter.hit() self.current_pitcher.hit() self.pitch_team_stats.hit() def __stats_gdp(self): '''Ground Double Play.''' self.bat_team_stats.gdp() self.current_batter.gdp() def __stats_gtp(self): '''Ground Triple Play.''' self.bat_team_stats.gtp() self.current_batter.gtp() def __stats_sacrifice(self): '''Sacrifice.''' self.bat_team_stats.sacrifice() self.current_batter.sacrifice() self.__stats_plate_app() def __stats_strike_out(self): '''Strike Out.''' self.bat_team_stats.strike_out() self.current_batter.strike_out() self.current_pitcher.strike_out() self.pitch_team_stats.strike_out() def __stats_run(self, scorer): '''Run.''' self.bat_team.player(scorer).stats.batting.run() self.current_pitcher.run() self.pitch_team_stats.run() self.bat_team_stats.run() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T04:17:34.890", "Id": "32890", "Score": "0", "body": "don't use names like `__foo`. it doesn't do anything useful, and it certainly doesn't keep anyone else from mucking around in your class; it's just annoying magic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:27:35.513", "Id": "32926", "Score": "0", "body": "It's intended to differentiate methods from those that are meant to be called by a user/consumer of this class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T19:48:50.730", "Id": "32939", "Score": "1", "body": "no, that's what `_foo` is for. `__foo` does name mangling, and at a glance looks like it's supposed to be `__foo__`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T20:39:40.190", "Id": "32953", "Score": "0", "body": "Yes, you're right, I think they should be single underscores. Not sure how I misread the docs the first time." } ]
[ { "body": "<p>Don't pass in the name of your database file. You should pass in a database connection object. As it stands you reopen the database in many different places across your code. You should really only open the database once and pass the connection around. If you do this:</p>\n\n<ol>\n<li>Your code will be simplified</li>\n<li>Your code will be more efficient</li>\n<li>You'll be able to run your unittests on the :memory: database which will make them faster.</li>\n</ol>\n\n<p>Extract a <code>GameStats()</code> object. All those <code>__stats_*</code> methods should be methods on that object. The fact that you have a bunch of methods with those prefixes is a big hint. A sizable chunk of the <code>Game</code> class seems to be concerned with those stats, and so its a good candidate for extraction.</p>\n\n<p>Don't use <code>__str__</code> for output. It's supposed to be a string representation of your object, not your user output. I'd actually pull all user output out of this (and your other classes). Its better if you have some objects purely dedicated to the logic of he game. Have completely separately classes to do the user output. </p>\n\n<p>Much of logic in <code>Game</code> should really be on <code>Inning</code> or <code>Count</code>. For example, the <code>strike</code> method.</p>\n\n<pre><code>def strike(self):\n '''Pitcher throws a strike.\n\n If there are 2 strikes, call the __strike_out method.\n Otherwise, just increment the strike count.\n\n '''\n if self.count.strikes == 2:\n self.__strike_out()\n else:\n self.count.strike()\n</code></pre>\n\n<p>Much of the logic here is concerned with the number of strikes which is <code>Count</code>'s domain. This function is thus calling out to be moved to <code>Count</code>. But you can't because you need to call <code>__strike_out</code>. You've got the relationship between <code>Count</code> and <code>Game</code> backwards. <code>Count</code> should have a reference to and call <code>Game</code> when there is a strike out. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T03:33:20.373", "Id": "20364", "ParentId": "20358", "Score": "4" } }, { "body": "<p>Your <code>__walk()</code> method is a good place to start.</p>\n\n<pre><code>def __walk(self, hbp=False):\n if not hbp:\n self.__stats_walk()\n if self.bases[0] != 0:\n if self.bases[1] != 0:\n if self.bases[2] != 0:\n self.__score_run(self.bases[2])\n self.__stats_rbi()\n else:\n self.bases[2] = self.bases[1]\n else:\n self.bases[1] = self.bases[0]\n else:\n self.bases[0] = self.bat_team.batter\n self.__next_batter()\n</code></pre>\n\n<p>Some of the problems I see there are:</p>\n\n<ul>\n<li>It has hard-coded logic for each of the four bases. A maxim of programming is that there are either none, one, two, or many. If there are four bases, then you should write your program as if there were a dozen bases.</li>\n<li>I don't think you have sufficiently modelled the objects involved in the game.</li>\n<li>It would be nice to separate the scorekeeping logic from the player movement logic.</li>\n</ul>\n\n<p>What is the definition of walking? Let's distill it down to its essence, and make it our goal to write the code as such:</p>\n\n<pre><code>def walk(self):\n self.bases[0].runner.advance(cascade=True)\n</code></pre>\n\n<p>Then let's see what kind of object modelling it takes to make that happen! Here's my proof-of-concept…</p>\n\n<pre><code>class Base:\n @staticmethod\n def make_diamond(game):\n bases = [\n Base(game, \"at bat\"),\n Base(game, \"first\"),\n Base(game, \"second\"),\n Base(game, \"third\"),\n HomeBase(game, \"home\"),\n ]\n for i in range(4):\n bases[i].next = bases[i + 1]\n bases[i + 1].prev = bases[i]\n return bases\n\n def __init__(self, game, name):\n self.game = game\n self.name = name\n self.runner = None\n\n def vacate(self):\n if self.runner:\n self.game.fire_event('left', self.runner, self)\n self.runner = None\n\n def accept(self, runner, cascade):\n self.game.fire_event('reached', runner, self)\n if self.runner and cascade:\n r = self.runner\n self.vacate()\n self.next.accept(r, True)\n self.runner = runner\n elif self.runner:\n runner.out()\n else:\n self.runner = runner\n\n def has_runner(self, runner):\n return self.runner == runner\n\n def __str__(self):\n return self.name\n\n######################################################################\n\nclass HomeBase(Base):\n def accept(self, runner, cascade):\n self.game.fire_event('scored', runner)\n\n def has_runner(self, runner):\n return False\n\n######################################################################\n\nclass Runner:\n number = 0\n\n def __init__(self, game):\n self.game = game\n self.name = \"Player %d\" % Runner.number\n Runner.number += 1\n\n def advance(self, cascade, num_bases=1):\n for i in range(num_bases):\n old_base = self.game.base_with_runner(self)\n if old_base:\n new_base = old_base.next\n old_base.vacate()\n new_base.accept(self, cascade)\n\n def out(self):\n self.game.fire_event('out', self)\n\n def __str__(self):\n return \"Runner %s\" % self.name\n\n######################################################################\n\nclass Play:\n def __init__(self, game, batter):\n self.game = game\n self.batter = batter\n\n######################################################################\n\nclass Game:\n def __init__(self):\n self.bases = Base.make_diamond(self)\n self.current_play = None\n self.event_listeners = []\n\n def next_batter(self):\n batter = Runner(self) # lineup.next_batter()\n self.bases[0].accept(batter, False)\n self.fire_event('at bat', batter)\n self.current_play = Play(self, batter)\n\n def hit_by_pitch(self):\n self.fire_event('hit by pitch', self.current_play.batter)\n self.bases[0].runner.advance(cascade=True)\n\n def walk(self):\n self.fire_event('walked', self.current_play.batter)\n self.bases[0].runner.advance(cascade=True)\n\n def base_with_runner(self, runner):\n return next(base for base in self.bases if base.has_runner(runner))\n\n\n def add_event_listener(self, listener):\n self.event_listeners.append(listener)\n\n def fire_event(self, event, *info):\n for listener in self.event_listeners:\n listener.handle(event, *info)\n\n######################################################################\n\nclass Statistician:\n def __init__(self, game):\n self.game = game\n game.add_event_listener(self)\n\n self.hit_by_pitch = 0\n self.runs = 0\n self.walks = 0\n\n def handle(self, event, *info):\n print (\"Event: %s %s \" % (info[0], event)) + ' '.join(map(str, info[1:]))\n if event == 'hit by pitch':\n self.hit_by_pitch += 1\n if event == 'scored':\n self.runs += 1\n if event == 'walked':\n self.walks += 1\n\n def __str__(self):\n return \"%d runs, %d HBP, %d walks\" % (self.runs, self.hit_by_pitch, self.walks)\n\n######################################################################\n\ndef test():\n g = Game()\n s = Statistician(g)\n\n g.next_batter()\n g.walk()\n g.next_batter()\n g.walk()\n g.next_batter()\n g.walk()\n g.next_batter()\n g.hit_by_pitch()\n\n print s\n\ntest()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T18:32:10.243", "Id": "30185", "ParentId": "20358", "Score": "3" } }, { "body": "<p>Another tip: you make \"output\" and then add to it a lot. Just make it right the first time! So, for example, in your <code>__str_finished_game</code> function, you can group the outputs from this:</p>\n\n<pre><code>def __str_finished_game(self):\n '''Output a finished game as a string.'''\n output = 'The game is over.\\n'\n output += 'The %s team won.\\n' % (self.winner)\n output += 'The final score was:\\n'\n output += '%s to %s' % (self.home.score, self.away.score)\n output += '\\n'\n if self.inning.number != self.inning.innings_per_game:\n output += 'The game took %s innings.\\n' % (self.inning.number)\n return output\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>def __str_finished_game (self):\n '''Output a finished game as a string.'''\n output = f'The game is over.\\nThe {self.winner} team won.\\nThe final score was:\\n{self.home.score} to {self.away.score}\\n.\"\n if self.inning.number != self.inning.innings_per_game: output += f\"The game took {self.inning.number} innings.\"\n return output\n</code></pre>\n\n<p>Note that the f-strings only work in later versions of Python 3 (since the 3.6 release), the concept is you can put it on one line. This saves a lot of lines because you do this many times throughout the program. Of course, you may want to intentionally do this for style, but this is definitely adding to your line total.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-26T05:00:12.310", "Id": "365377", "Score": "1", "body": "Welcome to Code Review! If you have a tip for the OP, try giving an example so it has some context. That will have more value as an answer than if it doesn't have it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-26T04:58:09.810", "Id": "190472", "ParentId": "20358", "Score": "1" } } ]
{ "AcceptedAnswerId": "20364", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:11:17.277", "Id": "20358", "Score": "4", "Tags": [ "python" ], "Title": "Gigantic class to model a baseball game" }
20358
<p>I am trying to factor integers using the trial division algorithm (Wikipedia: <a href="http://en.wikipedia.org/wiki/Trial_division" rel="nofollow">http://en.wikipedia.org/wiki/Trial_division</a>).</p> <p>I reviewed the Wikipedia entry for trial division and multiple other sources but I don't completely understand the trial division algorithm.</p> <p>I wrote the code below based on my findings and it finds all of the prime factors of a number.</p> <p>For example, input 20 and you get its prime factors 2 2 5. I would like to know if it can be simplified or better written (I want to stick with the trial division algorithm --- I don't plan on inputting numbers any larger than 9,999)?</p> <pre><code> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Prime Number Checker&lt;/title&gt; &lt;script&gt; window.onload = function() { // All the prime numbers under 1000 var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; // Find prime factors var n = 20; var primeFactors = ""; // Trial division algorithm for (var i = 0; primeNumbers[i] &lt; n; i++) { if (n % primeNumbers[i] == 0) { var temp = n; while (temp % primeNumbers[i] == 0) { temp = temp / primeNumbers[i]; primeFactors += " " + primeNumbers[i] + " "; } } } document.getElementById("divSolution").innerHTML = primeFactors; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="divSolution"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>A few comments :</p>\n\n<ol>\n<li><p>Before writing any code, perform the computation manually. How would you do it for 20? You'd do something along the lines like :</p>\n\n<ul>\n<li>let's try the first prime number : 2</li>\n<li>is 2 a divisor of 20 ? yes, it is. 20 is 2*10 so let's add 2 to the list of divisors and let's focus on 10 now.</li>\n<li>is 2 a divisor of 10 ? yes, it is. 10 is 2*5 so let's add 2 to the list of divisors and let's focus on 5 now.</li>\n<li>let's consider the next prime number. It's 3. Oh, 3*3 is actually bigger than 5 so we won't be able to find any other prime factor smaller than 5 : let's add 5 to the list of divisors.</li>\n<li>Try it yourself with numbers such a 8, 100, 19....</li>\n</ul></li>\n<li><p>Then, about your code : the first is I noticed that your loop condition is not right and you might get out of your array. Just try a value of n greater than 168 and you'll probably notice the issue.</p></li>\n</ol>\n\n<p>If you want to follow the wiki page and to something like : <code>for p in primes: if p*p &gt; n: break</code> what you really need to do is.</p>\n\n<pre><code>// Find prime factors\nvar n = 180;\nvar primeFactors = \"\";\n// Trial division algorithm\nfor (var i = 0, p=primeNumbers[i]; i &lt; primeNumbers.length &amp;&amp; p*p&lt;=n; i++, p=primeNumbers[i]) {\n while (n % p == 0) { \n primeFactors += \" \" + p + \" \";\n n/=p;\n }\n}\nif (n&gt;1)\n{\n primeFactors += \" \" + n + \" \";\n}\n\ndocument.getElementById(\"divSolution\").innerHTML = primeFactors;\n</code></pre>\n\n<p>(Sorry for rewriting the whole code)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T03:57:24.343", "Id": "20366", "ParentId": "20362", "Score": "2" } } ]
{ "AcceptedAnswerId": "20366", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T01:19:27.150", "Id": "20362", "Score": "0", "Tags": [ "javascript" ], "Title": "Integer Factorization using the Trial Division Algorithm" }
20362
<p>I'm not sure if there's a standard view where the placement of a success result should be in a conditional that can return multiple statuses. The success condition of this function is in the middle of the conditional block:</p> <pre><code>def redeem(pin) success = false message = nil if !self.date_claimed.nil? message = 'Reward already claimed' elsif self.reward.redemption_pin == pin success = true self.date_claimed = Time.zone.now self.save else message = "Wrong pin" end return {:success =&gt; success, :message =&gt; message} end </code></pre> <p>I could rewrite it to be at the end:</p> <pre><code>def redeem(pin) success = false message = nil if !self.date_claimed.nil? message = 'Reward already claimed' elsif self.reward.redemption_pin != pin message = "Wrong pin" else success = true self.date_claimed = Time.zone.now self.save end return {:success =&gt; success, :message =&gt; message} end </code></pre> <p>or I could rewrite it to be at the top but conditions become slightly more complex:</p> <pre><code>def redeem(pin) success = false message = nil if self.reward.redemption_pin == pin &amp;&amp; self.date_claimed.nil? success = true self.date_claimed = Time.zone.now self.save elsif date_claimed message = 'Reward already claimed' else message = "Wrong pin" end return {:success =&gt; success, :message =&gt; message} end </code></pre> <p>I personally think I prefer it to be at the beginning or the end, but in this function the end seems to be the best place.</p>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li><p>Imperative programming has its use cases (or so I've heard :-)) but implementing logic is definitely not one of them. <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">Some thoughts</a> on the matter. Use always expressions, not statements, to describe logic; that's it, don't begin with a <code>x = 1</code> and then modify <code>x</code> somewhere else in the code. Write expression branches instead (conditionals are in expressions in Ruby). Don't think in terms of \"how\" but in terms of \"what\".</p></li>\n<li><p><code>if !x.nil?</code> -> <code>if x</code>.</p></li>\n<li><p><code>obj.save</code> may fail but you are not checking it.</p></li>\n<li><p>Don't write explicit <code>return</code> (more on <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms\" rel=\"nofollow\">idiomatic Ruby</a>).</p></li>\n<li><p>As you say the order of checks is important. I usually check for \"problems\" first, and keep the \"ok\" scenario for the last branch.</p></li>\n<li><p>You are using a value (a hash) instead of an exception to signal errors. It's slightly not idiomatical in Ruby (in the sense that people tend not to do it, not that there's anything wrong with it), but personally I like it (and use it).</p></li>\n</ul>\n\n<p>You could write:</p>\n\n<pre><code>def redeem(pin)\n success, message = if date_claimed\n [false, 'Reward already claimed']\n ...\n end\n {:success =&gt; success, :message =&gt; message}\nend\n</code></pre>\n\n<p>However, returning <code>{success: ..., message: ...}</code> on each branch, yet slightly more verbose, looks pretty nice and declarative:</p>\n\n<pre><code>def redeem(pin)\n if date_claimed\n {success: false, message: \"Reward already claimed\"}\n elsif reward.redemption_pin != pin\n {success: false, message: \"Wrong pin\"}\n else \n update_attribute(:date_claimed, Time.zone.now)\n {success: true}\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T11:39:43.237", "Id": "32620", "Score": "1", "body": "I wasn't aware that I could assign variables via an array like that. Thanks a ton for the thorough answer and explanation. I also like the second style more." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T09:16:26.163", "Id": "20372", "ParentId": "20367", "Score": "2" } }, { "body": "<p>I don't like this </p>\n\n<pre><code>success = false\n</code></pre>\n\n<p>at the beginning.</p>\n\n<p>You can remove it, and later in your code use the double bang to get a boolean value</p>\n\n<pre><code>return {:success =&gt; !!success, :message =&gt; message}\n</code></pre>\n\n<p>I mean get rid of lines that didn't provide any functionality, in this case you will save a line, remaining the reability of the code.</p>\n\n<p>And when you set success to true, always write the condition for it, when it should be true.\nIn your second example, you mark your method as sucessfull in an else block. That means for me: \"If none of the previous conditions met, I'm sucesful\", but what happens, when aditional failure scenario will be written above the else block, or other stuff happen above the else block ?</p>\n\n<p>You definately should precise describe the conditions for a sucess state (like example 3)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T10:29:43.580", "Id": "20412", "ParentId": "20367", "Score": "0" } } ]
{ "AcceptedAnswerId": "20372", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T04:16:32.790", "Id": "20367", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Placement of success code in a conditional" }
20367
<p>Here is an algorithm to evaluate best matching <code>System.Type</code> for two types in hierarhy. This is one of answers for <a href="https://stackoverflow.com/q/14107683/443366">this StackOverflow question</a> by Ken Kin:</p> <blockquote> <p>Evaluate the maximum possible type to fit both of types</p> </blockquote> <h3>Algorithm</h3> <ol> <li>Searching for common base class (either concrete or abstract) <ul> <li><code>FindBaseClassWith</code> method</li> </ul></li> <li>If there is no common base class, search for common implemented interface <ul> <li>It's possible for one class to implement multiple interfaces, in this case return first common based interface</li> <li><code>FindInterfaceWith</code> method</li> </ul></li> </ol> <h3>Questions</h3> <ol> <li><code>GetInterfaceHierarchy</code> implementaion <ul> <li>I'm not sure that this is <em>correct</em> implementation in case of complex class hierarhy with many implemented interfaces</li> <li>Now all tests are passing for selected collection from BCL and my own testing hierarhy</li> </ul></li> <li>Are there any other flaws that I do not pay attention to?</li> <li>I had wrote this sample in LinqPad, that's why all unittests are located at <code>Main</code> method. Nevertheless, any improvments to <code>Test.Assert</code> are ok!</li> </ol> <p><strong>Full source code</strong> with unittests is available <a href="https://gist.github.com/4442677" rel="nofollow noreferrer">here</a></p> <pre><code>// provide common base class or implemented interface public static Type FindEqualTypeWith(this Type typeLeft, Type typeRight) { if(typeLeft == null || typeRight == null) return null; var commonBaseClass = typeLeft.FindBaseClassWith(typeRight) ?? typeof(object); return commonBaseClass.Equals(typeof(object)) ? typeLeft.FindInterfaceWith(typeRight) : commonBaseClass; } // searching for common base class (either concrete or abstract) public static Type FindBaseClassWith(this Type typeLeft, Type typeRight) { if(typeLeft == null || typeRight == null) return null; return typeLeft .GetClassHierarchy() .Intersect(typeRight.GetClassHierarchy()) .FirstOrDefault(type =&gt; !type.IsInterface); } // searching for common implemented interface // it's possible for one class to implement multiple interfaces, // in this case return first common based interface public static Type FindInterfaceWith(this Type typeLeft, Type typeRight) { if(typeLeft == null || typeRight == null) return null; return typeLeft .GetInterfaceHierarchy() .Intersect(typeRight.GetInterfaceHierarchy()) .FirstOrDefault(); } // iterate on interface hierarhy public static IEnumerable&lt;Type&gt; GetInterfaceHierarchy(this Type type) { if(type.IsInterface) return new [] { type }.AsEnumerable(); return type .GetInterfaces() .OrderByDescending(current =&gt; current.GetInterfaces().Count()) .AsEnumerable(); } // interate on class hierarhy public static IEnumerable&lt;Type&gt; GetClassHierarchy(this Type type) { if(type == null) yield break; Type typeInHierarchy = type; do { yield return typeInHierarchy; typeInHierarchy = typeInHierarchy.BaseType; } while(typeInHierarchy != null &amp;&amp; !typeInHierarchy.IsInterface); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T11:40:07.767", "Id": "32903", "Score": "2", "body": "Seems SE is a quiet and peaceful place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T08:58:36.487", "Id": "33069", "Score": "0", "body": "What is the question here? Do you want to hear comments on implementation, or poking for a different approach? And the main question - why do you need this functionality? I've never had the need to find common base classes using reflection" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T09:34:24.830", "Id": "33072", "Score": "0", "body": "This is [an answer for question on StackOverflow](http://stackoverflow.com/q/14107683/443366). If you've any comments regarding implemetation, you're welcome" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T10:25:43.820", "Id": "33267", "Score": "1", "body": "\"I'm not sure that this is *correct* implementation in case of complex class hierarhy with many implemented interfaces\". Please define *correct*." } ]
[ { "body": "<p>Your code does not take in account interface covariance and contravariance issues.</p>\n\n<p>Here is the sample code that demonstrates it:</p>\n\n<pre><code>class ObservableOfString : IObservable&lt;string&gt; { /*...*/ }\nclass ObservableOfObject : IObservable&lt;object&gt; { /*...*/ }\nclass ObserverOfObject : IObserver&lt;object&gt; { /*...*/ }\nclass ObserverOfString : IObserver&lt;string&gt; { /*...*/ }\nclass Program\n{\n\n static void Main(string[] args)\n {\n IObservable&lt;object&gt; observableIsCovariant = new ObservableOfString();\n IObserver&lt;string&gt; observerIsContravariant = new ObserverOfObject();\n Console.WriteLine(typeof(ObservableOfString).FindEqualTypeWith(typeof(ObservableOfObject)) ?? (object)\"&lt;NULL&gt;\"); // Would it not be more useful to return IObservable&lt;object&gt;?\n Console.WriteLine(typeof(ObserverOfString).FindEqualTypeWith(typeof(ObserverOfObject)) ?? (object)\"&lt;NULL&gt;\"); // Would it not be more useful to return IObserver&lt;string&gt;?\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>The fundamental issue is, as soon as you want to find the \"best common interface\", you are going to run in an issue, as \"best\" and \"common\" are at best dependent on the context. You should clearly identify which use cases you are going to support, in the context of <em>why</em> that method was needed, and write a specific implementation that solves your need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T10:48:38.983", "Id": "20756", "ParentId": "20369", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T06:27:59.767", "Id": "20369", "Score": "8", "Tags": [ "c#", "reflection" ], "Title": "Evaluate the best common type to fit both of types" }
20369
<p>I'm finally "done" with my small prototype for an element inside my website. I'm just a learner in the jQuery code and that reflects in my code. It's bloated, a lot of functions do the same thing, but for a red or green button which results in this kind of code.</p> <pre><code>$('.submenu').on('click','.rood',function() { $(this).closest('.container_vragen').fadeOut(400, function() { $(this).closest('.container_vragen').css({overflow : 'hidden', color : 'red'}); $(this).closest('.container_vragen').appendTo("#niet_geregeld"); $(this).closest('.container_vragen').fadeIn(400); }); }); $('.submenu').on('click','.groen',function() { $(this).closest('.container_vragen').fadeOut(400, function() { $(this).closest('.container_vragen').css({overflow : 'hidden', color : 'green'}); $(this).closest('.container_vragen').appendTo("#geregeld"); $(this).closest('.container_vragen').fadeIn(400); }); }); </code></pre> <p>As you can see most of the functions are the same, only the color and the <code>.appedTo</code> id changes. What's the best way to merge this code? I'm thinking there needs to be an <code>if</code> statement which filters what button is clicked. But I can't figure it out on my own.</p>
[]
[ { "body": "<p>Make a function.</p>\n\n<pre><code>function doStuff(obj, c) {\n obj.css({overflow: 'hidden', color: c}).fadeIn(400);\n}\n</code></pre>\n\n<p>Then call it</p>\n\n<pre><code>$('#submenu').click(function () {\n doStuff($('#geregeld'), 'green');\n});\n</code></pre>\n\n<p>(simplified example) </p>\n\n<p>Feel free to mess around: <a href=\"http://jsfiddle.net/rQFHt/\" rel=\"nofollow\">http://jsfiddle.net/rQFHt/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T18:50:58.880", "Id": "32650", "Score": "0", "body": "I understand what you're trying to do, but it's not working. If I use this code the click action on .groen is not calling the doStuff function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:50:12.980", "Id": "32662", "Score": "0", "body": "@PeterBoomsma : updated :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T10:34:53.780", "Id": "20374", "ParentId": "20373", "Score": "1" } }, { "body": "<p>You should think about chaining, to avoid repeating some class names :</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function doAnimation($element, $destElement, animationColor) {\n var $container_vragen = $element.closest('.container_vragen');\n $container_vragen.fadeOut(400, function() {\n $container_vragen.css({\n overflow : 'hidden',\n color : animationColor\n })\n .appendTo($destElement)\n .fadeIn(400);\n });\n}\n\nvar $niet_geregeld = $('#niet_geregeld');\nvar $geregeld = $('#geregeld');\n\n$('.submenu')\n.on('click','.rood',function() {\n doAnimation($(this), $niet_geregeld,'red');\n})\n.on('click','.groen',function() {\n doAnimation($(this), $geregeld,'green');\n});\n</code></pre>\n\n<p>I think preselecting <code>#geregeld</code> and <code>#niet_geregeld</code> is better for performances.</p>\n\n<p>You should rename the <code>doAnimation</code> function to its real purpose, like <code>animateSorting</code> or <code>animateForThatPurpose</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:07:50.460", "Id": "20382", "ParentId": "20373", "Score": "1" } }, { "body": "<p>Store your options separately, then loop over them:</p>\n\n<pre><code>var $submenu = $('.submenu');\nvar map = {\n 'rood': {\n color: 'red',\n appendTo: 'niet_geregeld'\n },\n 'groen': {\n color: 'green',\n appendTo: 'geregeld'\n }\n};\n\n$.each(map, function (elClass, options) {\n $submenu.on('click', '.' + elClass, function () {\n\n var $container = $(this).closest('.container_vragen');\n\n $container.fadeOut(400, function() {\n $container\n .css({overflow : 'hidden', color : options.color})\n .appendTo(\"#\" + options.appendTo)\n .fadeIn(400);\n });\n\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:04:07.303", "Id": "20390", "ParentId": "20373", "Score": "1" } }, { "body": "<p>You can combine the two like this</p>\n\n<pre><code>$('.submenu').on('click', '.groen,.rood', function () {\n var $el = $(this);\n var red = $el.is('.rood'); // is this element .rood\n $el.closest('.container_vragen').css({\n overflow: 'hidden',\n color: red ? 'red' : 'green' // if it's .rood make it red.. else make green\n })\n .appendTo(red ? \"#niet_geregeld\" : \"#geregeld\") // if .rood appendto #niet_geregeld else append to #geregeld\n .fadeIn(400)\n});\n</code></pre>\n\n<p>and use chaining so you don't have to keep querying the dom for the element.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:32:07.487", "Id": "20446", "ParentId": "20373", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T09:23:30.197", "Id": "20373", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Element inside a website" }
20373
<p>I have this method that basically takes a string and does different things depending on what the string starts with. Is there a cleaner way to write this method?</p> <pre><code>public String analyze(BotMessage message) { String lcmsg = message.message().toLowerCase(); //Not a command if(!lcmsg.startsWith("!")) return "-1"; //Message from whatever if(lcmsg.startsWith("!ping")) return "pong!"; if(lcmsg.startsWith("!tournament")) return tournament(message); //message from skype if(message.skype()) { if(lcmsg.startsWith("!settournament")) return settournament(message); if(lcmsg.startsWith("!promote")) return promote(message); if(lcmsg.startsWith("!checkin")) return checkin(message); if(lcmsg.startsWith("!checkout")) return checkout(message); if(lcmsg.startsWith("!checkedin")) return checkedin(message); if(lcmsg.startsWith("!updatetournament")) return updatetournament(); } return "-1"; } </code></pre>
[]
[ { "body": "<p>You can use Observer/Observable pattern for the <code>if(message.skipe(){..}</code> area.</p>\n\n<p>So each each observer evaluate the <code>if</code> and run the method (the methods are wrote inside the Observer).</p>\n\n<p>If a new test is needed, you have just to had a new Observer with no impact on other Observers.</p>\n\n<p>Many useful patterns are very clearly explained in O'Reilly \"Head First Design Patterns\" book.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:41:51.430", "Id": "32636", "Score": "0", "body": "The problem is that the class already is Observable so I feel it would just add confusion to make it an Observer aswell(if even possible)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:51:49.543", "Id": "32642", "Score": "0", "body": "@warbio no it is not a problem : for Java it is powerful to be an `observer observable` for managing nested/complex logical choices. To help maintenance you can put observers in a sub-package of observable, so hierarchy is visible at the first glance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T12:57:24.093", "Id": "20377", "ParentId": "20375", "Score": "1" } }, { "body": "<p>I don't like too much the fact that you use a <code>String</code> as the returned type of your function.</p>\n\n<p>What about using a class hierarchy or exceptions?</p>\n\n<p>I see opportunities to create a hierarchy even for the messages. Why don't you create a <code>BotMessage</code> and a <code>SkypeMessage</code>?</p>\n\n<p>Both should have the logic to decide what to do in the base case, maybe in an <code>analyze</code> method. The <code>analyze</code> method of the <code>SkypeMessage</code> should, in addition, manage the Skype-specific aspects.</p>\n\n<p>Finally you should simplify the code and remove the list of if statements.\nIntroduce a new set of objects to parse the messages. These objects should have a <code>match</code> method that check whether the string matches with their definition, and a <code>performAction</code> method that generates the return value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:51:12.630", "Id": "32641", "Score": "0", "body": "I like the idea of creating new classes to handle the commands because what I really want is it get rid of those nasty if-statements. As for the return type it wouldn't really help in this scenario to change it because of how the rest of the application works." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:16:59.247", "Id": "20383", "ParentId": "20375", "Score": "2" } }, { "body": "<p>For anyone interested I managed to rewrite the method following @mariosangiorgio advice.\nI made a Command interface and gave each command a own class.</p>\n\n<pre><code>public String analyze(Message message)\n{ \n //Not a command\n if(!message.getMessage().startsWith(\"!\")) return \"-1\";\n\n for(Command cmd : commands)\n {\n if(cmd.Match(message)) return cmd.preformAction(message);\n }\n\n return \"-1\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T07:26:14.243", "Id": "66059", "Score": "0", "body": "Returning `\"-1\"` still falls into the \"stringly typed\" antipattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T21:55:11.433", "Id": "20398", "ParentId": "20375", "Score": "0" } } ]
{ "AcceptedAnswerId": "20383", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T10:55:14.297", "Id": "20375", "Score": "5", "Tags": [ "java", "strings" ], "Title": "Conditional execution based on input string's prefix" }
20375
<p>I have inherited a node-js project, and I am completely new to it. Fortunately, it is already covered by unit tests.</p> <p>The class under test, <code>FmsRescuers</code>, has the responsibility of sending HTTP requests to a remote server. </p> <p>My first refactoring was to extract the HTTP behavior into the <code>HttpRequest</code> class, to allow testing that an operation requests the correct url with the correct data, without actually performing the http request. The <code>HttpRequest</code> class did not previously exist.</p> <p>I am looking for feedback on the unit test from a perspective of best practices. In particular, how do I best avoid the duplication of calling the <code>checkIn</code> function through the different tests?</p> <pre><code>require('../server/extensions'); var FmsRescuers = require('../server/fms_rescuers'); var Rescuer = require('./stubs/helper').Rescuer; var requestedPath; var requestedStationNumber; var requestedRescuerNumber; var httpRequest = { post: function(path, requestData, callback) { requestedPath = path; requestedStationNumber = requestData.stationNumber; requestedRescuerNumber = requestData.rescuerNumber; callback('', 200); } }; var rescuers = new FmsRescuers(httpRequest); var rescuer = new Rescuer(42, 'Name', new Date().addHours(-2).toTimeZonedString(), new Date().addHours(-1).toTimeZonedString()); exports.testCheckIn = { setUp: function(callback) { requestedPath = undefined; requestedStationNumber = undefined; requestedRescuerNumber = undefined; callback(); }, 'check in requests correct path' : function(test) { rescuers.checkIn(rescuer, 123, 3, function(result, status) { test.equal(requestedPath, '/attendance/checkin'); test.done(); }); }, 'check in sends correct station number' : function(test) { rescuers.checkIn(rescuer, 123, 3, function(result, status) { test.equal(requestedStationNumber, 123); test.done(); }); }, 'check in sends correct rescuer number' : function(test) { rescuers.checkIn(rescuer, 123, 3, function(result, status) { test.equal(requestedRescuerNumber, 42); test.done(); }); } }; </code></pre>
[]
[ { "body": "<p>You could use sinon.js to have the power of spies, stubs and mocks. <a href=\"http://sinonjs.org/\" rel=\"nofollow\">http://sinonjs.org/</a></p>\n\n<p>That way you could create a stub of <code>httpRequest</code>.</p>\n\n<p>Look for <code>stub.yield([arg1, arg2, ...])</code>.</p>\n\n<p><strong>Edit</strong> I added a code example. I did not fully tested the code, but it's how it would look like.</p>\n\n<pre><code>var sinon = require('sinon');\nrequire('../server/extensions');\nvar FmsRescuers = require('../server/fms_rescuers');\nvar Rescuer = require('./stubs/helper').Rescuer;\n\nvar mockedHttpRequest;\nvar rescuers;\nvar rescuer;\n\nexports.testCheckIn = { \n setUp: function(done) {\n var httpRequest { post: function () {} };\n mockedHttpRequest = sinon.mock(httpRequest); \n rescuers = new FmsRescuers(mockedHttpRequest); \n rescuer = new Rescuer(42, 'Name', new Date().addHours(-2).toTimeZonedString(), new Date().addHours(-1).toTimeZonedString());\n\n },\n\n 'check in requests correct path' : function(test) {\n var expectedPath = '/attendance/checkin'\n mockedHttpRequest\n .expects('post')\n .once()\n .withArgs(expectedPath)\n .yields('', 200);\n\n rescuers.checkIn(rescuer, 123, 3, function(result, status) {\n mockedHttpRequest.verify();\n test.equal(result, '');\n test.equal(status, 200);\n test.done();\n });\n },\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T12:49:41.173", "Id": "70381", "Score": "0", "body": "I added a code sample." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T21:20:57.210", "Id": "41002", "ParentId": "20379", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T13:59:09.320", "Id": "20379", "Score": "4", "Tags": [ "javascript", "unit-testing", "node.js" ], "Title": "Does this nodeunit test conform to best practices?" }
20379
<p>I have a DataSet with only two tables in it. The first table is a list of models (of products) with default parameters (settings), and the second table is a list of modules. A module is a product based on a given model but with some parameters that have been changed. A sample DataSet in XML format could be something like this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Parameters&gt; &lt;Model&gt; &lt;IdModel&gt;1&lt;/IdModel&gt; &lt;Par1&gt;10&lt;/Par1&gt; &lt;Par2&gt;0.5&lt;/Par2&gt; &lt;Par3&gt;15&lt;/Par3&gt; &lt;/Model&gt; &lt;Model&gt; &lt;IdModel&gt;2&lt;/IdModel&gt; &lt;Par1&gt;20&lt;/Par1&gt; &lt;Par2&gt;0.5&lt;/Par2&gt; &lt;Par3&gt;20&lt;/Par3&gt; &lt;/Model&gt; &lt;Module&gt; &lt;IdModule&gt;11&lt;/IdModule&gt; &lt;IdModel&gt;1&lt;/IdModel&gt; &lt;Par1&gt;11&lt;/Par1&gt; &lt;/Module&gt; &lt;Module&gt; &lt;IdModule&gt;12&lt;/IdModule&gt; &lt;IdModel&gt;1&lt;/IdModel&gt; &lt;Par3&gt;12&lt;/Par3&gt; &lt;/Module&gt; &lt;Module&gt; &lt;IdModule&gt;21&lt;/IdModule&gt; &lt;IdModel&gt;2&lt;/IdModel&gt; &lt;Par1&gt;21&lt;/Par1&gt; &lt;/Module&gt; &lt;/Parameters&gt; </code></pre> <p>What I need to do is to retrieve a module in this "database" and its parameters. The parameters are the default ones (those of the corresponding model) but with the personnalized ones that have been specified in the XML.</p> <p>I managed to retrieve such data but in a very non-efficient and non-elegant way as don't know much of SQL or Linq requests :</p> <pre><code> private static void RetrieveLaserSettings(DataSet ds, string Id) { //Retrieve the two tables from dataset DataTable Models = ds.Tables["Model"]; DataTable Modules = ds.Tables["Module"]; //The corresponding model and module Dictionary&lt;string, string&gt; model = new Dictionary&lt;string, string&gt;(); Dictionary&lt;string, string&gt; module = new Dictionary&lt;string, string&gt;(); //Look for the right module DataRow[] rowsModules = Modules.Select("IdModule = " + Id); if(rowsModules.Length &gt; 0) { if(rowsModules.Length &gt; 1) { Console.WriteLine("Several modules with the same ID"); return; } //Fill the data DataRow rowModule = rowsModules[0]; for(int i = 0; i &lt; rowModule.Table.Columns.Count; i++) { string columnName = rowModule.Table.Columns[i].ColumnName; string colValue = rowModule.ItemArray[i].ToString(); module.Add(columnName, colValue); } //Look for the model string modelId = rowModule["IdModel"].ToString(); DataRow[] rowsModels = Models.Select("IdModel = " + modelId); if(rowsModels.Length &gt; 0) { if(rowsModels.Length &gt; 1) { Console.WriteLine("Several models with the same ID"); return; } //Fill the data DataRow rowModel = rowsModels[0]; for(int i = 0; i &lt; rowModel.Table.Columns.Count; i++) { string columnName = rowModel.Table.Columns[i].ColumnName; if(string.Equals(columnName, "IdModel")) continue; string colValue = rowModel.ItemArray[i].ToString(); foreach(KeyValuePair&lt;string, string&gt; pair in module) { if(string.Equals(columnName, pair.Key.ToString()) &amp;&amp; !string.IsNullOrEmpty(pair.Value.ToString())) { colValue = pair.Value.ToString(); } } model.Add(columnName, colValue); } } } //Display the result foreach(KeyValuePair&lt;string, string&gt; pair in model) { Console.WriteLine(pair.Key.ToString() + " : " + pair.Value.ToString()); } } </code></pre> <p>Any help or suggestion is welcome !! Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:01:14.767", "Id": "32623", "Score": "1", "body": "Side note: do your really need to call `ToString()` on `string` property: `pair.Value.ToString()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:01:30.013", "Id": "32624", "Score": "1", "body": "Instead of using two `Dictionary<string, string>` create a `Model` and `Module` classes. then create a `List<Model>` this will allow you to neaten up the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:05:53.543", "Id": "32625", "Score": "0", "body": "(Alexei), it is indeed not necessary, but just in case, to be sure...\n(Jastill) That is what I'll do in a not so far future because a Module is in fact a model with personnalized parameters. I just wanted here to be more generic and to be XML driven instead of fixing the schema in a class. The \"exercise\" here is to play with kind of relational tables instead of searching by hand in tables.\nThanks for your comments !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:49:05.903", "Id": "32626", "Score": "0", "body": "@G_A Rest assured, you can be sure that `pair.Value` will always return a string or a null reference. The only things that the `ToString()` call adds is the overhead of an extra method call (possibly optimized away, but not necessarily) and the possibility of a NullReferenceException." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:55:21.073", "Id": "32627", "Score": "0", "body": "If it's a classic one-to-many (parent/child) relationship you have, you might find it helpful to add a DataRelation to the dataset: http://msdn.microsoft.com/en-us/library/dbwcse3d%28v=VS.80%29.aspx" } ]
[ { "body": "<p>Really, all I did was refactor your code into smaller methods.</p>\n\n<p>I'm loading the <code>Module</code> properties and values into a dictionary. I then get the corresponding <code>Model</code> and load it's properties into the same dictionary. During the filling of the dictionary, it ignores any data that is null, or if it has already been loaded.</p>\n\n<p>You can change the code to load the <code>Model</code> first and then the `Module if need be. If this doesn't help, I hope it atleast gets you on the right track.</p>\n\n<pre><code>private static void RetrieveLaserSettings(DataSet ds, string id)\n{\n try\n {\n var keydata = new Dictionary&lt;string, string&gt;();\n LoadData(keydata, ds.Tables[\"Module\"], string.Format(\"IdModule = {0}\", id));\n if (keydata.ContainsKey(\"IdModel\"))\n LoadData(keydata, ds.Tables[\"Model\"], string.Format(\"IdModel = {0}\", keydata[\"IdModel\"]));\n\n foreach (KeyValuePair&lt;string, string&gt; pair in keydata)\n {\n Console.WriteLine(pair.Key.ToString() + \" : \" + pair.Value.ToString());\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n\nprivate static void LoadData(IDictionary&lt;string, string&gt; keyVals, DataTable table, string idSelect)\n{\n DataRow[] rowsModules = table.Select(idSelect);\n if (rowsModules.Length &gt; 0)\n {\n if (rowsModules.Length &gt; 1)\n {\n throw new Exception(string.Format(\"Several {0}s with the same ID\",table.TableName));\n }\n FillRowDataInDictionary(keyVals, rowsModules[0]);\n }\n}\n\nprivate static void FillRowDataInDictionary(IDictionary&lt;string, string&gt; keyVals, DataRow dataRow)\n{\n for (var i = 0; i &lt; dataRow.Table.Columns.Count; i++)\n {\n var columnName = dataRow.Table.Columns[i].ColumnName;\n var colValue = dataRow.ItemArray[i];\n // Making sure we only want values that are not null and not already populated\n if (colValue!=DBNull.Value &amp;&amp; !keyVals.ContainsKey(columnName))\n {\n keyVals.Add(columnName, colValue.ToString());\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T14:33:58.733", "Id": "32628", "Score": "0", "body": "Thank you Shane, it is indeed more readable, I feel ashamed of my draft (because it is just a simple test of feasability). But as Steve Wellens suggested, I'll take a look at DataRelation in the DataSet which seems to be closer of what I'm searching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T14:57:10.430", "Id": "32629", "Score": "0", "body": "@G_A Don't feel bad about your code. Software is always a work in progress. I've written stuff much worse than that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T04:30:32.490", "Id": "20381", "ParentId": "20380", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T02:57:16.490", "Id": "20380", "Score": "1", "Tags": [ "c#", "sql", "xml", "linq" ], "Title": "(More) efficient and elegant way to retrieve data from a dataset?" }
20380
<p>Before, I had this code, sometimes it is longer:</p> <pre><code>String dbEntry = "idBldgInfo = '" + currentBldgID + "',scenario = '305',installCost='" + installCost + "',annualSave='" + annualSave + "',simplePayback='" + simplePayback + "',kwhPre='" + preKWH + "',kwhPost='" + postKWH + "',co2Pre='" + preCO2e + "',co2Post='" + postCO2e + "',mbtuPre='" + preMBtu + "',mbtuPost='" + postMBtu + "',shortDescription='" + econ4ShortDescription + "',category='" + category + "',longDescription='" + econ4LongDescription + "'"; </code></pre> <p>I refactored it into:</p> <pre><code>String newDbEntry = getDBEntryFromDBPairs( new DBPair("idBldgInfo", currentBldgID), new DBPair("scenario", "305"), new DBPair("installCost", installCost), new DBPair("annualSave", annualSave), new DBPair("simplePayback", simplePayback), new DBPair("kwhPre", preKWH), new DBPair("kwhPost", postKWH), new DBPair("co2Pre", preCO2e), new DBPair("co2Post", postCO2e), new DBPair("mbtuPre", preMBtu), new DBPair("mbtuPost", postMBtu), new DBPair("shortDescription", econ4ShortDescription), new DBPair("category", category), new DBPair("longDescription", econ4LongDescription)); </code></pre> <p>It looks only slightly better. Is it worth changing it?</p> <p>The <code>getDBEntryFromDBPairs</code> method is much more efficient since it uses a StringBuilder. But IDK. Any thoughts/suggestions are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:39:10.433", "Id": "32635", "Score": "1", "body": "What are you going to do with that `dbEntry`?\n\nBe sure you are not going to concatenate it with other strings to build a SQL query, it is extremely risky and will lead to [SQL Injections](http://en.wikipedia.org/wiki/SQL_injection)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:43:09.390", "Id": "32637", "Score": "0", "body": "@Mariosangiorgio All values are locally computed, the only one that is not is `currentBldgID`. `currentBldgID` is valided in the front-end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:48:12.093", "Id": "32639", "Score": "1", "body": "What are you using to connect to the database? Usually you can create a prepared statement and then use the APIs to create the bindings between the columns in the database and the values you want to store.\n\nMoreover, why aren't you using an Object Relational Mapping framework that would take care of persistence for you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:54:17.573", "Id": "32643", "Score": "0", "body": "@mariosangiorgio I am trying to make the best out of the code I inherited. I have not used Hibernate before, but might be a good learning experience. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T16:27:36.403", "Id": "32646", "Score": "0", "body": "Are you working on some legacy code?\nBe aware that introducing Hibernate in the project you will probably need to do a lot of refactoring." } ]
[ { "body": "<p>Your first implemenattion also uses <code>StringBuilder</code> under the hood.\nSee javadoc of <code>java.lang.String</code>:</p>\n\n<blockquote>\n <p>The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method</p>\n</blockquote>\n\n<p>So you cannot expect an speed improvement by your second version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T18:13:25.290", "Id": "32649", "Score": "0", "body": "Well, JLS only says it may do that. So why not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T18:51:41.913", "Id": "32651", "Score": "0", "body": "Experience shows it is done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:00:06.637", "Id": "32654", "Score": "0", "body": "I tried to make a test. But JIT optimizes the hell out of it, so the + concatenation turns out faster." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T16:53:09.160", "Id": "20387", "ParentId": "20385", "Score": "0" } }, { "body": "<p>I think your second approach is better. It is more readable and more easily maintained. I don't have much experience with databases, but lets say (sorry if its a stupid example) there is a database that causes problems for strings like \"<code>colId = colValue</code>\", and to fix it you need to remove the spaces. How many places there would be where you will go through <code>String dbEntry = ...;</code> statements to correct this problem? What if for a certain database you need to use <code>:</code> instead of <code>=</code>? Using data structures like this is definitely going to make your life a lot easier in such cases.</p>\n\n<p>So the conclusion is, are there any such cases that you need to consider where you might need to go through your code and change the resultant string? Because changing DBPair's implementation once would be a lot easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:18:49.983", "Id": "20424", "ParentId": "20385", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T15:31:25.227", "Id": "20385", "Score": "3", "Tags": [ "java", "strings" ], "Title": "String Building" }
20385
<p><a href="http://projecteuler.net/problem=3" rel="nofollow">Project Euler problem 3</a> asks:</p> <blockquote> <p>What is the largest prime factor of the number 600851475143?</p> </blockquote> <p>The first step I took is to determine the highest value number I should be looking at as a possibility (600851475143 / 2). Next I wanted to check each prime number as I go to see if it is a factor of 600851475143. If so, I store it in a variable denoting the highest prime factor encountered so far. </p> <p>On running the program, the prime factor '6857' is the last output I am seeing for several minutes in my output. I entered this as the answer and it was correct. My problem is finding a way to streamline the algorithm to greatly reduce the processing time.</p> <pre><code>public class Euler3 { public static void main(String[] args) { long max = 600851475143L / 2; long lgstPrime = 1; boolean isPrime = true; for (int i=2; i&lt;max; i++){ for (int j=2; j&lt;=i; j++){ if ((i % j == 0) &amp;&amp; (j != i)) isPrime = false; } if ((isPrime) &amp;&amp; (600851475143L % i == 0)) lgstPrime = i; isPrime = true; //reset } System.out.println("\n" + "the largest prime factor of the number 600851475143 is " + lgstPrime); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:07:38.430", "Id": "32655", "Score": "0", "body": "Use `sieve of eratosthenes` to find the primes then go through all the primes from largest down to find the largest factor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:22:59.737", "Id": "32656", "Score": "0", "body": "@LokiAstari That wouldn't be a good approach at the OP's level. The question is clearly a homework or quiz at an introductory level to loop programming, so the question is neither about primes nor algorithms. It's possible that the OP doesn't even know how to use arrays yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:17:50.070", "Id": "32671", "Score": "0", "body": "the OP does know how to use arrays, and this isn't a hw assignment, it's from Project Euler's site. I'm just practicing some problems there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T21:58:15.637", "Id": "32679", "Score": "0", "body": "Learning about and/or deriving algorithms like the sieve, rather than brute-forcing an answer, is one of the primary purposes of Project Euler. This is a great example of it working right :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T07:59:41.117", "Id": "32688", "Score": "0", "body": "Be careful that the [upper bound](http://en.wikipedia.org/wiki/Primality_test) you have to test is not `n/2` but `sqrt(n)`" } ]
[ { "body": "<p>You can use other techniques to find primes <code>sieve of Eratosthenes</code>:<br>\nBut since this is a code review I will review the code you have:</p>\n\n<p>The easiest optimization is to record primes as you go.<br>\nA number is prime if it is not divisible by any of the primes you have already found. Thus you don't need to check a number against all smaller numbers just all smaller primes.</p>\n\n<pre><code>public class Euler3 {\n\npublic static void main(String[] args)\n{\n long max = 600851475143L / 2;\n long lgstPrime = 1;\n boolean isPrime = true;\n\n\n // I use ArrayList solely because I am too lazy to think of a better\n // dynamically expanding array structure. You may find that other\n // structures are better this is solely to demonstrate the algorithmic\n // change that can be done in the code.\n ArrayList&lt;long&gt; primes = new ArrayList&lt;long&gt;();;\n primes.add(2);\n primes.add(3);\n\n // start at 5 ( we have added 2/3 and know 4 is not prime).\n // You should make this the same type as your max\n // Just in case sombody changes the value of max to something much bigger\n // without looking at the code.\n\n // We know that all even number are not prime.\n // So we can increment this loop by 2 each time.\n\n // With quick maths you see that multiples of 3 will hit multiples of 2 on even\n // multiples but not on add. So if you do increments of 2 followed by 4\n // then you will skip all the multiples of 2 and 3 thus removing a lot of numbers\n\n long inc = 2;\n for (long i=5; i&lt;max; i += inc, inc = 6 - inc)\n {\n\n // Move this to the top of the loop\n // This makes the code eaaser to write.\n // As you show we are assuming prime and then checking\n // for failure.\n isPrime = true; //reset \n\n\n // Inner loop just loop over the primes:\n for (long j=0;j &lt; primes.size(); ++j)\n {\n if (i % primes.get(j) == 0)\n {\n isPrime = false;\n break; // As soon as you find the number is not prime\n } // break out of the loop.\n } \n\n if (isPrime)\n {\n primes.add(i);\n if (600851475143L % i == 0)\n {\n lgstPrime = i;\n }\n }\n }\n}\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:35:12.180", "Id": "32659", "Score": "0", "body": "As a general note, this code may suffer from severe performance problems, due to the unnecessary boxing. Since the number of prime numbers within the question's range is about 78,000 (http://primes.utm.edu/howmany.shtml), it could be better to use an integer array with an initial capacity of 80,000. This would lead to a much better performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:32:02.913", "Id": "32673", "Score": "0", "body": "You can eliminate the `isPrime` variable for a micro-optimization. Looping through the primes collection backwards is a bit faster, reducing `primes.size()` to one invocation for the inner loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T21:06:32.503", "Id": "32677", "Score": "0", "body": "get() returns an int, I would need a long if it's an ArrayList<Long>." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T21:28:52.210", "Id": "32678", "Score": "0", "body": "@gjw80: get() should return the type store in the array. In this case Long." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:17:29.123", "Id": "20391", "ParentId": "20389", "Score": "2" } }, { "body": "<p>Your approach is naturally very slow. Let's calculate it together:</p>\n\n<ul>\n<li>For each number <code>i</code> between <code>2</code> and <code>max</code>, check whether it is prime.</li>\n<li>If <code>i</code> is prime, check whether it is a factor of your large number.</li>\n</ul>\n\n<p>For <code>i=10</code>, you're doing 10 checks in the first loop. For <code>i=100</code>, you're doing a 100 checks. For <code>i=1000</code>, you're doing a 1000 checks. How many are these? This is called an <a href=\"http://en.wikipedia.org/wiki/Arithmetic_progression#Sum\" rel=\"nofollow\">Arithmetic Progression</a>. When you've reached <code>i=1000</code>, you've made <code>1000*1001/2 = 500500</code> checks. At <code>i=6857</code>, you've made 23 million checks, and so on. Clearly you're not being efficient.</p>\n\n<p>For the purposes of code review, think about the following optimizations:</p>\n\n<ul>\n<li><p>Why do you need to check whether <code>i</code> is prime? Think about it. Wouldn't it be faster to check whether <code>(600851475143L % i == 0)</code> directly? How many checks would your code perform if you use this approach, compared to your previous approach?</p></li>\n<li><p>In your inner loop, why do you need the condition <code>j != i</code>? Could you remove that, and suffice with <code>j &lt; i</code> in the loop condition?</p></li>\n<li><p>When checking that whether a number is prime, do you need to check all the smaller numbers, or could it suffice to check a subset of them? To check whether <code>1009</code> is prime, do you need to divide it by <code>1008</code> or even <code>1000</code>? Do you need to divide it by <code>700</code>? Is there a smaller <code>value</code> where you can stop, and say confidently that this number is prime, because you checked all possibilities smaller than <code>value</code>?</p></li>\n<li><p>In addition to the previous point, can you think of a way to eliminate <em>exactly half</em> of all the values of <code>j</code> that you check?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-09T15:24:45.003", "Id": "99687", "Score": "0", "body": "Couldn't be answered any better in the context of a \"Project Euler\" program, where the challenge is to solve the problem, and not to find the answer. And even the hardest \"Project Euler\" questions can be answered without much mathematical knowledge." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:21:05.890", "Id": "20392", "ParentId": "20389", "Score": "4" } }, { "body": "<blockquote>\n <p>My problem is finding a way to streamline the algorithm to greatly reduce the processing time.</p>\n</blockquote>\n\n<p>Well, if we take into account that we are on Code Review, than an answer to this could be a little bit off the scope, as @HosamAly has already written, too. I will investigate this a little bit further.</p>\n\n<p>Problems related to prime numbers are studied very extensive. The conclusion of this is, whatever you do, you will most probably just reinvent the wheel.</p>\n\n<p>So the question should not be \"how to reduce the processing time\", it should be \"how to handle my problem\" which leads to the question of the problem definition. If your problem definition is just as mentioned \"What is the largest prime factor of the number 600851475143?\", then take the number, put it into <a href=\"http://www.wolframalpha.com/input/?i=600851475143\" rel=\"nofollow\">Wolfram Alpha</a>, and be done in 5 seconds.</p>\n\n<p>If your problem definition is more like \"How can I calculate the largest prime factor of a given integer?\" Then find <a href=\"http://goo.gl/udTmc\" rel=\"nofollow\">any algorithm/library</a>, check if it is suitable and be done.</p>\n\n<p>If your problem definition is a real world requirement, then find out the time constraint. It is always about time constraints for real world problems like this. Without a time constraint, you could improve it literally forever.</p>\n\n<p>If your problem definition is more like \"I want to improve my knowledge about coding and optimization in Java and I will try the problem xyz\" Then there is no real answer to this. You could ask probably for some solutions on stackoverflow (as far as I got it, they do not like questions for euler problems there, so hide it a little bit. I would post an answer there if you link it).</p>\n\n<p>Some suggestions about your code were already done, but I do not see the point in giving advices in optimization here.</p>\n\n<hr>\n\n<p>My suggestions about the code:</p>\n\n<pre><code>long lgstPrime = 1;\n</code></pre>\n\n<p>Please write the full name, so everyone can read and understand it. Is it longestPrime, largestPrime, logarithmstPrime? You do not save real time or space by saving some characters (assuming we are in Java and not something like fortran77).</p>\n\n<hr>\n\n<pre><code>long max = 600851475143L;\nfor (int i = 2; i &lt; max; i++) {\n ...\n}\n</code></pre>\n\n<p>I do not think that your code will work and output anything. This is an infinite loop. Why? Because <code>i</code> is an integer, it will overflow at <code>Integer.MAX_VALUE</code> (2^31 - 1 or 2147483647) starting at <code>Integer.MIN_VALUE</code> or -2147483648 again. This will never reach max which is greater than 2147483647. So the loop will run forever.</p>\n\n<p>Example to test:</p>\n\n<pre><code>final long max = 600851475143L;\nfor (int i = 0; i &lt; max; i++) {\n if (i == Integer.MAX_VALUE)\n System.out.println(\"will overflow now\");\n}\n</code></pre>\n\n<p>Better:</p>\n\n<pre><code>long max = 600851475143L;\nfor (long i = 2; i &lt; max; i++) {\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>For readability, stick to one coding style:</p>\n\n<pre><code>for (int i=2; i&lt;max; i++){\n for (int j=2; j&lt;=i; j++){\n if ((i % j == 0) &amp;&amp; (j != i))\n</code></pre>\n\n<p>Better:</p>\n\n<pre><code>for (int i = 2; i &lt; max; i++) {\n for (int j = 2; j &lt;= i; j++) {\n if ((i % j == 0) &amp;&amp; (j != i))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:52:31.857", "Id": "32702", "Score": "0", "body": "\"Because i is integer, integer will overflow at Integer.MAX_VALUE (2^31 - 1 or 2147483647) starting at Integer.MIN_VALUE or -2147483648 again. This will never reach max which is greater than 2147483647. So the loop will run forever.\"\n\nThis explains why the program never completes then..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:30:53.893", "Id": "32726", "Score": "0", "body": "I have come to a much better version based on several people's tips in this thread. Thanks for the assistance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T11:54:52.997", "Id": "20414", "ParentId": "20389", "Score": "7" } }, { "body": "<p>A much faster way to improve this algorithm is to do a Miller Rabin test on the first 12 or so primes, making sure that your number isn't one of the pseudo-primes in <a href=\"http://oeis.org/A014233\">this list</a>.</p>\n\n<p>Assuming the Miller Rabin test tells you that it's composite, then if you want the factor, only trial divide the first 100 or so prime numbers. Then use pollard-rho to get any possible larger factors.</p>\n\n<p>Further than that, I would have to know more about why you are doing this.</p>\n\n<ol>\n<li><p>If you are doing this to learn Java coding or for your own fun, or for a homework assignment, then implementing the above would be best left as an exercise for you to do on your own.</p></li>\n<li><p>If you are trying to solve a real world problem, much of the java code for this has already been written. For example, Richard Mathar implements the Miller Rabin test mentioned above in his Prime class. You can download his code <a href=\"http://arxiv.org/src/0908.3030v2/anc/org/nevec/rjm/Prime.java\">here</a>.</p></li>\n</ol>\n\n<p>When I compared his algorithm on the number 3825123056546412223 (which is prime) to a trial division test I wrote, I got:</p>\n\n<hr>\n\n<p>Miller Rabin test took 0.009 seconds to run.</p>\n\n<p>Naive trial division takes 9.495 seconds to run.</p>\n\n<hr>\n\n<p>A few comments to improve trial division</p>\n\n<ol>\n<li><p>As has already been pointed out, you only need to test the numbers up to and including the sqrt(n).</p></li>\n<li><p>If you don't want to store all of the prime numbers between 2 and n, one option after testing 2, 3, 5, and 7 is to keep track of the current number you are testing mod 3. The reason for this, is for example (7 % 3) = 1 so adding 2 will give you a number that's obviously divisible by 3. So if you want to end up with a number that's not divisible by 3 and also not divisible by 2, add 4 to get 11. Then (11 % 3) = 2, so obviously adding 4 is going to again, give you another number that's divisible by 3. So add 2 to get 13. Then (13 % 3) = 1.</p></li>\n</ol>\n\n<p>To make that more efficient, notice that the current number % 3 is going to switch back and forth between 1 and 2, and the number you want to add is going to switch back and forth between 2 and 4. </p>\n\n<p>This algorithm is simple to implement and will skip testing divisibility by any number divisible by 2 or 3 (assuming you start with a value that is not divisible by 2 or 3). The relevant code I use for this is:</p>\n\n<pre><code>// Assume that currvar is some number not divisible by 2 or 3\nint mod3int = (currvar % 3);\n// Put the below code inside of your loop\nif (mod3int == 1) {\n currvar += 4;\n mod3int = 2;\n} else {\n currvar += 2;\n mod3int = 1;\n}\n// Now test to see if your number is divisible by currvar\n</code></pre>\n\n<p>I imagine there are ways to make trial division even faster, but probably not worth wasting your time on. The Miller Rabin test mentioned above is going to be faster than probably any optimization on trial division you can come up with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-16T04:08:30.203", "Id": "41773", "ParentId": "20389", "Score": "6" } } ]
{ "AcceptedAnswerId": "20414", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:01:11.173", "Id": "20389", "Score": "2", "Tags": [ "java", "performance", "algorithm", "programming-challenge", "primes" ], "Title": "Faster way to determine largest prime factor" }
20389
<p>I am still trying to wrap my head around good programming practice and just wrote this routine to read in an Excel file and return all the sheets into a dataset:</p> <pre><code>Public Shared Function ReadExcelIntoDataSet(ByVal FileName As String, Optional ByVal TopRowHeaders As Boolean = False) As DataSet Try Dim retval As New DataSet Dim strConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &amp; _ FileName &amp; ";Extended Properties=""Excel 12.0;IMEX=1;" &amp; _ "HDR=" &amp; If(TopRowHeaders, "Yes", "No") &amp; """;" Using oleExcelConnection = New OleDb.OleDbConnection(strConnString) oleExcelConnection.Open() Using oleExcelCommandString = New OleDb.OleDbCommand("", oleExcelConnection) Using oleExcelAdapter = New OleDb.OleDbDataAdapter(oleExcelCommandString) Dim dtSchema As DataTable = oleExcelConnection.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, Nothing) For Each dr As DataRow In dtSchema.Rows Dim Sheetname As String = dr.Item("TABLE_NAME").ToString If Sheetname.EndsWith("$") Then oleExcelCommandString.CommandText = "Select * From [" &amp; Sheetname &amp; "]" oleExcelAdapter.Fill(retval, Sheetname) End If Next Return retval End Using End Using End Using Catch ex As Exception Dim ErrorData As String = "Unable to Read in Data from the Excel File " &amp; FileName &amp; vbCrLf &amp; _ "Module: Utility &gt; ReadExcelIntoDataSet" Throw New Exception(ErrorData &amp; vbCrLf &amp; "ERROR Data:" &amp; vbCrLf &amp; ex.Message) End Try End Function </code></pre> <p>My first questions are:</p> <ol> <li>Is the use of the <code>Using</code> statements good or is it some kind of over-kill and should this maybe be handled in a <code>Finally</code> statement in stead?</li> <li>Is this the best method to read in an Excel File (Given that they can be either .xls or .xlsx) in the fastest possible way?</li> <li>What is the best way to pass the error up to the calling code? Did my Catch statement do that well enough??</li> </ol>
[]
[ { "body": "<ol>\n<li><p>The <code>Using</code> is good practice and not overkill. Trying to dispose the resources in the <code>Finally</code> part has the disadvantage, that you don't know when the exception happened and which resources have been assigned by that time. The Using statement does this automatically for you internally: <code>If resouce &lt;&gt; Nothing Then resource.Dispose() End If</code></p></li>\n<li><p>You need different connection strings for the different Excel types. You can use this function:</p></li>\n</ol>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function GetConnectionString(ByVal filename As String) As String\n Const xlsConnString As String = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;\"\n Const xlsxConnString As String = \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;\"\n\n If Path.GetExtension(filename).Length = 5 Then ' .xlsx, .xltx\n Return String.Format(xlsxConnString, filename)\n Else ' .xls, .xlt\n Return String.Format(xlsConnString, filename)\n End If\nEnd Function\n</code></pre>\n\n<ol>\n<li>You can either propagate the exception or return <code>Nothing</code>. In my opinion, your version does it very well.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:12:47.707", "Id": "32667", "Score": "0", "body": "... One more question, if you'd be willing to answer it - It seems that the ACE.OLEDB connection opens the `.xls` files too... Is there any reason to use the `Jet` provider??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T20:16:13.600", "Id": "32669", "Score": "0", "body": "If it does it's okay! I supported only `xls` first and added support for `xlsx` later in one of my projects and did not realize that ACE.OLEDB supports the older format as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:45:20.610", "Id": "20395", "ParentId": "20393", "Score": "2" } } ]
{ "AcceptedAnswerId": "20395", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T19:25:16.137", "Id": "20393", "Score": "2", "Tags": [ "vb.net" ], "Title": "Using Statement for OleDB - Is this overkill?" }
20393
<p>I've written a small utility for monkey-patching native JavaScript constructor functions. For example, you can use it to modify input arguments before returning an instance (this can be useful for unit tests).</p> <p>There is much more detail about the utility <a href="https://github.com/jamesallardice/patchwork.js">on GitHub</a>, so it may be useful to read through the readme on there.</p> <p>I would be interested to know if I've hugely over-engineered this. There may be simpler techniques that I could take advantage of. Any comments are appreciated.</p> <p>Here is the code:</p> <pre><code>var patch = (function () { /*jshint evil: true */ "use strict"; var global = new Function("return this;")(), // Get a reference to the global object fnProps = Object.getOwnPropertyNames(Function); // Get the own ("static") properties of the Function constructor return function (original, originalRef, patches) { var ref = global[originalRef] = original, // Maintain a reference to the original constructor as a new property on the global object args = [], newRef, // This will be the new patched constructor i; patches.called = patches.called || originalRef; // If we are not patching static calls just pass them through to the original function for (i = 0; i &lt; original.length; i++) { // Match the arity of the original constructor args[i] = "a" + i; // Give the arguments a name (native constructors don't care, but user-defined ones will break otherwise) } if (patches.constructed) { // This string is evaluated to create the patched constructor body in the case that we are patching newed calls args.push("'use strict'; return (!!this ? " + patches.constructed + " : " + patches.called + ").apply(null, arguments);"); } else { // This string is evaluated to create the patched constructor body in the case that we are only patching static calls args.push("'use strict'; return (!!this ? new (Function.prototype.bind.apply(" + originalRef + ", [{}].concat([].slice.call(arguments))))() : " + patches.called + ".apply(null, arguments));"); } newRef = new (Function.prototype.bind.apply(Function, [{}].concat(args)))(); // Create a new function to wrap the patched constructor newRef.prototype = original.prototype; // Keep a reference to the original prototype to ensure instances of the patch appear as instances of the original newRef.prototype.constructor = newRef; // Ensure the constructor of patched instances is the patched constructor Object.getOwnPropertyNames(ref).forEach(function (property) { // Add any "static" properties of the original constructor to the patched one if (fnProps.indexOf(property) &lt; 0) { // Don't include static properties of Function since the patched constructor will already have them newRef[property] = ref[property]; } }); return newRef; // Return the patched constructor }; }()); </code></pre> <p>And here's an example usage (this is a real-world use case for working around a bug in date parsing in PhantomJS):</p> <pre><code>Date = patch(Date, "DateOriginal", { constructed: function () { var args = [].slice.call(arguments); if (typeof args[0] === "string" &amp;&amp; /^\d{4}\/\d{2}$/.test(args[0])) { args[0] = args[0] + "/02"; // Make sure the argument has a 'day' } return new (Function.prototype.bind.apply(DateOriginal, [{}].concat(args))); } }); </code></pre> <p>There are some more examples, and details of the arguments to <code>patch</code> in the GitHub readme.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T23:52:51.803", "Id": "32682", "Score": "1", "body": "Why not use [Object.create()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create)? Also what JS engine or environment will your scripts be running on? If it's web, then it shouldn't work in IE 6-8 because they don't support `Function.prototype.bind()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T08:26:37.450", "Id": "32689", "Score": "0", "body": "@LarryBattle - This will only run in environments that do support `Function#bind` (and any other ES5 methods in there). Polyfills for `bind` won't work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:07:11.077", "Id": "70304", "Score": "0", "body": "Curious what facilitated the need to do the `Function` / `eval`s?" } ]
[ { "body": "<p>I don't see any good reason why you're using some of these hacks. It took me a while to understand what you were doing and I was pretty much forced to step through it in debugger. Going to review this line by line and point out simplifications and patterns as I see fit. I'll be batching together all my suggestions into a counter proposal in <strong><a href=\"http://jsbin.com/zusup/1/edit\" rel=\"nofollow noreferrer\">this jsbin</a></strong>, using the unit tests from your repo.</p>\n<p>To start, it seems quite unneccessary and non standard to get the global scope your way (and I'm going to later argue you shouldn't need it)...</p>\n<pre><code>var global = new Function(&quot;return this;&quot;)();\n</code></pre>\n<p>Just do what every other package does and get scope at the start of your wrapper</p>\n<pre><code>(function(global) { })(this); //or use self w/e\n</code></pre>\n<p>I'm not a fan of your <a href=\"https://github.com/jamesallardice/patchwork.js/blob/6773e27a5af0ccc4529458e73002d522ff4973b8/patchwork.js#L32-36\" rel=\"nofollow noreferrer\"><code>fnProps</code> idea</a>. I would prefer you store <code>has = Object.prototype.hasOwnProperty;</code> and filter out items on the Function prototype as follows:</p>\n<pre><code>var has = Object.prototype.hasOwnProperty();\n/* .... */\n//To avoid storing generic function properties (like length) on newRef\nObject.getOwnPropertyNames(ref).forEach(function(key) {\n if(!has.call(Function, key)) newRef[key] = ref[key];\n});\n</code></pre>\n<p>I'm biased here, but as a past Mootools developer I keep comparing your function with <a href=\"http://mootools.net/docs/more/Class/Class.Refactor\" rel=\"nofollow noreferrer\">Class.refactor</a>. Personally I would prefer you add a reference to the original function on <code>newRef</code> - maybe as some property <code>_original</code> or let the user handle storing the original. I'm not a fan of adding a global for the original function.</p>\n<p>A question, why do you not pass <code>this</code> to your constructors? If you're wrapping some classes this seems like it may make usuage less intuitive.</p>\n<p><strong>Update</strong> (still at work and can't look into removing the <code>new Function()</code> approach yet but I think I found a great change... You can rewrite <a href=\"https://github.com/jamesallardice/patchwork.js/blob/6773e27a5af0ccc4529458e73002d522ff4973b8/patchwork.js#L28\" rel=\"nofollow noreferrer\">the extremely confusing <code>bind.apply(...)</code></a> like this (unit tests passing):</p>\n<pre><code>newRef = Function.apply(null, args);\n</code></pre>\n<p>I'm not a minifier but theres no good reason to do <code>!!this ? x : y</code></p>\n<h2>Counter proposal:</h2>\n<p>I believe you should drop the arity requirement and drop the global - instead inform the user they should cache the original locally. I've rewritten the code with these considerations in mind. Here's a <a href=\"http://jsbin.com/baguy/1\" rel=\"nofollow noreferrer\">jsbin with these changes</a> (note I haven't removed the global to respect your test cases):</p>\n<pre><code>var patch = (function (global) {\n /*jshint evil: true */\n\n &quot;use strict&quot;;\n var has = Object.prototype.hasOwnProperty,\n slice = Array.prototype.slice,\n bind = Function.bind;\n return function (original, patches) {\n var args = [],\n newRef, // This will be the new patched constructor\n i;\n\n patches.called = patches.called || original; // If we are not patching static calls just pass them through to the original function\n\n if (patches.constructed) { // This string is evaluated to create the patched constructor body in the case that we are patching newed calls\n newRef = function(/*args*/) {\n return (this &amp;&amp; this !== global ? patches.constructed : patches.called).apply(this, arguments);//note called with context\n };\n } else { // This string is evaluated to create the patched constructor body in the case that we are only patching static calls\n newRef = function(/*args*/) {\n return this &amp;&amp; this !== global ? new (bind.apply(original, [].concat({}, slice.call(arguments))))\n : patches.called.apply(this, arguments);\n };\n }\n\n // Create a new function to wrap the patched constructor\n newRef.prototype = original.prototype; // Keep a reference to the original prototype to ensure instances of the patch appear as instances of the original\n newRef.prototype.constructor = newRef; // Ensure the constructor of patched instances is the patched constructor\n\n Object.getOwnPropertyNames(original).forEach(function (property) { // Add any &quot;static&quot; properties of the original constructor to the patched one\n if (!has.call(Function, property)) { // Don't include static properties of Function since the patched constructor will already have them\n newRef[property] = original[property];\n }\n });\n\n return newRef; // Return the patched constructor\n };\n\n})(this);\n</code></pre>\n<p>Edit - missed an easy code size optimization:</p>\n<pre><code>newRef = function(/*args*/) {\n if(this &amp;&amp; this !== global) {\n return patches.constructed ? patches.constructed.apply(this, arguments)\n : new (bind.apply(original, [].concat({}, slice.call(arguments))))// create the patched constructor body in the case that we are only patching static calls;\n } else {\n return patches.called.apply(this, arguments);\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T13:33:47.197", "Id": "70609", "Score": "0", "body": "Thanks for answering. I don't remember the reasons for half of the code in the question (it was over a year ago). When I get a chance I'll look back over it and try to work out what I was doing and why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T13:50:41.087", "Id": "70610", "Score": "3", "body": "Good, I will get some action for my bounty ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T19:54:58.960", "Id": "70675", "Score": "0", "body": "This was interesting! Also you can get around that native `Function.prototype.bind` requirement with `eval` if desired" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T13:30:53.780", "Id": "41147", "ParentId": "20400", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T22:18:56.237", "Id": "20400", "Score": "16", "Tags": [ "javascript" ], "Title": "Monkey-patching native JavaScript constructors" }
20400
<p>I came up with a solution for the <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/50bff669014b8" rel="nofollow">InterviewStreet problem "Triplet"</a></p> <p>In short, there is an integer array <em>d</em> which does not contain more than two elements of the same value. How many distinct ascending triples (<code>d[i] &lt; d[j] &lt; d[k], i &lt; j &lt; k</code>) are present? </p> <p>It successfully passes 9 test cases of 15. but my solution exceeds time limit in other test cases.</p> <pre><code>import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * * @author Dumindu */ public class Triplets { public static void main(String args[]) { int[] arr,helper; Scanner scn=new Scanner(System.in); int x=scn.nextInt(); arr=new int[x]; helper=new int[x]; for(int i=0;i&lt;x;i++) { arr[i]=scn.nextInt(); } int triplets=0; helper[0]=0; Map&lt;Integer,Integer&gt; map1=new HashMap&lt;Integer,Integer&gt;(); for(int i=0;i&lt;x;i++) { int minVals=0; Set&lt;Integer&gt; set=new HashSet&lt;Integer&gt;(); int tempTrip=0; for(int j=i-1;j&gt;=0;j--) { if(arr[j]&lt;arr[i] &amp;&amp; !set.contains(arr[j])) { minVals++; tempTrip+=helper[j]; set.add(arr[j]); } } helper[i]=minVals; if(!map1.containsKey(arr[i])) { triplets+=tempTrip; map1.put(arr[i],tempTrip); } else { triplets=triplets-map1.get(arr[i])+tempTrip; } } System.out.println(triplets); } } </code></pre> <p>If there is a way to optimize this solution or approach it differently, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T11:36:42.230", "Id": "32680", "Score": "1", "body": "You didn't exactly go out of your way to help us understand your variable names." } ]
[ { "body": "<ol>\n<li>The problem looks like it would have a solution of complexity \\$O(n log n)\\$. Yours has \\$O(n^2)\\$. google \"number of increasing subsequences\". </li>\n<li>The site says input size can be \\$10^5\\$. A \\$O(n^2)\\$ algorithm with hash look-ups, hash inserts, and virtual function calls in the inner loop will not finish in a few minutes.</li>\n<li><p>By replacing </p>\n\n<pre><code>int x=scn.nextInt();\n</code></pre>\n\n<p>with </p>\n\n<pre><code>int x = 100000;\n</code></pre>\n\n<p>and</p>\n\n<pre><code> arr[i]=scn.nextInt();\n</code></pre>\n\n<p>with</p>\n\n<pre><code> arr[i] = i + 1;\n</code></pre>\n\n<p>you can easily test how your program performs with large input.</p></li>\n<li><p>A quick order of magnitude analysis: An increasing sequence of ~\\$10^5\\$ elements will have \\$~(10^5)^3\\$ increasing subsequences of length 3. Since \\$10^3 ~= 2^10\\$, \\$10^15 ~= 2^50\\$. \\$2^50\\$ >> \\$2^31\\$. So your <code>triplets</code> variable <strong>will overflow</strong>. It should be an <code>long</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T09:57:17.467", "Id": "20504", "ParentId": "20401", "Score": "1" } }, { "body": "<p>I found it difficult to understand your solution, I wrote another solution that first creates all triplets may also maybe some duplicate ones. Then I sort the triplets so that duplicates are \"together\" and then I remove duplicates.</p>\n\n<p>I would like to find an algorithm that does not create those duplicates so there would be no need to keep all triplets in memory, but I did not found a solution yet :(</p>\n\n<p>Anyway here is what I did:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class Solution {\n\n public static void main(String... args) {\n\n Scanner scanner = new Scanner(System.in);\n int elements = scanner.nextInt();\n int[] sequence = new int[elements];\n\n for (int i = 0; i &lt; elements; i++) {\n sequence[i] = scanner.nextInt();\n }\n\n// sequence[0] = 1;\n// sequence[1] = 1;\n// sequence[2] = 2;\n// sequence[3] = 2;\n// sequence[4] = 3;\n// sequence[5] = 4;\n\n List&lt;int[]&gt; triplets = new ArrayList&lt;&gt;();\n for (int i = 0; i &lt; elements; i++) {\n int first = sequence[i];\n for (int j = i; j &lt; elements; j++) {\n int second = sequence[j];\n if (second &gt; first) {\n for (int k = j; k &lt; elements; k++) {\n int third = sequence[k];\n if (third &gt; second) {\n triplets.add(new int[] { first, second, third });\n }\n }\n }\n }\n }\n\n Collections.sort(triplets, new Comparator&lt;int[]&gt;() {\n @Override\n public int compare(int[] o1, int[] o2) {\n\n int index = 0;\n int result = 0;\n int length = Math.min(o1.length, o2.length);\n do {\n result = Integer.compare(o1[index],o2[index]);\n } while (result == 0 &amp;&amp; ++index &lt; length);\n\n\n\n return result;\n }\n\n @Override\n public Comparator&lt;int[]&gt; reverse() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public Comparator&lt;int[]&gt; compose(Comparator&lt;? super int[]&gt; other) {\n throw new UnsupportedOperationException();\n }\n });\n\n int tripletsNb = 0;\n int[] currentTriplet = null;\n for (int[] t : triplets) {\n // count non-duplicate triplets\n if (!Arrays.equals(currentTriplet, t)) tripletsNb++;\n currentTriplet = t;\n // System.out.println(Arrays.toString(t));\n }\n\n System.out.println(tripletsNb);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T07:29:38.520", "Id": "20619", "ParentId": "20401", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T11:13:58.017", "Id": "20401", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "InterviewStreet Triplet optimization" }
20401
<p>I'm just starting with Ruby and decided to do two different implementations of Conway's Game of Life. In this first one I'm not using <code>cells</code> as a separate class and instead just track everything as a location on the board, using a state pattern I guess. </p> <p>Anyway, I want this code to display good Object-Oriented programming basics as well as construction via test-driven development, using rspec.</p> <p>Please critique away and tell me if it's under/over engineered for the problem, not extensible enough or too extended, as well as if my TDD progression was worthwhile, did I do enough or too few tests, or maybe not the right tests.</p> <h3>board.rb:</h3> <pre><code>class Board attr_accessor :width,:height def initialize(cells=[], width = 3, height = 3) @cells = cells @height = height @width = width end def live_cells @cells end def is_alive?(x,y) @cells.include?([x,y]) end def neighbors_to(x,y) @cells.select do |cell_x, cell_y| dx = (x-cell_x).abs dy = (y-cell_y).abs #If the tuple x,y is a neighbor of that cell then the following is true dx &lt;= 1 and dy &lt;= 1 and not (dx == 0 and dy == 0) end.length #We only care how many there are and do not care which cells in particular end def evolve survivors = [] #Scan the entire board (may be able to be more clever here but you need to check each dead cell for ressurection) @width.times do |x| @height.times do |y| survivors &lt;&lt; [x,y] if should_survive?(x,y) or should_ressurect?(x,y) end end #Populating the new board from survivors allows reference to the current generation while populating the next generation Board.new(survivors, self.width,self.height) end def should_survive?(x,y) (neighbors_to(x,y) == 2 or neighbors_to(x,y) == 3) and is_alive?(x,y) end def should_ressurect?(x,y) neighbors_to(x,y) == 3 and not is_alive?(x,y) end def print_board puts "Current Generation" puts @width.times do |x| @height.times do |y| print "#{is_alive?(x,y) ? '#' : '-'}" end puts end puts end end </code></pre> <h3>board_spec.rb:</h3> <pre><code>require 'spec_helper' describe Board do context "#new" do it "should be created empty if passed empty array" do Board.new([]).live_cells.should be_empty end it "should be created empty if passed nothing at all" do Board.new end it "should contain the cells created with it" do Board.new([[1,1],[2,2]]).live_cells.should be ==[[1,1],[2,2]] end end context "#evolve" do it "should evolve an empty board if empty" do next_gen = next_generation_for([]) next_gen.should be_empty end it "should kill a lonely cell (&lt; 2 neighbors)" do next_gen = next_generation_for([[1,1]]) next_gen.should be_empty end it "should keep a cell with 2 neighbors alive" do #pending("We need to count neighbors") next_gen = next_generation_for([[1,1],[1,2],[1,0]]) next_gen.should include([1,1]) end it "should keep a cell with 3 neighbors alive" do #pending("We need to count neighbors") next_gen = next_generation_for([[1,1],[1,2],[1,0],[0,0]]) next_gen.should include([1,1]) end it "should revive a dead cell with 3 neighbors (reproduction)" do #pending("Dimensions of the board to find dead cells") next_gen = next_generation_for([[1,0],[0,1],[2,1]]) next_gen.should include([1,1]) end it "should kill any cell with more than 3 neighbors" do next_gen = next_generation_for([[0,1],[2,1],[1,2],[1,0],[1,1]]) next_gen.should_not include([1,1]) end end def next_generation_for(seed,width = 3, height = 3) board = Board.new(seed, width, height) board.evolve.live_cells end it "should be able to handle the blinker formation 10 times" do seed = [[1,2],[1,1],[1,0]] n = 0 while n&lt;=10 next_gen = next_generation_for(seed) next_gen.should satisfy{|cells| cells =~[[0,1],[1,1],[2,1]] or [[1,2],[1,1],[1,0]]} seed = next_gen n+=1 end end it "should be able to handle the block formation 10 times" do seed = [[1,1],[2,1],[2,2],[1,2]] n = 0 while n &lt;= 10 next_gen = next_generation_for(seed) next_gen.should =~ [[1,1],[2,1],[2,2],[1,2]] seed = next_gen n+=1 end end it "should be able to handle the beehive formation 10 times" do seed = [[1,0],[2,0],[3,1],[2,2],[1,2],[0,1]] n = 0 while n &lt;= 10 next_gen = next_generation_for(seed,4,4) next_gen.should =~ [[1,0],[2,0],[3,1],[2,2],[1,2],[0,1]] seed = next_gen n+=1 end end it "should be able to print the current board" do board = Board.new([[1,1],[0,1],[0,2]],5,5) board.print_board end end describe Board, "counting neighbors" do it "should find zero neighbors to a solitary cell" do board = Board.new([[1,1]]) board.neighbors_to(1,1).should == 0 end it "should find one neighbor to a single cell" do board = Board.new([[1,1]]) board.neighbors_to(0,0).should == 1 board.neighbors_to(0,1).should == 1 board.neighbors_to(0,2).should == 1 board.neighbors_to(1,2).should == 1 board.neighbors_to(2,2).should == 1 board.neighbors_to(2,1).should == 1 board.neighbors_to(2,0).should == 1 board.neighbors_to(1,0).should == 1 end it "should find two neighbors to cells if needed" do board = Board.new([[0,1],[2,2]]) board.neighbors_to(1,1).should == 2 board.neighbors_to(1,2).should == 2 end it "should find three neighbors to cells if needed" do board = Board.new([[0,1],[2,2],[1,2]]) board.neighbors_to(1,1).should == 3 board.neighbors_to(2,2).should == 1 end end </code></pre> <p><code>spec_helper</code> just has a pointer to require board.rb. I'm trying to get into this practice for larger programs so adding new classes won't require me to edit individual spec files. I also have a file, run_game.rb, that simply allows me to choose different patterns and iterates the game.</p> <p>Some things that stand out to me:</p> <ul> <li>There is very little user fault tolerance, i.e. I can give it cells on a board that's too small and it runs just fine, it just never displays cells off the board. Is it worth the extra complication to solve such problems, i.e. make it more durable to a user or is this structure enough to communicate a foundation understanding of OO programming?</li> <li>Is there repetition in the <code>live_cells</code> method? I could just use <code>attr_accessor :cells</code> but that's far less readable.</li> <li>Would it be a "better" implementation from an OO programming standpoint to have <code>cells</code> as a class as well?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:10:38.367", "Id": "33846", "Score": "0", "body": "Small detail, but important: Never `x-y`, always `x - y`. Conversly, `x = -y`, never `x = - y`." } ]
[ { "body": "<p>Your code looks pretty good to me. I specially like how you don't update inplace a <code>Board</code> but create new ones on each iteration. And the OOP aspects of it seem also ok, I wouldn't write a <code>Cell</code> class when a pair <code>[x, y]</code> does just fine and there are not many methods you can encapsulate within (other than dead/alive, which isn't helpful as your existing cells are those alive). Some notes on details:</p>\n\n<ul>\n<li><p><code>def initialize(cells=[], width = 3, height = 3)</code>. I wouldn't recommend positional optional arguments, it gets messy pretty quickly. Maybe <code>def initialize(options = {})</code> with key arguments? Note that Ruby 2.0 has keyword arguments: <code>def initialize(cells: [], width: 3, height: 3)</code></p></li>\n<li><p><code>def is_alive?(x,y)</code> Add some spaces to let it breathe, it enhances readability: <code>def is_alive?(x, y)</code></p></li>\n<li><p><code>dx &lt;= 1 and dy &lt;= 1 and not (dx == 0 and dy == 0)</code>. <code>and</code>/<code>or</code> are used for control flow, <code>&amp;&amp;</code>/<code>||</code> for boolean expressions. And <code>!</code> is more idiomatic than <code>not</code>.</p></li>\n<li><p><code>@cells.select { ... }.length</code> note that this may be written <code>@cells.count { ... }</code>.</p></li>\n<li><p><code>survivors = []</code>. Your code is almost functional, don't give up:</p>\n\n<pre><code>survivors = (0...@width).to_a.product(0...@height).select do |x, y|\n should_survive?(x, y) || should_ressurect?(x, y)\nend\n</code></pre></li>\n<li><p><code>print_board</code>. I'd write it differently (also in functional style):</p>\n\n<pre><code>def print_board\n matrix = 0.upto(@width - 1).map do |x|\n 0.upto(@height - 1).map do |y|\n is_alive?(x, y) ? '#' : '-'\n end.join\n end.join(\"\\n\")\n puts \"Current Generation\\n\\n#{matrix}\\n\"\nend\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T00:09:32.533", "Id": "32883", "Score": "0", "body": "Great suggestions. I'll implement these as soon as I can and update the original post. I'm working on making my blocks more functional every day. It's very helpful to try it one way then push it to functional with your suggestions or on my own. Learning by doing ftw." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T19:54:54.330", "Id": "20441", "ParentId": "20402", "Score": "3" } }, { "body": "<p>I won't talk about style, because @tokland's comments are spot-on.</p>\n\n<p>However, some quick notes about efficiency. For large board sizes, this implementation is inefficient.</p>\n\n<p>For example, <code>neighbors_to</code> scans every cell on the board, and it is called multiple times. It is called twice from the <code>should_survive?</code> method:</p>\n\n<pre><code>def should_survive?(x,y)\n (neighbors_to(x,y) == 2 or neighbors_to(x,y) == 3) and is_alive?(x,y)\nend\n</code></pre>\n\n<p>You can reduce the call to one, and swap the order so you don't have to call it at all if the cell is alive:</p>\n\n<pre><code>def should_survive?(x,y)\n is_alive?(x,y) and [2,3].include? neighbors_to(x,y)\nend\n</code></pre>\n\n<p>The implementation of <code>neighbors_to</code> should simply collect each of the surrounding eight (maximum) spaces rather than scan the entire set of live cells.</p>\n\n<p>This also means you need to be able to query a cell directly, rather than scan all live cells as your <code>is_alive?</code> method currently does. I would recommend representing a board using a 2D array of spaces. I'd probably rename @cells to @live_cells to avoid confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T18:11:07.353", "Id": "34686", "Score": "0", "body": "Good suggestion. I'll change the neighbors_to method to check if eight surrounding cells are in the current set of @cells list rather than going through all of the cells." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T12:37:46.203", "Id": "21335", "ParentId": "20402", "Score": "4" } } ]
{ "AcceptedAnswerId": "20441", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T23:52:09.867", "Id": "20402", "Score": "4", "Tags": [ "ruby", "game-of-life", "rspec" ], "Title": "Ruby implementation of Conway's Game of Life" }
20402
<p>I'm wondering if you see anything terribly wrong with this code, or if you see any areas for improvement. My objective is to make sure its simple enough for someone else taking over my job to be able to pick up fairly quickly. </p> <p>My basic question has to do with the fact that in my model, I'm trying to distinguish between system errors that I want to show the end user, and ones that I don't want them to see. Here's some code from my model: </p> <pre><code> public function macaddresses($ip, $name) { try { //some code.... if ( $obj-&gt;connect() ) { //do something else return $macaddies } else { throw new Exception('Connection'); } //end if } catch (Exception $e) { $this-&gt;error_handler($e-&gt;getMessage()); return false; }//end catch }//end function private function error_handler($emess) { switch ($emess) { case 'Connection': $userfriendlyemess = "Unable to connect to device. Please contact administrator!"; break; //handling unknown errors default: $userfriendlyemess = "Oops! Something big just happened."; log_message('error', $emess); //write to ci logs break; }// end switch throw new Exception($userfriendlyemess); } // end function </code></pre> <p>Finally, the logic in my controller is where I make the calls to show_error. I know in CI i can use templates or something... but since I don't think there are going to be too many cases in my switch statement, i thought i'd try this approach. any suggestions would be appreciated. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T14:11:09.987", "Id": "32745", "Score": "0", "body": "Does anything else in the try block throw an exception other than the one shown? If not, it can be massively simplified" } ]
[ { "body": "<p>I don't really like the method of exception pseudo-typing you're doing, I'd use different objects to represent the type of exception rather than the content, like so:</p>\n\n<pre><code>function macaddresses($ip, $name)\n{\n try\n {\n //some code....\n if($obj-&gt;connect())\n {\n //do something else\n return $macaddies;\n }\n else\n {\n throw new UserVisibleException(\"Unable to connect to device. Please contact administrator!\");\n } \n }\n catch(Exception $e)\n {\n $this-&gt;processException($e);\n }\n}\n\nprivate function processException($exception)\n{\n if($exception instanceof UserVisibleException)\n {\n throw $exception;\n }\n else\n {\n log_message('error', $exception-&gt;getTraceAsString());\n throw new UserVisibleException(null, $exception);\n }\n}\n\nclass UserVisibleException extends Exception\n{\n public function __construct($message = null, $cause = null, $code = 1)\n {\n parent::__construct\n (\n $message === null ? \"Oops! Something big just happened.\" : $message,\n $code, $cause\n );\n }\n}\n</code></pre>\n\n<p>I put <code>processException()</code> as a method as it isn't clear whether you're using this design pattern elsewhere, but I assume so as you're connecting to something and there's usually other exceptions that can happen later. If you aren't, you can just stick it back into the catch block of <code>macaddresses()</code>.</p>\n\n<p>Additionally, if it isn't clear, the ternary is so you don't have to manually type in the message to attach a cause to an unknown exception being wrapped. And I took the liberty of replacing the generic message \"connection\" with the stack trace of the exception that caused it being passed to your logger, as this more detailed information will be useful should you wish to debug the cause of it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T14:23:25.687", "Id": "20461", "ParentId": "20403", "Score": "2" } }, { "body": "<p>There's no need to have functions dedicated to processing exceptions. This is exactly what the <code>try-catch</code> construct is designed to do.</p>\n\n<p>Best practice is to use inheritance to catch (and process) different exceptions different ways. For example, you could create a base <code>UserException</code> class (and inherit from it for more specific exceptions), which your <code>try-catch</code> blocks would show to the user:</p>\n\n<pre><code>&lt;?php\n\n// User-facing exception classes\nclass UserException extends Exception {}\n\nclass BadInputException extends UserException\n{\n public function __construct($message = 'Bad Input', $code = 400)\n {\n parent::__construct($message, $code);\n }\n}\n\n// All other exceptions are assumed to be hidden from the user\nclass DatabaseException extends Exception\n{\n public function __construct($message = 'Internal Server Error', $code = 500)\n {\n parent::__construct($message, $code);\n }\n}\n</code></pre>\n\n<p>Then, you catch the exceptions based on how you want them handled:</p>\n\n<pre><code>&lt;?php\n\ntry {\n // some action\n}\ncatch (UserException $e)\n{\n // show message to user\n}\ncatch (Exception $e)\n{\n // show generic message, log error, etc.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-11T23:25:30.970", "Id": "27282", "ParentId": "20403", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T00:24:46.797", "Id": "20403", "Score": "3", "Tags": [ "php", "error-handling" ], "Title": "error handling logic in php" }
20403
<p>I have a situation where depending on what the value of a uri segment is, my controller will load a different view. Here's what the code looks like in part:</p> <pre><code> //which view do we load? if (strpos(strtoupper($data['hardwaremodel']),"HP") !== false) { //hp view should be loaded $data['main_content']='hpad'; } elseif (strpos(strtoupper($data['hardwaremodel']),"DELL") !== false) { $data['main_content']='dellad'; } //load view. $this-&gt;load-&gt;view('includes/template', $data); </code></pre> <p>For many methods in my controller, I have similar logic. So another method would have the exact same code, but the names of the view would be different dpending on what action the user requested. So for example, instead of loading the Dell address page above ('dellad') it would load the Dell status page ('dellstatus')</p> <p>I'm wondering if I change my logic so that all the methods in the controller call a new function that determines what view to load for them will simplify things. </p> <p>I think the function would have to look something like: (just pseudocode)</p> <pre><code> private function loadview($callingfunctionname, $hardwaremodel) { switch ($callingfunctionname) { case 'functionA': if hardware = dell { return "viewabc" } else { return "viewdef" } break; case 'functionB': if hardware = dell { return "view123" } else { return "view456" } break; }//end switch } </code></pre> <p>But I don't know that it will really simplify things to it this way. Can you help me improve this code? the other point is that eventually, I will end up with more than 2 hardware types that I have to check for.</p> <p>Thanks. </p>
[]
[ { "body": "<p>I think I've come up with something cleaner: </p>\n\n<p>code in controller methods simplified to this:</p>\n\n<pre><code> //which view do we load?\n $viewnamePrefix = $this-&gt;checkhardwarename($data['hardwaremodel']);\n $data['main_content']=$viewnamePrefix.'ad';\n $this-&gt;load-&gt;view('includes/template', $data); \n</code></pre>\n\n<p>and then my new function to check hardware name:</p>\n\n<pre><code>private function checkhardwarename($hardwarename)\n{ \n if (strpos(strtoupper($hardwarename),\"HP\") !== false)\n {\n return 'hp';\n }\n elseif (strpos(strtoupper($hardwarename),\"DELL\") !== false)\n { \n return 'dell';\n }\n elseif (strpos(strtoupper($hardwarename),\"DELL%20SF\") !== false)\n {\n return 'dell_sf';\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T07:36:28.187", "Id": "35177", "Score": "1", "body": "Don't put your `DELL%20SF` conditional after the `DELL` conditional. `strpos` doesn't compare two strings, only locates the position of a given substring. Now, if a string contains `DELL%20SF` it certainly contains `DELL` too, so this means your `DELL` check will incorrectly flag `DELL%20SF` hardware too and the `DELL%20SF` condition will never be checked." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T00:56:59.510", "Id": "20405", "ParentId": "20404", "Score": "0" } }, { "body": "<p>I'd introduce a function that computes the data, so that you encapsulate all the rules there.</p>\n\n<pre><code>$data['main_content']=loadMainContent($data['hardwaremodel']));\n</code></pre>\n\n<p>Finally to improve the clarity you should incapsulate the check in a function in order to replace this line with <code>strpos(strtoupper($data['hardwaremodel']),\"HP\")</code> with something cleaner like <code>checkHardwareModel($data['hardwaremodel']),\"HP\")</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T08:20:12.187", "Id": "20410", "ParentId": "20404", "Score": "0" } }, { "body": "<p>Based on your answer, you should put the mapping in an array and create a for each loop. Maybe it would also be a good idea to extract the strtoupper($hardwarename) in a local variable that you don't do it in any if in the worst case. In addition to that you missed to add a default case, which might lead to an error in loading the template. Furthermore you have to move the longer DELL check in front of the shorter otherwise you will never reach this branch.</p>\n\n<pre><code>private function checkhardwarename($hardwarename)\n{ \n $mapping=array(\"HP\"=&gt;\"hp\",\n \"DELL%20SF\"=&gt;\"dell_sf\", \n \"DELL\"=&gt;\"dell\");\n $hardwarename=strtoupper($hardwarename);\n\n foreach ($mapping as $needle=&gt;$viewname) \n {\n if (strpos($hardwarename, $needle) !== false) return $viewname;\n }\n\n return \"default\";\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T13:55:42.183", "Id": "20633", "ParentId": "20404", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T00:46:54.337", "Id": "20404", "Score": "1", "Tags": [ "php" ], "Title": "Ideas for simplificaton - Logic to choose which view to load" }
20404
<p>The exercise is the bunny linked list exercise; the last beginner exercise from <a href="http://www.cplusplus.com/forum/articles/12974/" rel="nofollow">here</a>.</p> <p>I'm looking for feedback on absolutely everything that could make me a better programmer: </p> <ul> <li>Syntax</li> <li>Optimization</li> <li>Form</li> <li>Functions or variables naming</li> <li>Bugs</li> <li>Performance</li> <li>Code structure</li> </ul> <p>Keep in mind that I haven't completed all aspects of the exercise related to it running in real-time or outputting events to a file.</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;ctime&gt; #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include "BunnyNode.h" #include "BunnyList.h" //BUGS //Generate at least one female and one male on start //TO DO //Replace names with vectors(?) generated from separate .txt file //Output all turn events, birth, turn mutant, dies //Output all turns to file using std::cin; using std::cout; using std::endl; int main() { srand(time(0)); // Create rabbit LinkedList RabbitList * colony = new RabbitList; bool terminate = false; int turns = 0; //Add 5 rabbits to list for the first round colony-&gt;startCheck(turns); while(!terminate) { colony-&gt;printList(); cout &lt;&lt; endl; //Increment all rabbits age colony-&gt;incrementRabbitAge(); //Add babies colony-&gt;addBabies(); //Each mutant will convert one other bunny each turn colony-&gt;mutantConversion(); //Check if colony is 0 or 1000 colony-&gt;sizeCheck(terminate); cout &lt;&lt; "\nThe current mutant count is: " &lt;&lt; colony-&gt;mutantCount() &lt;&lt; endl; colony-&gt;printSize(); ++turns; if(colony-&gt;getColonySize() != 0) { cout &lt;&lt; "\nNext turn? Press any key to continue. (Press k to purge the colony.)" &lt;&lt; endl; char choice; cin &gt;&gt; choice; if(choice == 'k') colony-&gt;purge(); } } cout &lt;&lt; "\nTOTAL TURNS: " &lt;&lt; turns &lt;&lt; endl; delete colony; return 0; } </code></pre> <p><strong>BunnyList.cpp</strong></p> <pre><code>#include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include "BunnyList.h" #include "globals.h" using std::string; using std::cout; using std::endl; RabbitList::RabbitList(): head(NULL),size(0) {} RabbitList::~RabbitList() {} int RabbitList::randomGeneration(int x) { return rand() % x; } void RabbitList::generateRandomFeatures(RabbitNode * newRabbit) { newRabbit-&gt;sex = randomGeneration(2); //Generate gender first to determine first name newRabbit-&gt;colour = colourList[randomGeneration(MAX_COLOURS)]; //Generate colour int i = randomGeneration(10); if(newRabbit-&gt;sex) //Generate name newRabbit-&gt;firstName = maleFirstName[i]; else newRabbit-&gt;firstName = femaleFirstName[i]; i = randomGeneration(10); newRabbit-&gt;lastName = lastNames[i]; i = randomGeneration(100); //Generate mutant if(i &lt; BORN_MUTANT_PERCENT_CHANCE) newRabbit-&gt;radioactive_mutant_vampire_bunny = true; } //Turn checks void RabbitList::startCheck(int turns) { if(turns == 0) // Generate first 5 rabbits { for(int index = 0; index &lt; 5; ++index) { addRabbit(); } } } void RabbitList::sizeCheck(bool&amp; terminate) { if(getColonySize() == 0) terminate = true; else if(getColonySize() &gt;= MAX_COLONY_SIZE) { purge(); } } bool RabbitList::fatherCheck(RabbitNode * rabbit, bool&amp; fatherPresent) { if(rabbit-&gt;sex == 1 &amp;&amp; rabbit-&gt;age &gt;= 2 &amp;&amp; rabbit-&gt;radioactive_mutant_vampire_bunny == false) fatherPresent = true; return fatherPresent; } bool RabbitList::motherCheck(RabbitNode * rabbit) { if(rabbit-&gt;sex == 0 &amp;&amp; rabbit-&gt;age &gt;= 2 &amp;&amp; rabbit-&gt;radioactive_mutant_vampire_bunny == false) return true; else return false; } //Returns true if rabbit is older than 10, false otherwise bool RabbitList::ageCheck(RabbitNode * rabbit) { if(head) { if(rabbit-&gt;age &gt;= MAX_AGE &amp;&amp; rabbit-&gt;radioactive_mutant_vampire_bunny == false) { return 1; } else if(rabbit-&gt;age &gt;= MAX_MUTANT_AGE &amp;&amp; rabbit-&gt;radioactive_mutant_vampire_bunny == true) { return 1; } else return 0; } } //Add one year to all rabbit every turn, //Kill the rabbit if he goes over its allowed age, 10 for regular, 50 for mutant void RabbitList::incrementRabbitAge() { //If there's more than one node if(head) { RabbitNode * temp = head; RabbitNode * trail = NULL; while(temp != NULL) { //The rabbit is young enough to age if(!ageCheck(temp)) { temp-&gt;age += 1; trail = temp; temp = temp-&gt;next; } //The rabbit is too old else { //If we're on the first head node if(head == temp) { head = temp-&gt;next; cout &lt;&lt; "Bunny " &lt;&lt; getName(temp) &lt;&lt; " died!" &lt;&lt; endl; delete temp; temp = head; --size; } //If we're beyond the head node else { trail-&gt;next = temp-&gt;next; cout &lt;&lt; "Bunny " &lt;&lt; getName(temp) &lt;&lt; " died!" &lt;&lt; endl; delete temp; temp = trail-&gt;next; --size; } } } } } void RabbitList::addBabies() { if(head) { //Checks if there is at least one male in the colony bool fatherPresent = false; RabbitNode* temp = head; while(temp != NULL) { fatherCheck(temp, fatherPresent); temp = temp-&gt;next; } //Executes if there's at least one male if(fatherPresent == true) { temp = head; RabbitNode * trail = NULL; while(temp != NULL) { if(motherCheck(temp) == true) { addRabbit(temp); temp = temp-&gt;next; } else { temp = temp-&gt;next; } } } } } void RabbitList::addRabbit() { RabbitNode* newRabbit = new RabbitNode; if(!head) { head = newRabbit; generateRandomFeatures(newRabbit); } else { RabbitNode* temp = head; while(temp-&gt;next != NULL) temp = temp-&gt;next; RabbitNode* newRabbit = new RabbitNode; generateRandomFeatures(newRabbit); temp-&gt;next = newRabbit; } ++size; } void RabbitList::addRabbit(RabbitNode * mother) { RabbitNode* newRabbit = new RabbitNode; if(!head) { head = newRabbit; generateRandomFeatures(newRabbit); if(newRabbit-&gt;radioactive_mutant_vampire_bunny == true) cout &lt;&lt; "Radioactive Mutant Vampire "; cout &lt;&lt; "Bunny " &lt;&lt; getName(newRabbit) &lt;&lt; " was born!" &lt;&lt; endl; } else { RabbitNode* temp = head; while(temp-&gt;next != NULL) temp = temp-&gt;next; RabbitNode* newRabbit = new RabbitNode; generateRandomFeatures(newRabbit); // We'll replace the colour right after newRabbit-&gt;colour = mother-&gt;colour; // Set baby colour to be the same as the mother temp-&gt;next = newRabbit; if(newRabbit-&gt;radioactive_mutant_vampire_bunny == true) cout &lt;&lt; "Radioactive Mutant Vampire "; cout &lt;&lt; "Bunny " &lt;&lt; getName(newRabbit) &lt;&lt; " was born!" &lt;&lt; endl; } ++size; } int RabbitList::mutantCount() { int mutantTotal = 0; if(head) { RabbitNode * temp = head; while(temp != NULL) { if(temp-&gt;radioactive_mutant_vampire_bunny) ++mutantTotal; temp = temp-&gt;next; } } return mutantTotal; } //For each mutant rabbit, it will convert another one each turn void RabbitList::mutantConversion() { //Get the number of mutants in the colony int amountToConvert = mutantCount(); if(amountToConvert &gt; 0 &amp;&amp; head != NULL) { //Executes if there's still bunnies left to convert, or if all the bunnies aren't mutants yet while(amountToConvert != 0 &amp;&amp; mutantCount() != getColonySize()) { RabbitNode * temp = head; //Choose a bunny randomly in the colony to convert int bunnyToConvert = randomGeneration(getColonySize()); //Traverse list to get to the chosen bunny for(; bunnyToConvert &gt; 0; --bunnyToConvert) { temp = temp-&gt;next; } //Check if chosen bunny isn't already a mutant if(temp-&gt;radioactive_mutant_vampire_bunny == false) { temp-&gt;radioactive_mutant_vampire_bunny = true; cout &lt;&lt; getName(temp) &lt;&lt; " has turned into a mutant!" &lt;&lt; endl; --amountToConvert; } } } } void RabbitList::purge() { if(getColonySize() == 1) { delete head; head = NULL; --size; } if(head) { //Kill half the colony for(int amountToKill = (getColonySize()) / 2; amountToKill != 0;) { RabbitNode * curr = head; RabbitNode * trail = NULL; //Choose a bunny randomly in the colony to kill int bunnyToKill = randomGeneration(getColonySize()); //Traverse list to get to the chosen bunny to kill for(; bunnyToKill &gt; 0; --bunnyToKill) { trail = curr; curr = curr-&gt;next; } //If we're on the head node if(curr == head) { head = curr-&gt;next; delete curr; --size; --amountToKill; } //If we're beyond the head, but not on last node else if(curr-&gt;next != NULL) { trail-&gt;next = curr-&gt;next; delete curr; --size; --amountToKill; } //If we're on the last node else { trail-&gt;next = NULL; // crash delete curr; --size; --amountToKill; } } cout &lt;&lt; "Food shortage! Colony has been purged by half." &lt;&lt; endl; } } //DATA MEMBER ACCESSORS string RabbitList::getGender(RabbitNode * rabbit) { if(rabbit-&gt;sex == 1) return "Male"; else return "Female"; } string RabbitList::getName(RabbitNode * rabbit) { return rabbit-&gt;firstName + " " + rabbit-&gt;lastName; } int RabbitList::getColonySize() { return size; } void RabbitList::printList() { RabbitNode* temp = head; if(head) { while(temp != NULL) { printFeatures(temp); temp = temp-&gt;next; } } } void RabbitList::printFeatures(RabbitNode * rabbit) { if(head) { cout &lt;&lt; "\nNAME: " &lt;&lt; getName(rabbit) &lt;&lt; endl &lt;&lt; "AGE: " &lt;&lt; rabbit-&gt;age &lt;&lt; endl &lt;&lt; "COLOUR: " &lt;&lt; rabbit-&gt;colour &lt;&lt; endl &lt;&lt; "GENDER: " &lt;&lt; getGender(rabbit) &lt;&lt; endl; if(rabbit-&gt;radioactive_mutant_vampire_bunny) cout &lt;&lt; "Radioactive mutant vampire bunny!" &lt;&lt; endl; cout &lt;&lt; endl; } } void RabbitList::printSize() { if(head) cout &lt;&lt; "The colony's size is currently : " &lt;&lt; size &lt;&lt; endl; } </code></pre> <p><strong>BunnyNode.cpp</strong></p> <pre><code>#include "BunnyNode.h" using std::cout; using std::endl; RabbitNode::RabbitNode():next(NULL), firstName("none"), lastName("none"), colour("none"), age(0), radioactive_mutant_vampire_bunny(0) {} RabbitNode::~RabbitNode() {} </code></pre> <p><strong>BunnyList.h</strong></p> <pre><code>#ifndef GUARD_BUNNYLIST_H #define GUARD_BUNNYLIST_H #include &lt;string&gt; #include "BunnyNode.h" class RabbitList { public: //Constructor RabbitList(); ~RabbitList(); //Member methods int randomGeneration(int x); void generateRandomFeatures(RabbitNode * newRabbit); void startCheck(int turns); void sizeCheck(bool&amp; terminate); bool motherCheck(RabbitNode * rabbit); bool fatherCheck(RabbitNode * rabbit, bool&amp; fatherPresent); bool ageCheck(RabbitNode * rabbit); void incrementRabbitAge(); void addBabies(); void addRabbit(); void addRabbit(RabbitNode * mother); void purge(); int mutantCount(); void mutantConversion(); std::string getGender(RabbitNode * rabbit); std::string getName(RabbitNode * rabbit); int getColonySize(); void printList(); void printFeatures(RabbitNode * rabbit); void printSize(); private: RabbitNode* head; int size; }; #endif // GUARD_BUNNYLIST_H </code></pre> <p><strong>BunnyNode.h</strong></p> <pre><code>#ifndef GUARD_BUNNYNODE_H #define GUARD_BUNNYNODE_H #include &lt;iostream&gt; #include &lt;string&gt; class RabbitNode { friend class RabbitList; public: RabbitNode(); ~RabbitNode(); private: std::string firstName, lastName, colour; int age; bool sex; bool radioactive_mutant_vampire_bunny; RabbitNode* next; }; #endif // GUARD_BUNNYNODE_H </code></pre> <p><strong>globals.h</strong></p> <pre><code>#ifndef GUARD_GLOBALS_H #define GUARD_GLOBALS_H static const int MAX_COLOURS = 4; static const int MAX_AGE = 10; static const int MAX_MUTANT_AGE = 50; static const int MAX_COLONY_SIZE = 1000; static const int BORN_MUTANT_PERCENT_CHANCE = 2; //To do: replace with vectors(?) generated from separate .txt file static std::string maleFirstName[] = { "Bob", "Nick", "Roger", "Tim", "Ivan", "John", "Jack", "Vincent", "Dave", "Donald" }; static std::string femaleFirstName[] = { "Kate", "Jane", "Lisa", "Kim", "Allison", "Sophie", "Anna", "Lillian", "Sarah", "Alexandra" }; static std::string lastNames[] = { "Smith", "Williams", "Brown", "von Shaft", "Mitchell", "O'Connor", "Edwards", "Harris", "Wood", "Cooper" }; static std::string colourList[MAX_COLOURS] = { "White", "Brown", "Black", "Spotted" }; #endif // GUARD_BUNNYNODE_H </code></pre>
[]
[ { "body": "<p>Not a full review, but just some general comments on style and other C++ idioms. Note that I only looked at some of the code and wasn't looking at correctness.</p>\n\n<h2>Style</h2>\n\n<ul>\n<li>You should name your files with the same name as the class (eg. <code>class RabbitNode</code> would be in RabbitNode.h and RabbitNode.cpp)</li>\n<li>Always use braces <code>{}</code> on if/else and while blocks. Yes, you don't have to use them if it's a one-liner, but it avoids bugs in the future when you add more lines to the same <code>if</code> block and forget to add the braces</li>\n<li><p>Put items in the constructor's initialization list on separate lines. This makes for easier reading when there are many member variables, and it makes diffs cleaner when you make changes</p>\n\n<pre><code>RabbitNode::RabbitNode()\n : next(NULL)\n , firstName(\"none\")\n , lastName(\"none\")\n , colour(\"none\")\n , age(0)\n , radioactive_mutant_vampire_bunny(0)\n{}\n</code></pre></li>\n<li><p>Distinguish local variables from member variables in some way. Often people use a leading <code>_</code> or <code>m_</code>. This makes it easier to read code and know if you're touching locals or members, and it also makes using auto-complete features of your IDE easier. If you're coding and want to see all the members of your class to auto-complete, just start with <code>m_</code> for example to get the list.</p>\n\n<p>eg. In BunnyList.h</p>\n\n<pre><code>private:\n RabbitNode* m_head;\n int m_size;\n</code></pre></li>\n<li><p>Avoid globals. There are cases where they should be used, but generally should be avoided. Especially if you're just starting out, you should actively develop the habit to avoid them. In some cases, some of the constants you've defined in your Globals.h file are only used in one file, so just move the constants there. In most other cases, you can avoid globals by passing them in as parameters to functions or class constructors.</p></li>\n</ul>\n\n<h2>Includes / Forward declaration</h2>\n\n<p>The general rule is, only use an <code>#include</code> for what you need in that single file, and use forward declaration wherever possible instead of <code>#include</code>.</p>\n\n<p>A few examples:</p>\n\n<ul>\n<li>In BunnyNode.h, you aren't using anything from <code>&lt;iostream&gt;</code> here, so don't include it</li>\n<li>In BunnyList.h, you don't actually need the definition of <code>RabbitNode</code> since you only have a pointer member and pointer parameters. This means you can forward declare <code>RabbitNode</code> and leave out the <code>#include</code>. After making the above change, in BunnyList.cpp, you need the definition of <code>RabbitNode</code>, so the forward declaration you bring in from BunnyList.h won't be sufficient - you should now <code>#include BunnyNode.h</code> here. Check out <a href=\"https://stackoverflow.com/questions/553682/when-to-use-forward-declaration\">this StackOverflow question</a> for info on how/when to use forward declarations.</li>\n<li>I believe you're not using anything from <code>&lt;cstdlib&gt;</code> in BunnyList.cpp, so remove that <code>#include</code></li>\n</ul>\n\n<h2>Const</h2>\n\n<p>You are not using <code>const</code> keyword anywhere. Using <code>const</code> can not only prevent bugs, but also it makes the programmers intentions clear about how variables and functions are going to be used.</p>\n\n<p>In general, if a class member function will not change the state its member variables, it should be declared <code>const</code>. Note that this needs to be put in both the header and implementation file.</p>\n\n<p>eg. in BunnyList.h</p>\n\n<pre><code>void printSize() const;\n</code></pre>\n\n<p>eg. in BunnyList.cpp</p>\n\n<pre><code>void RabbitList::printSize() const\n{\n if(head)\n cout &lt;&lt; \"The colony's size is currently : \" &lt;&lt; size &lt;&lt; endl;\n}\n</code></pre>\n\n<p>In general, variables (including member variables) should be declared <code>const</code> if they will never change value. This goes for parameters too.</p>\n\n<p>eg. in BunnyList.h</p>\n\n<pre><code>// rabbit will not be altered in this function, so make it const\n// while we're at it, make the function const since this function will not alter any member variables\nbool ageCheck(const RabbitNode * rabbit) const;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T17:08:15.663", "Id": "32707", "Score": "0", "body": "Thank you for taking the time to write this! They are all very valid points and very clearly explained." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T03:52:34.263", "Id": "32738", "Score": "2", "body": "Don't use leading underscores for variable names. `_` (and `__`) are reserved for compiler usage. The rules are overly complex, see http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier - but basically the takeaway is it's easiest not to use `_` or `__` to start a variable name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T23:06:17.080", "Id": "32831", "Score": "0", "body": "Great, I'll just use m_ instead. @MahlerFive : Is rand() defined elsewhere? That is why I needed to include cstdlib." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T20:58:34.823", "Id": "32954", "Score": "0", "body": "Didn't see the usage of rand(), in that case you do need cstdlib" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T08:24:00.287", "Id": "20411", "ParentId": "20407", "Score": "10" } }, { "body": "<p>Like @MahlerFive, I haven't checked your code for correctness. Here are some general comments:</p>\n\n<ul>\n<li><p>Consider using coding standards. Check your code against them. This will make your coding style consistent. Our dept, for example, has taken Google's coding standards (found <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\" rel=\"nofollow\">here</a>) and modified them. Everyone in our dept. follows those conventions. The entire codebase has now started to look similar. Makes it much easier to read code.</p>\n\n<p>This will help you avoid inconsistencies like <code>RabbitNode* next</code> and <code>RabbitNode * next</code> (notice the position of <code>*</code> in the two cases).</p></li>\n<li><p><a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Friends\" rel=\"nofollow\">Avoid using friend declarations. Use them only if you must.</a></p></li>\n<li><p><a href=\"http://www.stackoverflow.com/questions/1282295/what-exactly-is-nullptr\">Consider using <code>nullptr</code> instead of <code>NULL</code></a>. </p>\n\n<p>This suggestion is not valid if you're using an older compiler that\ndoesn't support nullptr but since you're learning C++ you should know\nthe newer facilities in it. nullptr is something that has been\nintroduced in the latest standard of C++.</p></li>\n<li><p><a href=\"http://www.google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces\" rel=\"nofollow\">Consider using a <code>namespace</code></a>.</p></li>\n<li><p>Functions that return a bool should be named starting with a verb, for example, motherCheck() should probably be hasMother(). In your code, there are two functions:</p>\n\n<pre><code>void sizeCheck(bool&amp; terminate);\n</code></pre>\n\n<p></p>\n\n<pre><code>bool motherCheck(RabbitNode * rabbit);\n</code></pre>\n\n<p>One returns a <code>void</code> and another a <code>bool</code>, but they're both named similarly.</p></li>\n<li><p>Consider using a smart pointer instead of bare pointer. You have this in your code:</p>\n\n<pre><code>RabbitList * colony = new RabbitList;\n</code></pre>\n\n<p>The answer to <em>What is a smart pointer and why must you use it?</em> can be found <a href=\"http://www.stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one\">here</a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T23:03:46.553", "Id": "32830", "Score": "0", "body": "Great reply, thank you for your time. All replies so far have pointed to using smart pointers and such; I'll have to give it a shot as soon as I can figure out how to setup my compiler to use the new coding standards.\n\nShould a boolean variable also be named with a verb, or it's good enough with functions that return a bool? I just want to clarify this. Also, can you give me a hint that would point me in the right direction to replace my friend declaration? Right now, BunnyList needs the friendship of RabbitNode to access its member variables, so removing it completely breaks my program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T21:08:02.243", "Id": "32955", "Score": "0", "body": "In general, ALL functions should use a verb, since functions *do* things. Also, in general, all variables and classes should be a noun, since they *are* things. This doesn't just apply to bools and functions that return bools.\n\nYou can avoid using `friend` by giving RabbitNode a public interface instead of just being a simple bag of variables. For example, you only want to set the `sex` of the RabbitNode when it is created, and then after that you only want to be able to check it. In this case, you should add `sex` as a parameter to the constructor, and then add a public `getSex()` function" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T03:33:38.920", "Id": "20455", "ParentId": "20407", "Score": "3" } }, { "body": "<p>A few more bits of advice:</p>\n<h2>Usage of New</h2>\n<p>In <code>main.cpp</code> you <code>new</code> an instance of <code>RabbitList</code>, only to <code>delete</code> it at the end of the function. If a variable doesn't need to outlive the scope of the function it is defined in, there is no reason to <code>new</code> it. Instead, you should stack-allocate it, that is:</p>\n<pre><code>RabbitList colony;\n</code></pre>\n<p>This guarantees it will be cleaned up in case of an unhandled exception being thrown.</p>\n<h2>Memory Leaks</h2>\n<p>Your <code>RabbitList</code> destructor is empty, however, in your <code>addRabbit</code> methods, you do:</p>\n<pre><code> RabbitNode* newRabbit = new RabbitNode;\n</code></pre>\n<p>This memory is never freed through <code>delete</code>, hence you have what is called a <em>memory leak</em> - memory that has been allocated that can never be deallocated. To fix this, you'll need to make sure that you walk through each node in your destructor, freeing as you go:</p>\n<pre><code>RabbitList::~RabbitList()\n{\n RabbitNode* tmp = NULL;\n while(head != NULL) {\n tmp = head-&gt;next; //Make sure we hold a pointer to the next node\n delete head;\n head = tmp;\n }\n}\n</code></pre>\n<p>The other option is to use a <code>unique_ptr</code>, however, this may be too confusing for the moment, and is only available through boost or as part of C++11.</p>\n<h2>Lack of Copy Constructor/Assignment Operator</h2>\n<p>Suppose you wanted to copy an already-initialized <code>RabbitList</code>, either by:</p>\n<pre><code>RabbitList colony;\n//Some actions on colony\nRabbitList next_colony(colony); //copy construction\nRabbitList another_colony = colony; //copy assignment\n</code></pre>\n<p>These two functions correspond to:</p>\n<pre><code>RabbitList::RabbitList(const RabbitList&amp; rhs); //Copy constructor\nRabbitList&amp; RabbitList::operator=(const RabbitList&amp; rhs); //Copy assignment\n</code></pre>\n<p>There are two ways to fix this: either declare them both <code>private</code>, which will throw up a compiler error if anyone tries to perform either of these copies, or implement them. These functions can actually be a little bit tricky to implement, but I'd suggest reading <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">this</a> StackOverflow post about what is called the &quot;Rule of Three&quot; if you do decide to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T22:50:03.633", "Id": "32828", "Score": "0", "body": "VERY good advice, thank you. Especially memory leaks; I should have specified that I was specifically looking for feedback about this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T04:32:22.983", "Id": "20458", "ParentId": "20407", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T03:51:49.713", "Id": "20407", "Score": "10", "Tags": [ "c++", "beginner", "linked-list" ], "Title": "Linked list of bunny objects" }
20407
<p>I want to filter the options of a large select group based on text input in a textbox. I am currently using this code to filter from a <code>SELECT</code> group based on the text of a input box.</p> <p>Can you please tell me whether there is a more efficient way of doing this? My <code>SELECT</code> group is very large with around 7000 entries, which is why I am looking for the most optimized way.</p> <pre><code>&lt;script&gt; var fullcelllist = $(); var lastVal =""; $(window).load(function(){ $("#celllist option").each(function(){ fullcelllist.push($(this).val()); }); }); $("#filtercell").keyup(function() { if(lastVal.length &lt; $(this).val().length){ $("#celllist option:not([value*='"+$(this).val().toUpperCase()+"'])").each(function() { $(this).remove(); }); }else{ stregexp = new RegExp($(this).val(),"i"); temparr = $.grep(fullcelllist, function (value) { if(value.match(stregexp)) return value; return null; }); newopt = ""; temparr.sort(); $.each(temparr,function(i){ newopt += "&lt;option value='"+temparr[i]+"'&gt;"+temparr[i]+"&lt;/option&gt;"; }); $("#celllist").html(""); $("#celllist").append(newopt); } lastVal = $(this).val(); }); &lt;/script&gt; &lt;input type="text" id="filtercell"&gt; &lt;select id ="celllist" multiple="multiple"&gt; // HERE all OPTIONS using PHP &lt;select&gt; </code></pre>
[]
[ { "body": "<p>Your jQuery could be somewhat more efficient if you minimize <code>$(...)</code> element look-ups by storing them as variables or chaining them.</p>\n\n<p>Also, I think you will see some benefit to replacing some jQuery constructs with their pure JS alternatives (<code>$.each</code> -> <code>for</code>, etc..)</p>\n\n<p>Check out <a href=\"http://jsperf.com/caching-jquery-selectors\" rel=\"nofollow noreferrer\">this set of jsPerf tests</a> from <a href=\"https://stackoverflow.com/a/10055208/363701\">this StackOverflow answer</a>.</p>\n\n<pre><code>&lt;script&gt;\nvar fullcelllist = $(),\n lastVal =\"\",\n $celllistOption = $(\"#celllist option\");\n\n// ...\n\n$(\"#filtercell\").keyup(function() {\n var $this = $(this),\n $thisVal = $this.val();\n\n// ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T08:29:00.720", "Id": "32739", "Score": "0", "body": "thanks .. i didn't know that reusing $(...) would hamper my performance! Good to know, I'll change accordingly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:43:32.457", "Id": "20421", "ParentId": "20415", "Score": "3" } }, { "body": "<p>You can do something like this </p>\n\n<pre><code>var options = $(\"#celllist option\"); // cache all your options right away\n\n$(\"#filtercell\").keyup(function () {\n var stregexp = new RegExp($(this).val(), \"i\"); // your regex\n $(\"#celllist\").append(options); // append will add all missing options\n var x = $.grep(options, function (value) { // get all the options where value doesn't match\n return !value.value.match(stregexp)\n });\n $(x).detach(); // detach them from dom\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/WzwEq/\" rel=\"nofollow\">FIDDLE</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:14:55.617", "Id": "20444", "ParentId": "20415", "Score": "1" } } ]
{ "AcceptedAnswerId": "20421", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T12:08:00.297", "Id": "20415", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Filtering a SELECT group using jQuery" }
20415
<p>I frequently run a script similar to the one below to analyze an arbitrary number of files in parallel on a computer with 8 cores. </p> <p>I use Popen to control each thread, but sometimes run into problems when there is much stdout or stderr, as the buffer fills up. I solve this by frequently reading from the streams. I also print the streams from one of the threads to help me follow the progress of the analysis.</p> <p>I'm curious on alternative methods to thread using Python, and general comments about the implementation, which, as always, has room for improvement. Thanks!</p> <pre><code>import os, sys import time import subprocess def parallelize(analysis_program_path, filenames, N_CORES): ''' Function that parallelizes an analysis on a list of files on N_CORES number of cores ''' running = [] sys.stderr.write('Starting analyses\n') while filenames or running: while filenames and len(running) &lt; N_CORES: # Submit new analysis filename = filenames.pop(0) cmd = '%s %s' % (analysis_program_path, filename) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sys.stderr.write('Analyzing %s\n' % filename) running.append((cmd, p)) i = 0 while i &lt; len(running): (cmd, p) = running[i] returncode = p.poll() st_out = p.stdout.read() st_err = p.stderr.read() # Read the buffer! Otherwise it fills up and blocks the script if i == 0: # Just print one of the processes sys.stderr.write(st_err) if returncode is not None: st_out = p.stdout.read() st_err = p.stderr.read() sys.stderr.write(st_err) running.remove((cmd, p)) else: i += 1 time.sleep(1) sys.stderr.write('Completely done!\n') </code></pre>
[]
[ { "body": "<p>Python has what you want built into the standard library: see the <a href=\"http://docs.python.org/2/library/multiprocessing.html\" rel=\"noreferrer\"><code>multiprocessing</code> module</a>, and in particular the <a href=\"http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map\" rel=\"noreferrer\"><code>map</code> method</a> of the <a href=\"http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"noreferrer\"><code>Pool</code> class</a>.</p>\n\n<p>So you can implement what you want in one line, perhaps like this:</p>\n\n<pre><code>from multiprocessing import Pool\n\ndef parallelize(analysis, filenames, processes):\n '''\n Call `analysis` for each file in the sequence `filenames`, using\n up to `processes` parallel processes. Wait for them all to complete\n and then return a list of results.\n '''\n return Pool(processes).map(analysis, filenames, chunksize = 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:23:54.503", "Id": "20514", "ParentId": "20416", "Score": "5" } } ]
{ "AcceptedAnswerId": "20514", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T12:47:40.057", "Id": "20416", "Score": "4", "Tags": [ "python", "multithreading" ], "Title": "Python parallelization using Popen" }
20416
<p>I often need to return empty collections.<br> One of those days I wrote the following to return a cached instance:</p> <pre><code>public static class Array&lt;T&gt; { // As a static field, it gets created only once for every type. public static readonly T[] Empty = new T[0]; } </code></pre> <p>I didn't know about <code>Enumerable&lt;T&gt;.Empty()</code> maybe it didn't exist back then. Although I know now, I still use this one.</p> <p>There are still many functions in BCL that need an array instead of <code>IEnumerable&lt;T&gt;</code>, <code>IList&lt;T&gt;</code> or <code>IReadOnlyList&lt;T&gt;</code>. And array implements all of these so it can be used anywhere.</p> <pre><code>// All these variables share the same array's reference. string[] empty1 = Array&lt;string&gt;.Empty; IEnumerable empty2 = Array&lt;string&gt;.Empty; IEnumerable&lt;string&gt; empty3 = Array&lt;string&gt;.Empty; </code></pre> <p>What do you think about this class?<br> Can you see any other advantages/disadvantages of it over <code>Enumerable&lt;T&gt;.Empty()</code>? </p> <p>And about implementation:<br> Do you think making the caching using a static field would cause any problem?</p> <hr> <p>Edit: Array class now has a static, generic <a href="https://docs.microsoft.com/dotnet/api/system.array.empty" rel="nofollow noreferrer">Empty</a> method, essentially deprecating this implementation.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:27:53.627", "Id": "32698", "Score": "0", "body": "I wasn't aware of this little gem. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:46:37.013", "Id": "32701", "Score": "0", "body": "@Jesse: You sir, are very welcome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T15:16:41.013", "Id": "32790", "Score": "0", "body": "What are your typical use cases for this class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:25:45.060", "Id": "32900", "Score": "0", "body": "@Leonid: I use it mostly on socket programming (to send an empty frame) and on collection returning methods that are called often: `IEnumerable<Foo> GetRelatedFoos(Foo foo) { if (foo.Operations == 0) return Array<Foo>.Empty; return GetRelatedFoosInternal(foo); }` where `GetRelatedFoosInternal(Foo foo)` is an iterator block. By separating these methods I can avoid initializing the iterator's state machine unless necessary and by returning `Array<Foo>.Empty` instead of `new Foo[0]` I can use the single, empty `Foo[]` instance for every `GetRelatedFoos` call that should return empty." } ]
[ { "body": "<p>I think it entirely depends on context.</p>\n\n<p><code>Enumerable&lt;T&gt;.Empty()</code> was clearly introduced for syntactic sugar in Linq. I see no reason to use it over a plain old new-statement.</p>\n\n<p>The wider question about caching and efficiency depends on the code-base. Calling a list \"Empty\" explicitly states intent and could help readability, but if you later go on to add items to that collection in any way, it actually makes the code more confusing.</p>\n\n<p>As far as any problems with the \"cached, static\" field go, the obvious problem is that if someone was foolish enough to place a lock on that static list, it could cause all manner of issues in your application as it'd act as a point of coupling.</p>\n\n<p>I'd <em>always</em> avoid using shared static references if you don't need them for any specific reason, especially if it's a perceived performance problem that has never been encountered. You can't really get much safer than an instance variable with a new empty list in it.</p>\n\n<p>Conversely, if you're really up against the wire with performance, there may be a good reason here, but you'd probably find that if you're micro-optimising list initialisation, there's a better higher level optimisation to be made.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:14:53.330", "Id": "32695", "Score": "2", "body": "Well, one of the reasons I went with array is that arrays with no elements are completely immutable. Since the field is also read-only, there is no way someone can change that cached instance of the array (it will forever be empty). About making it static: There are a lot of public static fields (and singletons that return static instances) even in BCL, so the probability of someone may put o lock on them shouldn't affect an API's design in my opinion. Also, I believe if someone does that, he really deserves the problems it will cause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:15:09.257", "Id": "32696", "Score": "0", "body": "+1 for your point on my approach being a micro-optimization though; you're right about that. I could just return `new T[0]` and that wouldn't hurt the performance in most of the cases but I couldn't see a reason for it. Now I know that `Enumerable<T>.Empty()` also does caching and I think locking `Enumerable<string>.Empty()` does probably the same thing with locking `Array<string>.Empty`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:33:30.183", "Id": "20420", "ParentId": "20417", "Score": "0" } }, { "body": "<p>Your solution is absolutely correct and practical. </p>\n\n<p>In fact <code>Enumerable.Empty&lt;T&gt;</code> also returns empty array under the hood, just slightly in a different way (they have a separate instance holder class that is lazily initialized).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T16:57:02.510", "Id": "20435", "ParentId": "20417", "Score": "4" } }, { "body": "<p>While it most certainly is nifty to save a little bit of time by using cached collections, returning the same empty collection every time an empty collection needs to be returned is digging yourself into a hole:</p>\n\n<p>Consider what happens if the user decides to also 'save a little bit of time' by re-using the collection that your function returned. The empty collection you were returning everywhere would not be empty anymore and the re-used empty collections would cause many bugs.</p>\n\n<p>I would say best practice is to use a memorypool of any kind to pool the collections you use in time-critical code and using that to get the empty collection. This way you achieve the same speed as when returning a cached collection, but without the limitation that the empty collection cannot be used for anything, ever.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-29T17:53:01.120", "Id": "324978", "Score": "4", "body": "Arrays are non-resizable, so there is no risk with it becoming anything but 'empty'. The only way I can see this possibly going wrong is if you compare references, either expecting all empty arrays to be the same, or (for some bizarre reason) using such arrays as keys (both seem unlikely, and would probably indicate a deficiency elsewhere). I don't think there was any suggestion in the OP to provide such a facility for `List` or other such dynamic data structures." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-29T17:04:10.670", "Id": "171520", "ParentId": "20417", "Score": "1" } } ]
{ "AcceptedAnswerId": "20435", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T12:55:29.047", "Id": "20417", "Score": "7", "Tags": [ "c#", ".net", "array", "collections" ], "Title": "Cached empty collections" }
20417
<p>I've just created a teeny little script to count the seconds until I get auto-logged off. I already solved my issue with my ssh client settings, but I'd still like any help making the bash script nicer to read, or just tips in general.</p> <pre><code>#!/bin/bash count=0 while ( [ : ] ) do count=$(($count+1)) n=${n:-0} for i in `seq 0 $n`; do echo -en '\b'; done n="${#count}" echo -n $count sleep 1 done </code></pre>
[]
[ { "body": "<p>If the answer is what you care for,</p>\n\n<p>in your .bash_profile :</p>\n\n<pre><code>touch \"~/.loggued_in\"\n</code></pre>\n\n<p>in your .bash_logout:</p>\n\n<pre><code>date -r ~/.loggued_in ; date\n</code></pre>\n\n<p>and check if there is a timeout setup:</p>\n\n<pre><code>{ set ; env ; } | egrep 'TM|TIME|OUT' | sort | uniq\n</code></pre>\n\n<p>and lastly, if connecting via something like Putty (or other), they can be setup to have a \"keepalive\" sent regularly (usually a \"nop\"). In Putty, \"Settings - Connection - seconds between keepalives\" (0 by default : set it to, say, 50 if you get auto loggued off after 1mn)</p>\n\n<p>ok, about the code itself : very nice for displaying the time in an interresting manner (sort of like a progress bar). If you prefer it in one place (and no need for an extra $n) :</p>\n\n<pre><code>while ( [ : ] ); do count=$(($count+1)); echo -en '\\b\\b\\b\\b'; printf \"%4s\" $count; sleep 1; done\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:25:10.833", "Id": "32697", "Score": "0", "body": "sorry for the 3 first parts: i got used to questions on so ... I believe my answer is not at all what you need here, ie code review - wise... But your script is quite fine already. Let's see what others propose as interresting modifications" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:45:53.070", "Id": "32700", "Score": "0", "body": "Thanks guys for your comments. I tried to give you guys a point but it's saying I have to login (which I don't want to do right now). It let me do the check box though. Oh and yes I had already determined how to prevent ssh disconnects. It did take me a long time, I should have asked on here. :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:21:50.217", "Id": "20419", "ParentId": "20418", "Score": "0" } }, { "body": "<pre><code>count=0\nwhile true; do\n printf \"\\r%d\" $((++count))\n sleep 1\ndone\n</code></pre>\n\n<p>Your while condition is doing a lot of work just to return true: you launch a subshell, and evaluate a test giving a 1-character string (which will <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#index-test\">always return true</a>). Make it simpler and more readable by just executing the <a href=\"http://man.cx/true\"><code>true</code></a> program.</p>\n\n<p>Note that variable names inside an arithmetic expression do not require the leading dollar sign in most cases. That's quietly documented <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic\">here</a>:</p>\n\n<blockquote>\n <p>\"Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.\"</p>\n</blockquote>\n\n<p><code>printf</code> is more portable than <code>echo</code>, if that's a concern for you. I also find it makes your intentions more obvious.</p>\n\n<p>Instead of backing up the right number of characters, just carriage return to the first column and overwrite the previous contents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:12:13.053", "Id": "32720", "Score": "0", "body": "No freaking way. I _did_ previously know about /bin/true, I just didn't think of it. However, I never knew bash had a ++ syntax, nor did I realize I can use variable names _without_ the dollar sign. THANKS!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T16:09:51.287", "Id": "20433", "ParentId": "20418", "Score": "5" } } ]
{ "AcceptedAnswerId": "20433", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:04:13.333", "Id": "20418", "Score": "7", "Tags": [ "bash" ], "Title": "Counting seconds until auto-log-off" }
20418
<p>This morning I was trying to find a good way of using <code>os.path</code> to load the content of a text file into memory, which exists in the root directory of my current project.</p> <p><a href="http://halfcooked.com/blog/2012/06/01/python-path-relative-to-application-root/" rel="noreferrer">This approach</a> strikes me as a bit hackneyed, but after some thought it was exactly what I was about to do, except with <code>os.path.normpath(os.path.join(__file__, '..', '..'))</code> </p> <p>These relative operations on the path to navigate to a <em>static</em> root directory are brittle.</p> <p>Now, if my project layout changes, these associations to the (former) root directory change with it. I wish I could assign the path to find a target, or a destination, instead of following a sequence of navigation operations.</p> <p>I was thinking of making a special <code>__root__.py</code> file. Does this look familiar to anyone, or know of a better implementation?</p> <pre><code>my_project | | __init__.py | README.md | license.txt | __root__.py | special_resource.txt | ./module |-- load.py </code></pre> <p>Here is how it is implemented:</p> <pre><code>"""__root__.py""" import os def path(): return os.path.dirname(__file__) </code></pre> <p>And here is how it could be used:</p> <pre><code>"""load.py""" import __root__ def resource(): return open(os.path.join(__root__.path(), 'special_resource.txt')) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:41:47.363", "Id": "33095", "Score": "0", "body": "You should choose an answer or provide more information." } ]
[ { "body": "<p>your approach seems ok, but as it is not a common problem/solution, you should document what your <code>__root__.py</code> file is doing.</p>\n\n<p>One thing: you should not use double leading and trailing underscores, see <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">pep8</a> </p>\n\n<blockquote>\n <p><strong>double_leading_and_trailing_underscore</strong>: \"magic\" objects or attributes that live in user-controlled namespaces. E.g. <code>__init__</code>,\n <code>__import__</code> or <code>__file__</code>. Never invent such names; only use them as documented.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T21:03:25.463", "Id": "20448", "ParentId": "20428", "Score": "1" } }, { "body": "<p>I never heard of <code>__root__.py</code> and don't think that is a good idea.</p>\n\n<p>Instead create a <code>files.py</code> in a <code>utils</code> module:</p>\n\n<pre><code>MAIN_DIRECTORY = dirname(dirname(__file__))\ndef get_full_path(*path):\n return join(MAIN_DIRECTORY, *path)\n</code></pre>\n\n<p>You can then import this function from your <code>main.py</code>:</p>\n\n<pre><code>from utils.files import get_full_path\n\npath_to_map = get_full_path('res', 'map.png')\n</code></pre>\n\n<p>So my project directory tree looks like this:</p>\n\n<pre><code>project_main_folder/\n utils/\n __init__.py (empty)\n files.py\n main.py\n</code></pre>\n\n<p>When you import a module the Python interpreter searches if there's a built-in module with that name (that's why your module name should be different or you should use <a href=\"http://docs.python.org/2/tutorial/modules.html#intra-package-references\" rel=\"nofollow\">relative imports</a>). If it hasn't found a module with that name it will (among others in <code>sys.path</code>) search in the directory containing your script. You can find further information in the <a href=\"http://docs.python.org/2/tutorial/modules.html#the-module-search-path\" rel=\"nofollow\">documentation</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T03:17:33.217", "Id": "32884", "Score": "0", "body": "But how do you import `main` without knowing where the main directory is already?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:28:32.857", "Id": "32919", "Score": "0", "body": "I modified my answer to include the import line and also put the function in the module `utils.files`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T01:23:28.473", "Id": "32966", "Score": "0", "body": "My question remains the same: how do you import `utils.files` without knowing where `utils` is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:54:35.510", "Id": "32994", "Score": "0", "body": "When you put the code that imports `utils.files` in `main.py` Python will automatically figure it out. I added further information to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:08:40.777", "Id": "33022", "Score": "0", "body": "Oh. What if I'm in `dir1/module1.py` and I want to `import dir2.module2`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:52:36.303", "Id": "33025", "Score": "0", "body": "Note that `dir1` and `dir2` need to contain an `__init__.py` to be considered as a module. Then you could probably (not tested) use relative imports: `from ..dir2.module2 import get_bla`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T21:26:20.993", "Id": "20449", "ParentId": "20428", "Score": "4" } }, { "body": "<p>A standard way to achieve this would be to use the <code>pkg_resources</code> module which is part of the <code>setuptools</code> module. <code>setuptools</code> is used to create an installable python package.</p>\n\n<p>You can use pkg_resources to return the contents of your desired file as a string and you can use pkg_resources to get the actual path of the desired file on your system.</p>\n\n<p>Let's say that you have a module called <code>stackoverflow</code>.</p>\n\n<pre><code>stackoverflow/\n|-- app\n| `-- __init__.py\n`-- resources\n |-- bands\n | |-- Dream\\ Theater\n | |-- __init__.py\n | |-- King's\\ X\n | |-- Megadeth\n | `-- Rush\n `-- __init__.py\n\n3 directories, 7 files\n</code></pre>\n\n<p>Now let's say that you want to access the file <code>Rush</code>. Use <code>pkg_resources.resouces_filename</code> to get the path to <code>Rush</code> and <code>pkg_resources.resource_string</code> to get the contents of <code>Rush</code>, thusly:</p>\n\n<pre><code>import pkg_resources\n\nif __name__ == \"__main__\":\n print pkg_resources.resource_filename('resources.bands', 'Rush')\n print pkg_resources.resource_string('resources.bands', 'Rush')\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>/home/sri/workspace/stackoverflow/resources/bands/Rush\nBase: Geddy Lee\nVocals: Geddy Lee\nGuitar: Alex Lifeson\nDrums: Neil Peart\n</code></pre>\n\n<p>This works for all packages in your python path. So if you want to know where lxml.etree exists on your system:</p>\n\n<pre><code>import pkg_resources\n\nif __name__ == \"__main__\":\n print pkg_resources.resource_filename('lxml', 'etree')\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>/usr/lib64/python2.7/site-packages/lxml/etree\n</code></pre>\n\n<p>The point is that you can use this standard method to access files that are installed on your system (e.g pip install xxx) and files that are within the module that you're currently working on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-29T13:37:17.713", "Id": "174315", "ParentId": "20428", "Score": "0" } } ]
{ "AcceptedAnswerId": "20449", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T15:09:55.653", "Id": "20428", "Score": "6", "Tags": [ "python" ], "Title": "Accessing the contents of a project's root directory in Python" }
20428
<p>I'm trying to track down what I suppose to be memory/thread leak in one of my programs.</p> <p>My program uses a function to upload a file to a <a href="http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/" rel="nofollow noreferrer">Windows Azure Storage Blob</a>. In order to make this function resilient to various transient error conditions (such as intermittent network failures, etc.), I want to make use of the <a href="http://entlib.codeplex.com/wikipage?title=TopazTplSep2012UpdateReleaseNotes" rel="nofollow noreferrer">Transient Fault Handling Application Block for Windows Azure</a> "topaz", part of Enterprise Library, which includes a configurable retry mechanism.</p> <p>Also, in order to circumvent timeout conditions when dealing with large file and improve and reduce the scope for portions of the upload that should be repeated in case of failure, I try to <a href="http://wely-lau.net/2012/02/26/uploading-big-files-in-windows-azure-blob-storage-with-putlistblock/" rel="nofollow noreferrer">upload the specified file stream in chunks</a>, that each get uploaded independently.</p> <p>Finally, in order to adhere to <a href="http://acloudyplace.com/2012/01/8-essential-best-practices-in-windows-azure-blob-storage/" rel="nofollow noreferrer">best practices using Windows Azure Storage</a>, I make use of asynchronous operations as much as possible when dealing with Windows Azure, in an attempt to improve the scalability of my apps.</p> <p>Here is the resulting snippet function :</p> <pre><code> public static Task ChunkedUploadStreamAsync(CloudBlockBlob blob, Stream source, BlobRequestOptions options, int chunkSize, RetryPolicy policy) { var blockids = new List&lt;string&gt;(); var blockid = 0; var count = 0; var bytes = new byte[chunkSize]; // first create a list of TPL Tasks for uploading blocks asynchronously var tasks = new List&lt;Task&gt;(); while ((count = source.Read(bytes, 0, bytes.Length)) != 0) { var id = Convert.ToBase64String(BitConverter.GetBytes(++blockid)); Func&lt;Task&gt; uploadTaskFunc = () =&gt; new TaskFactory() .FromAsync( (asyncCallback, state) =&gt; blob.BeginPutBlock(id, new MemoryStream(bytes, 0, count), null, null, null, null, asyncCallback, state) , blob.EndPutBlock , null ) .ContinueWith(antecedent =&gt; blockids.Add(id), TaskContinuationOptions.NotOnFaulted); tasks.Add(policy.ExecuteAsync(uploadTaskFunc)); } return new TaskFactory().ContinueWhenAll( tasks.ToArray(), array =&gt; { // propagate exceptions and make all faulted Tasks as observed Task.WaitAll(array); // create continuation task for committing uploaded blocks Func&lt;Task&gt; commitTaskFunc = () =&gt; new TaskFactory() .FromAsync( (asyncCallback, state) =&gt; blob.BeginPutBlockList(blockids, asyncCallback, state) , blob.EndPutBlockList , null); policy .ExecuteAsync(commitTaskFunc) .Wait(); }); } </code></pre> <p>With Performance Monitor, I can observe that after calling this function, the number of threads and amount of memory used by my program is increasing significantly. For instance, here is a snapshot of just one call of this function :</p> <p><img src="https://i.stack.imgur.com/lkLcM.png" alt="Thread Leakage after just one call!"></p> <p>Please, can someone advise as to where I'm doing something wrong. Please, suggest a better design if necessary.</p>
[]
[ { "body": "<p>There are several issues in your code that make it error-prone:</p>\n\n<ul>\n<li>you are using a single byte array to feed all memory streams, thus the same data may be sent in different chunks. Same stands for <code>count</code>.</li>\n<li>the order of chunks in <code>blockids</code> can be different to the one you've sent so resulting BLOB will have incorrect order of blocks.</li>\n<li>there is a potential thread contention on <code>blockids</code> as different threads may add a new element at the same time causing all sorts of problems like missing blocks in resulting list, incorrect block IDs etc.</li>\n<li>use <code>Task.Factory</code> instead of <code>new TaskFactory()</code></li>\n<li>if you create a task and immediately wait for it then you don't need that task, so you can replace the last <code>BeginPutBlockList</code> with synchronous version</li>\n</ul>\n\n<p>Other than that I don't see memory leak from the graphs you provided. Threads may still be alive in a thread pool, and memory may not be collected by GC yet.</p>\n\n<p>Here is what I've got as a result (note that it may consume more memory as you need to store all the chunks that are currently being sent in memory):</p>\n\n<pre><code> private static Task PutBlockAsync(CloudBlockBlob blob, string id, Stream stream, RetryPolicy policy)\n {\n Func&lt;Task&gt; uploadTaskFunc = () =&gt; Task.Factory\n .FromAsync(\n (asyncCallback, state) =&gt; blob.BeginPutBlock(id, stream, null, null, null, null, asyncCallback, state)\n , blob.EndPutBlock\n , null\n );\n return policy.ExecuteAsync(uploadTaskFunc);\n }\n\n public static Task ChunkedUploadStreamAsync(CloudBlockBlob blob, Stream source, BlobRequestOptions options, int chunkSize, RetryPolicy policy)\n {\n var blockids = new List&lt;string&gt;();\n var blockid = 0;\n\n int count;\n\n // first create a list of TPL Tasks for uploading blocks asynchronously\n var tasks = new List&lt;Task&gt;();\n\n var bytes = new byte[chunkSize];\n while ((count = source.Read(bytes, 0, bytes.Length)) != 0)\n {\n var id = Convert.ToBase64String(BitConverter.GetBytes(++blockid));\n blockids.Add(id);\n tasks.Add(PutBlockAsync(blob, id, new MemoryStream(bytes, 0, count), policy));\n bytes = new byte[chunkSize]; //need a new buffer to avoid overriding previous one\n }\n\n return Task.Factory.ContinueWhenAll(\n tasks.ToArray(),\n array =&gt;\n {\n // propagate exceptions and make all faulted Tasks as observed\n Task.WaitAll(array);\n policy.ExecuteAction(() =&gt; blob.PutBlockList(blockids));\n });\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T16:49:16.250", "Id": "20434", "ParentId": "20429", "Score": "4" } } ]
{ "AcceptedAnswerId": "20434", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T15:16:34.520", "Id": "20429", "Score": "1", "Tags": [ "c#", "asynchronous", "task-parallel-library" ], "Title": "TPL Thread Leak and Memory Leak" }
20429
<p>I am in the process of writing a simple Node.JS webserver. I am about halfway there in terms of functionality. Please see the full code in <a href="http://pastebin.com/h2KBWDTH" rel="nofollow noreferrer">this Pastebin</a> (the client-side code is not shown as I want to focus on server-side).</p> <p>Before I implement the rest of the functionality, I would like to pause and reflect and the quality of my code, regarding (quoting points from the FAC):</p> <ul> <li>Best practices and design pattern usage</li> <li>Security issues</li> </ul> <p>I am not a Node.JS expert, and I am sure that issues with my code will stick out straight away. I have decided to keep all my code in just one file because the server is so short. Regarding security, I have setup a Node HTTPS server, and used the session management based on cookies from Express.JS.</p> <pre><code>// TODO: Close Mongo connections upon exit var express = require('express'); var mongoose = require('mongoose'); var fs = require('fs'); var https = require('https'); var shellCommand = require('child_process').exec; var privateKey = fs.readFileSync('./../ssl/localhost.key').toString(); var certificate = fs.readFileSync('./../ssl/localhost.crt').toString(); // Instantiate express var server = express() .use(express.static('./../')) .use(express.cookieParser()) .use(express.bodyParser()) .use(express.session({secret: 'Secret!'})) .set('views', './../'); https.createServer({ key: privateKey, cert: certificate }, server).listen(80, 'localhost'); // Connect to the database mongoose.connect('localhost', 'users'); // Define our model var User = mongoose.model('Users', mongoose.Schema({ username: 'string', password: 'string', rights: 'string' }) ); // Clear the database User.remove({}, function () {}); // Add admin new User({ username: 'admin', password: 'admin', rights: 'Administrator' }).save(); new User({ username: 'Steve', password: 'test', rights: 'Administrator' }).save(); new User({ username: 'Justin', password: 'test', rights: 'Operator' }).save(); server.get('/usersList', function(req, res) { User.find({}, null, {sort: {username: 1}}, function (err, users) { res.send(users); }); }); server.get('/protocols', function(req, res) { var response = {}; shellCommand('tdcli proto list | grep -v dpi_', function (err, stdout, stderr) { var lines = stdout.split('\n'); for(var i = 2; i &lt; lines.length; i += 1) { var line = lines[i]; var name = line.split(/\W+/)[1]; var status = line.match(/(enabled|disabled)/)[0]; response[name] = status; } res.send(response); }); }); server.get('/statistics', function(req, res) { var response = {}; for(var i = 0; i &lt; 3; i += 1) { response[i] = 0.25 + 1 / 2 * Math.random(); } shellCommand('top -b -n 1', function (err, stdout, stderr) { var lines = stdout.split('\n'); var line; var elements; var memory; var cpu; for(i = 0; i &lt; lines.length; i += 1) { line = lines[i]; elements = line.split(/\s+/); if(elements[0] == 'Mem:') { memory = +(elements[3].slice(0, -1)); } if(elements[0] == 'Cpu(s):') { cpu = +((100 - +elements[4].slice(0, -4)).toFixed(1)); } } response[3] = cpu; response[4] = memory; res.send(response); }); }); server.post('/login', function(req, res) { var receivedUsername = req.body.username; var receivedPassword = req.body.password; User.find({ username: receivedUsername }, function (err, users) { if(printError(err)) return; var user = users[0]; if(!user) { console.error('No user', receivedUsername); return; } var correctPassword = user.password; if(receivedPassword === correctPassword) { req.session.username = user.username; req.session.rights = user.rights; res.send({ message: 'Valid' }); } else { res.send({ message: 'Invalid', correctPassword: correctPassword }); } }); }); server.post('/logout', function(req, res) { req.session.username = undefined; req.session.rights = undefined; sendOK(res); }); server.post('/newUser', function (req, res) { if (req.session.rights === 'Administrator') { var receivedUsername = req.body.username; User.find({ username: receivedUsername }, function (err, users) { if(users.length !== 0) { res.send({ message: 'Error: User exists!' }); } else { new User(req.body).save(function (err) { if(printError(err)) return; }); res.send({ message: 'OK' }); } }); } else { res.send({ message: 'Error: Permission denied' }); } }); server.post('/removeUser', function (req, res) { var receivedUsername = req.body.username; User .find({username: receivedUsername}) .remove(function (err) { if(printError(err)) { sendError(res); } }); sendOK(res); }); server.post('/editUser', function (req, res) { var oldUsername = req.body.oldUsername; var newUser = req.body.user; User.update({username: oldUsername}, { username: newUser.username, password: newUser.password, rights: newUser.rights }, function(err, numberAffected, rawResponse) { if(printError(err)) { sendError(res); } }); sendOK(res); }); function sendOK(res) { res.send({ message: 'OK' }); } function sendError(res) { res.send({ message: 'Error' }); } function printError(err) { if(err) { console.error('ERROR!'); } return err; } </code></pre>
[]
[ { "body": "<p>First of all you need to separate your code into multiple files.\nUsually its something like models/controllers etc.\nI know it is very useful for copy pasting it to places like this but it will not do for the long run.</p>\n\n<p>Even without testing your code I am pretty sure that this is not correct.\nMongoose as most database related libraries are async.</p>\n\n<pre><code> User.update({username: oldUsername}, {\n username: newUser.username,\n password: newUser.password,\n rights: newUser.rights\n }, function(err, numberAffected, rawResponse) {\n if(printError(err)) {\n sendError(res);\n }\n });\n\n sendOK(res);\n</code></pre>\n\n<p>On this example you are sending \"Ok\" to the client even if the update fails.\nYou need to always send the response from inside the last callback.</p>\n\n<p>One more issue with your mongoose related code is that your delete should also be nested inside your find.</p>\n\n<pre><code>User\n .find({username: receivedUsername})\n .remove(function (err) {\n if(printError(err)) {\n sendError(res);\n }\n });\n</code></pre>\n\n<p>Find will return an array of users which you will need to loop and .remove()</p>\n\n<p>You could also use the mongoose's static methods to group user related methods. This will allow you to have user specific code in a common place rather than all over.<br>\n<a href=\"http://mongoosejs.com/docs/guide.html#statics\" rel=\"nofollow\">http://mongoosejs.com/docs/guide.html#statics</a> </p>\n\n<p>Other than that your code seems sane enough. The wrappers for keeping consistency with the responses seems fine. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:10:59.790", "Id": "30588", "ParentId": "20436", "Score": "2" } }, { "body": "<p>Also, you're missing error handling for all your mongoose connection and database calls. If an update/query failed, it would be an uncaught exception which would crash your server.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:52:35.440", "Id": "30597", "ParentId": "20436", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T17:01:17.970", "Id": "20436", "Score": "1", "Tags": [ "javascript", "security", "node.js", "server" ], "Title": "Simple Node.JS webserver" }
20436
<p>I am using Bootstrap for a front-end project. I would like feedback concerning my HTML markup. I have spent quite some time polishing it, and I feel it is somewhat "mature". I have run the W3C HTML validator on it, and it only complains about three things:</p> <ol> <li>My use of <code>center</code> tags (consider this a "known issue")</li> <li>"Element <code>legend</code> not allowed as child of element div in this context." (I do not understand this error.)</li> <li>My use of <code>X-UA-Compatible</code> in the <code>meta</code> tag (common practice, but not standard)</li> </ol> <p>Here are other things I am aware of:</p> <ol> <li>All the JavaScript should be bundled in just one file to reduce the number of requests. (I will do this for production.)</li> <li>The same as above, but for CSS.</li> <li>The code is a little lengthy, but I prefer to keep everything in just one file.</li> <li>The code is not commented.</li> </ol> <p>What are best practices I have not followed in my code?</p> <pre><code>&lt;!doctype html&gt; &lt;!-- Bootstrap customisations: No responsiveness @navbarBackground: #568FB6 @navbarBackgroundHighlight: lighten(#568FB6, 12%) --&gt; &lt;head&gt; &lt;meta charset='utf-8'&gt; &lt;meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'&gt; &lt;title&gt;DeepFlow&lt;/title&gt; &lt;link href='./img/favicon.ico' rel='icon'&gt; &lt;link href='./css/bootstrap.css' rel='stylesheet'&gt; &lt;link href='./css/font-awesome.css' rel='stylesheet'&gt; &lt;link href='./css/global.css' rel='stylesheet'&gt; &lt;link href='./css/login.css' rel='stylesheet'&gt; &lt;link href='./css/custom.css' rel='stylesheet'&gt; &lt;script src='./RGraph/libraries/RGraph.common.core.js'&gt;&lt;/script&gt; &lt;script src='./RGraph/libraries/RGraph.common.annotate.js'&gt;&lt;/script&gt; &lt;script src='./RGraph/libraries/RGraph.common.effects.js'&gt;&lt;/script&gt; &lt;script src='./RGraph/libraries/RGraph.common.dynamic.js'&gt;&lt;/script&gt; &lt;script src='./RGraph/libraries/RGraph.gauge.js'&gt;&lt;/script&gt; &lt;script src='./RGraph/libraries/RGraph.line.js'&gt;&lt;/script&gt; &lt;script src='./js/jquery.js'&gt;&lt;/script&gt; &lt;script&gt;jQuery.fx.speeds._default = 800;&lt;/script&gt; &lt;script src='./js/underscore.js'&gt;&lt;/script&gt; &lt;script src='./js/bootstrap.js'&gt;&lt;/script&gt; &lt;script src='./js/ajax.js'&gt;&lt;/script&gt; &lt;script src='./js/navbar.js'&gt;&lt;/script&gt; &lt;script src='./js/login.js'&gt;&lt;/script&gt; &lt;script src='./js/users.js'&gt;&lt;/script&gt; &lt;script src='./js/editUser.js'&gt;&lt;/script&gt; &lt;script src='./js/addUser.js'&gt;&lt;/script&gt; &lt;script src='./js/statistics.js'&gt;&lt;/script&gt; &lt;script src='./js/protocols.js'&gt;&lt;/script&gt; &lt;script src='./js/export.js'&gt;&lt;/script&gt; &lt;script src='./js/tuple.js'&gt;&lt;/script&gt; &lt;script src='./js/network.js'&gt;&lt;/script&gt; &lt;/head&gt; &lt;div class='navbar navbar-fixed-top' style='display:none'&gt; &lt;div class='navbar-inner'&gt; &lt;div class='container'&gt; &lt;div class='brand'&gt;DeepFlow&lt;/div&gt; &lt;div id='navbar-container'&gt; &lt;ul class='nav panes-nav'&gt; &lt;li id='statistics-label'&gt;&lt;a&gt;Statistics&lt;/a&gt;&lt;/li&gt; &lt;li id='protocols-label'&gt;&lt;a&gt;Protocols&lt;/a&gt;&lt;/li&gt; &lt;li id='tuples-label'&gt;&lt;a&gt;Tuples&lt;/a&gt;&lt;/li&gt; &lt;li id='exports-label'&gt;&lt;a&gt;Exports&lt;/a&gt;&lt;/li&gt; &lt;li id='users-label'&gt;&lt;a&gt;Users&lt;/a&gt;&lt;/li&gt; &lt;li id='network-label'&gt;&lt;a&gt;Network&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class='nav pull-right'&gt; &lt;li id='sign-out'&gt;&lt;a&gt;Log out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='wrap'&gt; &lt;br&gt; &lt;br&gt; &lt;br&gt; &lt;div class='container'&gt; &lt;div class='alert alert-error' style='display:none'&gt; &lt;span id='error-message'&gt;&lt;/span&gt; &lt;button type='button' class='close' data-dismiss='alert'&gt;×&lt;/button&gt; &lt;/div&gt; &lt;div class='hero-unit' id='login-unit'&gt; &lt;h2&gt;Welcome to DeepFlow&lt;/h2&gt; &lt;p&gt;Please log in&lt;/p&gt; &lt;center id='login-box' class='pull-right control-group'&gt; &lt;div class='clearfix'&gt; &lt;input type='text' placeholder='Username' id='login-username'/&gt; &lt;/div&gt; &lt;div class='clearfix'&gt; &lt;input type='password' placeholder='Password' id='login-password'/&gt; &lt;/div&gt; &lt;button class='btn btn-primary' type='submit' id='login-button'&gt;Log in&lt;/button&gt; &lt;/center&gt; &lt;/div&gt; &lt;div class='row pane' id='statistics-pane' style='display:none'&gt; &lt;legend&gt;Network&lt;/legend&gt; &lt;div class='form-horizontal well'&gt; &lt;div class='offset1'&gt; &lt;div class='control-group statistics-group'&gt; &lt;label class='control-label graph-label'&gt; &lt;div&gt;Packets per second&lt;/div&gt; &lt;p class='live-statistic' data-ending='' data-precision='0'&gt;&lt;/p&gt; &lt;/label&gt; &lt;div class='controls'&gt; &lt;canvas id='pps_graph' width='500' height='100'&gt;[No canvas support]&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group statistics-group'&gt; &lt;label class='control-label graph-label'&gt; &lt;div&gt;Throughput&lt;/div&gt; &lt;p class='live-statistic' data-ending='&amp;nbsp;kB/s' data-precision='0'&gt;&lt;/p&gt; &lt;/label&gt; &lt;div class='controls'&gt; &lt;canvas id='throughput_graph' width='500' height='100'&gt;[No canvas support]&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='statistics-group'&gt; &lt;label class='control-label graph-label'id='packets-dropped-group'&gt; &lt;div&gt;Packets dropped&lt;/div&gt; &lt;p class='live-statistic' data-ending='' data-precision='0'&gt;&lt;/p&gt; &lt;/label&gt; &lt;div class='controls'&gt; &lt;canvas id='packets_dropped_graph' width='500' height='100'&gt;[No canvas support]&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;legend&gt;System&lt;/legend&gt; &lt;div class='form-horizontal well'&gt; &lt;div class='offset1'&gt; &lt;div class='control-group statistics-group'&gt; &lt;label class='control-label graph-label'&gt; &lt;div&gt;CPU usage&lt;/div&gt; &lt;p class='live-statistic' data-ending='&amp;nbsp;%' data-precision='2'&gt;&lt;/p&gt; &lt;/label&gt; &lt;div class='controls'&gt; &lt;canvas id='cpu_graph' width='500' height='100'&gt;[No canvas support]&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='statistics-group'&gt; &lt;label class='control-label graph-label'&gt; &lt;div&gt;Memory usage&lt;/div&gt; &lt;p class='live-statistic' data-ending='&amp;nbsp;k' data-precision='0'&gt;&lt;/p&gt; &lt;/label&gt; &lt;div class='controls'&gt; &lt;canvas id='memory_graph' width='500' height='100'&gt;[No canvas support]&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='row pane' id='protocols-pane' style='display:none'&gt; &lt;legend&gt;Protocol list&lt;/legend&gt; &lt;table class='table table-hover table-condensed offset3' id='protocol-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Protocol&lt;/th&gt; &lt;th id='protocol-status-column'&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id='protocol-rows'&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class='row pane' id='tuples-pane' style='display:none'&gt; &lt;legend&gt;List of tuples&lt;/legend&gt; &lt;table class='table table-hover offset3' id='tuple-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Total&lt;/th&gt; &lt;th id='tuples-status-column'&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id='tuples-rows'&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class='row pane' id='exports-pane' style='display:none'&gt; &lt;legend&gt;Configure export destinations&lt;/legend&gt; &lt;table class='table table-hover' id='exports-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;URL&lt;/th&gt; &lt;th&gt;IP&lt;/th&gt; &lt;th&gt;Port&lt;/th&gt; &lt;th&gt;Format&lt;/th&gt; &lt;th id='exports-edit-column'&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id='exports-rows'&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class='modal hide fade' id='edit-export-modal'&gt; &lt;div class='modal-header'&gt; &lt;span type='button' class='close' data-dismiss='modal' aria-hidden='true'&gt;&amp;times;&lt;/span&gt; &lt;h3&gt;Edit export &lt;code id='edit-export-old'&gt;&lt;/code&gt;&lt;/h3&gt; &lt;/div&gt; &lt;div class='modal-body'&gt; &lt;form class='form-horizontal'&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;New IP&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='edit-export-ip' placeholder='IP'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;New port&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='edit-export-port' placeholder='Port'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;label class='control-label'&gt;New format&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='edit-export-format' placeholder='Format'/&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class='modal-footer'&gt; &lt;span class='btn' id='edit-export-close'&gt;Close&lt;/span&gt; &lt;span class='btn btn-primary' id='edit-export-save'&gt;Save changes&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='row pane' id='users-pane' style='display:none'&gt; &lt;div class='span6'&gt; &lt;legend&gt;List of users&lt;/legend&gt; &lt;table class='table table-hover' id='users-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;User&lt;/th&gt; &lt;th&gt;Rights&lt;/th&gt; &lt;th id='users-edit-column'&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id='user-rows'&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id='new-user-box' class='span6'&gt; &lt;legend&gt;Add a new user&lt;/legend&gt; &lt;form class='form-horizontal well'&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;Username&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' class='username' id='new-user-username' placeholder='Username'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;Password&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='password' class='password' id='new-user-password' placeholder='Password'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;Rights&lt;/label&gt; &lt;div class='controls'&gt; &lt;div class='btn-group' data-toggle='buttons-radio' id='new-user-rights'/&gt; &lt;span class='btn'&gt;Administrator&lt;/span&gt; &lt;span class='btn' id='new-user-operator'&gt;Operator&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='controls'&gt; &lt;span class='btn btn-primary' id='new-user-button'&gt;Add new user&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class='modal hide fade' id='edit-user-modal'&gt; &lt;div class='modal-header'&gt; &lt;span class='close' data-dismiss='modal' aria-hidden='true'&gt;&amp;times;&lt;/span&gt; &lt;h3&gt;Edit user &lt;code id='edit-user-old-username'&gt;&lt;/code&gt;&lt;/h3&gt; &lt;/div&gt; &lt;div class='modal-body'&gt; &lt;form class='form-horizontal'&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;New username&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' class='username' id='edit-user-username' placeholder='(Leave unchanged)'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;New password&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='password' class='password' id='edit-user-password' placeholder='(Leave unchanged)'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;label class='control-label'&gt;New rights&lt;/label&gt; &lt;div class='controls'&gt; &lt;div class='btn-group' data-toggle='buttons-radio' id='edit-user-rights'&gt; &lt;span class='btn'&gt;Administrator&lt;/span&gt; &lt;span class='btn'&gt;Operator&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class='modal-footer'&gt; &lt;span class='btn btn-danger pull-left' data-action='remove'&gt;&lt;i class='icon-trash'&gt;&lt;/i&gt; Remove&lt;/span&gt; &lt;span class='btn' data-action='close'&gt;Close&lt;/span&gt; &lt;span class='btn btn-primary' data-action='save'&gt;Save changes&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='pane' id='network-pane' style='display:none'&gt; &lt;div class='row'&gt; &lt;div class='alert alert-info' style='display:none'&gt; Use this pane to configure the server network. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. &lt;/div&gt; &lt;form class='span6 form-horizontal'&gt; &lt;legend&gt;Basic configurations&lt;/legend&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;IP address&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='network-ip' placeholder='IP address'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;Subnet mask&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='network-mask' placeholder='Subnet mask'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;Default gateway&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='network-gateway' placeholder='Default gateway'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;form class='span6 form-horizontal'&gt; &lt;legend&gt;Optional fields&lt;/legend&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;DNS hostname&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='network-dns' placeholder='DNS hostname'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='control-group'&gt; &lt;label class='control-label'&gt;NTP server hostname&lt;/label&gt; &lt;div class='controls'&gt; &lt;input type='text' id='network-ntp' placeholder='NTP server hostname'/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;br&gt; &lt;br&gt; &lt;br&gt; &lt;center&gt; &lt;span class='btn btn-large btn-primary' id='network-save'&gt;Save and reboot server now&lt;/span&gt; &lt;/center&gt; &lt;/div&gt; &lt;div id='push'&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='footer'&gt; &lt;div class='container'&gt; &lt;span class='muted credit'&gt;&amp;copy; Copyright 2013 Qosmos SA. All rights reserved.&lt;/span&gt; &lt;img id='logo' src='./img/logo_grey.png' alt='logo'/&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Other items to consider:</p>\n\n<ul>\n<li>Place JavaScript at the bottom (before the closing body tag).</li>\n<li>Find other ways to avoid the flash of <a href=\"http://www.learningjquery.com/2008/10/1-way-to-avoid-the-flash-of-unstyled-content\" rel=\"nofollow noreferrer\">unstyled content</a>.</li>\n<li>Avoid hard-coding text (e.g., \"DeepFlow\", \"System\") with an eye to internationalization.</li>\n<li>Use CSS to change layout, not multiple <code>&lt;br /&gt;</code> tags.</li>\n<li>Leave <code>\"style='display:none'\"</code> in CSS; change the class instead.</li>\n<li><a href=\"http://usability.com.au/2005/06/accessible-data-tables-2005/\" rel=\"nofollow noreferrer\">Accessibility</a> and its corresponding mark-up.</li>\n<li>Use tools like JSLint, CSSLint, in addition to the W3C validation tool.</li>\n<li>Good use of unique <code>id</code> attributes.</li>\n<li>Wrap <code>input</code> fields with <code>label</code> elements when possible; this allows users to click the label associated with the input field to give that field focus.</li>\n<li>\"logo\" should probably be \"Qosmos Logo\".</li>\n<li>Technically, you don't need <code>&amp;copy;</code> and the word Copyright.</li>\n<li>Add a <code>body</code> tag to help <a href=\"https://stackoverflow.com/a/5642982/59087\">ensure consistency</a> across all browsers.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:31:05.423", "Id": "32727", "Score": "0", "body": "The reason I have the `style` in the HTML is because the CSS could load *after* the HTML, which might cause some elements to appear briefly before the CSS is fully loaded." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:31:55.310", "Id": "32728", "Score": "0", "body": "Regarding accessibility, I have made sure to have an `alt` attribute for the only image. What else do you suggest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:42:29.193", "Id": "32732", "Score": "0", "body": "Regarding your note `(before the closing body tag)` I do not have a `body` tag. Well, at least it is implicit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:47:09.557", "Id": "32733", "Score": "0", "body": "Regarding the `doctype`, I grabbed it from [HTML5 boilerplate](https://github.com/h5bp/html5-boilerplate/blob/master/index.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:52:23.163", "Id": "32734", "Score": "0", "body": "The `doctype` should be fine as is; Google and StackOveflow also use such a minimal declaration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T22:23:58.953", "Id": "32735", "Score": "0", "body": "Regarding wrapping `input` fields with `label` elements, could you give an example? I have tried and I cannot get focus when clicking the `label`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T22:56:51.183", "Id": "32736", "Score": "0", "body": "http://stackoverflow.com/a/774065/59087" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:26:53.293", "Id": "20445", "ParentId": "20439", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:59:27.537", "Id": "20439", "Score": "3", "Tags": [ "html" ], "Title": "Bootstrap: HTML markup review" }
20439
<p>I currently have code that looks like this</p> <pre><code>private string _stringField; protected string StringField { get { if (_stringField == null) _stringField = GetStringField(); return _stringField; } } </code></pre> <p>ReSharper is suggesting I change the property to: </p> <pre><code>protected string StringField { get { return _stringField ?? (_stringField = GetStringField()); } } </code></pre> <p>This isn't an idiom I've seen before and probably would have to think about the first time I saw it; is this something I should be concerned would confuse other people too?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T19:52:15.160", "Id": "32722", "Score": "4", "body": "That and using Lazy<> is how I tend to do my properties when wanting something like this. Just seems more consise to me. As for confusing others? Possibly but it might also teach them something..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:02:45.107", "Id": "32724", "Score": "0", "body": "@dreza Thanks for pointing out Lazy<>; most of my C# work has been with 3.5 or earlier and this is the first I've seen it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T13:28:04.863", "Id": "32744", "Score": "0", "body": "Even with `Lazy<T>`, I still tend to use this approach in most cases. Choose whichever feels simpler to you and don't worry about confusing other people. I totally agree with @dreza here: That piece of code is clear enough for someone who saw something like that for the first time to _get it_ in one minute." } ]
[ { "body": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\">??</a> is well known operator in C#. It doesn't confuse but reduce coding. </p>\n\n<p>Both snippets have same meaning.</p>\n\n<p>But if it is .NET 4.0 onwards, i would rather use <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\"><code>Lazy&lt;T&gt;</code></a>.</p>\n\n<pre><code>private Lazy&lt;string&gt; lazyStringField = new Lazy&lt;string&gt;(GetStringField);\nprotected string StringField\n{\n get\n {\n return lazyStringField.Value;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:01:08.963", "Id": "32723", "Score": "0", "body": "I'm aware of the ?? operator; what I've never seen before was it being glued together with an assignment statement like that before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T00:57:12.890", "Id": "32833", "Score": "0", "body": "How much slower is this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T21:05:44.543", "Id": "32869", "Score": "4", "body": "While I'd agree that normally `??` doesn't confuse, I'd argue that it's usage here combined with the rarely-used side effect of `=` which returns the value just set *is* confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:47:57.357", "Id": "67735", "Score": "0", "body": "lazy properties are not supported in CF and should be implemented manually" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T19:57:07.370", "Id": "20442", "ParentId": "20440", "Score": "16" } }, { "body": "<p>I noticed that ReSharper's suggestion too and I decided to turn it off. I think that an expression should be used either for its value or for its side-effects, <em>but not both</em>. If you do both, your code will be more confusing. This principle is known as <a href=\"http://en.wikipedia.org/wiki/Command-query_separation\" rel=\"nofollow noreferrer\">command-query separation</a>.</p>\n\n<p>And I agree with others that using <code>Lazy&lt;T&gt;</code> is even better. If you're still on .Net 3.5 (or older), <a href=\"https://stackoverflow.com/q/3207580/41071\">it shouldn't be that hard to write your own version of that class</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T19:47:08.970", "Id": "32865", "Score": "0", "body": "I've turned off that suggestion as well. Sometimes ReSharper's suggestions make the code less intuitive..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T19:12:04.083", "Id": "20519", "ParentId": "20440", "Score": "7" } } ]
{ "AcceptedAnswerId": "20442", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T19:41:26.213", "Id": "20440", "Score": "16", "Tags": [ "c#", "lazy" ], "Title": "Lazy loaded property readability" }
20440
<p>I'm working on an A* search algorithm implemention and this is what I came up with for the open list:</p> <pre><code>from heapq import heappush, heappop class OpenList(set): ''' This uses a heap for fast retrieval of the node with the lowest path score. It also uses a set for efficiently checking if a node is contained. ''' REMOVED = object() def __init__(self, *args, **kwargs): set.__init__(self, *args, **kwargs) self._heap = [] def add(self, node): set.add(self, node) heappush(self._heap, (node.get_path_score(), node)) def remove(self, node): set.remove(self, node) i = self._heap.index((node.get_path_score(), node)) self._heap[i] = self.REMOVED def pop_node_with_lowest_path_score(self): ''' remove and return the node with the lowest path score ''' item = heappop(self._heap) while item is self.REMOVED: item = heappop(self._heap) set.remove(self, item[1]) return item[1] </code></pre> <p>Should I keep the path_score in the heap, when I mark the item as removed as in the following code:</p> <pre><code>self._heap[i] = (node.get_path_score(), self.REMOVED) </code></pre> <p>What do you think about it? What can be made more efficient, simple or cleaner?</p>
[]
[ { "body": "<h3>1. Bug</h3>\n\n<ol>\n<li><p>You don't properly synchronize the set and the heap in all cases. For example, when taking a union:</p>\n\n<pre><code>&gt;&gt;&gt; a = OpenList()\n&gt;&gt;&gt; a |= set([1,2,3])\n&gt;&gt;&gt; a\nOpenList([1, 2, 3])\n&gt;&gt;&gt; a._heap\n[]\n</code></pre>\n\n<p>If you insist on your class being a subclass of <code>set</code>, then you probably ought to intercept <em>every</em> method that modifies the set (and there are quite a few: <code>__isub__</code>, <code>__ior__</code>, <code>__ixor__</code>, <code>__iand__</code>, <code>discard</code>, <code>difference_update</code>, <code>intersection_update</code>, <code>symmetric_difference_update</code>, <code>update</code>, and <code>clear</code>, not to mention <code>copy</code>) and ensure that the heap is modified in a corresponding fashion.</p>\n\n<p>But this would be overkill for what ought to be a fairly simple class. What I would do instead would be to inherit from <code>object</code> instead of <code>set</code>, and implement the set as an instance member <code>_set</code>, in the same way that you have <code>_heap</code> as an instance member. With this approach, you can ensure that operations on <code>_set</code> always have corresponding operations on <code>_heap</code> so that they cannot get out of sync.</p></li>\n</ol>\n\n<h3>2. Other issues</h3>\n\n<ol>\n<li><p>Your class is not as general as it could be. In particular, it can only be used to store objects which have a <code>get_path_score</code> method. Why not allow the user to pass in a <code>key</code> function that gets the score for an object? (As in <a href=\"http://docs.python.org/2/library/functions.html#sorted\" rel=\"nofollow\"><code>sorted</code></a> and <a href=\"http://docs.python.org/2/library/heapq.html#heapq.nlargest\" rel=\"nofollow\"><code>heapq.nlargest</code></a> and similar functions.)</p></li>\n<li><p>You call the superclass method directly via <code>set</code> rather than via the <a href=\"http://docs.python.org/2/library/functions.html#super\" rel=\"nofollow\"><code>super()</code></a> function. This means that it's not possible for someone to create a new class that subclasses both your class and some other class <code>C</code>. (Because the method resolution order will go directly from your class to <code>set</code> instead of via the other class <code>C</code>.)</p></li>\n<li><p>In the <code>remove</code> method, you replace the removed item with a placeholder. This takes time O(<em>n</em>) because you have to find the item in the heap. But removing the item from the heap and re-heapifying would also take O(<em>n</em>), and it would be simpler (because then there would be no need to handle the placeholder item in the <code>pop</code> method). So it's not clear to me that your approach is worth it.</p>\n\n<p>You should think about what you are trying to achieve: if you really want to have fast removal of items, then you need to be cleverer about how you find the removed item in the heap; but if you're happy for removal to be O(<em>n</em>), then you can simplify the code by just deleting the item from the heap and re-heapifying the remainder.</p></li>\n</ol>\n\n<h3>3. Naming and documentation</h3>\n\n<ol>\n<li><p>The data structure used by the A* search algorithm is usually known as a <a href=\"http://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow\">priority queue</a>: that is, a collection of items each of which is associated with a <em>priority</em> (or score), and which can be retrieved in order of their priority. So I think you could choose a better name than <code>OpenList</code> for your class.</p></li>\n<li><p>Your docstring for the class is written with the wrong audience in mind. It contains <em>implementation details</em> (\"uses a heap ... also uses a set\") but this is not helpful for users of the class, who want to know <em>what it is for</em> and <em>how to use it</em>.</p></li>\n<li><p>Your class is a good candidate for a <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"nofollow\">doctest</a> or two.</p></li>\n<li><p>The method name <code>pop_node_with_lowest_path_score</code> is absurd. Why not just <code>pop</code>?</p></li>\n</ol>\n\n<h3>4. Rewrite</h3>\n\n<p>Here's how I'd rewrite the class to fix all the issues discussed above, assuming that you really do want fast removal of items. I'll let you reverse-engineer it to figure out how it works!</p>\n\n<pre><code>from heapq import heappush, heappop\n\nclass PriorityQueueElement(object):\n \"\"\"\n A proxy for an element in a priority queue that remembers (and\n compares according to) its score.\n \"\"\"\n def __init__(self, elem, score):\n self._elem = elem\n self._score = score\n self._removed = False\n\n def __lt__(self, other):\n return self._score &lt; other._score\n\nclass PriorityQueue(object):\n \"\"\"\n A priority queue with O(log n) addition, O(1) membership test and\n amortized O(log n) removal.\n\n The `key` argument to the constructor specifies a function that\n returns the score for an element in the priority queue. (If not\n supplied, an element is its own score).\n\n The `add` and `remove` methods add and remove elements from the\n queue, and the `pop` method removes and returns the element with\n the lowest score.\n\n &gt;&gt;&gt; q = PriorityQueue([3, 1, 4])\n &gt;&gt;&gt; q.pop()\n 1\n &gt;&gt;&gt; q.add(2); q.pop()\n 2\n &gt;&gt;&gt; q.remove(3); q.pop()\n 4\n &gt;&gt;&gt; list(q)\n []\n &gt;&gt;&gt; q = PriorityQueue('vext cwm fjord'.split(), key = lambda s:len(s))\n &gt;&gt;&gt; q.pop()\n 'cwm'\n \"\"\"\n def __init__(self, *args, **kwargs):\n self._key = kwargs.pop('key', lambda x:x)\n self._heap = []\n self._dict = {}\n if args:\n for elem in args[0]:\n self.add(elem)\n\n def __contains__(self, elem):\n return elem in self._dict\n\n def __iter__(self):\n return iter(self._dict)\n\n def add(self, elem):\n \"\"\"\n Add an element to a priority queue.\n \"\"\"\n e = PriorityQueueElement(elem, self._key(elem))\n self._dict[elem] = e\n heappush(self._heap, e)\n\n def remove(self, elem):\n \"\"\"\n Remove an element from a priority queue.\n If the element is not a member, raise KeyError.\n \"\"\"\n e = self._dict.pop(elem)\n e._removed = True\n\n def pop(self):\n \"\"\"\n Remove and return the element with the smallest score from a\n priority queue.\n \"\"\"\n while True:\n e = heappop(self._heap)\n if not e._removed:\n del self._dict[e._elem]\n return e._elem\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T14:28:57.023", "Id": "20509", "ParentId": "20451", "Score": "7" } } ]
{ "AcceptedAnswerId": "20509", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T22:23:15.693", "Id": "20451", "Score": "5", "Tags": [ "python", "algorithm", "heap", "a-star" ], "Title": "A* search algorithm: open set and heap" }
20451
<p>I'm a Scala beginner and looking at the <code>trim()</code> method of the Java API. I noticed side effects, so I attempted to implement a functional version in Scala.</p> <p>Here is the Java version: </p> <pre><code>public String trim() { int len = count; int st = 0; int off = offset; /* avoid getfield opcode */ char[] val = value; /* avoid getfield opcode */ while ((st &lt; len) &amp;&amp; (val[off + st] &lt;= ' ')) { st++; } while ((st &lt; len) &amp;&amp; (val[off + len - 1] &lt;= ' ')) { len--; } return ((st &gt; 0) || (len &lt; count)) ? substring(st, len) : this; } </code></pre> <p>My Scala version iterates over a string, and when it encounters a space char, the tail of the string is returned. The entire string is then reversed, so it can access the trailing whitespace. This new string is iterated over until a space char is encountered and the tail of this string is returned. This new string is then reversed again to maintain the original string order: </p> <pre><code>def trim(stringToTrim : String) : String = { def removePreString[String](list : List[String]) : java.lang.String = list match { case head :: tail =&gt; { if(head.toString.equals(" ")){ removePreString(tail) } else { head.toString + tail.mkString } } }//end removePreString val preString = removePreString(stringToTrim.toList) val reveresedString = preString.toList.reverse val reveresedPostString = removePreString(reveresedString) reveresedPostString.reverse }//end trim </code></pre> <p>How can this code be improved? Does it seem wasteful reversing the string twice?</p>
[]
[ { "body": "<p>No good idea about the concern of reversing the list twice. But you may</p>\n\n<ol>\n<li><p>Let you inner function return a List instead of a string thus having less conversions from list to string and string to list.</p></li>\n<li><p>Change your match to the following pattern (not tested):</p>\n\n<pre><code>case \" \" :: tail =&gt; removePreString(tail)\ncase _ =&gt; _\n</code></pre></li>\n</ol>\n\n<p>I just realize you could also use on a list <code>def dropWhile(p: (A) ⇒ Boolean): List[A]</code> which drops longest prefix of elements that satisfy a predicate. You could then chain dropWhile not a space | reverse | dropwhile not a space | reverse...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T09:07:42.693", "Id": "20503", "ParentId": "20452", "Score": "3" } }, { "body": "<p>you can test for a whitespace in patter matching, an alternative version of your <code>removePreSign</code> method therefore could be written as:</p>\n\n<pre><code>def removePreString(list : List[Char]): String = list match {\n case ' ' :: tail =&gt; removePreString(tail)\n case _ =&gt; list.mkString\n}\n</code></pre>\n\n<p>but as pgras noted, you can simply use <code>str.dropWhile(_ == ' ')</code> which avoids the whole <code>String &lt;=&gt; List</code> issue.</p>\n\n<p>A possible way to do it without <code>reverse</code> and <code>dropWhile</code> using only recursion:</p>\n\n<pre><code>def trim(stringToTrim : String) : String = {\n def removeLeading(str: String): String =\n if (str startsWith \" \" ) removeLeading(str tail)\n else str\n\n def removeTrailing(str: String): String =\n if (str endsWith \" \") removeTrailing(str dropRight 1 )\n else str\n\n removeTrailing(removeLeading(stringToTrim))\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T21:38:48.030", "Id": "32870", "Score": "0", "body": "your function 'removePreString' does not work for Strings with trailing whitespace. e.g - \" this is a test \"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T09:31:47.687", "Id": "32895", "Score": "0", "body": "neither does the original function, it is just another way to achieve the same thing, but as noted above it is equivalent to dropWhile" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T18:41:59.033", "Id": "20518", "ParentId": "20452", "Score": "2" } }, { "body": "<ul>\n<li>Since left and right trim may be useful on their own, expose them.</li>\n<li>View <code>String</code> as a list of <code>Char</code> instead of converting to <code>List[String]</code></li>\n<li>The recursion creates a string at each step ! Take advantage of the rich library of methods for lists (and the like).</li>\n<li>For instance, reversing twice is fine as long you manipulate iterators.</li>\n</ul>\n\n<p>Applying these advices leads to :</p>\n\n<pre><code>def trimLeft (s: String) = s dropWhile ( _ == ' ' )\ndef trimRight (s: String) = (s.reverseIterator dropWhile ( _ == ' ' ))\n .toSeq.reverseIterator mkString\nval trim = trimLeft _ compose trimRight _\n</code></pre>\n\n<p>It you prefer to extract the sub-string of interest at once, there are fine functions to find the indices you need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T19:07:50.787", "Id": "20913", "ParentId": "20452", "Score": "1" } } ]
{ "AcceptedAnswerId": "20503", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T00:09:55.710", "Id": "20452", "Score": "6", "Tags": [ "java", "beginner", "strings", "scala" ], "Title": "A scala implementation of the Java trim method" }
20452
<p>I'm developing an iPhone app that is heavily Calendar-based, and it requires a good amount of (what I'm calling) "date boundaries." </p> <p>I use these "date boundaries" to fetch EKEvents from specific calendars and display data for specific years, months, and quarters.</p> <p><em><strong>SPECIAL NOTE:</em></strong> This app is for government employees, specifically military, so the first day of their fiscal year is Oct 1st. (convenient, huh?) I can't use the calendar object to get "events from a quarter" because the fiscal year is all out of whack, so I have to do everything manually, ergo the "date boundaries."</p> <p><em><strong>My Question:</em></strong> Can these NSDateComponents objects be initialized in a loop? I'm not having performance issues, but I would prefer to have way less code to edit.</p> <p>I need more than just a few of these dates, and I'm currently manually initializing all of them using <code>NSDateComponents</code> in my singleton class <code>-(id)init method</code>, like this:</p> <pre><code>-(id) init; { self = [super init]; if (!self) return nil; NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; NSDate *now = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; NSString *refDate = [dateFormatter stringFromDate:now]; NSString *year = [refDate substringWithRange:NSMakeRange(0,4)]; NSString *month = [refDate substringWithRange:NSMakeRange(5,2)]; self.currentYear = [year integerValue]; int currentMonth = [month integerValue]; if (currentMonth &lt;= 9) { self.currentYear = [year integerValue] -1; } //init date boundaries that are used in several data model methods // notice Q1 starts Oct, 1st NSDateComponents *previousYearQ4EndComps = [[NSDateComponents alloc] init]; [previousYearQ4EndComps setYear:self.currentYear - 1]; [previousYearQ4EndComps setMonth:9]; [previousYearQ4EndComps setDay:30]; [previousYearQ4EndComps setHour:24]; [previousYearQ4EndComps setMinute:59]; [previousYearQ4EndComps setSecond:59]; self.previousYearQ4Ends = [cal dateFromComponents:previousYearQ4EndComps]; NSDateComponents *lastYearQ1StartComps = [[NSDateComponents alloc] init]; [lastYearQ1StartComps setYear:self.currentYear - 1]; [lastYearQ1StartComps setMonth:10]; [lastYearQ1StartComps setDay:1]; [lastYearQ1StartComps setHour:1]; [lastYearQ1StartComps setMinute:0]; [lastYearQ1StartComps setSecond:0]; self.lastYearQ1Starts = [cal dateFromComponents:lastYearQ1StartComps]; NSDateComponents *lastYearQ1EndComps = [[NSDateComponents alloc] init]; [lastYearQ1EndComps setYear:self.currentYear - 1]; [lastYearQ1EndComps setMonth:12]; [lastYearQ1EndComps setDay:31]; [lastYearQ1EndComps setHour:24]; [lastYearQ1EndComps setMinute:59]; [lastYearQ1EndComps setSecond:59]; self.lastYearQ1Ends = [cal dateFromComponents:lastYearQ1EndComps]; NSDateComponents *lastYearQ2StartComps = [[NSDateComponents alloc] init]; [lastYearQ2StartComps setYear:self.currentYear]; [lastYearQ2StartComps setMonth:1]; [lastYearQ2StartComps setDay:1]; [lastYearQ2StartComps setHour:1]; [lastYearQ2StartComps setMinute:0]; [lastYearQ2StartComps setSecond:0]; self.lastYearQ2Starts = [cal dateFromComponents:lastYearQ2StartComps]; NSDateComponents *lastYearQ2EndComps = [[NSDateComponents alloc] init]; [lastYearQ2EndComps setYear:self.currentYear]; [lastYearQ2EndComps setMonth:3]; [lastYearQ2EndComps setDay:31]; [lastYearQ2EndComps setHour:24]; [lastYearQ2EndComps setMinute:59]; [lastYearQ2EndComps setSecond:59]; self.lastYearQ2Ends = [cal dateFromComponents:lastYearQ2EndComps]; // more date boundaries... self.eventStore = [[EKEventStore alloc] init]; self.aftpCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore]; self.thisYearsAFTPEvents = [[NSMutableArray alloc] init]; self.lastYearsAFTPEvents = [[NSMutableArray alloc] init]; // init the rest of my arrays... return self; </code></pre> <p>}</p> <p>And here is an example of how I'm using the <code>NSDates</code> I create from the <code>NSDateComponents</code> to retrieve events from the calendar, which works perfectly fine:</p> <pre><code>- (void)fetchAFTPEvents { NSDate *now = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; NSString *refDate = [dateFormatter stringFromDate:now]; NSString *year = [refDate substringWithRange:NSMakeRange(0,4)]; NSString *month = [refDate substringWithRange:NSMakeRange(5,2)]; self.currentYear = [year integerValue]; int currentMonth = [month integerValue]; if (currentMonth &lt;= 9) { self.currentYear = [year integerValue] -1; } NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.aftpCalendar = [self.eventStore calendarWithIdentifier:[defaults valueForKey:@"AFTPs"]]; NSArray *calendarArray = [NSArray arrayWithObject:self.aftpCalendar]; // Fetch Last Year Q1 Events NSPredicate *lyQ1Predicate = [self.eventStore predicateForEventsWithStartDate:self.lastYearQ1Starts endDate:self.lastYearQ1Ends calendars:calendarArray]; [self.lastYearsQ1AFTPEvents addObjectsFromArray:[self.eventStore eventsMatchingPredicate:lyQ1Predicate]]; [self.lastYearsAFTPEvents addObject:self.lastYearsQ1AFTPEvents]; // fetch the rest of the events... // call delegate [mainViewControllerDelegate updateLabels]; } </code></pre> <p>Thanks in advance for any help.</p>
[]
[ { "body": "<p>you could maintain one array with the starts of the quarters and one withe the ends. as only the months changes, you need just those.<br>\nThan you iterate over them and generate the dates</p>\n\n<pre><code>NSArray *startsOfQuarters = @[@10, @1, @4 , @7];\nNSArray *endOfQuarters = @[@12, @3, @6 , @9];\n\nNSMutableArray *startDates = [NSMutableArray array];\n\n[startsOfQuarters enumerateObjectsUsingBlock:^(NSNumber *month, NSUInteger idx, BOOL *stop){\nNSDateComponents *startComps = [[NSDateComponents alloc] init];\n [startComps setYear:self.currentYear - 1];\n [startComps setMonth:[month integerValue]];\n [startComps setDay:1];\n [startComps setHour:1];\n [startComps setMinute:0];\n [startComps setSecond:0];\n\n // create date from components\n [startDates addObject: date];\n}];\n</code></pre>\n\n<p>do similar for ends.</p>\n\n<p>Now the first quarter's boundries are defined by <code>startDates[0]</code> and <code>endDates[0]</code>, se second by <code>startDates[1]</code> and <code>endDates[1]</code> and so on.</p>\n\n<hr>\n\n<blockquote>\n <p>«Two or more, use a for»<br>\n — Edsger W. Dijkstra</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:53:47.710", "Id": "32753", "Score": "0", "body": "Thanks! It'll take me a while to try this, so I'll report back to mark your answer if it works :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T18:52:30.603", "Id": "20464", "ParentId": "20456", "Score": "1" } } ]
{ "AcceptedAnswerId": "20464", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T03:52:43.690", "Id": "20456", "Score": "2", "Tags": [ "optimization", "performance", "objective-c", "ios" ], "Title": "Initialize a bunch of NSDateComponents objects at once (in a loop)?" }
20456
<p>Following snippet reads CSV Line count using BinaryReader. </p> <p>Currently it checks <code>\r</code> and <code>\n</code> for line delimiters.</p> <pre><code> private static int GetLineCount(string fileName) { BinaryReader reader = new BinaryReader(File.OpenRead(fileName)); int lineCount = 0; char lastChar = reader.ReadChar(); char newChar = new char(); do { newChar = reader.ReadChar(); if (lastChar == '\r' &amp;&amp; newChar == '\n') { lineCount++; } lastChar = newChar; } while (reader.PeekChar() != -1); return lineCount; } </code></pre> <p>I want to use <code>Environment.NewLine</code> string and make it work on <code>windows\unix</code>.</p> <p>I want to refactor above to find word occurance and then match for the word <code>Environment.NewLine</code>. The issue is that I am not able to refactor following for word (more specifically change <code>lastChar</code> , <code>newChar</code> into Array.</p> <pre><code> do { newChar = reader.ReadChar(); if (lastChar == '\r' &amp;&amp; newChar == '\n') { lineCount++; } lastChar = newChar; } while (reader.PeekChar() != -1); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T17:10:05.567", "Id": "32747", "Score": "1", "body": "Both `BinaryReader` and `File.OpenRead()` are `IDisposable` resources - wrap them in a `using` statement for deterministic disposal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T18:55:26.203", "Id": "32748", "Score": "0", "body": "Wait, are you trying to do line count or an array comparison (as the title suggests)? Also, do you need an exact count in the case of a large file? If you know the total file size and you know the length of the first 20,000 lines, then you could have a good guess of what the line count is approximately. What are you trying to do at the higher level?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:00:04.337", "Id": "32749", "Score": "0", "body": "Array-comparison (or specifically word comparison) comes into picture as I want to use `Environment.NewLine`. At higher level I am finding exact line count for big files ( >1GB) for progress reporting. Currently It is done using Stream Current Read position divided by file length. But that is not acceptable (as inconsistent due to other file types involved), in our overall context." } ]
[ { "body": "<p><code>Environment.NewLine</code> always returns <code>\\r\\n</code> so it won't help you in parsing different line endings.</p>\n\n<p>If your task is to count the number of lines then it would be much easier just to do smth. like:</p>\n\n<pre><code> private static int GetLineCount(string fileName)\n {\n return File.ReadLines(fileName).Count();\n }\n</code></pre>\n\n<p><code>ReadLines</code> method automatically parses different line endings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T12:57:06.847", "Id": "32742", "Score": "2", "body": "1. Environment.NewLine returns line feed. On unix it is LF (\\n), on Mac it is CR(\\r), on windows it is CRLF(\\r\\n). 2. Try running the code on large files (> 2 GB), It will throw OutOfMemoryException." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:49:41.207", "Id": "32750", "Score": "0", "body": "@Tilak: Why would you line count a 2gb file?..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:53:17.880", "Id": "32752", "Score": "0", "body": "2GB is for illustration, Files are large in size (100MB - 1GB), but to answer your question, I need to show message like `Processing x row in Total N rows`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:22:19.773", "Id": "32754", "Score": "1", "body": "@Tilak, I've used `ReadLines` method that returns a stream of lines. You probably confused it with `ReadAllLines` which indeed loads all lines in memory. The only case when this code would throw `OutOfMemoryException` is when your file would have a line longer than 2GBs which is very-very unlikely for text files" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:30:15.353", "Id": "32755", "Score": "0", "body": "@Tilak about `Environment.NewLine` - are you talking about running this .NET code on Mac/Unix? Or parsing files coming from those platforms? [.NET framework explicitly specifies](http://typedescriptor.net/browse/members/828101-System.Environment.NewLine) `\\r\\n` as a value for `Environment.NewLine`, not sure about Mono." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:30:31.237", "Id": "32756", "Score": "0", "body": "@You are right that I got confused with `ReadAllLines`. I need to check this out, but as it is returning `IEnumerable` i suspect it loads all the data into memory (may be not that i need to check)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:35:16.087", "Id": "32757", "Score": "0", "body": "I can guarantee that `ReadLines` reads the file lazily" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:28:53.663", "Id": "32759", "Score": "0", "body": "Thanks. It is good to know. (I was aware that something of this sort exist for reading file lines/enumerating files/directories) but never looked at the API. But still I was expecting refactoring of my code. `File.ReadLines` functionality (corresponding to my requirements) can be achieved with `StreamReader.ReadLine` in a loop. There is a trade-off (how much, i need to benchmark) to convert line into string which is not needed for line count." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:41:42.460", "Id": "32760", "Score": "0", "body": "`File.ReadLines` does exactly that, reads the lines using `StreamReader.ReadLine` and returns them as lazy `IEnumerable<string>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T20:23:52.670", "Id": "32867", "Score": "0", "body": "On Mono on Unix `Environment.Newline` indeed returns just `\"\\n\"`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T20:25:56.773", "Id": "32868", "Score": "0", "body": "In any case when your task is to calculate line count it's more important where the file came from rather than current OS" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T12:14:07.523", "Id": "20459", "ParentId": "20457", "Score": "2" } } ]
{ "AcceptedAnswerId": "20459", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T04:18:11.863", "Id": "20457", "Score": "1", "Tags": [ "c#" ], "Title": "Clean code for array comparison" }
20457
<p>Today I solved a question from Google Code Jam: mimicking a cell phone keypad messaging.</p> <p>Here is the program, with <code>goto</code> statements. I know it is an unstructured style to use <code>goto</code>, but I still did because it improved speed.</p> <pre><code>#include &lt;stdio.h&gt; int main() { char c, c1 = NULL; int top; top: while((c = getchar()) != '\n') { if (c == ' ')printf("0"); if(c == 'a' || c == 'b' || c == 'c') { if(c1 == 'a' || c1 == 'b' || c1 == 'c') printf(" "); if(c == 'a') printf("2"); if(c == 'b') printf("22"); if(c == 'c') printf("222"); c1 = c; goto top; } if(c == 'd' || c == 'e' || c == 'f') { if(c1 == 'd' || c1 == 'e' || c1 == 'f') printf(" "); if(c == 'd') printf("3"); if(c == 'e') printf("33"); if(c == 'f') printf("333"); c1 = c; goto top; } if(c == 'g' || c == 'h' || c == 'i') { if(c1 == 'g' || c1 == 'h' || c1 == 'i') printf(" "); if(c == 'g') printf("4"); if(c == 'h') printf("44"); if(c == 'i') printf("444"); c1 = c; goto top; } if(c == 'j' || c == 'k' || c == 'l') { if(c1 == 'j' || c1 == 'k' || c1 == 'l') printf(" "); if(c == 'j') printf("5"); if(c == 'k') printf("55"); if(c == 'l') printf("555"); c1 = c; goto top; } if(c == 'm' || c == 'n' || c == 'o') { if(c1 == 'm' || c1 == 'n' || c1 == 'o') printf(" "); if(c == 'm') printf("6"); if(c == 'n') printf("66"); if(c == 'o') printf("666"); c1 = c; goto top; } if(c == 'p' || c == 'q' || c == 'r' || c == 's') { if(c1 == 'p' || c1 == 'q' || c1 == 'r' || c1 == 's') printf(" "); if(c == 'p') printf("7"); if(c == 'q') printf("77"); if(c == 'r') printf("777"); if(c == 's') printf("7777"); c1 = c; goto top; } if(c == 't' || c == 'u' || c == 'v') { if(c1 == 't' || c1 == 'u' || c1 == 'v') printf(" "); if(c == 't') printf("8"); if(c == 'u') printf("88"); if(c == 'v') printf("888"); c1 = c; goto top; } if(c == 'w' || c == 'x' || c == 'y' || c == 'z') { if(c1 == 'w' || c1 == 'x' || c1 == 'y' || c1 == 'z') printf(" "); if(c == 'w') printf("9"); if(c == 'x') printf("99"); if(c == 'y') printf("999"); if(c == 'z') printf("9999"); c1 = c; goto top; } } } </code></pre> <p>The above program without <code>goto</code>:</p> <pre><code>#include &lt;stdio.h&gt; int main() { char c, c1 = NULL; while((c = getchar()) != '\n') { if (c == ' ')printf("0"); if(c == 'a' || c == 'b' || c == 'c') { if(c1 == 'a' || c1 == 'b' || c1 == 'c') printf(" "); if(c == 'a') printf("2"); if(c == 'b') printf("22"); if(c == 'c') printf("222"); } if(c == 'd' || c == 'e' || c == 'f') { if(c1 == 'd' || c1 == 'e' || c1 == 'f') printf(" "); if(c == 'd') printf("3"); if(c == 'e') printf("33"); if(c == 'f') printf("333"); } if(c == 'g' || c == 'h' || c == 'i') { if(c1 == 'g' || c1 == 'h' || c1 == 'i') printf(" "); if(c == 'g') printf("4"); if(c == 'h') printf("44"); if(c == 'i') printf("444"); } if(c == 'j' || c == 'k' || c == 'l') { if(c1 == 'j' || c1 == 'k' || c1 == 'l') printf(" "); if(c == 'j') printf("5"); if(c == 'k') printf("55"); if(c == 'l') printf("555"); } if(c == 'm' || c == 'n' || c == 'o') { if(c1 == 'm' || c1 == 'n' || c1 == 'o') printf(" "); if(c == 'm') printf("6"); if(c == 'n') printf("66"); if(c == 'o') printf("666"); } if(c == 'p' || c == 'q' || c == 'r' || c == 's') { if(c1 == 'p' || c1 == 'q' || c1 == 'r' || c1 == 's') printf(" "); if(c == 'p') printf("7"); if(c == 'q') printf("77"); if(c == 'r') printf("777"); if(c == 's') printf("7777"); } if(c == 't' || c == 'u' || c == 'v') { if(c1 == 't' || c1 == 'u' || c1 == 'v') printf(" "); if(c == 't') printf("8"); if(c == 'u') printf("88"); if(c == 'v') printf("888"); } if(c == 'w' || c == 'x' || c == 'y' || c == 'z') { if(c1 == 'w' || c1 == 'x' || c1 == 'y' || c1 == 'z') printf(" "); if(c == 'w') printf("9"); if(c == 'x') printf("99"); if(c == 'y') printf("999"); if(c == 'z') printf("9999"); } c1 = c; } } </code></pre> <p>Which one is better? How can I come to a realization that X program is better compared to Y?</p> <p>By the way, I did not use any Derived data typed and pointers because I did not find it useful here.</p>
[]
[ { "body": "<p>I didn't write any C in the last few years but I think you could use <a href=\"http://www.acm.uiuc.edu/webmonkeys/book/c_guide/1.6.html#continue\" rel=\"nofollow\"><code>continue</code></a> instead of <code>goto</code> in the first version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:51:17.960", "Id": "32751", "Score": "2", "body": "continue looks correct" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T15:55:30.897", "Id": "20463", "ParentId": "20462", "Score": "1" } }, { "body": "<p>Because your outer-layer tests are mutually exclusive (ie. only one can occur), you should use <code>else</code> rather than <code>goto</code> or <code>continue</code>. The <code>else</code> is used when the condition for which <code>if</code> tests is false:</p>\n\n<pre><code> if (c == ' ') {\n printf(\"0\");\n }\n else if (c == 'a' || c == 'b' || c == 'c')\n {\n if(c1 == 'a' || c1 == 'b' || c1 == 'c')\n printf(\" \");\n if(c == 'a') printf(\"2\");\n else if(c == 'b') printf(\"22\");\n else if(c == 'c') printf(\"222\");\n c1 = c;\n }\n else if(c == 'd' || c == 'e' || c == 'f')\n { ... }\n else if ...\netc\n</code></pre>\n\n<p>note also that <code>c</code> and <code>c1</code> should be declared <code>int</code> and that <code>c1 = NULL</code> is wrong (as <code>NULL</code> is declared as <code>(void *) 0</code>; use <code>c1 = '\\0'</code>.</p>\n\n<p>Moreover, turn more warnings ON in your compiler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:40:42.030", "Id": "20468", "ParentId": "20462", "Score": "0" } }, { "body": "<p>Terminating when <code>getchar()</code> encounters <code>\\n</code> is poor practice. If the program encounters <kbd>EOF</kbd> before <kbd>Newline</kbd>, then it will enter an infinite loop.</p>\n\n<p>Considering that you only support lowercase, it would be nice if you folded the input to lowercase.</p>\n\n<p>That is one long, uninspired while-loop, full of cut-and-paste code. I recommend a completely different approach. Defining a <code>print_t9()</code> function makes the code more meaningful and reusable.</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n/**\n * Determines the key and the number of repetitions of that key to type\n * character c in T9. If c is a supported character, returns true.\n * If c is unsupported, returns false, and the contents of *key and *reps\n * are undefined.\n */\nstatic _Bool t9_lookup(char c, int *key, int *reps) {\n static const char t9_table[][5] = {\n \" \", /* 0 */\n \"\", \"abc\", \"def\", /* 1 2 3 */\n \"ghi\", \"jkl\", \"mno\", /* 4 5 6 */\n \"pqrs\", \"tuv\", \"wxyz\" /* 7 8 9 */\n };\n\n c = tolower(c);\n for (*key = 0; *key &lt; sizeof(t9_table); (*key)++) {\n char *p;\n if ((p = strchr(t9_table[*key], c))) {\n if (reps) {\n *reps = p - t9_table[*key] + 1;\n }\n return true;\n }\n }\n return false;\n}\n\n/**\n * If c is one of the supported characters, prints the T9 representation and\n * returns true. Otherwise, returns false. If the T9 representation uses the\n * same key as the previous character, a space is printed as a separator.\n */\n_Bool print_t9(FILE *output, char c, char prev_c) {\n int key, reps, prev_key;\n if (!t9_lookup(c, &amp;key, &amp;reps)) return false;\n\n if (t9_lookup(prev_c, &amp;prev_key, NULL) &amp;&amp; key == prev_key) {\n fprintf(output, \" \");\n }\n while (reps--) {\n fprintf(output, \"%d\", key);\n }\n return true;\n}\n\nint main() {\n for (char prev_c = '\\0', c; EOF != (c = getchar()); prev_c = c) {\n print_t9(stdout, c, prev_c) || putchar(c);\n }\n return 0;\n}\n</code></pre>\n\n<p>You should probably support digits as well, to be typed with one additional keypress. All it would take to support that enhancement is a simple change:</p>\n\n<pre><code> static const char t9_table[][6] = {\n \" 0\",\n \"1\", \"abc2\", \"def3\",\n \"ghi4\", \"jkl5\", \"mno6\",\n \"pqrs7\", \"tuv8\", \"wxyz9\"\n };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-25T04:34:36.240", "Id": "58004", "ParentId": "20462", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T14:38:56.323", "Id": "20462", "Score": "3", "Tags": [ "c", "programming-challenge", "comparative-review" ], "Title": "Mimicking T9 cell messaging" }
20462
<p>I'm sure this can be done in less lines and in a more clean way?</p> <pre><code>function BaseClass() { BaseClass.prototype.talk = function () { alert("I'm BaseClass"); } } function MyClass() { BaseClass.call(this); } MyClass.prototype = new BaseClass(); MyClass.base = {}; MyClass.base.talk = MyClass.prototype.talk; MyClass.prototype.talk = function () { alert("I'm MyClass"); MyClass.base.talk(); } var a = new MyClass(); a.talk(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T06:51:00.757", "Id": "32767", "Score": "0", "body": "Why are you declaring `BaseClass.prototype.talk` inside the constructor?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T06:52:40.713", "Id": "32768", "Score": "0", "body": "@JosephSilber: I don't know. Am I not suppose to do it there? Why wouldn't I declare it there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T06:54:15.313", "Id": "32769", "Score": "0", "body": "Because then you're recreating the function every time you create a new object. The prototype is used to store functions that are shared between your objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:00:57.920", "Id": "32770", "Score": "0", "body": "@JosephSilber: Ah, so how would you rewrite all of this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:17:10.497", "Id": "32771", "Score": "0", "body": "You basically have it all figured out. I changed it around a tiny bit, and posted it below." } ]
[ { "body": "<pre><code>function BaseClass () {}\n\nBaseClass.prototype.talk = function () {\n alert(\"I'm BaseClass\");\n}\n\nfunction MyClass() {\n BaseClass.call(this);\n}\n\nMyClass.prototype = new BaseClass();\nMyClass.base = BaseClass.prototype;\n\nMyClass.prototype.talk = function () {\n alert(\"I'm MyClass\");\n MyClass.base.talk.apply(this, arguments);\n}\n\nvar a = new MyClass();\na.talk();\n</code></pre>\n\n<p>To make all this easier on yourself, don't re-invent the wheel. Look into John Resig's tiny inheritance library: <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"nofollow\"><strong>Simple JavaScript Inheritance</strong></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:32:27.383", "Id": "32772", "Score": "0", "body": "cool but the `talk.apply(this, arguments);` looks nasty" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:34:45.137", "Id": "32773", "Score": "0", "body": "@acidzombie24 - Sure. Wish we didn't need it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:16:35.647", "Id": "20478", "ParentId": "20465", "Score": "1" } } ]
{ "AcceptedAnswerId": "20478", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T19:47:26.917", "Id": "20465", "Score": "1", "Tags": [ "javascript" ], "Title": "Javascript class+call base class?" }
20465
<p>I am running a simulation with 250 interacting agents and have a few functions that are called over and over again. Even with precomputing all distances between agents before the N<sup>2</sup> (250x250) interaction loop, my simulation is still very slow. Are there any C++ optimization tricks that I could use to speed these up?</p> <p>This is the most-used function in my simulation. It calculates the distance<sup>2</sup> between two agents in a continuous space. I have a feeling there isn't much that can be done to further optimize this, but you guys have surprised me with some tricks before:</p> <pre><code>double tGame::calcDistanceSquared(double fromX, double fromY, double toX, double toY) { double diffX = fromX - toX; double diffY = fromY - toY; return ( diffX * diffX ) + ( diffY * diffY ); } </code></pre> <p>Here's another expensive function in my simulation. It calculates the angle from one agent to another agent relative to the 'from' agent's heading. As you can see, I already did a little precomputing with the <code>atan2()</code> function (and that DOES speed things up a bit, despite what I've read in other posts).</p> <pre><code>double tGame::calcAngle(double fromX, double fromY, double fromAngle, double toX, double toY) { double Ux = 0.0, Uy = 0.0, Vx = 0.0, Vy = 0.0; Ux = (toX - fromX); Uy = (toY - fromY); Vx = cosLookup[(int)fromAngle]; Vy = sinLookup[(int)fromAngle]; int firstTerm = (int)((Ux * Vy) - (Uy * Vx)); int secondTerm = (int)((Ux * Vx) + (Uy * Vy)); if (fabs(firstTerm) &lt; 1000 &amp;&amp; fabs(secondTerm) &lt; 1000) { return atan2Lookup[firstTerm + 1000][secondTerm + 1000]; } else { return atan2(firstTerm, secondTerm) * 180.0 / cPI; } } </code></pre> <p>Finally, here's the monster function that uses the <code>calcDistanceSquared()</code> function so much. This is run every simulation time step, and there's 2,000 time steps per simulation (and MANY simulations). The most expensive part is the <code>calcDistanceSquared()</code> in the N<sup>2</sup> loop.</p> <pre><code>void tGame::recalcPredAndPreyDistTable(double preyX[], double preyY[], bool preyDead[], double predX, double predY, double predDists[250], double preyDists[250][250]) { for (int i = 0; i &lt; 250; ++i) { if (!preyDead[i]) { predDists[i] = calcDistanceSquared(predX, predY, preyX[i], preyY[i]); preyDists[i][i] = 0.0; for (int j = i + 1; j &lt; 250; ++j) { if (!preyDead[j]) { preyDists[i][j] = preyDists[j][i] = calcDistanceSquared(preyX[i], preyY[i], preyX[j], preyY[j]); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:12:16.023", "Id": "32791", "Score": "2", "body": "Use a space partitioning algorithm to avoid the N^2 loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:16:49.410", "Id": "32792", "Score": "0", "body": "Just my 2 cents: is it *really* necessary for each of the 250 agents to interact with *all* other 249? For swarm AI, usually only the *n* nearest are used, which basically makes the `N^2` a `N`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:18:55.197", "Id": "32793", "Score": "0", "body": "@Constantinius I am simulating a retina for each prey, thus I have to *at least* know if each prey is within a visible range." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:19:48.267", "Id": "32794", "Score": "0", "body": "@GManNickG Excuse my ignorance (I've never used a space partitioning algorithm before), but would it take a large overhaul to implement a space partitioning algorithm in a continuous space like this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:26:34.037", "Id": "32795", "Score": "3", "body": "@RandyOlson: Large overhaul or not, you have to do it. Speed up and optimization is rarely about the little nanosecond improvements you might spend (waste) time finding. It's about structuring your data efficiently for your use. Anything beyond the smallest toy games need to organize their entities in space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:26:56.767", "Id": "32796", "Score": "0", "body": "Is it possible there are some simulations where the behavior of the agents doesn't have to be recalculated every step? In other words, for some objects in your graph, there are groups of time steps that can be calculated either based on a single polynomial, or that are only affected by a small set of neighboring objects. That's probably what GMan means by space partitioning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:28:04.817", "Id": "32797", "Score": "0", "body": "@GManNickG Any recommended tutorials for converting a continuous space into a partitioned space?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:31:51.597", "Id": "32798", "Score": "0", "body": "@AustinMullins To be honest: I'm not sure. I would imagine there are time steps that I am recalculating the distance between certain agents when I really don't need to (e.g., because they haven't moved, or are off by themselves somewhere), but I haven't been able to come up with any tricks that don't end up being even more expensive than just calculating the distance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:09:28.090", "Id": "32799", "Score": "0", "body": "What are you using the distances for? If you're only looking at the smallest few, there will be some computational geometry tricks that will help you. If you're doing gravity or something, you can use the fast multipole method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:15:36.827", "Id": "32800", "Score": "0", "body": "@tmyklebu I am simulating a retina for each agent, thus I have to at least know if each agent is within a visible range." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T02:29:00.633", "Id": "32801", "Score": "0", "body": "Instead of recalculating all the distances, can you calculate only the few that have moved. Perhaps change the design so that when an entity moves, it notifies your object? See Publisher / Subscriber Design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T02:31:40.227", "Id": "32802", "Score": "0", "body": "Try Loop Unrolling (search the web or SO)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T07:37:34.887", "Id": "32803", "Score": "0", "body": "@RandyOlson Look into using an octree." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T08:22:15.923", "Id": "32804", "Score": "0", "body": "@ThomasMatthews Loop unrolling is unlikely to help here, as the problem is with the algorithm, not the implementation or the limits of C's assertions on its pointers." } ]
[ { "body": "<p>It looks good to me. I would change </p>\n\n<pre><code> if (!preyDead[i])\n {\n</code></pre>\n\n<p>To</p>\n\n<pre><code> if (preyDead[i])\n continue;\n</code></pre>\n\n<p>Just so its less nested. Same with preyDead[j]. But everything looks fine to me.\nA tip I once saw on SO is, if your list order doesn't matter you can sort the preyDead so all the dead would be at the beginning or end and that will help branch prediction. However thats assuming its not really expensive to sort it and that its a very erratic bool and it isnt true/false 90% of the time already.</p>\n\n<p>Thats a uber optimize that may not help, it shouldn't be done less you really really want to</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:39:27.730", "Id": "20467", "ParentId": "20466", "Score": "3" } }, { "body": "<p>It is being said that compilers can vectorize stuff better if there are no ifs in loops. So, in that spirit, try to remove the if from the inner loop of <code>recalcPredAndPreyDistTable()</code> to see if it does not vectorize better and thus generate better code and thus is not a performance win despite the recomputation of distances between the dead prey.</p>\n\n<p>Second thought, if you have a compiler that supports OpenMP, try to parallelize the outer loop, like this:</p>\n\n<pre><code>#pragma omp parallel for\n for (int i = 0; i &lt; 250; ++i)\n {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T23:14:07.150", "Id": "20469", "ParentId": "20466", "Score": "1" } }, { "body": "<p>If this is possible - try to rewrite methods header like this.\nOnce I get valuable speed-up. This is because you have no need to copy arrays, you can give to your method only addresses.</p>\n\n<pre><code>void tGame::recalcPredAndPreyDistTable(double &amp;preyX[], double &amp;preyY[], bool &amp;preyDead[],\n double predX, double predY,\n double &amp;predDists[250], double &amp;preyDists[250][250])\n</code></pre>\n\n<p><strong>EDIT:</strong> will this work?</p>\n\n<pre><code>void tGame::recalcPredAndPreyDistTable(double *preyX, double *preyY, bool *preyDead,\n double predX, double predY,\n double *predDists, double **preyDists)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:18:39.990", "Id": "32805", "Score": "0", "body": "If I remember right, arrays are passed by reference by default in C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:26:13.750", "Id": "32806", "Score": "0", "body": "Randy is kind of correct. C arrays are just pointers, no more, no less... So, this adds nothing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T22:48:28.667", "Id": "32807", "Score": "2", "body": "@AlexChamberlain: Please, do **not** maintain the false assertion that arrays are pointers alive!!! Arrays are **not** pointers, they *decay* into pointers easily, but they are **not** pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T22:51:17.613", "Id": "32808", "Score": "1", "body": "@cupidon4uk: The code in your answer will not compile, `double &preyX[]` means *array of unknown number of references to `double`* which is not legal in C++. Even if you added parenthesis as in `double (&preyX)[]` meaning *reference to an array...* it would still not compile as you cannot have a reference to an array of an unknown number of elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T08:19:11.013", "Id": "32809", "Score": "0", "body": "@dribeas Really? C style arrays are pretty much just pointers once you pass then to another function. Of course, in a function they reserve space on the stack. Now, in C++, you shouldn't use C arrays any more. Use std::array if you can, otherwise tr1 or boost. Pass them by const reference and all is good with the world. Furthermore, if you want to return an array, just return an array. Compilers will optimise out the copy." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T21:11:27.697", "Id": "20493", "ParentId": "20466", "Score": "0" } }, { "body": "<p>I don't believe you will not get maximum benefits from code changes, but see my answer here:<br>\n<a href=\"https://stackoverflow.com/questions/2074099/coding-practices-which-enable-the-compiler-optimizer-to-make-a-faster-program/2075264#2075264\">Optimization Coding Practices</a></p>\n\n<p>One issue that is screaming out is why are you making so many iterations?<br>\nFor example, do <em>all</em> the positions need to be recalculated?</p>\n\n<p>Can you cache the calculations?<br>\nYou only need to perform the calculations if something moves. You can quickly detect if something moves by comparing the coordinates (don't need to calculate distances here).</p>\n\n<p>Another observation is that you are currently <em>polling</em>, that is, looping until something moves. You may want to change your paradigm to event driven: when something changes, it sends out a message or notification. With the Event Driven paradigm, your reduce a lot of computation for things that don't change. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T02:41:47.353", "Id": "20494", "ParentId": "20466", "Score": "1" } }, { "body": "<p>Almost certainly whatever you try to achieve with \"fromAngle\" and atan2, can be accomplished with pure vector math.</p>\n\n<p>Re-arrange the matrix (with extra level of indirection in other parts of the code) so that the prayDead[i]==true are in the beginning of the array (and prayDead[i]==false) are at the end.</p>\n\n<p>It does not only reduce branch prediction, but decreases from N*N to (N-n)*(N-n).</p>\n\n<p>Also it may not be optimal to try to reduce the operations from N*N to N*N/2 by computing an upper triangle. It's better to make a simple loop that the compiler can parallelize (that's 4x gain compared to max 2x gain from reducing the symmetry.)</p>\n\n<p>Further, it's often better to split 256x256 operations to 32x32 x 8x8 operations or so. Then each block will benefit from the array being in cache -- however in this case it may again be beneficial to permute upper triangle blocks:</p>\n\n<pre><code>a b c &lt;-- here the diagonal blocks (a,d,f) are calculated as usual\nB d e but B,C,E can be calculated by rotating the results of (b,c,e)\nC E f\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T16:42:06.960", "Id": "20496", "ParentId": "20466", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T20:22:21.990", "Id": "20466", "Score": "10", "Tags": [ "c++", "performance", "computational-geometry" ], "Title": "Calculating angles and distances" }
20466
<p>In my library <a href="http://androidtransfuse.org" rel="nofollow">Transfuse</a> I use a code generator to build a handful of classes that look up resources. Each of these look up classes are proxied by a static utility class so they may be referenced before the generated class is built. For instance, the <code>Parcels</code> class can be used to wrap an object with a generated <code>Parcelable</code> class:</p> <pre><code>ExampleParcel parcel = new ExampleParcel(); Parcelable parcelable = Parcels.wrap(parcel); // ... load into bundle as extra, etc </code></pre> <p><code>Parcels</code> proxies a generated class called <code>Transfuse$Parcels</code>.</p> <p><code>Parcels</code>:</p> <pre><code>public final class Parcels { public static final String PARCELS_NAME = "Parcels"; public static final String PARCELS_REPOSITORY_NAME = "Transfuse$Parcels"; public static final String PARCELS_PACKAGE = "org.androidtransfuse"; private static ParcelRepository instance; static{ try{ Class injectorClass = Class.forName(PARCELS_PACKAGE + "." + PARCELS_REPOSITORY_NAME); instance = (ParcelRepository) injectorClass.newInstance(); } catch (ClassNotFoundException e) { instance = null; } catch (InstantiationException e) { throw new TransfuseRuntimeException("Unable to instantiate generated ParcelRepository", e); } catch (IllegalAccessException e) { throw new TransfuseRuntimeException("Unable to access generated ParcelRepository", e); } } private Parcels(){ // private utility class constructor } public static Parcelable wrap(Object input) { if(instance == null){ throw new TransfuseRuntimeException("Unable to find " + PARCELS_REPOSITORY_NAME + " class"); } return instance.wrap(input); } } </code></pre> <p><code>Transfuse$Parcels</code>:</p> <pre><code>@Generated(value = "org.androidtransfuse.TransfuseAnnotationProcessor", date = "01/12/2013 16:56:02 MST") public class Transfuse$Parcels implements ParcelRepository { private final Map&lt;Class, ParcelableFactory&gt; parcelWrappers = new HashMap&lt;Class, ParcelableFactory&gt;(); public Transfuse$Parcels() { parcelWrappers.put(...); } @Override public Parcelable wrap(Object input) { return parcelWrappers.get(input.getClass()).buildParcelable(input); } // Define ParcelableFactory classes... } </code></pre> <p>Is this technique of loading the generated class using the static initialization block optimal? As you can see, if the class is not found (not generated possibly) then the <code>ParcelRepository</code> instance ends up being <code>null</code> and <code>wrap()</code> would always return <code>null</code>. Should <code>wrap()</code> throw a runtime exception if an instance is not found instead?</p> <p>If you take a look at the library, the code above is a simplification for example purposes: <a href="https://github.com/johncarl81/transfuse/blob/master/transfuse-api/src/main/java/org/androidtransfuse/Parcels.java" rel="nofollow">Parcels</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T09:30:32.297", "Id": "33436", "Score": "0", "body": "Is there a reason why  `Parcels` and `Transfuse$Parcels` can not be in the same `jar`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T16:16:16.193", "Id": "33452", "Score": "0", "body": "Yes, because Parcels is the public API, whereas Transfuse$Parcels is generated per client code configuration. Parcels is readily available while Transfuse$Parcels may not even exist until compile time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T17:03:20.183", "Id": "33458", "Score": "0", "body": "What are your criteria for optimal?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T18:33:51.520", "Id": "33464", "Score": "0", "body": "Good question. \"Optimal\" is rather subjective. Personally, I prefer to only use static if absolutely necessary, so if static is not required, then that solution would be preferred. Also, are all the exceptions thrown necessary and correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T18:34:19.337", "Id": "33465", "Score": "0", "body": "I encourage you to take a look at the real code in the library as well: https://github.com/johncarl81/transfuse/blob/master/transfuse-api/src/main/java/org/androidtransfuse/Parcels.java" } ]
[ { "body": "<p>I ended up taking a bit of a different route with this problem. It seems I was not adding additional proxied resources if they were not contained within the current compiled package... as in, they were included in included libraries. So, my proxy utility looks like the following:</p>\n\n<pre><code>public abstract class GeneratedCodeRepository&lt;T&gt; {\n\n private ConcurrentMap&lt;Class, T&gt; generatedMap = new ConcurrentHashMap&lt;Class, T&gt;();\n\n public GeneratedCodeRepository(String repositoryPackage, String repositoryName) {\n loadRepository(getClass().getClassLoader(), repositoryPackage, repositoryName);\n }\n\n public T get(Class clazz){\n T result = generatedMap.get(clazz);\n if (result == null) {\n T value = findClass(clazz);\n if(value == null){\n return null;\n }\n result = generatedMap.putIfAbsent(clazz, value);\n if (result == null) {\n result = value;\n }\n }\n\n return result;\n }\n\n public abstract T findClass(Class clazz);\n\n /**\n * Update the repository class from the given classloader. If the given repository class cannot be instantiated\n * then this method will throw a TransfuseRuntimeException.\n *\n * @throws TransfuseRuntimeException\n * @param classLoader\n */\n public final void loadRepository(ClassLoader classLoader, String repositoryPackage, String repositoryName){\n try{\n Class repositoryClass = classLoader.loadClass(repositoryPackage + \".\" + repositoryName);\n Repository&lt;T&gt; instance = (Repository&lt;T&gt;) repositoryClass.newInstance();\n generatedMap.putAll(instance.get());\n\n } catch (ClassNotFoundException e) {\n //nothing\n } catch (InstantiationException e) {\n throw new TransfuseRuntimeException(\"Unable to instantiate generated Repository\", e);\n } catch (IllegalAccessException e) {\n throw new TransfuseRuntimeException(\"Unable to access generated Repository\", e);\n }\n }\n}\n</code></pre>\n\n<p><code>findClass()</code> then can be defined to lookup the given repository class using reflection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T02:12:57.110", "Id": "23711", "ParentId": "20470", "Score": "2" } } ]
{ "AcceptedAnswerId": "23711", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T00:09:59.923", "Id": "20470", "Score": "2", "Tags": [ "java", "performance", "proxy", "dynamic-loading" ], "Title": "Generated code proxy" }
20470
<p>The full code is located here: <a href="https://gist.github.com/4521540" rel="nofollow noreferrer">https://gist.github.com/4521540</a></p> <p>It's a dummy <code>List</code> in C++. My concern is with freeing up memory. It doesn't crash when I run my code. It looks like my <code>if/else</code> covers everything.</p> <ol> <li>It starts by deleting the second item if there is. That's what the while loop does. </li> <li>If there is only one present (or left with one), delete <code>startNode</code>. </li> </ol> <p><code>startNode</code> is a pointer points to the first item in the list. <code>endNode</code> always points to the last item in the list. </p> <p>Am I deleting the pointer or the underlying object?</p> <p>I do mostly Python. Last time I wrote a serious C++ homework was about 2 years ago in my algorithm class so I really can't remember everything off my head.</p> <pre><code>~List() { // there is at least one item if(startNode != 0) { // release memory starting from the second item ListNode *current, *soon; current = this-&gt;startNode-&gt;next; while(current != 0) // if there are at least two items { /* When there is no more items after current, * delete current and leave. * Otherwise, free up current and move on to * the next item. */ if(current-&gt;next != 0) { soon = current-&gt;next; delete current; current = soon; } else { delete current; break; } } } delete this-&gt;startNode; delete this-&gt;endNode; } </code></pre> <p>Also, do I need to delete the <code>myList</code> in my main program? I think when I exit the program, the destructor is automatically called. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-05T14:53:59.873", "Id": "351322", "Score": "0", "body": "You also might want to read up on smart pointers. You can protect against memory leaks and double deletes by using `std::unique_ptr`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-03T08:14:50.147", "Id": "366869", "Score": "0", "body": "Do you have a test suite for this? And have you run it under Valgrind (or other memory checker of your choice)?" } ]
[ { "body": "<p>A cleaner way would be to go iteratively through the list. </p>\n\n<p>I would do something like:</p>\n\n<pre><code>~List()\n{ \n if(startNode == NULL)\n return;\n\n if(startNode-&gt;Next != 0)\n { \n delete this-&gt;startNode-&gt;Next;\n }\n delete this-&gt;startNode;\n}\n</code></pre>\n\n<p>This will go through your list, and <code>startNode-&gt;Next</code> will be the new startNode (this), thus it should delete the whole list just fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T02:13:40.733", "Id": "32765", "Score": "0", "body": "You meant `while (startNode->next != 0)`?Also, correct me if I am wrong: I only need to provide a destructor if there's `new` in the class/struct implementation, right? Do I need to delete anything in `main`? Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T09:32:31.047", "Id": "32777", "Score": "0", "body": "This code will only delete the first and second node. Even if you change the `if` to a `while`, you would need to add a temporary variable in there to keep track of the `next` before deleting it, and then re-assigning startNode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T11:18:19.593", "Id": "32780", "Score": "0", "body": "It depends what type startNode is actually. I would do it like a listNode, and have in that listNode a reference to the Next node. Then a delete on the first node would go through to every single one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T14:14:46.510", "Id": "32785", "Score": "0", "body": "-1, this doesn’t work – you’re confusing `List` and `ListNode` here. This won’t iterate through the list nodes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T14:21:36.350", "Id": "32786", "Score": "0", "body": "Clearly each node saves the next node. So you can just iterate through the list. I don't get what you are trying to point here, with proper implementation this works. List object stores the first Node, and each node points to the next, so you can pass the delete from one node to the next." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:00:46.630", "Id": "32818", "Score": "0", "body": "The destructor of a node should not delete nodes it is connected to. If you tried to remove and delete a single node from a list you would end up deleting everything after it. A node doesn't \"own\" the next node, it simply connects to it - the `List` \"owns\" each node, and so the `List` should destroy them." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T01:22:51.107", "Id": "20473", "ParentId": "20472", "Score": "-2" } }, { "body": "<p>First, to answer your questions about new/delete: Everything you <code>new</code>, you must <code>delete</code> at some point, or you leak memory. When you <code>new</code>, you are given a pointer to the object that has been allocated. Similarly, when you use <code>delete</code>, you must use a pointer to that same object, and the memory that was allocated will be freed. After doing this, the pointer will be pointing at freed memory and you should not <code>delete</code> this again. It doesn't matter where you use <code>new</code>, in <code>main()</code> or otherwise, you need to <code>delete</code> it at some point.</p>\n\n<p>Now to your code: Your code will double-delete either the first node when the list size is 1, or the last node, when the list size is greater than 1. Double deletes cause undefined behaviour including crashes.</p>\n\n<p>Let's look at list of size 1 first. Your while loop won't be entered, and you basically skip down to the end where you do</p>\n\n<pre><code>delete this-&gt;startNode;\ndelete this-&gt;endNode;\n</code></pre>\n\n<p>Since startNode and endNode should both be pointing to the only node in the list, it will get deleted twice!</p>\n\n<p>If you have a list of more items, the loop will delete every item except the first. Then the last two statements occur. In this case, <code>this-&gt;endNode</code> will be the original end of the list (since you never alter it here) and so it will be deleted twice.</p>\n\n<p>Here is a simpler version that just deletes every node, starting from the first.</p>\n\n<pre><code>~List\n{\n ListNode* current = startNode;\n ListNode* next;\n\n while (current != NULL) {\n next = current-&gt;next;\n delete current;\n current = next;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-15T22:37:30.167", "Id": "512088", "Score": "0", "body": "That *can* be shortened: `for (auto p = startNode; p;) delete std::exchange(p, p->next);`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T09:30:12.363", "Id": "20480", "ParentId": "20472", "Score": "3" } } ]
{ "AcceptedAnswerId": "20480", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T01:14:11.720", "Id": "20472", "Score": "5", "Tags": [ "c++", "linked-list", "memory-management" ], "Title": "Destructor for a linked list" }
20472
<p>This is my code and I would like to get it code reviewed. It is functional and behaves as expected.</p> <p>I pass some basic types to the <code>Serialize()</code> function and then deserialize the output to get back the original value.</p> <pre><code>size_t returnSize(const char* s) { string string(s); return string.size(); }; template&lt;typename T&gt; size_t returnSize(const T&amp; t) { return sizeof(t); }; template&lt;typename T&gt; string Serialize(const T&amp; t) { T* pt = new T(t); vector&lt;char&gt; CasttoChar; for (int i =0 ;i&lt;returnSize(t);i++) { CasttoChar.push_back(reinterpret_cast&lt;const char*&gt;(pt)[i]); } delete pt; return string( CasttoChar.begin(), CasttoChar.end() ); }; template&lt;&gt; string Serialize&lt;string&gt;(const string&amp; t) { return Serialize(t.c_str()); }; template&lt;typename T&gt; T DeSerialize(const string&amp; cstr) { const T* a = reinterpret_cast&lt;const T*&gt;(cstr.c_str()); return *a; } template&lt;&gt; string DeSerialize&lt;string&gt;(const string&amp; cstr) { return DeSerialize&lt;char*&gt;(cstr); } int _tmain(int argc, _TCHAR* argv[]) { int x = 97; string c = Serialize&lt;int&gt;(x); cout &lt;&lt; DeSerialize&lt;int&gt;(c) &lt;&lt; endl; char g = 'g'; string c2 = Serialize&lt;char&gt;(g); cout &lt;&lt; DeSerialize&lt;char&gt;(c2) &lt;&lt; endl; string k = "blabla"; string c3 = Serialize&lt;const char*&gt;(k.c_str()); cout &lt;&lt; DeSerialize&lt;char*&gt;(c3) &lt;&lt; endl; string ka = "string"; string c4 = Serialize&lt;string&gt;(ka); cout &lt;&lt; (DeSerialize&lt;string&gt;(c4)).c_str(); system("PAUSE"); return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T08:33:28.297", "Id": "32775", "Score": "0", "body": "You're duplicating a string on the heap only to take its size?" } ]
[ { "body": "<p>First of all, fundamentally: <code>std::string</code> is a data type to hold <em>text</em>. Exclusively. It should <strong>not</strong> be used to hold binary data. Use a <code>std::vector&lt;(unsigned) char&gt;</code> for that.</p>\n\n<p>Secondly, you are using heap allocation without needing to:</p>\n\n<pre><code>T* pt = new T(t);\n</code></pre>\n\n<p>This makes no sense at all, and introduces the potential of a memory leak. You could simply make a copy – but you don’t even need to do that. Just work on the original data.</p>\n\n<p>Next, about naming; it’s general convention in C++ to use underscore_separated_names rather than camelCase or PascalCase. This is only a convention but I’d follow it unless there’s a very compelling reason not to.</p>\n\n<p>Also on the topic of naming: <code>returnSize</code> is redundant, <code>return</code> has no place in the name. Rename it to <code>object_size</code> or something along those lines. You are also inconsistent in your naming convention here.</p>\n\n<p>To get the size of a zero-terminated string, use <code>std::strlen</code>, that’s more efficient than converting to a <code>std::string</code>.</p>\n\n<p>Finally, the code simply doesn’t work. It creates a bit-by-bit shallow representation. That only works for simple composite objects, it no longer works for objects that use pointers or references internally – you’ve already noticed that, because otherwise you wouldn’t need to create a special chase for <code>char*</code> and <code>std::string</code>. Incidentally, for the case of <code>char*</code> you specialise <code>returnSize</code> but for the case of <code>std::string</code> you specialise <code>Serialize</code> and <code>DeSerialize</code>. That’s asymmetrical and means that you have several places that might require changing when new types are added. You should reduce this to a single point which requires specialisation.</p>\n\n<p>Ignoring that, I’d rewrite the code as follows:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\ntypedef unsigned char byte_t;\ntypedef std::vector&lt;byte_t&gt; buffer;\n\nstd::size_t object_size(const char* s) {\n return std::strlen(s);\n};\n\ntemplate&lt;typename T&gt;\nstd::size_t object_size(T const&amp; obj) {\n return sizeof(obj);\n};\n\ntemplate&lt;typename T&gt;\nbuffer serialize(const T&amp; obj) {\n std::size_t size = object_size(obj);\n buffer buf(size);\n\n byte_t const* obj_begin = reinterpret_cast&lt;byte_t const*&gt;(&amp;obj);\n std::copy(obj_begin, obj_begin + size, buf.begin());\n\n return buf;\n};\n\ntemplate&lt;&gt;\nbuffer serialize&lt;std::string&gt;(std::string const&amp; str) {\n return serialize(str.c_str());\n};\n\ntemplate&lt;typename T&gt;\nT deserialize(buffer const&amp; buf) {\n return *reinterpret_cast&lt;const T*&gt;(&amp;buf[0]);\n}\n\ntemplate&lt;&gt;\nstd::string deserialize&lt;std::string&gt;(buffer const&amp; buf) {\n return deserialize&lt;char*&gt;(buf);\n}\n\nint main() {\n using std::cout;\n\n int x = 97;\n buffer c = serialize(x);\n cout &lt;&lt; deserialize&lt;int&gt;(c) &lt;&lt; \"\\n\";\n\n char g = 'g';\n buffer c2 = serialize(g);\n cout &lt;&lt; deserialize&lt;char&gt;(c2) &lt;&lt; \"\\n\";\n\n std::string k = \"blabla\";\n buffer c3 = serialize(k.c_str());\n cout &lt;&lt; deserialize&lt;char*&gt;(c3) &lt;&lt; \"\\n\";\n\n std::string ka = \"string\";\n buffer c4 = serialize(ka);\n cout &lt;&lt; deserialize&lt;std::string&gt;(c4) &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>… but like I said, this solution doesn’t generalise and is pretty useless in practice. Have a look at <a href=\"http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html\">Boost.Serialization</a> for a proper implementation. Unfortunately this is quite a complex problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T19:48:06.683", "Id": "32816", "Score": "4", "body": "Sorry dont agree with this: `It’s general convention in C++ to use underscore_separated_names`. I tend to see more C++ code that is camel case. But I also see lots with '_'. Personal I prefer camel case (which is why I also tend to see it more). But you should generally follow the conventions of your current employer (or project)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T19:59:47.223", "Id": "32817", "Score": "0", "body": "@Loki for local variables? Ugh. But in general I think one should follow the practice established by the standard library of the respective language, otherwise you *will* have to mix styles. I’d go as far as claiming that underscore-separated will *always* be the only generally agreed-on convention in C++ because as soon as that’s no longer the case people are obviously no longer using the standard library pervasively in their code and the resulting code won’t be idiomatic C++. It may be better (or whatever) but it’s no longer idiomatic C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:18:45.977", "Id": "32819", "Score": "0", "body": "@konrad thank you for this detailed answer, unfortunately I can't use boost serialization since its not a header only library. As for your comment regarding this solution cannot be generalized to serialize objects that contain pointers or references, I agree I wanted to serialize basic types only and each class (to be serialized) will implement its own toString() function that will use the above serialize methods to serialize the basic types of that class. I know it's not cleanest but do I have an alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:21:48.623", "Id": "32820", "Score": "0", "body": "@Kam Hmm. I don’t think that “not header only” is a compelling argument, to be honest. Similarly, “cannot use Boost” has **no** place in C++ nowadays. It’s akin to saying “I cannot use the standard library”. To paraphrase Stroustrup: doing anything in C++ without a library is hard. Use libraries. They’re your friends." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:28:47.600", "Id": "32821", "Score": "0", "body": "@konrad, it's a solution I am trying to develop for the company I work for, and they restrict the use of external binaries :$" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:37:00.597", "Id": "32822", "Score": "0", "body": "@konrad knowing this would you have any other advice for me? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T21:52:35.497", "Id": "32826", "Score": "0", "body": "@Kam Ah that sucks. Some companies have serious technical deficiencies like that (I’ve worked on a project with the same problem, I’m since then allergic to this kind of stupidity). Unfortunately I don’t know any other serialisation library for C++. The fundamental approach on display here works though. Doing serialisation “right” is very complex (again, see Boost.Serialization). With the constraint of keeping it simple, this is probably the best you can get." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T14:05:23.787", "Id": "20490", "ParentId": "20474", "Score": "8" } }, { "body": "<p>I'll expand on the portability aspect that wasn't quite explained in the other answer:</p>\n\n<p>Be aware that <code>_tmain()</code>, <code>_TCHAR</code>, and <code>system(\"PAUSE\")</code> are specific to Windows environments, <a href=\"https://stackoverflow.com/a/895894/1950231\">while the first two are also Microsoft extensions that are <em>not</em> considered standard C++</a>.</p>\n\n<p>This can be fixed by changing</p>\n\n<ul>\n<li><code>_tmain()</code> to <code>main()</code></li>\n<li><code>_TCHAR</code> to <code>char</code></li>\n<li><p><code>system(\"PAUSE\")</code> to something like <code>std::cin.get()</code></p>\n\n<p>However, if you can get your IDE to pause automatically, then you won't need your own.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T01:10:11.323", "Id": "59066", "ParentId": "20474", "Score": "2" } } ]
{ "AcceptedAnswerId": "20490", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T01:24:02.557", "Id": "20474", "Score": "6", "Tags": [ "c++", "strings", "serialization" ], "Title": "std::vector memory manipulation with serialization and deserialization" }
20474
<p>I am new to web apps and I am having a difficult time structuring my apps. I put together a very simple math web app which I wish to expand on. The app has the following pages/screens:</p> <ul> <li>Home screen</li> <li>About screen</li> <li>Math question screen</li> <li>Answer check screen</li> <li>Results screen.</li> </ul> <p>Right now the app works fine and is probably structured fine since it is very basic but I wish to expand on it in the future and want a solid foundation to build from. How can I improve the structure? I have researched this and it seems my best bet is to divide each screen into a separate folder (home folder - home.html, home.css, home.js... about folder...) then load the pages into a main page shell?</p> <p>My code is below and on JS Bin: <a href="http://jsbin.com/ilukop/1/edit" rel="nofollow">http://jsbin.com/ilukop/1/edit</a></p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;title&gt;App-to-Convert&lt;/title&gt; &lt;script type="text/javascript"&gt; var field1 = 0; //field1 and field2 are the values being added together var field2 = 0; var question_num = 0; //question_num counts up to 10 //The showPanel function displays the panel with the given id function showPanel(id) { //Check if 10 questions have been answered, then redirect to the "Done" screen if ((id=="question") &amp;&amp; (question_num==10)) id="done"; var panels = new Array("welcome","question","correct","incorrect","about","done"); //Loop through and show the requested panel while hiding all of the others for (var i=0; i&lt;panels.length; i++) { document.getElementById(panels[i]).style.display = (id==panels[i]) ? "block" : "none"; } if (id=="welcome") { //Welcome screen resets the question number question_num = 0; } else if (id=="question") { //Increment the question number ++question_num; //Create two random numbers field1 = Math.floor(Math.random() * 11); field2 = Math.floor(Math.random() * 11); //Show the two numbers on the screen document.getElementById("field1").innerHTML = field1; document.getElementById("field2").innerHTML = field2; //Clear the answer field and set the input focus var ans = document.getElementById("answer"); ans.value = ""; ans.focus(); } } //The checkAnswer function compares the input to field1+field2 and shows correct or incorrect feedback function checkAnswer() { //Get the input var ans = document.getElementById("answer").value; //Show the "correct" panel if the input equals field1+field2, otherwise show "incorrect" showPanel((ans==(field1+field2)) ? "correct" : "incorrect"); } &lt;/script&gt; &lt;style type="text/css"&gt; #math_quiz { /* main container */ position: relative; width: 550px; height: 400px; font-family: 'Times New Roman', Times, serif; font-size: 24px; text-align: center; color: #121212; } #math_quiz p { margin-left: 40px; margin-right: 40px; } #math_quiz .field { /* the two numbers to be added */ position: absolute; width: 75px; height: 27px; font-weight: bold; text-align: right; } #math_quiz .panel { /* each panel is 550x400 */ position: absolute; left: 0px; top: 0px; width: 550px; height: 400px; display: none; } #math_quiz a { /* gold buttons with black borders */ position: absolute; background-color: #FF9900; border: solid 5px #000000; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 15px 10px 15px; display: block; } #math_quiz #plus_sign { /* static "+" sign */ position:absolute; left:25px; top:127px; font-size:34px; font-weight:bold; } #math_quiz #horz_line { /* horizontal line above the answer */ position:absolute; left:17px; top:167px; width:295px; height:5px; background-color:#000000; } #math_quiz #answer { /* input field */ position:absolute; left:75px; top:182px; width:175px; height:32px; font-family:'Times New Roman', Times, serif; color:#121212; font-size:24px; font-weight:bold; text-align:right; border:solid 1px #000000; padding-right:5px; } &lt;/style&gt; &lt;/head&gt; &lt;body bgcolor="#FFFFFF"&gt; &lt;div id="math_quiz"&gt; &lt;div id="welcome" class="panel" style="display:block"&gt; &lt;h3&gt;Math App&lt;/h3&gt; &lt;a style="left:21px;top:267px;" href="#" onClick="showPanel('question');return false;"&gt;Play Button&lt;/a&gt; &lt;a style="left:225px;top:268px;" href="#" onClick="showPanel('about');return false;"&gt;About Button&lt;/a&gt; &lt;/div&gt; &lt;div id="question" class="panel"&gt; &lt;div id="field1" class="field" style="left:170px;top:102px;"&gt;&lt;/div&gt; &lt;div id="field2" class="field" style="left:170px;top:132px;"&gt;&lt;/div&gt; &lt;div id="plus_sign"&gt;+&lt;/div&gt; &lt;div id="horz_line"&gt;&lt;/div&gt; &lt;input id="answer"/&gt; &lt;a style="left:182px;top:277px;" href="#" onClick="checkAnswer();return false;"&gt;OK Button&lt;/a&gt; &lt;/div&gt; &lt;div id="correct" class="panel"&gt; &lt;h3&gt;Correct!&lt;/h3&gt; &lt;a style="left:210px;top:216px;" href="#" onClick="showPanel('question');return false;"&gt;OK Button&lt;/a&gt; &lt;/div&gt; &lt;div id="incorrect" class="panel"&gt; &lt;h3&gt;Incorrect!&lt;/h3&gt; &lt;a style="left:210px;top:216px;" href="#" onClick="showPanel('question');return false;"&gt;OK Button&lt;/a&gt; &lt;/div&gt; &lt;div id="about" class="panel"&gt; &lt;p&gt;About text would go here.&lt;/p&gt; &lt;a style="left:180px;top:277px;" href="#" onClick="showPanel('welcome');return false;"&gt;OK Button&lt;/a&gt; &lt;/div&gt; &lt;div id="done" class="panel"&gt; &lt;h3&gt;You're done. You answered 10 questions.&lt;/h3&gt; &lt;a style="left:180px;top:277px;" href="#" onClick="showPanel('welcome');return false;"&gt;OK Button&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>If you organize the app into several pages/folders, then response will be slower, passing values around more complicated, and you will have several scripts instead of one to manage. So I would not do this until it becomes really too big to manage in a single page. Remember one of the key advantages of javascript is to get an immediate response to user actions instead of having to wait for a new page to load each time. Splitting it into separate pages would allow you to have a stable link to a particular screen (currently you can only link to the 'welcome' screen of your app), but that can also be implemented using javascript in a single page. If your app becomes an AJAX one, with server-side code as well as HTML/javascript, then separate pages might make more sense.</p>\n\n<p>Without knowing how you intend to develop the app it is difficult to give specific advice, but usually it makes sense to organize the script into classes and objects rather than just functions. You could have an object <code>panel</code> for instance, capable of storing state internally and with appropriate methods.</p>\n\n<p>Most developers also prefer setting event handlers within the script rather than in the HTML, as it is easier to see how things work and you can change event handlers if needed. \nThe following is an example of how you might reorganize it (untested)</p>\n\n<pre><code>function Panel(id) {\n var el = document.getElementById(id), self = this;\n this.show = function() { \n el.style.display = 'block';\n if (self.run) self.run();\n };\n this.hide = function() { el.style.display = 'none' };\n // can be extended\n}\nfunction Panels(ids) {\n var objs = {},\n questionNum = 0, \n field1 = 0, \n field2 = 0;\n for (var i = 0, id; id = ids[i]; i++) {\n objs[id] = new Panel(id);\n this[id] = getFunction(show, id);\n }\n // needed for reasons of variable scope:\n function getFunction(f, p) {return function() {f(p)}}\n function show(showId) {\n for (var i = 0, id; id = ids[i]; i++) {\n objs[id][id == showId ? 'show' : 'hide']();\n }\n }\n // You could add methods here that extend particular panels\n objs.welcome.run = function() {\n questionNum = 0;\n };\n objs.question.run = function() {\n ++ questionNum;\n // etc. Put all the logic for the question panel here\n };\n}\npanels = new Panels([\"welcome\",\"question\",\"correct\",\"incorrect\",\"about\",\"done\"]);\n// set event handlers here, e.g.\ndocument.getElementById('playButton').onclick = panels.question; \n\n...\n&lt;a id=\"playButton\"&gt;Play Button&lt;/a&gt;\n...\n</code></pre>\n\n<p>Given that you have lots of repetition in your HTML, it will probably also be better to build the panel display in javascript rather than only using the javascript to display/hide elements that are already in the page. (And note that this would be difficult to achieve if you split the app across several pages.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T03:43:15.027", "Id": "20500", "ParentId": "20475", "Score": "1" } } ]
{ "AcceptedAnswerId": "20500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T01:24:52.337", "Id": "20475", "Score": "3", "Tags": [ "javascript", "css", "html5" ], "Title": "Structuring Simple HTML5 / CSS3 / JavaScript Math Web App" }
20475
<p>I am curious to know if there is a faster, better, and more efficient way to accomplish this program that acquires employee information:</p> <pre><code> &lt;?php session_start(); //require 'functions.php'; //require 'DB.php'; $employeeID = $_SESSION['employeeID']; $clockIn = $_GET['clockIn']; $clockOut = $_GET['clockOut']; $timeToday = date("g:i a"); $dateToday = date("m/d/y"); $jobDescription = $_GET['jobDesc']; $equipType = $_GET['equipTypeRan']; $unitNumber = $_GET['unitNumber']; $unitHours = $_GET['unitHours']; if (isset($clockIn)) { echo "You clocked in at: " . $timeToday . " on " . $dateToday; try { $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)'); $stmt-&gt;execute(array(':employeeID' =&gt; $_SESSION['employeeID'], ':dateToday' =&gt; $dateToday, ':timeIn' =&gt; $timeToday)); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } $conn = null; } else if (isset($clockOut)) { try { $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID'); $stmt-&gt;execute(array(':employeeID' =&gt; $_SESSION['employeeID'],':dateToday' =&gt; $dateToday, ':timeOut' =&gt; $timeToday)); $stmt = $conn-&gt;prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID'); $stmt-&gt;execute(array(':employeeID' =&gt; $_SESSION['employeeID'], ':dateToday' =&gt; $dateToday)); $stmt-&gt;setFetchMode(PDO::FETCH_BOTH); $results = $stmt-&gt;fetch(); $timeInDB = $results[0]; } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } $time_one = new DateTime($timeInDB); $time_two = new DateTime($timeToday); $difference = $time_one-&gt;diff($time_two); echo "You clocked in at: " . $timeInDB . "&lt;br&gt;"; echo "You clocked out at: " . $timeToday . "&lt;br&gt;"; echo $difference-&gt;format('Total working time %h hours %i minutes'); }else { try{ $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare("SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday"); $stmt-&gt;execute(array(':employeeID' =&gt; $employeeID, ':dateToday' =&gt; $dateToday)); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } if($stmt-&gt;fetchColumn() &gt; 0){ try{ $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours, `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL'); $stmt-&gt;execute(array(':employeeID' =&gt; $employeeID, ':timeOut' =&gt; $timeToday, ':dateToday' =&gt; $dateToday, ':jobDescription' =&gt; $jobDescription, ':equipType' =&gt; $equipType, ':unitNumber' =&gt; $unitNumber, ':unitHours' =&gt; $unitHours)); $stmt = $conn-&gt;prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)'); $stmt -&gt;execute(array(':employeeID' =&gt; $employeeID, ':dateToday'=&gt; $dateToday, ':timeIn' =&gt; $timeToday)); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } echo "There was an update"; } else { echo "There was no Match"; } require 'summary.php'; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T17:56:12.260", "Id": "32812", "Score": "4", "body": "Why make the db connection so many times? Why not only once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T07:59:29.347", "Id": "32971", "Score": "2", "body": "I guess there is not much to improve performance-wise (not in a noticeable order). However there's a lot of code duplication in there which could be reduced." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T14:53:06.043", "Id": "72565", "Score": "1", "body": "setting `PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION` will do exactly the same as wrapping your code in try catch. you can verify by removing them all together, a wrong query will still echo the same messages you echo in your catch part, but without the need of writing all those extra lines." } ]
[ { "body": "<p>Defining the same connection multiple times can be avoided, and also, putting everything in <code>try/catch</code> serves no purpose if the only thing you do in the catch is displaying the message which would be displayed anyway with the error reporting mode you set on the <code>$conn</code></p>\n\n<p>I also find that naming PDOStatements can help a bit for readability, instead of always using <code>$stmt</code>. Here it all happens in few lines, but sometimes, using a prepared statement far away in the code can be easier if they have significant names.</p>\n\n<p>Doing this, I noticed your <code>clockIn</code> PDOStatement is done twice. Since the <code>if</code> prevents it from happening twice, it's OK, but perhaps you could find some use in preparing your PDOStatements outside of loops, then executing them in the loops.</p>\n\n<pre><code>&lt;?php\n\nsession_start();\n//require 'functions.php';\n//require 'DB.php';\n$employeeID = $_SESSION['employeeID'];\n$clockIn = $_GET['clockIn'];\n$clockOut = $_GET['clockOut'];\n$timeToday = date(\"g:i a\");\n$dateToday = date(\"m/d/y\");\n$jobDescription = $_GET['jobDesc'];\n$equipType = $_GET['equipTypeRan'];\n$unitNumber = $_GET['unitNumber'];\n$unitHours = $_GET['unitHours'];\n\n$conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');\n$conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$putClockIn = $conn-&gt;prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');\n\nif (isset($clockIn)) {\n echo \"You clocked in at: \" . $timeToday . \" on \" . $dateToday;\n $putClockIn-&gt;execute(array(\n ':employeeID' =&gt; $_SESSION['employeeID'],\n ':dateToday' =&gt; $dateToday,\n ':timeIn' =&gt; $timeToday\n ));\n $conn = null;\n} else {\n if (isset($clockOut)) {\n $putClockOut = $conn-&gt;prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID');\n $putClockOut-&gt;execute(array(\n ':employeeID' =&gt; $_SESSION['employeeID'],\n ':dateToday' =&gt; $dateToday,\n ':timeOut' =&gt; $timeToday\n ));\n $getTimeIn = $conn-&gt;prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID');\n $getTimeIn-&gt;execute(array(':employeeID' =&gt; $_SESSION['employeeID'], ':dateToday' =&gt; $dateToday));\n //$getTimeIn-&gt;setFetchMode(PDO::FETCH_BOTH);\n $results = $getTimeIn-&gt;fetch(PDO::FETCH_BOTH); // no need to set a mode for stmt if you ain't using it anywhere else, pass it directly in fetch()\n $timeInDB = $results[0];\n $time_one = new DateTime($timeInDB);\n $time_two = new DateTime($timeToday);\n $difference = $time_one-&gt;diff($time_two);\n echo \"You clocked in at: \" . $timeInDB . \"&lt;br&gt;\";\n echo \"You clocked out at: \" . $timeToday . \"&lt;br&gt;\";\n echo $difference-&gt;format('Total working time %h hours %i minutes');\n } else {\n $getCurrentSessions = $conn-&gt;prepare(\"SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday\");\n $getCurrentSessions-&gt;execute(array(':employeeID' =&gt; $employeeID, ':dateToday' =&gt; $dateToday));\n if ($getCurrentSessions-&gt;fetchColumn() &gt; 0) {\n $closeSession = $conn-&gt;prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours, \n `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL');\n $closeSession-&gt;execute(array(\n ':employeeID' =&gt; $employeeID,\n ':timeOut' =&gt; $timeToday,\n ':dateToday' =&gt; $dateToday,\n ':jobDescription' =&gt; $jobDescription,\n ':equipType' =&gt; $equipType,\n ':unitNumber' =&gt; $unitNumber,\n ':unitHours' =&gt; $unitHours\n ));\n $putClockIn-&gt;execute(array(\n ':employeeID' =&gt; $employeeID,\n ':dateToday' =&gt; $dateToday,\n ':timeIn' =&gt; $timeToday\n ));\n echo \"There was an update\";\n } else {\n echo \"There was no Match\";\n }\n }\n}\n\nrequire 'summary.php';\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:55:21.453", "Id": "42815", "ParentId": "20476", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T04:13:30.887", "Id": "20476", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "Acquiring employee information" }
20476
<p>I'm particularly concerned about where I have declared the functions, can I move them around to clean up the code without breaking anything? The "conjugate" function contains a lot of stuff that has nothing to do with actually conjugating verbs and rather handles output strings and html DOM objects. I really want to minimalize/optimize that function so it only does the essential and have the other DOM stuff handled by a more appropriate function but I'm scared to break anything lol</p> <p>Also my use of multiple global variables, is there a better way to do that?</p> <p>Sorry for the incredibly noobish question but I have kinda rushed through this to get my ideas down as quick as possible and it's suddenly become a bit overwhelming :/</p> <p>Thanks in advance for any help!</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="./jquery.js"&gt;&lt;/script&gt; &lt;style&gt; .answer { list-style-type: none; cursor: pointer; font-family: fontin; } #base, .answer { padding:10px 15px; background-color: #B7BECC; overflow: auto; margin: 20px 1px; border: 1px solid; font-size: 18.7pt; text-align: center; display:inline; } #base { border-radius: 10px; } .answers{ margin-top:30px; } #container{ margin: 21px auto; position: relative; width: 100%; max-width: 1000px; text-align: center; min-width: 600px; } &lt;/style&gt; &lt;script&gt; $(function () { var video = $("#video").get(0); var baseverbs = ["작다", "놀다", "닦다"]; var questionnum = 0; var correct = ""; //set mouseover colors $(".answer").each(function () { $(this).mouseover(function () { var bg = $(this).css("background-color"); if (bg == "rgb(183, 190, 204)" || bg == "#b7becc") { $(this).css("background-color", "#E5E8EE") } }).mouseout(function () { var bg = $(this).css("background-color"); if (bg == "rgb(229, 232, 238)" || bg == "#e5e8ee") { $(this).css("background-color", "#B7BECC") } }) }); function seperate(x) { x = x.charCodeAt(); var y = {}; var z = {}; y["tail"] = (x - 44032) % 28; y["vowel"] = 1 + ((x - 44032 - y["tail"]) % 588 / 28); y["lead"] = 1 + (parseInt((x - 44032) / 588)); z["vowel"] = vowels[y["vowel"]]; z["tail"] = tails[y["tail"]]; z["lead"] = leads[y["lead"]]; return z; } var vowels = "0ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ".split(""); var leads = "0ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ".split(""); var tails = "0ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈ".split(""); function buildhangeul(x) { var tail = tails.indexOf(x["tail"]); var vowel = vowels.indexOf(x["vowel"]); var lead = leads.indexOf(x["lead"]); var codepoint = tail + (vowel - 1) * 28 + (lead - 1) * 588 + 44032; return String.fromCharCode(codepoint); } function pausehere(time) { video.addEventListener('timeupdate', function (e) { if (this.currentTime &gt;= time &amp;&amp; this.currentTime &lt; (time + 0.3)) { this.pause() } }, true); }; function conjugate(baseverbs) { var baseverb = baseverbs[questionnum]; $("#base").text(baseverb); $(".answer").css("background-color", "#B7BECC"); var output = {}; output.incorrect = []; var tstr = baseverb; var each = tstr.split(""); if (each[each.length - 1] == "다") { var stemlast = each[each.length - 2]; var lastjamo = seperate(stemlast); //ㅂ irregular if (lastjamo["tail"] == "ㅂ") { lastjamo["tail"] = "0"; stemlast = buildhangeul(lastjamo); output.correct = each.slice(0, -2).join("") + stemlast + "워"; output.incorrect[0] = each.slice(0, -1).join("") + buildhangeul({ "lead": "ㅇ", "vowel": lastjamo["vowel"], "tail": "0" }); output.incorrect[1] = each.slice(0, -1).join("") + "워"; output.incorrect[2] = each.slice(0, -2).join("") + stemlast + "와"; } //ㅏ and ㅗ regular else if (lastjamo["vowel"] == "ㅏ" &amp;&amp; lastjamo["tail"] != "0" || lastjamo["vowel"] == "ㅗ" &amp;&amp; lastjamo["tail"] != "0") { output.correct = stemlast + "아"; output.incorrect[0] = buildhangeul({ "lead": lastjamo["lead"], "vowel": lastjamo["vowel"], "tail": "0" }) + buildhangeul({ "lead": lastjamo["tail"], "vowel": lastjamo["vowel"], "tail": "0" }); output.incorrect[1] = stemlast + "ㅏ"; output.incorrect[2] = stemlast; } //ㅓ, ㅜ, and ㅣ regular else if (lastjamo["vowel"] == "ㅓ" &amp;&amp; lastjamo["tail"] != "0" || lastjamo["vowel"] == "ㅜ" &amp;&amp; lastjamo["tail"] != "0" || lastjamo["vowel"] == "ㅣ" &amp;&amp; lastjamo["tail"] != "0") { output.correct = stemlast + "어"; } //ㅏ and ㅓ reductive else if (lastjamo["vowel"] == "ㅏ" &amp;&amp; lastjamo["tail"] == "0" || lastjamo["vowel"] == "ㅓ" &amp;&amp; lastjamo["tail"] == "0") { output.correct = stemlast; output.incorrect[0] = stemlast + buildhangeul({ "lead": "ㅇ", "vowel": lastjamo["vowel"], "tail": "0" }); output.incorrect[1] = buildhangeul({ "lead": lastjamo["lead"], "vowel": "ㅐ", "tail": "0" }); output.incorrect[2] = baseverb; } //ㅗ and ㅜ reductive else if (lastjamo["vowel"] == "ㅗ" &amp;&amp; lastjamo["tail"] == "0") { lastjamo["vowel"] = "ㅘ"; output.correct = buildhangeul(lastjamo); output.incorrect[0] = stemlast + "와"; output.incorrect[1] = stemlast + "아"; output.incorrect[2] = buildhangeul({ "lead": lastjamo["lead"], "vowel": "ㅝ", "tail": "0" }); } else if (lastjamo["vowel"] == "ㅜ" &amp;&amp; lastjamo["tail"] == "0") { lastjamo["vowel"] = "ㅝ"; output.correct = buildhangeul(lastjamo); output.incorrect[0] = stemlast + buildhangeul({ "lead": "ㅇ", "vowel": "ㅝ", "tail": "0" }); output.incorrect[1] = buildhangeul({ "lead": lastjamo["lead"], "vowel": "ㅜ", "tail": "0" }) + buildhangeul({ "lead": "ㅇ", "vowel": "ㅓ", "tail": "0" }); output.incorrect[2] = buildhangeul({ "lead": lastjamo["lead"], "vowel": "ㅘ", "tail": "0" }); } //ㅣreductive else if (lastjamo["vowel"] == "ㅣ" &amp;&amp; lastjamo["tail"] == "0") { lastjamo["vowel"] = "ㅕ"; output.correct = each.slice(0, -2).join("") + buildhangeul(lastjamo); } //르 irregular else if (stemlast == "르") { var secondlastjamo = seperate(each[each.length - 3]); secondlastjamo["tail"] = "ㄹ"; if (secondlastjamo["vowel"] == "ㅗ") { stemlast = "라" } else if (secondlastjamo["vowel"] == "ㅜ") { stemlast = "러" }; var secondlast = buildhangeul(secondlastjamo); output.correct = each.slice(0, -3).join("") + secondlast + stemlast; }; } else { alert("Only Korean verbs in dictionary form please ;)") } $("#wrong0").text(output.incorrect[0]); $("#wrong1").text(output.incorrect[1]); $("#wrong2").text(output.incorrect[2]); $("#correct").text(output.correct); correct = output.correct; random($(".answers")); $(".answer").css("border-radius", "0px"); $('.answer').first().css('border-radius', '10px 0px 0px 10px'); $('.answer').last().css('border-radius', '0px 10px 10px 0px'); } $('.answer').click(function () { if (video.currentTime &lt;= 160){$("#warning").text("Not yet!").fadeIn(300).delay(1400).fadeOut(300);return} if ($(this).text() === correct) { //if correct //skip to congratulations $(this).css("background-color", "#62F05F"); questionnum++; if (questionnum === 1) { video.currentTime = 164.2; video.play(); pausehere(166.8); }else if(questionnum === 2){ video.currentTime = 167.1; video.play(); pausehere(170); }else if(questionnum === 3){ video.currentTime = 171.7; video.play(); } //if incorrect } else { //skip to try again msg $(this).css("background-color", "red"); video.currentTime = 160.5; video.play(); pausehere(164); } alert(questionnum); if (questionnum &gt;= 3){return;}; setTimeout(conjugate(baseverbs), 300); }); $("#reset").click(function () { video.currentTime = 0; videostart() }); function videostart() { video.play(); //pause after tutorial pausehere(159); } var random = function (r) { r.children().sort(function (a, b) { return Math.floor(Math.random() * 3) - 1; }).appendTo(r); }; videostart(); conjugate(baseverbs); }) &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="videowrapper"&gt; &lt;video id="video" no-controls&gt; &lt;source src="conjugation tut.mp4" type="video/mp4"&gt; &lt;source src="play.ogg" type='video/ogg'&gt; &lt;source src="play.webm" type="video/webm"&gt;Your browser does not support the video tag.&lt;/video&gt; &lt;br /&gt; &lt;button id="reset"&gt;Replay&lt;/button&gt; &lt;/div&gt; &lt;br /&gt; &lt;div id="base"&gt;&lt;/div&gt; &lt;ul class="answers"&gt; &lt;li class="answer" id="wrong0"&gt;&lt;/li&gt; &lt;li class="answer" id="wrong1"&gt;&lt;/li&gt; &lt;li class="answer" id="wrong2"&gt;&lt;/li&gt; &lt;li class="answer" id="correct"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;br /&gt;&lt;br /&gt;&lt;br&gt; &lt;div id="warning"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I didn't really have a chance to really take this apart but your first foreach loop binding the mouseover events can actually be written like in this jsfiddle <a href=\"http://jsfiddle.net/KSzFy/\" rel=\"nofollow\">http://jsfiddle.net/KSzFy/</a></p>\n\n<p>When you call a event binding function on a jquery array it will apply the event to all items in the jquery array.</p>\n\n<p>As far as dealing with global functions and variables, its best to wrap all of them in a javascript object and then bind that object to the window. That way you are still keeping the potential for naming collisions to a minimum but you are also creating ad-hoc name spaces for yourself.</p>\n\n<pre><code> window.pageSpaceName = {\n publicVariable : 'value',\n publicFunction : function(){alert('I do something')}\n}\n</code></pre>\n\n<p>Also since all JS objects are really just hashes, jquery has a handy function called extend that will combine objects together for you allowing you to 'import' separate pieces of your js namespace together.</p>\n\n<p>Assume we have a top level javascript object with functions that are required across the entire site.</p>\n\n<pre><code>(function(){\n $.extend(true, siteNameSpace, {pageSpaceName : {\n publicVariable : 'value',\n publicFunction : function(){alert('I do something')}\n }});\n}).call(this);\n</code></pre>\n\n<p>then on your page you can access your variables and functions like so</p>\n\n<pre><code>window.siteNameSpace.pageSpaceName.publicFunction();\n</code></pre>\n\n<p>If you have all of your objects in self executing blocks and are using extend like in the example importing the namespaces will be as simple as including the script file on the page. </p>\n\n<p>I generally create a 'global' namespace object and include it in the base page of the site so every child page will already have that base object created for it.</p>\n\n<pre><code>window.siteNameSpace = {};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T05:49:36.970", "Id": "33601", "Score": "0", "body": "the signature of $.extend is $.extend(isDeepCopy,target,source)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T15:21:43.130", "Id": "33671", "Score": "1", "body": "So just to state it explicitly - the namespacing technique actually creates more global variables than the OP's function which creates zero while namespacing creates at least one. This is still very useful for code organization but it IS more globals and should be avoided if you don't need it (for example if you don't need to share code). One gotcha that I've seen people run into with this is when they have global utility functions that call other global utility functions in the same namespace - you can't rely on `this` I recommend writing it in module pattern style: http://goo.gl/5Ubyj" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T05:48:23.603", "Id": "20971", "ParentId": "20495", "Score": "3" } } ]
{ "AcceptedAnswerId": "20971", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T16:17:03.650", "Id": "20495", "Score": "4", "Tags": [ "javascript", "jquery", "html", "html5" ], "Title": "This blueprint has already become a mess, please suggest some restructuring" }
20495
<p>I want to remove my goto's in this code but I'm not sure how. There must be a cleaner way to write my code. Perhaps move the "if" statement to the end of each loop then use break?</p> <p>Sorry if this is a stupid question, I'm self-taught, and I'm finishing up my first sizable program. Any suggestions as to how I can clean my code is welcomed, even though it isn't stated in my question.</p> <p>Also this is just my beta release, so please forgive all the sillyness.</p> <pre><code> public void BtnRandomizeClick(object sender, EventArgs e) { Nowthatitssaved: //Goto marker -- Loops the saved/not saved stuff based on file dialog switch (MessageBox.Show(@"Did you SAVE your edited list?", @"Just checking... It's important.", MessageBoxButtons.YesNo)) { #region Dialog Yes case DialogResult.Yes: if (FileChosen == null) { MessageBox.Show( @"Please select a file to load before trying to randomize. You need some entries to randomize first eh?", "Oh fiddlesticks..."); return; } dataGridAssociates.Rows.Clear(); var masterList = new List&lt;Associate&gt;(); var divertsList = new List&lt;Associate&gt;(); var mheList = new List&lt;Associate&gt;(); var loadingList = new List&lt;Associate&gt;(); var lines = File.ReadAllLines(FileChosen); //Array of all the lines in the text file foreach (var assocStringer in lines) { if (assocStringer == null) continue; var entries = assocStringer.Split('|'); var obj = (Associate) _bindingSource.AddNew(); if (obj == null) continue; if (entries.Length &lt; 7) break; obj.FirstName = entries[0]; obj.LastName = entries[1]; obj.AssocId = entries[2]; obj.AssocRfid = entries[3]; obj.CanDoDiverts = Boolean.Parse(entries[4]); obj.CanDoMhe = Boolean.Parse(entries[5]); obj.CanDoLoading = Boolean.Parse(entries[6]); obj.UniqueRandomID = Guid.NewGuid().ToString(); masterList.Add(obj); } var sortedMaster = masterList.OrderBy(d =&gt; d.UniqueRandomID).ToList(); var loaderCountRequested = 0; var mheCountRequested = 0; var divertCountRequested = 0; var validDivertEntry = int.TryParse(txtDivertWorkers.Text, out divertCountRequested); var validMHEEntry = int.TryParse(txtMHEWorkers.Text, out mheCountRequested); var validLoaderEntry = int.TryParse(txtLoadersNeeded.Text, out loaderCountRequested); //See if whomever used the inputs correctly if (validDivertEntry == false) { MessageBox.Show(@"Please use an integer in the 'Divert Workers' textbox and try again"); return; } if (validMHEEntry == false) { MessageBox.Show(@"Please use an integer in the 'MHE Workers' textbox and try again"); return; } if (validLoaderEntry == false) { MessageBox.Show(@"Please use an integer in the 'Loaders' textbox and try again"); return; } var canDoDivertsQuery = sortedMaster.Where(a =&gt; a.CanDoDiverts); var canDoMHEQuery = sortedMaster.Where(b =&gt; b.CanDoMhe); var canDoLoadingQuery = sortedMaster.Where(c =&gt; c.CanDoLoading); var loaders = 0; var mhes = 0; var diverters = 0; //Begin the sorting method foreach (Associate someAssocVar in canDoLoadingQuery) { if (loaders == loaderCountRequested) goto MHEKTHX; loadingList.Add(someAssocVar); loaders++; listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + " " + loadingList[loaders - 1].LastName); } MHEKTHX: sortedMaster.RemoveAll(loadingList.Contains); foreach (Associate someAssocVar in canDoMHEQuery) { if (mhes == mheCountRequested) goto DivertsKTHX; mheList.Add(someAssocVar); mhes++; listBoxMHE.Items.Add(mheList[mhes - 1].FirstName + " " + mheList[mhes - 1].LastName); } DivertsKTHX: sortedMaster.RemoveAll(mheList.Contains); foreach (Associate someAssocVar in canDoDivertsQuery) { if (diverters == divertCountRequested) goto DoneKTHX; divertsList.Add(someAssocVar); diverters++; listBoxDiverts.Items.Add(divertsList[diverters - 1].FirstName + " " + divertsList[diverters - 1].LastName); } DoneKTHX: sortedMaster.RemoveAll(divertsList.Contains); MessageBox.Show(@"You have " + sortedMaster.Count() + @" associates unassigned."); break; #endregion #region Dialog No case DialogResult.No: if (MessageBox.Show(@"Would you like to save your work then?", @"It really does matter...", MessageBoxButtons.YesNo) == DialogResult.Yes) { var saveDialog = new SaveFileDialog { InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments), // ReSharper disable LocalizableElement Filter = "Text (*.txt)|*.txt|All Files (*.*)|*.*", // ReSharper restore LocalizableElement FilterIndex = 1 }; if (saveDialog.ShowDialog() == DialogResult.OK) { FileChosen = saveDialog.FileName; var assocToText = DatagridToString(dataGridAssociates, '|'); using (var outfile = new StreamWriter(saveDialog.FileName)) outfile.Write(assocToText); } goto Nowthatitssaved; } break; #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T21:41:13.317", "Id": "32825", "Score": "2", "body": "In this particular case, when labels are directly after the loops, each of the `goto`s can be replaced by a regular `break` from the `foreach` loop. I'm not posting this as an answer 'cause IMHO it does not really cover the topic fully (the code could probably use some refactoring/rewrite) and I can't really do much more from the phone ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T22:57:10.887", "Id": "32829", "Score": "1", "body": "Dude, your conditions seem to be independent of the loop variables, so you can have 4 if statements. After that you can have 4 different methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T04:32:25.150", "Id": "32843", "Score": "0", "body": "You will get a lot of feedback. I think you accepted an answer too soon. Reminding the user to save a list is a bad idea. You should either auto-save it or disable the Randomize button. Then use an assertion if you must." } ]
[ { "body": "<p>As a first pass here is what I got. It is nowhere close to what it should be, but it is a start. If you gave more code, I could perfect it further but right now I do not know where the variables are coming from. </p>\n\n<pre><code>public void Sort()\n{\n //Begin the sorting method\n if (loaders != loaderCountRequested) \n {\n foreach (Associate someAssocVar in canDoLoadingQuery)\n {\n loadingList.Add(someAssocVar);\n loaders++;\n listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + \n \" \" + loadingList[loaders - 1].LastName);\n\n }\n }\n\n sortedMaster.RemoveAll(loadingList.Contains);\n if (mhes != mheCountRequested)\n {\n foreach (Associate someAssocVar in canDoMHEQuery)\n { \n mheList.Add(someAssocVar);\n mhes++;\n listBoxMHE.Items.Add(mheList[mhes - 1].FirstName + \n \" \" + mheList[mhes - 1].LastName);\n }\n }\n\n sortedMaster.RemoveAll(mheList.Contains);\n if (diverters != divertCountRequested)\n {\n foreach (Associate someAssocVar in canDoDivertsQuery)\n {\n divertsList.Add(someAssocVar);\n diverters++;\n listBoxDiverts.Items.Add(divertsList[diverters - 1].FirstName + \n \" \" + divertsList[diverters - 1].LastName);\n }\n }\n\n sortedMaster.RemoveAll(divertsList.Contains);\n MessageBox.Show(@\"You have \" + sortedMaster.Count() + @\" associates unassigned.\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T02:38:49.930", "Id": "32840", "Score": "0", "body": "I added the rest of my code from the button click. Hope that helps? This is a really messy/hacky almost embarassing code, but it's the first sizable program I've written as I've mentioned before. Haven't taken any programming classes or anything so go easy on me haha. My whole program is ~630 lines, I'm guessing it could be condensed down to <200 easy. I just don't understand much yet aside from using loops and gotos. I came from Pascal into C#. Big difference..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T23:04:22.607", "Id": "20498", "ParentId": "20497", "Score": "1" } }, { "body": "<p>Here's another stab at something. Mainly I think I see a bunch of duplicated code in your lists, so what about something along the lines of</p>\n\n<pre><code>private IList&lt;Associate&gt; GetAssociates(IEnumerable&lt;Associate&gt; query, int loadFrom, int maxItems)\n{\n var numberRequested = maxItems - loadFrom;\n return query.Take(numberRequested).ToList();\n}\n\nprivate void LoadAssociatesInto(ListBox container, IEnumerable&lt;Associate&gt; associates)\n{\n container.Items.AddRange(associates.Select(p =&gt; string.format(\"{0} {1}\", p.FirstName, p.LastName)).ToArray&lt;object&gt;());\n}\n\n// ... and your main code\nvar associates = GetAssociates(canDoLoadingQuery, loaders, loaderCountRequested);\nLoadAssociatesInto(listBoxLoaders, associates);\nsortedMaster.RemoveAll(associates);\n\n// similiar code for canDoMHEQuery and canDoDivertsQuery\n\n// finally\nMessageBox.Show(@\"You have \" + sortedMaster.Count() + @\" associates unassigned.\");\n</code></pre>\n\n<p>The 3 lines for doing each of these could also be moved into a method as well so further refactoring would reduce the core code down to 4 lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T01:07:34.600", "Id": "32834", "Score": "0", "body": "This is cool! Might be hard for a noob to swallow ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T02:28:03.367", "Id": "32838", "Score": "0", "body": "@dreza This is very cool, but yeah I'm having a hard time taking it in... I'm new to c#, and extremely new to using LINQ (just read about it on Friday). Using methods like you mentioned, how would that look ultimately? How would I call the method? I think using methods is something I'm missing from my whole program..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T02:40:39.880", "Id": "32841", "Score": "0", "body": "Specifically I don't understand using IList<> and IEnumerable<>, also don't understand creating my own methods very well... Only method I've created has been my DatagridView to String method used in saving my datagrid to a text file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T05:57:11.033", "Id": "32844", "Score": "0", "body": "@JesterBaze I agree with Leonid that you should probably let your question mature for a bit. By accepting my answer to soon you are less likely to get feedback. So, to get a more variety of help perhaps un-accept mine and see what other ideas/comments you get :) I'll update my answer soon as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:57:13.917", "Id": "32927", "Score": "0", "body": "@dreza why are you using `TakeWhile(p => loadFrom++ < maxItems)` instead of `Take(maxItems - loadFrom)` ? This avoids having your LINQ Query rely on a side effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T19:09:42.783", "Id": "32932", "Score": "0", "body": "@Brian true, I could use .Take(maxItems - loadFrom). Just hadn't thought about that. What would be a side effect of TakeWhile?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T21:29:43.230", "Id": "32957", "Score": "0", "body": "@dreza: The side effect is that you are modifying loadFrom. In this specific instance, the side effect is localized, so nothing will break. However, it is still frowned upon; I strongly recommend avoiding side effects in your LINQ code if at all possible. This includes increment/decrement, assignments, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T22:04:31.510", "Id": "32959", "Score": "0", "body": "@Brian yep, nice. adjusted accordingly" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T01:01:34.957", "Id": "20499", "ParentId": "20497", "Score": "2" } }, { "body": "<p>I didnt check carefully but really 3 (at least) were because you didnt realize, know or remember break isn't only used in switch statements. The other one is really something suggesting if it should loop again or not.</p>\n\n<p>You should run your code and my code <a href=\"http://www.quickdiff.com/\" rel=\"nofollow\">in a diff tool</a> to easily see the few lines that changed.</p>\n\n<pre><code>public void BtnRandomizeClick(object sender, EventArgs e)\n{\n var DoAgain=true;\n while(DoAgain){\n DoAgain=false;\n switch (MessageBox.Show(@\"Did you SAVE your edited list?\", @\"Just checking... It's important.\",\n MessageBoxButtons.YesNo))\n {\n #region Dialog Yes\n\n case DialogResult.Yes:\n if (FileChosen == null)\n {\n MessageBox.Show(\n @\"Please select a file to load before trying to randomize. You need some entries to randomize first eh?\",\n \"Oh fiddlesticks...\");\n return;\n }\n dataGridAssociates.Rows.Clear();\n var masterList = new List&lt;Associate&gt;();\n var divertsList = new List&lt;Associate&gt;();\n var mheList = new List&lt;Associate&gt;();\n var loadingList = new List&lt;Associate&gt;();\n var lines = File.ReadAllLines(FileChosen); //Array of all the lines in the text file\n\n foreach (var assocStringer in lines)\n {\n if (assocStringer == null) continue;\n var entries = assocStringer.Split('|');\n var obj = (Associate) _bindingSource.AddNew();\n if (obj == null) continue;\n if (entries.Length &lt; 7) break;\n obj.FirstName = entries[0];\n obj.LastName = entries[1];\n obj.AssocId = entries[2];\n obj.AssocRfid = entries[3];\n obj.CanDoDiverts = Boolean.Parse(entries[4]);\n obj.CanDoMhe = Boolean.Parse(entries[5]);\n obj.CanDoLoading = Boolean.Parse(entries[6]);\n obj.UniqueRandomID = Guid.NewGuid().ToString();\n masterList.Add(obj);\n }\n var sortedMaster = masterList.OrderBy(d =&gt; d.UniqueRandomID).ToList();\n var loaderCountRequested = 0;\n var mheCountRequested = 0;\n var divertCountRequested = 0;\n var validDivertEntry = int.TryParse(txtDivertWorkers.Text, out divertCountRequested);\n var validMHEEntry = int.TryParse(txtMHEWorkers.Text, out mheCountRequested);\n var validLoaderEntry = int.TryParse(txtLoadersNeeded.Text, out loaderCountRequested);\n\n //See if whomever used the inputs correctly\n if (validDivertEntry == false)\n {\n MessageBox.Show(@\"Please use an integer in the 'Divert Workers' textbox and try again\");\n return;\n }\n if (validMHEEntry == false)\n {\n MessageBox.Show(@\"Please use an integer in the 'MHE Workers' textbox and try again\");\n return;\n }\n if (validLoaderEntry == false)\n {\n MessageBox.Show(@\"Please use an integer in the 'Loaders' textbox and try again\");\n return;\n }\n\n var canDoDivertsQuery = sortedMaster.Where(a =&gt; a.CanDoDiverts);\n var canDoMHEQuery = sortedMaster.Where(b =&gt; b.CanDoMhe);\n var canDoLoadingQuery = sortedMaster.Where(c =&gt; c.CanDoLoading);\n var loaders = 0;\n var mhes = 0;\n var diverters = 0;\n\n //Begin the sorting method\n foreach (Associate someAssocVar in canDoLoadingQuery)\n {\n if (loaders == loaderCountRequested)\n break;\n loadingList.Add(someAssocVar);\n loaders++;\n listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + \" \" +\n loadingList[loaders - 1].LastName);\n\n }\n sortedMaster.RemoveAll(loadingList.Contains);\n\n foreach (Associate someAssocVar in canDoMHEQuery)\n {\n if (mhes == mheCountRequested)\n break;\n mheList.Add(someAssocVar);\n mhes++;\n listBoxMHE.Items.Add(mheList[mhes - 1].FirstName + \" \" +\n mheList[mhes - 1].LastName);\n }\n\n sortedMaster.RemoveAll(mheList.Contains);\n\n foreach (Associate someAssocVar in canDoDivertsQuery)\n {\n if (diverters == divertCountRequested)\n break;\n divertsList.Add(someAssocVar);\n diverters++;\n listBoxDiverts.Items.Add(divertsList[diverters - 1].FirstName + \" \" +\n divertsList[diverters - 1].LastName);\n }\n\n sortedMaster.RemoveAll(divertsList.Contains);\n\n MessageBox.Show(@\"You have \" + sortedMaster.Count() + @\" associates unassigned.\");\n break;\n #endregion\n\n #region Dialog No\n\n case DialogResult.No:\n if (MessageBox.Show(@\"Would you like to save your work then?\", @\"It really does matter...\",\n MessageBoxButtons.YesNo) == DialogResult.Yes)\n {\n var saveDialog = new SaveFileDialog\n {\n InitialDirectory =\n Convert.ToString(Environment.SpecialFolder.MyDocuments),\n // ReSharper disable LocalizableElement\n Filter = \"Text (*.txt)|*.txt|All Files (*.*)|*.*\",\n // ReSharper restore LocalizableElement\n FilterIndex = 1\n };\n if (saveDialog.ShowDialog() == DialogResult.OK)\n {\n FileChosen = saveDialog.FileName;\n var assocToText = DatagridToString(dataGridAssociates, '|');\n using (var outfile = new StreamWriter(saveDialog.FileName))\n outfile.Write(assocToText);\n }\n DoAgain=true;\n }\n break;\n\n #endregion\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T21:58:28.990", "Id": "32872", "Score": "0", "body": "Not bad! However I'm thinking that I can reduce it further from that if I can figure out how to make my own Methods, but thats a cool solution, thankyou!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T04:33:59.663", "Id": "20501", "ParentId": "20497", "Score": "1" } }, { "body": "<p>Another tip. You can write code like this which will make it easier to move chucks into functions. </p>\n\n<pre><code>{\n int heyGuessWhatICanDeclThisAgainLater=1;\n blah blah blah\n if (blah != blahblahblah)\n {\n blah\n }\n}\n{\n bool heyGuessWhatICanDeclThisAgainLater= true;//not even the same type\n //but confusing if a dif type. But good for single letter loop vars/temps\n //like foreach(var v in list) { ...\n if (blah == blahblahblah || blu blu blah)\n {\n blah\n }\n}\n</code></pre>\n\n<p>Also you shouldnt create so many variables (or reuse any vars. assign once is a good idea). You should just write</p>\n\n<pre><code>foreach (Associate someAssocVar in sortedMaster.Where(a =&gt; a.CanDoDiverts))\n</code></pre>\n\n<p>Its confusing to see code declare variables one place and used WAYYYY LATER.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T00:08:10.683", "Id": "20525", "ParentId": "20497", "Score": "1" } }, { "body": "<p>Here's a variety of refactorings. I didn't start off intending to change the code this much, but I figure I might as well post it now...</p>\n\n<p>You say \"I think using methods is something I'm missing from my whole program...\", and I agree. Extracting out code into methods is the single best thing you can do to improve this. You will make your code more structured and easier to understand, and be able to remove any redundancies.</p>\n\n<p>Now some individual items:</p>\n\n<ul>\n<li><p>Firstly, the Random ID on the Associate class appears to only be needed to shuffle the list. It is not an intrinsic part of the Associate, so it doesn't belong there. Remove it and shuffle the list directly.</p></li>\n<li><p>One thing that often helps is to always declare your variables as late as possible. This tends to reveal the structure of your code better. Let's do that with the sorting part of the code:</p>\n\n<pre><code>var loadingList = new List&lt;Associate&gt;();\nvar canDoLoadingQuery = masterList.Where(c =&gt; c.CanDoLoading);\nvar loaders = 0;\nforeach (Associate someAssocVar in canDoLoadingQuery)\n{\n if (loaders == loaderCountRequested)\n break;\n loadingList.Add(someAssocVar);\n loaders++;\n listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + \" \" +\n loadingList[loaders - 1].LastName);\n\n}\nmasterList.RemoveAll(loadingList.Contains);\n\n// one removed to save space\n\nvar divertsList = new List&lt;Associate&gt;();\nvar canDoDivertsQuery = masterList.Where(a =&gt; a.CanDoDiverts);\nvar diverters = 0;\nforeach (Associate someAssocVar in canDoDivertsQuery)\n{\n if (diverters == divertCountRequested)\n break;\n divertsList.Add(someAssocVar);\n diverters++;\n listBoxDiverts.Items.Add(divertsList[diverters - 1].FirstName + \" \" +\n divertsList[diverters - 1].LastName);\n}\nmasterList.RemoveAll(divertsList.Contains);\n</code></pre></li>\n</ul>\n\n<p>Notice that they all have the same structure. This should indicate to you that this is common code that can be shared. Let's extract one instance into a method:</p>\n\n<pre><code>private List&lt;Associate&gt; AssignLoaders(List&lt;Associate&gt; masterList, int loaderCountRequested)\n{\n var loadingList = new List&lt;Associate&gt;();\n var canDoLoadingQuery = masterList.Where(c =&gt; c.CanDoLoading);\n var loaders = 0;\n foreach (Associate someAssocVar in canDoLoadingQuery)\n {\n if (loaders == loaderCountRequested)\n break;\n loadingList.Add(someAssocVar);\n loaders++;\n listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + \" \" +\n loadingList[loaders - 1].LastName);\n }\n return loadingList;\n}\n</code></pre>\n\n<p>This is called like so:</p>\n\n<pre><code>var loadingList = AssignLoaders(masterList, loaderCountRequested);\nmasterList.RemoveAll(loadingList.Contains);\n</code></pre>\n\n<p>Now how can we make this more generic so that we can share it with the other two uses? We need to be able to pass in the condition. With LINQ we can use a <code>Func&lt;Associate, bool&gt;</code> - that is, a function which takes an associate and returns a bool. You already have some of these in your code (the <code>c =&gt; c.CanDoLoading</code> in the <code>Where</code> calls).</p>\n\n<p>Let's make the condition a parameter:</p>\n\n<pre><code>private List&lt;Associate&gt; AssignLoaders(List&lt;Associate&gt; masterList, Func&lt;Associate, bool&gt; filter, int loaderCountRequested)\n{\n var loadingList = new List&lt;Associate&gt;();\n var canDoLoadingQuery = masterList.Where(filter);\n var loaders = 0;\n foreach (Associate someAssocVar in canDoLoadingQuery)\n {\n if (loaders == loaderCountRequested)\n break;\n loadingList.Add(someAssocVar);\n loaders++;\n listBoxLoaders.Items.Add(loadingList[loaders - 1].FirstName + \" \" +\n loadingList[loaders - 1].LastName);\n }\n return loadingList;\n}\n</code></pre>\n\n<p>This is called like this:</p>\n\n<pre><code>var loadingList = AssignLoaders(masterList, c =&gt; c.CanDoLoading, loaderCountRequested);\n</code></pre>\n\n<p>Now the <code>AssignLoaders</code> knows almost nothing about whether it is looking for loaders, so we can use it for the other types as well. Let's rename the variables to indicate that, then tidy it up (with a little LINQ) and make it able to assign to any destination listbox:</p>\n\n<pre><code>private List&lt;Associate&gt; AssignAssociates(IEnumerable&lt;Associate&gt; associates, Func&lt;Associate, bool&gt; filter, int numberRequested, ListBox destination)\n{\n var assignedAssociates = new List&lt;Associate&gt;();\n assignedAssociates.AddRange(associates.Where(filter).Take(numberRequested));\n foreach (var associate in assignedAssociates)\n {\n destination.Items.Add(associate.FirstName + \" \" + associate.LastName);\n }\n return assignedAssociates;\n}\n</code></pre>\n\n<p>The listbox stuff doesn't really fit right here, it looks a bit ugly. Let's split it into two separate methods:</p>\n\n<pre><code>private void AddAssociatesToListBox(List&lt;Associate&gt; associates, ListBox listBox)\n{\n foreach (var associate in associates)\n {\n listBox.Items.Add(associate.FirstName + \" \" + associate.LastName);\n }\n}\n\nprivate List&lt;Associate&gt; AssignAssociates(IEnumerable&lt;Associate&gt; associates, Func&lt;Associate, bool&gt; filter, int numberRequested)\n{\n return associates.Where(filter).Take(numberRequested).ToList();\n}\n</code></pre>\n\n<p>Now the sorting code looks like:</p>\n\n<pre><code>var loadingList = AssignAssociates(masterList, c =&gt; c.CanDoLoading, loaderCountRequested);\nAddAssociatesToListBox(loadingList, listBoxLoaders);\nmasterList.RemoveAll(loadingList.Contains);\n\n// one skipped to save space\n\nvar divertsList = AssignAssociates(masterList, c =&gt; c.CanDoDiverts, divertCountRequested);\nAddAssociatesToListBox(divertsList, listBoxDiverts);\nmasterList.RemoveAll(divertsList.Contains);\n</code></pre>\n\n<p>Additionally, if you give the Associate class a <code>ToString</code> override then <code>AddAssociatesToListBox</code> becomes irrelevant (delete it!) and you can just write:</p>\n\n<pre><code>var divertsList = AssignAssociates(masterList, c =&gt; c.CanDoDiverts, divertCountRequested);\nlistBoxDiverts.DataSource = divertsList;\nmasterList.RemoveAll(divertsList.Contains);\n</code></pre>\n\n<ul>\n<li><p>We can do a similar refactoring to this previous one with the validation code:</p>\n\n<pre><code>int loaderCountRequested;\nif (!CountIsValid(txtLoadersNeeded, \"Loaders\", out loaderCountRequested)) return;\n</code></pre></li>\n</ul>\n\n<p>And the extracted method:</p>\n\n<pre><code>private bool CountIsValid(TextBox textBox, string textBoxName, out int countRequested)\n{\n var validEntry = int.TryParse(textBox.Text, out countRequested);\n if (validEntry == false)\n {\n MessageBox.Show(string.Format(@\"Please use an integer in the '{0}' textbox and try again.\", textBoxName));\n }\n return validEntry;\n}\n</code></pre>\n\n<p>I'd actually recommend you look at using one of the built-in validation mechanisms, but I'm not very well versed in Windows Forms. Maybe someone can point the way in a comment.</p>\n\n<ul>\n<li>For your main method, I don't think you need to reload the file each time. It makes sense to randomize what is currently in the data grid. As long as you don't clear it your user won't lose any data.</li>\n</ul>\n\n<p>This actually means that your complicated <code>goto</code> logic simply disappears as it is not needed. (You will see this in the code I post below.)</p>\n\n<ul>\n<li><p>Separate out the loading and saving code. This makes it a bit cleaner and easier to see what is going on, and allows us to do other things more easily, like:</p></li>\n<li><p>Track the state of the data. By checking if the user has modified the data, you can be smarter about asking them when to save their changes. This can be done by attaching to an event on the grid. I've called the variable that tracks this <code>_unsavedChanges</code>. It is also reset when the user loads or saves data.</p></li>\n</ul>\n\n<p>Here are my modifications in toto. I've guessed at the implementation of <code>DatagridToString</code> but it seems to work:</p>\n\n<pre><code>public partial class Main : Form\n{\n public Main()\n {\n InitializeComponent();\n\n _unsavedChanges = false;\n }\n\n private string _currentFile;\n</code></pre>\n\n<p>First, the randomization method and its minions:</p>\n\n<pre><code> void BtnRandomizeClick(object sender, EventArgs e)\n {\n if (_currentFile == null)\n {\n MessageBox.Show(@\"Please select a file to load before trying to randomize. You need some entries to randomize first eh?\",\n \"Oh fiddlesticks...\");\n return;\n }\n\n // Get a list of all associates\n var masterList = _bindingSource.OfType&lt;Associate&gt;().ToList();\n masterList.Shuffle(new Random());\n\n //See if whomever used the inputs correctly\n int divertCountRequested;\n if (!CountIsValid(txtDivertWorkers, \"Divert Workers\", out divertCountRequested)) return;\n\n int mheCountRequested;\n if (!CountIsValid(txtMHEWorkers, \"MHE Workers\", out mheCountRequested)) return;\n\n int loaderCountRequested;\n if (!CountIsValid(txtLoadersNeeded, \"Loaders\", out loaderCountRequested)) return;\n\n //Begin the sorting method\n var loadingList = AssignAssociates(masterList, c =&gt; c.CanDoLoading, loaderCountRequested);\n listBoxLoaders.DataSource = loadingList;\n masterList.RemoveAll(loadingList.Contains);\n\n var mheList = AssignAssociates(masterList, c =&gt; c.CanDoMhe, mheCountRequested);\n listBoxMHE.DataSource = mheList;\n masterList.RemoveAll(loadingList.Contains);\n\n var divertsList = AssignAssociates(masterList, c =&gt; c.CanDoDiverts, divertCountRequested);\n listBoxDiverts.DataSource = divertsList;\n masterList.RemoveAll(divertsList.Contains);\n\n MessageBox.Show(@\"You have \" + masterList.Count() + @\" associates unassigned.\");\n }\n\n private bool CountIsValid(TextBox textBox, string textBoxName, out int countRequested)\n {\n var validEntry = int.TryParse(textBox.Text, out countRequested);\n if (validEntry == false)\n {\n MessageBox.Show(string.Format(@\"Please use an integer in the '{0}' textbox and try again.\", textBoxName));\n }\n return validEntry;\n }\n\n private List&lt;Associate&gt; AssignAssociates(IEnumerable&lt;Associate&gt; associates, Func&lt;Associate, bool&gt; filter, int numberRequested)\n {\n return associates.Where(filter).Take(numberRequested).ToList();\n }\n</code></pre>\n\n<p>Now, code that loads and saves the files:</p>\n\n<pre><code> private bool _unsavedChanges;\n\n private bool CheckForUnsavedChanges()\n {\n if (_unsavedChanges)\n {\n if (MessageBox.Show(@\"Would you like to SAVE your edited list?\", @\"Save your changes?\", MessageBoxButtons.YesNo) == DialogResult.Yes)\n {\n if (!PromptToSaveFile())\n return false; // the user cancelled\n }\n }\n\n return true;\n }\n\n private void LoadFile(string filename)\n {\n _bindingSource.Clear(); // remove any old entries\n\n var lines = File.ReadAllLines(filename); //Array of all the lines in the text file\n foreach (var assocStringer in lines)\n {\n if (assocStringer == null) continue;\n var entries = assocStringer.Split('|');\n var obj = (Associate) _bindingSource.AddNew();\n if (obj == null) continue;\n if (entries.Length &lt; 7) break;\n obj.FirstName = entries[0];\n obj.LastName = entries[1];\n obj.AssocId = entries[2];\n obj.AssocRfid = entries[3];\n obj.CanDoDiverts = Boolean.Parse(entries[4]);\n obj.CanDoMhe = Boolean.Parse(entries[5]);\n obj.CanDoLoading = Boolean.Parse(entries[6]);\n }\n _unsavedChanges = false;\n }\n\n string DatagridToString(DataGridView dataGrid, char joiner)\n {\n var join = joiner.ToString();\n var sb = new StringBuilder();\n foreach (DataGridViewRow row in dataGrid.Rows)\n {\n var cells = row.Cells.Cast&lt;DataGridViewCell&gt;();\n if (cells.Any(cell =&gt; cell.Value == null)) // for now, skip any lines with null cells\n continue;\n\n sb.AppendLine(string.Join(join, cells.Select(cell =&gt; cell.Value))); // concatenate the cells\n }\n return sb.ToString();\n }\n\n bool PromptToOpenFile()\n {\n var openDialog = new OpenFileDialog()\n {\n InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments),\n Filter = @\"Text (*.txt)|*.txt|All Files (*.*)|*.*\",\n FilterIndex = 1\n };\n\n if (openDialog.ShowDialog() == DialogResult.OK)\n {\n _currentFile = openDialog.FileName;\n LoadFile(_currentFile);\n return true;\n }\n\n return false;\n }\n\n bool PromptToSaveFile()\n {\n var saveDialog = new SaveFileDialog\n {\n InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments),\n Filter = @\"Text (*.txt)|*.txt|All Files (*.*)|*.*\",\n FilterIndex = 1,\n CheckFileExists = true,\n };\n\n if (saveDialog.ShowDialog() == DialogResult.OK)\n {\n _currentFile = saveDialog.FileName;\n SaveFile(_currentFile);\n return true;\n }\n\n return false;\n }\n\n void SaveFile(string filename)\n {\n var assocToText = DatagridToString(dataGridAssociates, '|');\n using (var outfile = new StreamWriter(filename))\n outfile.Write(assocToText);\n\n _unsavedChanges = false;\n }\n</code></pre>\n\n<p>And finally the events. You should be able to figure out what they do by their names. (There are two more buttons, Save and Load.)</p>\n\n<pre><code> private void btnSave_Click(object sender, EventArgs e)\n {\n PromptToSaveFile();\n }\n\n private void btnLoad_Click(object sender, EventArgs e)\n {\n if (!CheckForUnsavedChanges())\n return;\n\n PromptToOpenFile();\n }\n\n private void dataGridAssociates_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n {\n _unsavedChanges = true;\n }\n}\n</code></pre>\n\n<p>I've uploaded my whole project <a href=\"http://porg.es/CR20497.zip\" rel=\"nofollow\">here</a>. It should be runnable as-is. It contains the shuffle method, my Associate object, and the form.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T21:29:41.453", "Id": "32956", "Score": "0", "body": "Holy crap you are truly amazing. I can't thank you enough for such a thorough answer! This is perfect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T22:55:49.130", "Id": "32964", "Score": "1", "body": "@Porges: I prefer to avoid creating a new instance of `Random` on each call to `BtnRandomizeClick` . While it is unlikely that the user will manage to create two instances of `Random` with the same seed (i.e., by running `BtnRandomizeClick` twice within the same tick), it still strikes me as bad practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T05:11:38.633", "Id": "32969", "Score": "0", "body": "@Brian: Yes, I'd normally stash that somewhere. (The main thing I was trying to show is that the Shuffle method shouldn't create the Random instance itself or a duplicate seed is much more likely to occur in normal usage.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:54:05.920", "Id": "20538", "ParentId": "20497", "Score": "1" } } ]
{ "AcceptedAnswerId": "20538", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T21:20:40.933", "Id": "20497", "Score": "3", "Tags": [ "c#", "beginner", "csv", "gui" ], "Title": "Prompting a user to save and regenerate some entries in a file" }
20497
<p>I've discovered that using hashed passwords with salts is a much better idea than MD5/SHA256, so I'm not hashing them with PBKDF2. However, I'm wondering if this is a correct approach to authorizing my user. I also have logic for logging authorizations. When the same IP has entered an incorrect login/pass, it becomes banned for 5 minutes.</p> <ul> <li>Administrator <code>a</code> is passing <code>Username</code> and <code>Password</code>.</li> <li>Checking if <code>Username</code> exists.</li> <li>Checking if the password is correct for this user.</li> </ul> <pre><code>[HttpPost] [ValidateAntiForgeryToken] public ActionResult Authorize(Administrator a) { // Check if there are no failed login attempts in last 5 minutes if (!this.CanAdminLogin) { TempData["loginTooManyAttempts"] = true; return RedirectToAction("index", "home"); } // If model is not validated return login view to show error messages (javascript disabled) if (!TryValidateModel(a)) { return View("Authorize", a); } // Check if username exists, if not then log and show that login failed var admin = _db.Administrators.Where(x =&gt; x.Username == a.Username).SingleOrDefault(); if (admin == null || admin.Username != a.Username) { this.LogAuthorization(a, false); TempData["loginFailed"] = true; return RedirectToAction("index", "home"); } // Username exists, check if passwords match ICryptoService cryptoService = new PBKDF2(); string hash = cryptoService.Compute(a.Password, admin.PasswordSalt); if (hash == admin.Password) { this.LogAuthorization(a, true); Session["adminId"] = admin.ID; } else { this.LogAuthorization(a, false); TempData["loginFailed"] = true; } // Login successfull return RedirectToAction("index", "home"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T03:47:46.320", "Id": "88931", "Score": "0", "body": "I think code like `_db.Administrators.Where(...)` should be put in a repository to aid Unit Testing." } ]
[ { "body": "<p>I really think that you should merge all of these if statements, make them an if/elseif/else statement. just move all the variable declarations to the top.</p>\n\n<p>then it turns into this</p>\n\n<pre><code>[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Authorize(Administrator a)\n{\n var admin = _db.Administrators.Where(x =&gt; x.Username == a.Username).SingleOrDefault();\n ICryptoService cryptoService = new PBKDF2();\n string hash = cryptoService.Compute(a.Password, admin.PasswordSalt);\n if (!this.CanAdminLogin) // Check if there are no failed login attempts in last 5 minutes\n {\n TempData[\"loginTooManyAttempts\"] = true;\n return RedirectToAction(\"index\", \"home\");\n }\n else if (!TryValidateModel(a)) // If model is not validated return login view to show error messages (javascript disabled)\n {\n return View(\"Authorize\", a);\n }\n else if (admin == null || admin.Username != a.Username) // Check if username exists, if not then log and show that login failed\n {\n this.LogAuthorization(a, false);\n TempData[\"loginFailed\"] = true;\n return RedirectToAction(\"index\", \"home\");\n }\n else if (hash == admin.Password) // Username exists, check if passwords match\n {\n this.LogAuthorization(a, true);\n Session[\"adminId\"] = admin.ID;\n }\n else\n {\n this.LogAuthorization(a, false);\n TempData[\"loginFailed\"] = true;\n }\n\n // Login successfull\n return RedirectToAction(\"index\", \"home\");\n}\n</code></pre>\n\n<p>I also moved the comments to the end of the line that they attach to. Keep in mind that some of these comments are not needed at all.</p>\n\n<p>The Comments that are needed here</p>\n\n<pre><code>// Check if there are no failed login attempts in last 5 minutes\n</code></pre>\n\n<p>This is only needed because otherwise I wouldn't have known why the Admin couldn't log in or that there was an instance that would change this boolean.</p>\n\n<pre><code>// If model is not validated return login view to show error messages (javascript disabled)\n</code></pre>\n\n<p>I can tell from the code what is going on, but I am not sure what <code>(javascript disabled)</code> has to do with this code? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-16T16:34:45.837", "Id": "87105", "ParentId": "20507", "Score": "3" } } ]
{ "AcceptedAnswerId": "87105", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T13:54:30.683", "Id": "20507", "Score": "6", "Tags": [ "c#", "logging", "asp.net-mvc-4", "authorization" ], "Title": "PBKDF2 authorization" }
20507
<p>I have following code for doing custom paging from an asp.net web application. </p> <p><strong>Points of interest</strong></p> <ol> <li>It uses Link Buttons as suggested in <a href="https://stackoverflow.com/questions/14335067/passing-search-parameters-to-same-page-when-hyperlink-clicked">https://stackoverflow.com/questions/14335067/passing-search-parameters-to-same-page-when-hyperlink-clicked</a></li> <li>The link buttons are added in Page_Load itself as listed in <a href="https://stackoverflow.com/questions/14364332/dynamic-controls-event-handlers-working">https://stackoverflow.com/questions/14364332/dynamic-controls-event-handlers-working</a></li> <li>It is made as user control for reuse</li> </ol> <p><strong>QUESTIONS</strong></p> <ol> <li>Is there any pitfalls in this approach?</li> <li>Is there any improvement suggestions?</li> </ol> <p><strong>User Control Markup</strong></p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PagingUserControl.ascx.cs" Inherits="PagingTestWebApplication.PagingUserControl" %&gt; &lt;div class="pagingSection" id="pagingSection" runat="server"&gt; &lt;asp:LinkButton ID="lnkPrevious" runat="server" CssClass='page-numbers prev' Visible="false" OnClick="LinkButton_Click"&gt;Prev&lt;/asp:LinkButton&gt; &lt;asp:LinkButton ID="lnkFirst" runat="server" CssClass='page-numbers' Visible="false" OnClick="LinkButton_Click"&gt;1&lt;/asp:LinkButton&gt; &lt;asp:Label runat="server" ID="lblFirstDots" CssClass="page-numbers prev" Visible="false" Text="..."&gt;&lt;/asp:Label&gt; &lt;asp:PlaceHolder ID="plhDynamicLink" runat="server"&gt;&lt;/asp:PlaceHolder&gt; &lt;asp:Label runat="server" ID="lblSecondDots" Visible="false" CssClass="page-numbers prev" Text="..."&gt;&lt;/asp:Label&gt; &lt;asp:LinkButton ID="lnkLast" runat="server" CssClass='page-numbers' Visible="false" OnClick="LinkButton_Click"&gt;Last&lt;/asp:LinkButton&gt; &lt;asp:LinkButton ID="lnkNext" runat="server" CssClass='page-numbers next' Visible="false" OnClick="LinkButton_Click"&gt;Next&lt;/asp:LinkButton&gt; &lt;/div&gt; </code></pre> <p><strong>User Control Code Behind</strong></p> <pre><code>public partial class PagingUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public int PreviousIndex { get; set; } public int CurrentClickedIndex { get; set; } public event EventHandler PaginationLinkClicked; protected void LinkButton_Click(object sender, EventArgs e) { //Assumption: Text of the LinkButton will be same as index LinkButton clickedLinkButton = (LinkButton)sender; if (String.Equals(clickedLinkButton.Text, "Next")) { //Next Page index will be one greater than current //Note: If the current index is the last page, "Next" control will be in disabled state CurrentClickedIndex = PreviousIndex + 1; } else if (String.Equals(clickedLinkButton.Text, "Prev")) { //Previous Page index will be one less than current //Note: If the current index is the first page, "Prev" control will be in disabled state CurrentClickedIndex = PreviousIndex - 1; } else { CurrentClickedIndex = Convert.ToInt32(clickedLinkButton.Text, CultureInfo.InvariantCulture); } //Raise event if (this.PaginationLinkClicked != null) { this.PaginationLinkClicked(clickedLinkButton, e); } } public void PreAddAllLinks(int tableDataCount,int pageSize, int currentIndex) { if (tableDataCount &gt; 0) { PagingInfo info = PagingHelper.GetAllLinks(tableDataCount, pageSize, currentIndex); //Remove all controls from the placeholder plhDynamicLink.Controls.Clear(); if (info.PaginationLinks != null) { foreach (LinkButton link in info.PaginationLinks) { //Adding Event handler must be done inside Page_Laod /Page_Init link.Click += new EventHandler(LinkButton_Click); //Validation controls should be executed before link click. link.ValidationGroup = "Search"; this.plhDynamicLink.Controls.Add(link); } } } } public void AddPageLinks(int tableDataCount, int pageSize, int index) { if (tableDataCount &gt; 0) { pagingSection.Visible = true; PagingInfo info = PagingHelper.GetPageLinks(tableDataCount, pageSize, index); //Remove all controls from the placeholder plhDynamicLink.Controls.Clear(); if (info.PaginationLinks != null) { lnkPrevious.Visible = info.PaginationLinks.Count &gt; 0 ? true : false; lnkNext.Visible = info.PaginationLinks.Count &gt; 0 ? true : false; foreach (LinkButton link in info.PaginationLinks) { //Validation controls should be executed before link click. link.ValidationGroup = "Search"; this.plhDynamicLink.Controls.Add(link); } } //Dots visiblity if (info.IsEndDotsVisible != null) { lblSecondDots.Visible = Convert.ToBoolean(info.IsEndDotsVisible, CultureInfo.InvariantCulture); } else { lblSecondDots.Visible = false; } if (info.IsStartDotsVisible != null) { lblFirstDots.Visible = Convert.ToBoolean(info.IsStartDotsVisible, CultureInfo.InvariantCulture); } else { lblFirstDots.Visible = false; } //First and Last Links if (info.IsFirstLinkVisible != null) { lnkFirst.Visible = Convert.ToBoolean(info.IsFirstLinkVisible, CultureInfo.InvariantCulture); } else { lnkFirst.Visible = false; } if (info.IsLastLinkVisible != null) { lnkLast.Visible = Convert.ToBoolean(info.IsLastLinkVisible, CultureInfo.InvariantCulture); lnkLast.Text = info.NumberOfPagesRequired.ToString(CultureInfo.InvariantCulture); } else { lnkLast.Visible = false; } //For first page, there is no previous if (index != 1 &amp;&amp; info.NumberOfPagesRequired != 1) { lnkPrevious.Enabled = true; } else { lnkPrevious.Enabled = false; } //For last page there is no Next if (index != info.NumberOfPagesRequired &amp;&amp; info.NumberOfPagesRequired != 1) { lnkNext.Enabled = true; } else { lnkNext.Enabled = false; } } else { pagingSection.Visible = false; } } } </code></pre> <p>DTO</p> <pre><code>public class PagingInfo { public Collection&lt;LinkButton&gt; PaginationLinks { get; set; } public bool? IsEndDotsVisible { get; set; } public bool? IsStartDotsVisible { get; set; } public bool? IsFirstLinkVisible { get; set; } public bool? IsLastLinkVisible { get; set; } public int NumberOfPagesRequired { get; set; } } </code></pre> <p>Helper</p> <pre><code>public static class PagingHelper { public static PagingInfo GetAllLinks(int totalRecordsInTable, int pageSize, int previousIndex) { string LinkButtonIDPrefix = "lnK"; PagingInfo pagingInfo = new PagingInfo(); pagingInfo.PaginationLinks = new Collection&lt;LinkButton&gt;(); if (totalRecordsInTable &gt; 0) { int itemsBeforePage = 4; int itemsAfterPage = 2; int dynamicDisplayCount = itemsBeforePage + 1 + itemsAfterPage; Double numberOfPagesRequired = Convert.ToDouble(totalRecordsInTable / pageSize); if (totalRecordsInTable % pageSize != 0) { numberOfPagesRequired = numberOfPagesRequired + 1; } if (numberOfPagesRequired == 0) { numberOfPagesRequired = 1; } //Note: This function adds only the probable Links that the user can click (based on previous click). //This is needed sice dynamic controls need to be added while Page_Load itself for event handlers to work //In case of any bug, easiest way is add all links from 1 to numberOfPagesRequired //Following is an optimized way int endOfLeftPart = dynamicDisplayCount; //User may click "1". So the first 7 items may be required for display. Hence add them for event handler purpose for (int i = 1; i &lt;= endOfLeftPart; i++) { //Create dynamic Links LinkButton lnk = new LinkButton(); lnk.ID = LinkButtonIDPrefix + i.ToString(CultureInfo.InvariantCulture); lnk.Text = i.ToString(CultureInfo.InvariantCulture); pagingInfo.PaginationLinks.Add(lnk); } int startOfRighPart = Convert.ToInt32(numberOfPagesRequired) - dynamicDisplayCount + 1; //User may click the last link. So the last 7 items may be required for display. Hence add them for event handler purpose for (int i = startOfRighPart; i &lt;= Convert.ToInt32(numberOfPagesRequired); i++) { //Links already added should not be added again if (i &gt; endOfLeftPart) { //Create dynamic Links LinkButton lnk = new LinkButton(); lnk.ID = LinkButtonIDPrefix + i.ToString(CultureInfo.InvariantCulture); lnk.Text = i.ToString(CultureInfo.InvariantCulture); pagingInfo.PaginationLinks.Add(lnk); } } //User may click on 4 items before current index as well as 2 items after current index for (int i = (previousIndex - itemsBeforePage); i &lt;= (previousIndex + itemsAfterPage); i++) { //Links already added should not be added again if (i &gt; endOfLeftPart &amp;&amp; i &lt; startOfRighPart) { //Create dynamic Links LinkButton lnk = new LinkButton(); lnk.ID = LinkButtonIDPrefix + i.ToString(CultureInfo.InvariantCulture); lnk.Text = i.ToString(CultureInfo.InvariantCulture); pagingInfo.PaginationLinks.Add(lnk); } } } return pagingInfo; } public static PagingInfo GetPageLinks(int totalRecordsInTable, int pageSize, int currentIndex) { string LinkButtonIDPrefix = "lnK"; PagingInfo pagingInfo = new PagingInfo(); pagingInfo.PaginationLinks = new Collection&lt;LinkButton&gt;(); if (totalRecordsInTable &gt; 0) { int itemsBeforePage = 4; int itemsAfterPage = 2; int dynamicDisplayCount = itemsBeforePage + 1 + itemsAfterPage; Double numberOfPagesRequired = Convert.ToDouble(totalRecordsInTable / pageSize); if (totalRecordsInTable % pageSize != 0) { numberOfPagesRequired = numberOfPagesRequired + 1; } if (numberOfPagesRequired == 0) { numberOfPagesRequired = 1; } //Generate dynamic paging int start; if (currentIndex &lt;= (itemsBeforePage + 1)) { start = 1; } else { start = currentIndex - itemsBeforePage; } int lastAddedLinkIndex = 0; int? firtsAddedLinkIndex = null; for (int i = start; i &lt; start + dynamicDisplayCount; i++) { if (i &gt; numberOfPagesRequired) { break; } //Create dynamic Links LinkButton lnk = new LinkButton(); lnk.ID = LinkButtonIDPrefix + i.ToString(CultureInfo.InvariantCulture); lnk.Text = i.ToString(CultureInfo.InvariantCulture); lastAddedLinkIndex = i; if (firtsAddedLinkIndex == null) { firtsAddedLinkIndex = i; } //Check whetehr current page if (i == currentIndex) { lnk.CssClass = "page-numbers current"; } else { lnk.CssClass = "page-numbers"; } pagingInfo.PaginationLinks.Add(lnk); } if (numberOfPagesRequired &gt; dynamicDisplayCount) { //Set dots (ellipse) visibility pagingInfo.IsEndDotsVisible = lastAddedLinkIndex == numberOfPagesRequired ? false : true; pagingInfo.IsStartDotsVisible = firtsAddedLinkIndex &lt;= 2 ? false : true; //First and Last Page Links pagingInfo.IsLastLinkVisible = lastAddedLinkIndex == numberOfPagesRequired ? false : true; pagingInfo.IsFirstLinkVisible = firtsAddedLinkIndex == 1 ? false : true; } pagingInfo.NumberOfPagesRequired = Convert.ToInt32(numberOfPagesRequired); } return pagingInfo; } } </code></pre> <p><strong>ASPX Page</strong></p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LijosTest.aspx.cs" Inherits="PagingTestWebApplication.LijosTest" %&gt; &lt;%@ Register TagPrefix="CP" TagName="LijosPager" Src="~/PagingUserControl.ascx" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;style type="text/css"&gt; .page-numbers { border: 1px solid #CCC; color: #808185; display: block; float: left; font-size: 9pt; margin-right: 3px; padding: 4px 4px 3px; text-decoration: none; } .page-numbers.current { background-color: #808185; border: 1px solid #808185; color: white; font-weight: bold; } .page-numbers.next, .page-numbers.prev { border: 1px solid white; font-size: 12pt; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:TextBox ID="txtEmpName" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID="btnSearch" runat="server" Text="Button" ValidationGroup="Search" OnClick="btnSearch_Click" /&gt; &lt;div&gt; &lt;asp:GridView ID="grdEmployee" runat="server"&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;CP:LijosPager ID="uclPager" runat="server" /&gt; &lt;asp:HiddenField ID="hdnCurrentIndex" runat="server" Value="Blank Value" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>ASPX Code Behind</strong></p> <pre><code>public partial class LijosTest : System.Web.UI.Page { private int pageSize = 25; private int pageIndex = 1; protected void Page_Load(object sender, EventArgs e) { //Register event handler for user control event this.uclPager.PaginationLinkClicked += new EventHandler(paginationLink_Click); if (Page.IsPostBack) { //During all postbacks - Add the pagination links to the page int tableDataCount = DatabaseSimulator.GetEmployeesCount(txtEmpName.Text); string defaultInitialValueForHiddenControl = "Blank Value"; int indexFromPreviousDataRetrieval = 1; if (!String.Equals(hdnCurrentIndex.Value, defaultInitialValueForHiddenControl)) { indexFromPreviousDataRetrieval = Convert.ToInt32(hdnCurrentIndex.Value, CultureInfo.InvariantCulture); } //Set property of user control uclPager.PreviousIndex = indexFromPreviousDataRetrieval; //Call method in user control uclPager.PreAddAllLinks(tableDataCount, pageSize, indexFromPreviousDataRetrieval); } } protected void btnSearch_Click(object sender, EventArgs e) { //When Search is clicked, reset the index to 1 (first page) pageIndex = 1; BindBusinessProcessActivitiesData(); } protected void paginationLink_Click(object sender, EventArgs e) { //When link is clicked, set the pageIndex from user control property pageIndex = uclPager.CurrentClickedIndex; BindBusinessProcessActivitiesData(); } private void BindBusinessProcessActivitiesData() { string name = txtEmpName.Text; List&lt;Employee&gt; searchResult = DatabaseSimulator.GetData(name, pageSize, pageIndex).ToList(); grdEmployee.DataSource = searchResult; grdEmployee.DataBind(); //Index hdnCurrentIndex.Value = pageIndex.ToString(CultureInfo.InvariantCulture); //Get total number of records int tableDataCount = DatabaseSimulator.GetEmployeesCount(name); uclPager.AddPageLinks(tableDataCount, pageSize, pageIndex); } } </code></pre> <p>Database Part</p> <pre><code>public static class DatabaseSimulator { public static IEnumerable&lt;Employee&gt; GetData(string name, int pageSize,int index) { IEnumerable&lt;Employee&gt; employeesSource = SearchEmployees(name); int skipUpto = ((index-1) * pageSize); IEnumerable&lt;Employee&gt; searchResult = employeesSource.Skip(skipUpto).Take(pageSize); return searchResult; } public static int GetEmployeesCount(string name) { List&lt;Employee&gt; employees = GetEmployees(); int employeesCount = 0; if (String.IsNullOrEmpty(name)) { employeesCount = employees.Count; } else { List&lt;Employee&gt; selectedEmployees = employees.Where(r =&gt; r.Name == name).ToList(); employeesCount = selectedEmployees.Count; } return employeesCount; } private static IEnumerable&lt;Employee&gt; SearchEmployees(string name) { List&lt;Employee&gt; employees = GetEmployees(); if (String.IsNullOrEmpty(name)) { return employees; } return employees.Where(r =&gt; r.Name == name); } private static List&lt;Employee&gt; GetEmployees() { List&lt;Employee&gt; employees = new List&lt;Employee&gt;(); for (int i = 1; i &lt;= 400; i++) { Employee emp = new Employee(); emp.EmpID = i; if (i % 2 == 0) { emp.Name = "Divisible by 2"; } else if (i % 3 == 0) { emp.Name = "Divisible by 3"; } else if (i % 5 == 0) { emp.Name = "Divisible by 5"; } else if (i % 7 == 0) { emp.Name = "Divisible by 7"; } else { emp.Name = "Other -- "+ i.ToString(); } employees.Add(emp); } return employees; } } public class Employee { public int EmpID { get; set; } public string Name { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T15:06:30.487", "Id": "33278", "Score": "1", "body": "@Knownasilya. Thanks. I have accepted possible answers. 75% acceptance now" } ]
[ { "body": "<p>I have come across a scenario that will fail: Suppose there is an image button control in the same page along with our button. Our code for pre-adding links will be called in all postbacks. </p>\n\n<p>Assume that the value in textbox is supposed to be an integer. We have added a validation that will fire when button is clicked. But when image button is clicked this validation should not be fired [The image button is redirecting to another page. Hence no validation should be there].</p>\n\n<p>In the above scenario, when image button is clicked (with a non-integer value in textbox), a postback will happen and it will cause an exception. </p>\n\n<p>To handle this scnario, we need to know the <code>control's ID that caused the postback</code>. I hope the answer in <a href=\"https://stackoverflow.com/questions/3175513/on-postback-how-can-i-check-which-control-cause-postback-in-page-init-event\">https://stackoverflow.com/questions/3175513/on-postback-how-can-i-check-which-control-cause-postback-in-page-init-event</a> will be helpful for this purpose.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T17:18:30.310", "Id": "20830", "ParentId": "20510", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T14:30:32.940", "Id": "20510", "Score": "3", "Tags": [ "c#", "asp.net", "sql-server" ], "Title": "Custom Paging in ASP.Net Web Application" }
20510
<p>On an IRC channel I'm a member of, one particular person mocks every piece of code I post, even if it's a rough draft or if I haven't coded in months. I am pretty well versed with computer theory and knowledge, but my skills with programming lack due to little practice. This particular code was from a project I was starting and I was putting down some ideas/structure on GitHub, when he pointed out this particular snippet.</p> <p>So, after a couple months of trying to get the discipline to start coding again, I coded this and my question is: If indenting like this is bad, what other things did I do wrong here, assuming the logic is sound (I never tested it, I went on hiatus)? Also, what would you do to avoid the indenting?</p> <pre><code>void parse_arguments(int count, char * arguments[]){//probably add file pointer here to pass to load, change return type when an API is decided. int currentArg, paramIndex; for(currentArg = 1; currentArg &lt;= count; currentArg++){ if(arguments[currentArg][0] == '-'){ for(paramIndex = 0; paramIndex &lt; PARAMMAX; paramIndex++){ if(strcmp(arguments[currentArg][1], arglist[paramIndex]) == 0){ switch(paramIndex){ case 0: //load(currentArg + 1); currentArg++; break; default: break; } break; } } } } } </code></pre> <p>Note: <code>arglist</code> is a statically declared array of chars.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T16:59:47.070", "Id": "32854", "Score": "9", "body": "http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html" } ]
[ { "body": "<p>Your code looks perfectly reasonable and the indentation is very standard. The only issue I can see is that C arrays are zero based so the loop </p>\n\n<pre><code>for(currentArg = 1; currentArg &lt;= count; currentArg++){\n</code></pre>\n\n<p>should possibly be</p>\n\n<pre><code>for(currentArg = 0; currentArg &lt; count; currentArg++){\n</code></pre>\n\n<p>If you're parsing a command line and deliberately ignoring arg[0], it'd be worth adding a comment to your code saying this. And whether <code>count</code> is the total number of arguments (meaning that your loop exit condition should be <code>currentArg &lt; count</code>) or the number of arguments to be parsed in this function (meaning that <code>currentArg &lt;= count</code> is a valid exit condition)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:44:37.423", "Id": "32857", "Score": "1", "body": "That's probably as a result of passing argc,argv where argv[0] is the application. All other arguments are flags. So I don't agree that this is a problem or unexpected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:59:07.987", "Id": "32862", "Score": "0", "body": "@LokiAstari Thanks. I've updated my answer to take account of your comment. I agree that starting the loop from index 1 is likely to be correct but an exit condition of `currentArg <= count` still seems questionable. At the very least, this shows that the function would benefit from some comments about its arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T18:18:23.313", "Id": "32864", "Score": "0", "body": "Using a '<' would be much more intuitive and easier to read the intentions, that makes sense. Thanks for the help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:27:02.500", "Id": "32908", "Score": "1", "body": "I'd fix the out-of-bounds bug, keep the 1 but avoid \"magic numbers\". Instead, do something like `#define FIRST_CMDLINE_ARG 1` and then `for(currentArg = FIRST_CMDLINE_ARG; currentArg < count; ...`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:04:56.443", "Id": "20512", "ParentId": "20511", "Score": "1" } }, { "body": "<pre><code>void parse_arguments(int count, char * arguments[]){//probably add file pointer here to pass to load, change return type when an API is decided.\n int currentArg, paramIndex;\n\n for(currentArg = 1; currentArg &lt;= count; currentArg++){\n</code></pre>\n\n<p>Why are you counting from zero? In C arrays start from zero, but you are starting from 1. As it stands it looks like you skip the first argument and then read one past the end</p>\n\n<pre><code> if(arguments[currentArg][0] == '-'){\n for(paramIndex = 0; paramIndex &lt; PARAMMAX; paramIndex++){\n if(strcmp(arguments[currentArg][1], arglist[paramIndex]) == 0){\n</code></pre>\n\n<p>Isn't <code>arguments[currentArg][1]</code> a <code>char</code>? How are you passing it to <code>strcmp</code>?</p>\n\n<pre><code> switch(paramIndex){\n case 0:\n //load(currentArg + 1);\n currentArg++;\n</code></pre>\n\n<p>I recommend against manipulating loop counters inside your loop. It makes it harder to follow whats going on. </p>\n\n<pre><code> break;\n default:\n break;\n }\n break;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>So much indentation suggests that you should break this down into smaller functions. I'd also suggest that you store the results of the arguments into a struct. </p>\n\n<p>A general sketch of how I'd do this:</p>\n\n<pre><code>struct options\n{\n char * filename;\n int numberOfRabbits;\n};\n\nstruct parameter\n{\n char * name; // 'x' for option '-x'\n bool requiresOption; // whether or not we should have an option\n void (*handler)(struct options * options, char * argument);\n};\n\nvoid parse_arguments(int count, char * arguments[], struct options * options)\n{\n char * argument;\n int position = 0;\n while(position &lt; count)\n {\n struct parameter * param = determine_parameter(arguments[position++]);\n if(!parameter)\n {\n panic(); // don't know this parameter\n }\n if(param.requiresOption)\n {\n argument = arguments[position++];\n }else{\n argument = NULL;\n }\n param.handler(options, argument);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:45:57.953", "Id": "32858", "Score": "0", "body": "This is obviously parsing command line flags. There it is natural to start index from 1 as the argv[0] is the application name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:46:52.867", "Id": "32859", "Score": "0", "body": "Since flags usually have parameters incrementing the loop counter in the loop here is also relatively standard. The problem is actually the lack of checks to make sure there is an extra parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:51:11.470", "Id": "32860", "Score": "0", "body": "@LokiAstari, agreed on `argv[0]` being the application name. But the loop still goes one past the end of the list of arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:51:51.657", "Id": "32861", "Score": "1", "body": "@LokiAstari, I certainly understand why he's incrementing the index there. I just think that if you are going to monkey around with the index like that you should use a while loop to better show your intention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T18:16:22.657", "Id": "32863", "Score": "0", "body": "Oops! The strcmp was a relic from when I was going to parse strings instead! Thanks for the example and for whatever reason I forgot break it down into smaller functions. This was really helpful, thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:20:07.770", "Id": "20513", "ParentId": "20511", "Score": "5" } }, { "body": "<p>Parsing arguments to a C program is a problem that has been solved. I understand that you want to flex your C muscles again. I would recommend flexing them by reusing libraries.</p>\n\n<p>This will accomplish a few things:</p>\n\n<ul>\n<li>Reduce the number of bugs in your code.</li>\n<li>Leverage a more flexible way of parsing arguments.</li>\n<li>Give you more time to work on more interesting parts of your program.</li>\n<li>Give you practice integrating external libraries into your code.</li>\n<li>Eliminate the arrow code.</li>\n</ul>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://www.purposeful.co.uk/software/gopt/\" rel=\"nofollow noreferrer\">http://www.purposeful.co.uk/software/gopt/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/2913767/library-for-parsing-arguments-gnu-style\">https://stackoverflow.com/questions/2913767/library-for-parsing-arguments-gnu-style</a></li>\n<li><a href=\"http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html#Parsing-Program-Arguments\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html#Parsing-Program-Arguments</a></li>\n<li><a href=\"https://stackoverflow.com/questions/189972/argument-parsing-helpers-for-c-unix\">https://stackoverflow.com/questions/189972/argument-parsing-helpers-for-c-unix</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T18:27:16.113", "Id": "20515", "ParentId": "20511", "Score": "2" } } ]
{ "AcceptedAnswerId": "20513", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T16:47:03.953", "Id": "20511", "Score": "4", "Tags": [ "c", "parsing" ], "Title": "Criticize C argument parsing method" }
20511
<p>I am trying to create a randomly generated array of x numbers with no duplicates. I am choosing numbers, one at a time, then comparing each new number to the numbers already in the array. </p> <p>Here is my code. At the end I should have an array of seven numbers, none that match, but sometimes I get a nil:</p> <pre><code>array = [] #DEFINES THE ARRAY array[0] = rand(10) #THIS CHOOSES FIRST NUMBER (FN) AND PUTS IT IN THE FIRST ARRAY SPOT p "fn = #{array[0]}" for i in 1..6 #START OF FOR LOOP TO GET 6 NUMBERS IN THE ARRAY - WHY 6? THE FIRST NUMBER THAT POPPED IN MY HEAD p "Iteration #{i} -------------------------" # THIS IS JUST SO I KNOW WHERE I AM IN THE LOOPS @x = rand(10) #THIS CHOOSES THE NEXT NUMBER AND ALL NUMBERS AFTER array.each do |uc| # THIS IS THE LOOP THAT COMPARES ALL NUMBERS @type = @x == uc ? "yes" : "no" #DOES THE CHOSEN NUMBER EQUAL ANY NUMBER IN THE ARRAY p "does #{uc} = #{@x}? #{@type}" if @type == "yes" # IF THE COMPARE IS TRUE, I DON'T WANT ANYTHING DONE. IT WILL CYCLE THRU AND GET A NEW NUMBER i = 1 p "YES #{@x} = #{uc}" break end #END OF IF YES end #END OF ARRAY EACH if @type == "no" #IF NO, PUT NEXT NUMBER (@X) INTO THE NEXT ARRAY SPOT. p "in last if type= #{@type}" #THESE STATEMENTS JUST PRINT OUT THE DIFFERENT VARIABLES SO I KNOW I AM GETTING WHAT I EXPECT p "in last if x = #{@x}" p "in last if i = #{i}" @x = array[i] #THIS "SHOULD" FILL THE NEXT ARRAY SPOT - BUT DOESN'T SEEM TO p "#{array[i]} is in the array" #THIS PRINT OUT IS BLANK - STATEMENT ABOVE DID NOT WORK. p array[i] end #END OF IF NO end #END OF FOR LOOP p array #PRINTS OUT THE CONTENTS OF THE ARRAY </code></pre> <p>I know there are probably quicker and easier ways to do this, but I am starting out with what I know, and building up.</p>
[]
[ { "body": "<p>I don't understand what you really want, but this simple one-liner generates an array of ten elements (from 1 to 10) with a random order. Tweak it to meet your needs:</p>\n\n<pre><code>(1..10).to_a.shuffle\n#=&gt; [4, 10, 1, 7, 3, 5, 8, 2, 9, 6]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T18:54:34.983", "Id": "32931", "Score": "1", "body": "Actually it had to be `(0...10).to_a.shuffle.take(7)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T14:10:20.193", "Id": "41002", "Score": "0", "body": "Why did u append @steenslag answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T17:22:57.070", "Id": "41017", "Score": "0", "body": "@Nakilon, I hadn't understood that the OP wanted only 7 elements (I am not sure yet, he didn't give feedback), your comment make my realize this. So I just completed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T17:52:34.277", "Id": "41021", "Score": "0", "body": "@tokland, but everyone can *realize* the best solution – why to accumulate answers, that were already posted by another people?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T19:50:34.157", "Id": "20521", "ParentId": "20520", "Score": "6" } }, { "body": "<ol>\n<li>Why do you put empty lines everywhere? They don't make your code more readable.</li>\n<li>If you used <code>@</code> not because you are writing classes, but just to fix scope problems, you may try either use <code>$</code> instead or even better define <code>type</code> variable outside the nested loop (before <code>array.each do |uc|</code>).</li>\n<li>And the main thing. Ruby's loops are more highlevel, than in, for example, C. And you can't directly change the <code>i</code> value. So you should use keyword <code>redo</code> to repeat the iteration. <a href=\"http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_containers.html\" rel=\"nofollow\">http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_containers.html</a></li>\n<li>You may use <code>puts</code> instead of <code>p</code> to get rid of <code>\"\"</code>, but it may need <code>STDOUT.sync = true</code> fix under Windows.</li>\n<li>Also you need <code>array[i] = x</code> instead of <code>x = array[i]</code>. If you aren't experienced in programming, I would recommend to start with C/C++.</li>\n</ol>\n\n<p>So here is your program. Not refactored yet, but fixed.</p>\n\n<pre><code>array = []\narray[0] = rand 10\nputs \"fn = #{array[0]}\"\nfor i in 1..6\n puts \"Iteration #{i} -------------------------\"\n x = rand 10\n array.each do |uc|\n $type = x == uc ? \"yes\" : \"no\"\n puts \"does #{uc} = #{x}? #{$type}\"\n if $type == \"yes\"\n puts \"YES #{x} = #{uc}\"\n break\n end\n end\n if $type == \"no\"\n puts \"in last if type= #{$type}\"\n puts \"in last if x = #{x}\"\n puts \"in last if i = #{i}\"\n array[i] = x\n puts \"#{array[i]} is in the array\"\n p array[i]\n else\n redo\n end\nend\np array\n</code></pre>\n\n<h3>Now refactoring:</h3>\n\n<p>You need to know, that Ruby arrays have a method <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F\" rel=\"nofollow\"><code>#include?</code></a>, which you may use instead of loop. We will lose debugging ability a bit, but it makes program more pretty, and now we don't need to make <code>type</code> variable global.</p>\n\n<pre><code>array = []\narray[0] = rand 10\nputs \"fn = #{array[0]}\"\nfor i in 1..6\n puts \"Iteration #{i} -------------------------\"\n x = rand 10\n type = array.include?(x) ? \"yes\" : \"no\"\n puts \"does array include #{x}? #{type}\"\n if type == \"no\"\n puts \"in last if type=#{type}, x=#{x}, i=#{i}\"\n array[i] = x\n puts \"#{array[i]} is in the array\"\n else\n redo\n end\nend\np array\n</code></pre>\n\n<p>Then get rid of <code>\"yes\"</code> and <code>\"no\"</code>, and use native Ruby <code>true</code> and <code>false</code>. And you may add <a href=\"http://ruby-doc.org/core-1.9.3/Object.html#method-i-tap\" rel=\"nofollow\"><code>tap</code></a> to any object for debugging purposes - this universal method returns the object itself after execution, so you will be able to comment it later via putting <code>#</code> before <code>.tap</code> (when you don't need debug output) without breaking the program.</p>\n\n<pre><code>array = []\narray[0] = rand 10\nputs \"fn = #{array[0]}\"\nfor i in 1..6\n puts \"Iteration #{i} -------------------------\"\n x = rand 10\n if (type = array.include? x).tap{ puts \"does array include #{x}? #{type : \"yes\" : \"no\"}\" }\n redo\n else\n puts \"in last if type=#{type}, x=#{x}, i=#{i}\"\n array[i] = x\n puts \"#{array[i]} is in the array\"\n end\nend\np array\n</code></pre>\n\n<p>But actually you print the <code>type</code> the second time only when it is <code>false</code>, so don't do it. Also we don't need <code>else</code> in this case, because <code>redo</code> will throw us away from this iteration. And actually we can start from iteration 0 and then change <code>for</code> to <code>times</code>. But we will lose the <code>puts \"fn=\"</code> (I don't know, whether you really need it).</p>\n\n<pre><code>array = []\n7.times do |i|\n puts \"Iteration #{i} -------------------------\"\n x = rand 10\n redo if array.include?(x).tap{ |type| puts \"does array include #{x}? #{type ? \"yes\" : \"no\"}\" }\n puts \"x=#{x}, i=#{i}\"\n array[i] = x\n puts \"#{array[i]} is in the array\"\nend\np array\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:12:25.467", "Id": "32924", "Score": "0", "body": "Outstanding. Thank you very much for showing me how my code was wrong in the first place, and then going farther by simplifying it in easy to understand steps. I learned much, and I greatly appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T20:23:25.580", "Id": "20522", "ParentId": "20520", "Score": "4" } }, { "body": "<p>The <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-sample\" rel=\"noreferrer\">sample</a> method does what you want: </p>\n\n<pre><code>(1..10).to_a.sample(7) #=&gt; [2, 9, 1, 6, 8, 10, 4]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-22T14:32:38.497", "Id": "359174", "Score": "0", "body": "That could return duplicates I believe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-22T17:29:49.387", "Id": "359207", "Score": "2", "body": "@kamoroso94 from the [docs](http://ruby-doc.org/core-2.5.0/Array.html#method-i-sample): \"(...) in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-22T17:32:45.070", "Id": "359208", "Score": "0", "body": "thanks for the correction! I'm still learning Ruby, so I must have misremembered." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T22:15:02.430", "Id": "20731", "ParentId": "20520", "Score": "9" } } ]
{ "AcceptedAnswerId": "20521", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T19:29:56.047", "Id": "20520", "Score": "4", "Tags": [ "ruby" ], "Title": "How do I generate a list of n unique random numbers in Ruby?" }
20520
<p>I'm very new both to programming and to R so please bear with me :-) I've written the following bit of code, which works perfectly well and runs through a data file with 17446 rows in about 35 seconds. I don't really have a problem with this but am sure that this could be a lot more elegant with probably the use of the tapply function. I would love to see how you experts would rewrite this more efficiently and am sure the rewrite would teach me a lot. I've included the first few rows of the output file and hopefully the code should be fairly obvious (it must be if I managed to write it!!); it's a simple filter based on the standard deviation of a subset in one column dictating the output to another column which is set up at the start of the code. If a value in the NEE column is more than 2 stdevs of the preceeding three values then the value is taken from the mean of a subset in the NEE2 column else the value is copied from the first (if that makes sense). Please also note the "count" variable as I need to retrieve the amount of values replaced. Hope this piques someone's interest and thanks in advance for all of your time. JonP</p> <pre><code>Dspke &lt;- read.csv(file.choose()) nr = nrow(Dspke) count = 0 Dspke$NEE2 &lt;- (1:nr) #creates a new column ready for input of values for (i in 4:nr) { #standard deviation of the previous three values in NEE stdev &lt;- sd(Dspke$NEE[(i-2):i]) #if stdev&gt;2 then NEE2 value is mean of the previous 3 values in NEE2 else copy value from NEE if(stdev&gt;=2) { Dspke$NEE2[i] &lt;- mean(Dspke$NEE2[(i-2):i-1]) count = count+1 }else { Dspke$NEE2[i] &lt;- Dspke$NEE[i] } } write.csv(Dspke,"Dspke.csv") Date_Time NEE NEE2 1 03/01/2012 13:00 -2.300000 1.00000 2 03/01/2012 13:30 -2.385610 2.00000 3 03/01/2012 14:00 -2.081935 3.00000 4 03/01/2012 14:30 -1.778260 -1.77826 5 03/01/2012 15:00 -2.409490 -2.40949 6 03/01/2012 15:30 -0.741030 -0.74103 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:23:03.283", "Id": "32873", "Score": "0", "body": "Can you confirm that `NEE2` in `mean(Dspke$NEE2[(i-2):i-1])` is really meant to be `NEE2` and not `NEE`? `NEE2` seems like an odd choice, and this has a bearing on the complexity of the solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:36:35.490", "Id": "32874", "Score": "0", "body": "Sorry, struggling to keep up with the replies, yes the NEE2 is intentional, the new value is the mean of the corrected not the original values, otherwise I would just carry the outliers with me. As for \"count\", I just retrieve the value with command line afterwards." } ]
[ { "body": "<p>The <code>embed</code> function is well-suited for constructing trailing vectors by row:</p>\n\n<pre><code> Dspke[ , paste0(\"E3\", 1:3)] &lt;- NA # create columns to hold the trailing values\n Dspke[4:nrow(Dspke), 5:7] &lt;- embed(Dspke$NEE, 3)\n Dspke$NEE3 &lt;- ifelse( apply(Dspke[,5:7], 1, sd) &gt;2, #test\n rowMeans(Dspke[,5:7]), # result if TRUE\n Dspke[,\"NEE\"]) # result if FALSE\n</code></pre>\n\n<p>I see the count vector being created but cannot tell from your description what it is supposed to do. Perhaps you should store the value of:</p>\n\n<pre><code>&gt; apply(Dspke[,5:7], 1, sd) &gt; 2)\n 1 2 3 4 5 6 \n NA NA NA FALSE FALSE FALSE \n</code></pre>\n\n<p>(Not a very good test of the code presented by the data since all of the tests are FALSE.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:20:25.080", "Id": "32875", "Score": "0", "body": "In OP's example, the current mean's calculated from the last three corrected values, not the last three original values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:24:03.620", "Id": "32876", "Score": "0", "body": "Groan. My comment about the lack of a good test set is bearing bitter fruit. Well, my solution IS more elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:32:51.337", "Id": "32877", "Score": "0", "body": "Hi, thanks for the reply. Well I tried that but get the error message...Error in `*tmp*`[[j]] : recursive indexing failed at level 2\nIn addition: Warning message:\nIn matrix(value, n, p) :\n data length [52332] is not a sub-multiple or multiple of the number of rows [17443]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:40:53.767", "Id": "32878", "Score": "0", "body": "Are you now seeing why it is strongly recommended that you post the output of dput() on your sample data rather than relying on us to reconstruct it from console output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:50:26.213", "Id": "32879", "Score": "0", "body": "Yes tried that, it outputs a file with 11639 rows which appears to bear very little relationship to my actual output file. Bearing in mind my input file is 17446 rows long. No worries, I'll see if I can get a good understanding of the script you posted, I'm sure once I understand it how it works I'll be able to apply it to my file. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T19:58:48.780", "Id": "32880", "Score": "0", "body": "Posting `dput(head(Dspke))` should not have given such a large output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T23:13:10.400", "Id": "32881", "Score": "0", "body": "O yeh, didn't think of that, I did mention that this was very new to me. Obviously I need to spend a lot more time learning before I trouble you guys. No worries, just thought it might be of interest, as I said the code works fine. Thanks for the input." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:13:48.533", "Id": "20524", "ParentId": "20523", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T17:52:38.097", "Id": "20523", "Score": "3", "Tags": [ "r" ], "Title": "More elegant filter script in R" }
20523
<p>I am building a web service that gets data via Stored Procedures from a db and provides the result as JSON. The solution is built as a MVC 4 Web API project. I have to retrieve the data via Stored Procedures for several reasons (security, SQLAnywhere db, etc).</p> <p>It is a relatively small scale project so I have opted for not defining a Model in the Web Service layer to save work (and possibly performance). There will likely be models in the front end application (which will be a MVC 4 Web Application).</p> <p>The reasons why I am including an extra layer in the form of a Web Service is to a) add extra security, and b) that there will likely be a iPhone app for part of the application which then can utilize the same web service as the site.</p> <p>It is working as I want it to, so what I want feedback on is</p> <ol> <li>What do you think of the general approach to build a MVC 4 Web API solution without explicit models?</li> <li>Do you have any comments on how to improve the details of the implementation?</li> </ol> <p>One potential thought I have had is to skip the dataset and make a direct call to the Stored Procedure and loop over a datareader, which could potentially be faster. The other potential change is to loop over the datatable and build up the JSON manually instead of using the serializer.</p> <p>What I like about the current solution is that it can be done on very few lines of code and that I do not have to manually name each JSON object since it is inherited from the datatable within the dataset. </p> <p>I define a dataset called dsProducts that is loaded with a TableAdapter.</p> <pre><code> // GET api/products public string Get() { string result = ""; dsProductTableAdapters.GetProductsTableAdapter taTemp = new dsProductsTableAdapters.GetProductsTableAdapter(); dsProducts dsTemp = new dsProducts(); try { taTemp.Fill(dsTemp.GetProducts); result = jsonHelper.convertJSONString(dsTemp.GetProducts); } catch (Exception ex) { result = "{\"error\":\"1\"}"; } return result; } </code></pre> <p>The convertJSONString and its help functions are defined as:</p> <pre><code> public static string convertJSONString(DataTable table) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(table.ToDictionary()); } static Dictionary&lt;string, object&gt; ToDictionary(this DataTable dt) { return new Dictionary&lt;string, object&gt; { { dt.TableName, dt.convertTableToDictionary() }}; } static object convertTableToDictionary(this DataTable dt) { var columns = dt.Columns.Cast&lt;DataColumn&gt;().ToArray(); return dt.Rows.Cast&lt;DataRow&gt;().Select(r =&gt; columns.ToDictionary(c =&gt; c.ColumnName, c =&gt; r[c])); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T14:26:44.287", "Id": "79972", "Score": "0", "body": "I believe `taTemp` and `dsTemp` are both objects of classes which implement `IDisposable` and therefore should be wrapped in `using` statements to ensure proper deterministic disposal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-13T12:23:29.853", "Id": "203916", "Score": "0", "body": "Get rid of StoredProc -> Plug-In a ORM -> Serialize your DTO's -> Expose via API's" } ]
[ { "body": "<p>General approach to build Web API without models, doesn't give the full web API capabilities.</p>\n\n<p>E.g: </p>\n\n<ol>\n<li>Help: You cannot have Web API help generated automatically.</li>\n<li>You cannot return error handling scenarios: status, message</li>\n</ol>\n\n<p>If you don't want to create the DTOs (Models), you can use the dynamic types. JSON formatter works well with the dynamic types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-10T19:42:22.170", "Id": "53917", "ParentId": "20526", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T01:05:50.553", "Id": "20526", "Score": "6", "Tags": [ "c#", "asp.net", "web-services" ], "Title": "Web API and Stored Procedures" }
20526
<p>I was wondering if there was a way to rewrite this to be a bit more clean. It seems a bit odd to have a <code>mouseenter</code> and a <code>mouseleave</code> for this. Surely there's a toggle of some kind?</p> <pre><code>$(document).ready(function() { // Post header animation $('h1.post').mouseenter(function() { $(this).animate({ paddingLeft: 10 }, 300); }); $('h1.post').mouseleave(function() { $(this).animate({ paddingLeft: 0 }, 300); }); // Navbar hover animation $("h1#button").mouseenter(function() { $(this).animate({opacity: 0.60}, 100); }); $("h1#button").mouseleave(function() { $(this).animate({opacity: 1}, 100); }); // Contact div toggle $("h1.icons").click(function() { $(".icon-wrapper").slideToggle("slow"); }); }); </code></pre> <p>My website is <a href="http://gamer-simms.herokuapp.com" rel="nofollow noreferrer">http://gamer-simms.herokuapp.com</a> if you want to look.</p>
[]
[ { "body": "<p>You can condense this a bit by using jQuery's <a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\"><code>hover</code></a> method:</p>\n\n<pre><code>$('h1.post').hover(function() {\n $(this).animate({ paddingLeft: 10 }, 300);\n}, function() {\n $(this).animate({ paddingLeft: 0 }, 300);\n});\n\n$(\"h1#button\").hover(function() {\n $(this).animate({opacity: 0.60}, 100);\n}, function() {\n $(this).animate({opacity: 1}, 100);\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T01:25:55.883", "Id": "20528", "ParentId": "20527", "Score": "2" } } ]
{ "AcceptedAnswerId": "20528", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T01:13:54.917", "Id": "20527", "Score": "1", "Tags": [ "javascript", "beginner", "jquery" ], "Title": "Header and navbar animations on a website" }
20527
<p>I have created some code in Java that slices up an image into rows and columns and then saves each image to the file system. This works but there are some improvements I would like to make</p> <p>I would like it to automatically know the original file name and extension using the StringTokenizer class so I do not have to hard code them into the class.</p> <p>for example...</p> <p>I want the filenames to be</p> <pre><code>targetFolder+"/"+originalfilename+"-"+(count++)"."+extension </code></pre> <p>Any general comments on the code would be appreciated too because there may be a better way of doing this</p> <pre><code>import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class GridImage implements Runnable { private BufferedImage image; private int rows, columns; private BufferedImage[][] smallImages; private int smallWidth; private int smallHeight; public GridImage(String filename, int rows, int columns) { this.rows = rows; this.columns = columns; try { image = ImageIO.read(new File(filename)); } catch (IOException e) { e.printStackTrace(); } this.smallWidth = image.getWidth() / columns; this.smallHeight = image.getHeight() / rows; smallImages = new BufferedImage[columns][rows]; } public void run() { int count = 0; for (int x = 0; x &lt; columns; x++) { for (int y = 0; y &lt; rows; y++) { smallImages[x][y] = image.getSubimage(x * smallWidth, y * smallHeight, smallWidth, smallHeight); try { ImageIO.write(smallImages[x][y], "png", new File("tile-" + (count++) + ".png")); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { GridImage image = new GridImage("img/card-grid-image-mass-effect.jpg", 4, 15); new Thread(image).start(); } } </code></pre> <p>This code actually produces the smaller images with a different filetype from the original</p> <p>What's the best way to slice up an image into a two dimentional array of tiles and save them to the bloody laptop?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T07:44:59.947", "Id": "32894", "Score": "0", "body": "First step in changing some behavior: put it in a separate place. You should write a `getFileName( ... )` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T22:25:05.737", "Id": "32961", "Score": "0", "body": "What are you doing with any 'leftover' pixels? Eg a 15 pixel image with 7 columns -> 7 columns of 2 pixels each + 1 pixel leftover. You may not be doing enough error checking (ie more columns than pixels, pre-existing files). Also, your result files can't be used to recreate the original - you give the images a count, but not their original position." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T13:29:46.800", "Id": "32984", "Score": "0", "body": "The code assumes that the original image was created with equal space between columns and rows, Is it possible to recreate the original from the 2d array of buffered images? The update to the code below adds the ability to return this array. However, I don't need to recreate the original, I just need to use the separate pieces. Either as files if I need to use that method, or as an array if I need to use that method" } ]
[ { "body": "<p>Not sure I understand your problem but what about changing the signature of you constructor to:</p>\n\n<pre><code>GridImage(String path, String filename, int rows, int columns)\n</code></pre>\n\n<p>And have path and filename be attributes of your object.</p>\n\n<p>I don't know why you implemented it as a runnable, but then I would also put all the code in the run method (starting with loading the file)...</p>\n\n<p>OK I got what you are asking now, do the following:</p>\n\n<pre><code>File originalImage = new File(filename);\nString path = originalImage.getPath();\nString fileName = originalImage.getName();\n</code></pre>\n\n<p>Now you have all you need to create your new files.</p>\n\n<p>BTW: have a look at <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/File.html\" rel=\"nofollow\">the File javadoc</a>...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T13:55:37.243", "Id": "32905", "Score": "0", "body": "I don't know why I implemented a Runnable either, but I thought that if I was going to create a class that could do all the work I needed it to internally then using object.start() would look nice semantically. I have updated the code below." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T15:20:39.330", "Id": "32917", "Score": "0", "body": "Edit to the comment above, I meant... new Thread(image).start();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T13:25:13.783", "Id": "32983", "Score": "0", "body": "Thanks pgras, that was something like what I was looking for" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T09:47:52.900", "Id": "20536", "ParentId": "20529", "Score": "1" } }, { "body": "<p>You can pass arguments to the application like the name of the image file and the target directory. These will be received by the <code>main</code> method, so you don't need to hardwire these names.</p>\n\n<p>You run your application like:</p>\n\n<p><code>java GridImage thisismybigimage.jpg targetfolder</code></p>\n\n<p>Then in <code>main</code> args[0] will be <code>\"thisismybigimage.jpg\"</code> and args[1] will be <code>targetfolder</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T13:51:12.930", "Id": "32904", "Score": "0", "body": "I don't mind hard coding in the main method, it is infact the line - ImageIO.write(smallImages[x][y], \"png\", new File(\"tile-\"+ (count++) + \".png\")); - that I don't want to hardcode. I put a main method in every class to test how I will use the class. I have posted a new version of the class below." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T12:28:20.577", "Id": "20541", "ParentId": "20529", "Score": "0" } }, { "body": "<p>I have broken down my class into smaller methods to improve readability and added the behaviour that creates a subfolder called save in the directory of the original image, but I am still hard coding my filenames and directory names. I can't see where I could get it to automatically figure out where to save the new images in the saveSmallImages() method </p>\n\n<pre><code>import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic class GridImage implements Runnable {\n private BufferedImage image;\n private String filename;\n private int rows, columns;\n private BufferedImage[][] smallImages;\n private int smallWidth;\n private int smallHeight;\n private String targetDir;\n private int imageCounter;\n\n\n public GridImage(String filename, int rows, int columns) {\n this.rows = rows;\n this.columns = columns;\n this.filename = filename;\n init();\n }\n\n private void init() {\n this.image = this.getGridImage();\n this.smallWidth = image.getWidth() / columns;\n this.smallHeight = image.getHeight() / rows;\n this.smallImages = new BufferedImage[columns][rows];\n }\n\n private BufferedImage getGridImage() {\n try {\n return ImageIO.read(new File(filename));\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public void run() {\n this.createSmallImages();\n this.createDirectoryForSaving(\"img/save\");\n this.saveSmallImages();\n }\n\n private void createSmallImages() {\n imageCounter = 0;\n for (int y = 0; y &lt; rows; y++) {\n for (int x = 0; x &lt; columns; x++) {\n smallImages[x][y] = image.getSubimage(x * smallWidth, y\n * smallHeight, smallWidth, smallHeight);\n imageCounter++;\n }\n }\n System.out.println(\"Images created: \" + imageCounter);\n }\n\n private void createDirectoryForSaving(String dir) {\n this.targetDir = dir;\n if (!(new File(dir).mkdirs())) {\n System.err.println(\"Directory could not be created\");\n }\n }\n\n private void saveSmallImages() {\n imageCounter = 0;\n for (int y = 0; y &lt; rows; y++) {\n for (int x = 0; x &lt; columns; x++) {\n try {\n ImageIO.write(smallImages[x][y], \"png\", new File(targetDir+\"/tile-\"\n + (imageCounter++) + \".png\"));\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n System.out.println(\"Images saved: \" + imageCounter);\n }\n\n public BufferedImage[][] getSmallImages() {\n return this.smallImages;\n }\n\n public static void main(String[] args) {\n GridImage image = new GridImage(\"img/card-grid-image-mass-effect.jpg\",\n 4, 15);\n new Thread(image).start();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:59:58.793", "Id": "32912", "Score": "0", "body": "just to be sure, it is OK for you to hardcode the source image name, but you would like to have the target image names generated from a pattern using the source file name ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T15:11:36.153", "Id": "32913", "Score": "0", "body": "Yes I want it to automatically create a folder in the directory of the original image and then save all the files to that folder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T15:28:19.027", "Id": "32918", "Score": "0", "body": "I didn't read your question properly... I would like the new images to be based on the original file name for example image.jpg becomes subdir/image-1.jpg, subdir/image-2.jpg etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T09:48:10.990", "Id": "32973", "Score": "0", "body": "OK I've edited my first answer..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:01:10.587", "Id": "20545", "ParentId": "20529", "Score": "0" } } ]
{ "AcceptedAnswerId": "20536", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T02:30:25.357", "Id": "20529", "Score": "2", "Tags": [ "java" ], "Title": "Slicing up an image into rows and columns in Java" }
20529
<p>For a quiz web app, I decided the best way to store quiz questions, answers, and other user data related to the question was to use an array of objects for the quiz. I'm not sure if this is the best way to go about it since static information such as the questions and answers will be mixed with user data.</p> <p>Each object in the array contains the quiz question, answer, if the user has enabled the question, and if the question has already been asked during the quiz session.</p> <p>During a quiz session I wish to ask all questions that are enabled and haven't been asked yet. My script works but I am concerned it is inefficient (with a bank of 1000+ questions)? Is it alright to store user data with my quiz questions? Will this make adding additional questions down the road more difficult? Can I improve what I have or should I look for a different approach?</p> <p>My script: JS Bin: <a href="http://jsbin.com/owehix/1/edit" rel="nofollow">http://jsbin.com/owehix/1/edit</a></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script&gt; window.onload = function() { ///////////////////////////////////////////////// // CREATE SAMPLE QUIZ ARRAY TO USE IN EXAMPLE // ///////////////////////////////////////////////// // Quiz constructor function quizConstructor(question, answer, enabled, asked) { this.question = question; this.answer = answer; this.enabled = enabled; this.asked = asked; } // Create quiz array var quiz = new Array(); // All quiz questions and answers quiz[0] = new quizConstructor("Montgomery", "Alabama", false, 0); quiz[1] = new quizConstructor("Juneau", "Alaska", true, 0); quiz[2] = new quizConstructor("Phoenix", "Arizona", true, 0); quiz[3] = new quizConstructor("Little Rock", "Arkansas", false, 0); quiz[4] = new quizConstructor("Sacramento", "California", true, 0); quiz[5] = new quizConstructor("Denver", "Colorado", false, 0); quiz[6] = new quizConstructor("Hartford", "Connecticut", false, 0); quiz[7] = new quizConstructor("Dover", "Delaware", false, 0); quiz[8] = new quizConstructor("Tallahassee", "Florida", false, 0); quiz[9] = new quizConstructor("Atlanta", "Georgia", true, 0); ///////////////////////////////////////////////// // END: CREATE SAMPLE QUIZ ARRAY TO USE IN EXAMPLE // ///////////////////////////////////////////////// // Find the number of questions that the user has enabled var numEnabled = 0; for (var i = 0; i &lt; quiz.length; i++) { if (quiz[i].enabled == true) { numEnabled++; } } // Ask all enabled questions in random order for (var i = 0; i &lt; numEnabled; i++) { // Find random question that hasn't been asked yet do { var randomNum = Math.floor(Math.random() * quiz.length); } while (quiz[randomNum].enabled == false || quiz[randomNum].asked == 1); // Ask question var question = quiz[randomNum].question + " is the capital of which state?"; document.getElementById("divSolution").innerHTML += "&lt;p&gt;" + question + "&lt;/p&gt;"; // Mark question as asked quiz[randomNum].asked++; } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="divSolution"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>How you're making the questions really looks ugly. How about this way?</p>\n\n<pre><code>var quiz = [{\n question: \"Montgomery\",\n answer: \"Alabama\",\n enabled: false,\n asked: 0\n},{\n question: \"Juneau\",\n answer: \"Alaska\",\n enabled: true,\n asked: 0\n}, {} /* ... */ ];\n\n// Now instantiate every quiz\nquiz = quiz.map(function(el) {\n return new quizConstructor(el.question, el.answer, el.enabled, el.asked);\n});\n</code></pre>\n\n<p>Now if you're not doing anything more with your <code>quizConstructor</code> object, you can just as well use plain objects. (What's done before instantiating every quiz up there.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T07:51:31.800", "Id": "20533", "ParentId": "20532", "Score": "1" } }, { "body": "<pre><code> do {\n\n var randomNum = Math.floor(Math.random() * quiz.length);\n\n } while (quiz[randomNum].enabled == false || quiz[randomNum].asked == 1);\n</code></pre>\n\n<p>Instead of repeating until finding a question asked exactly once,\nkeep a set of questions to be asked\nand remove questions that won't be asked anymore from that set.\nWith more than 1000 questions above loop will run ~700 times for the last question.\nAnd in 1% of the occasions that loop will run ~4600 times for the last question.\nYour users may or may not notice the performance difference but it's just wasteful.</p>\n\n<p>Keeping a set of questions to be asked also makes the criteria used for deciding which questions asked anymore more configurable, modifiable. Imagine what would you change if you would ask every question twice or keep asking questions until they were answered correctly thrice in a row, etc.</p>\n\n<p>Moreover, since US only has 50 states and a handful of territories, and you plan to have a collection of 1000 questions, this part should be somewhere else:</p>\n\n<pre><code> var question = quiz[randomNum].question + \" is the capital of which state?\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T08:37:13.743", "Id": "20534", "ParentId": "20532", "Score": "1" } }, { "body": "<p>For adaptability I would set up a Quiz class that can ask any question, not just one about state capitals, then have another object or function that makes questions specifically about state capitals. Also, you can attach a method to the Quiz class so each question can 'ask' itself; you will probably want to add another method that also checks the user's answer.</p>\n\n<p>A more efficient way to get all the enabled questions in random order is to make an array of the enabled questions (<code>enabled</code>) then <code>splice</code> a random element from <code>enabled</code> until it is empty. (In fact, in the code below, the array <code>quiz</code> is not used at all, only <code>enabled</code>. Maybe you want to do something later with the non-enabled questions?)</p>\n\n<p>(<a href=\"http://jsfiddle.net/F5dLf/1/\" rel=\"nofollow\">JSFiddle</a> for the code below and <a href=\"http://jsfiddle.net/F5dLf/3/\" rel=\"nofollow\">another one</a> using prototypes to set up StateQuiz as a class).</p>\n\n<pre><code>function Quiz(question, answer, enabled, asked) {\n this.question = question;\n this.answer = answer;\n this.enabled = enabled == false ? false : true;\n this.asked = asked ? asked : 0;\n}\nQuiz.prototype.ask = function () {\n document.getElementById(\"divSolution\").innerHTML += \"&lt;p&gt;\" + this.question + \"&lt;/p&gt;\";\n this.asked++;\n}\nfunction stateQuiz(capital, state, enabled) {\n return new Quiz(capital + ' is the capital of which state?', state, enabled);\n}\n\n// Create quiz array\nvar question, \n quiz = [],\n enabled = [],\n stateCapitals = [\n ['Montgomery', 'Alabama', false],\n ['Juneau', 'Alaska', true],\n ['Phoenix', 'Arizona', true],\n ['Little Rock', 'Arkansas', false],\n [\"Sacramento\", \"California\", true],\n [\"Denver\", \"Colorado\", false],\n [\"Hartford\", \"Connecticut\", false],\n [\"Dover\", \"Delaware\", false],\n [\"Tallahassee\", \"Florida\", false],\n [\"Atlanta\", \"Georgia\", true]\n ];\n\nfor (var i = 0; i &lt; stateCapitals.length; i++) {\n question = stateQuiz(stateCapitals[i][0], stateCapitals[i][1], stateCapitals[i][2]);\n quiz.push(question);\n if (question.enabled) enabled.push(question);\n}\n// Ask all enabled questions in random order\nwhile (enabled.length) {\n // splice removes an element from the array and returns the removed element\n question = enabled.splice(Math.floor(Math.random() * enabled.length), 1)[0];\n question.ask();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:01:00.623", "Id": "20544", "ParentId": "20532", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T06:31:04.903", "Id": "20532", "Score": "1", "Tags": [ "javascript" ], "Title": "Using an Array of Objects to Store Quiz Questions/Answers" }
20532
<p>I define in the Settings Tab of a VB.Net class library some user scoped settings. I want to expose these settings to other projects that reference the class library. I chose to do this using a public Module. This works, but it requires exposing each and every setting manually. Is there a better way?</p> <pre><code>Public Module Settings Public Property SomeSetting As Integer Get Return My.Settings.SomeSetting End Get Set(value As Integer) My.Settings.SomeSetting = value My.Settings.Save() End Set End Property End Module </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:09:51.100", "Id": "32898", "Score": "2", "body": "You *could* expose the `Settings` module wholesale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:28:08.830", "Id": "32901", "Score": "0", "body": "@KonradRudolph Can you elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:47:54.097", "Id": "32902", "Score": "1", "body": "Just have a (read-only) property which returns the `My.Settings` object (no setter required)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T01:00:11.953", "Id": "57204", "Score": "0", "body": "If you're going to expose getters *and* setters, you might as well make the settings `public`, no?" } ]
[ { "body": "<p>I think it's a fairly verbose way of exposing app settings. How about this?</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ukvaw.png\" alt=\"enter image description here\"></p>\n\n<p><sub>(taken from an answer on <a href=\"https://stackoverflow.com/questions/11873656/how-to-make-application-properties-settings-public-and-stay-that-way\">this SO question</a>)</sub></p>\n\n<p>This essentially comes down to what @KonradRudolph's comment was saying - the reason you \"need\" your <code>Settings</code> module is <em>probably</em> because the settings' access modifier is set to <code>Internal</code>, which means it's not accessible to other assemblies.</p>\n\n<p>If you need to expose app settings to other assemblies, you just change that access modifier to <code>Public</code> and you're done.</p>\n\n<p>Doing this:</p>\n\n<pre><code>Public Module Settings\n Public Property AppSettings As Settings\n Get\n Return My.Settings\n End Get\n End Property\nEnd Module\n</code></pre>\n\n<p>Is then totally redundant. Even more so, doing what you've done (exposing each setting individually) becomes more painful to maintain than it needs to be; if the settings are public then you expose the settings class itself and whatever you change is immediately available to client assemblies.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:15:49.780", "Id": "35657", "ParentId": "20537", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T09:48:34.590", "Id": "20537", "Score": "3", "Tags": [ "vb.net" ], "Title": "Is this the correct way to expose a setting for a vb.net class library?" }
20537
<p>I have developed a new router after having learnt a lot from my previous attempts and I will be using this in sites I make from now on.</p> <p>In a previous question, the issue of <code>REQUEST_URI</code> being too inflexible made me wonder if I could make adjustments to allow it to route <code>$_POST</code> and <code>$_GET</code> requests too?</p> <p>Please let me know what you think and how it could be improved as I am still learning:</p> <p> <pre><code>class Router { public $offset = 9 ; // Adjust according to subdir length. public $start_page = 'Index' ; // Change to your home/default page. private $classAliases = array( 'pretty-url' =&gt; 'UglyClassName', ) ; private $methodAliases = array( 'pretty-method' =&gt; 'uglyMethodName', ) ; function __construct() { $url = substr(rtrim($_SERVER['REQUEST_URI'], '/'), $this-&gt;offset) ; $command = explode('/', $url, 3) ; if(isset($command[0])) { $class = ucfirst($this-&gt;autoMap($command[0]), $this-&gt;classAliases) ; } if(class_exists($class) &amp;&amp; preg_match('/[^A-Za-z0-9]/', $class) == false) { $controller = new $class ; if($method = (isset($command[1]) ? $command[1] : NULL)) { $method = (strstr($method, '?') ? substr($url, 0, strrpos($method, '?')) : $method) ; $method = $this-&gt;autoMap($method, $this-&gt;methodAliases) ; if(method_exists($class, $method) &amp;&amp; preg_match('/[^A-Za-z0-9]/', $method) == false) { $params = array() ; if(stristr($url, '?')) // Parameters passed the conventional way... { $queryString = substr($url, strrpos($url, '?')+1) ; parse_str($queryString, $params) ; } elseif(isset($command[2])) // ...or the clean URL way. { $params = explode('/', $command[2]) ; } call_user_func_array(array($controller, $method), $params) ; } elseif($method) { $this-&gt;throwError('Method '.$method.' does not exist.') ; } } else { // Default index method. if(method_exists($class, 'index')) { $controller-&gt;index() ; } else { $this-&gt;throwError('Class '.$class.' has no index method.') ; } } } elseif(!$class) { $controller = new $this-&gt;start_page ; $controller-&gt;index() ; } else { $this-&gt;throwError('Class '.$class.' does not exist.') ; } } private function throwError($e) { if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) // Ajax request... { echo $e ; } else { // ...or normal request. new Error($e) ; } } private function autoMap($alias, $routes) { if(array_key_exists($alias, $routes)) { return $routes[$alias] ; } return $alias ; } } </code></pre>
[]
[ { "body": "<p>Where you have:</p>\n\n<blockquote>\n<pre><code>$class = ucfirst($this-&gt;autoMap($command[0]), $this-&gt;classAliases);\n</code></pre>\n</blockquote>\n\n<p>I think it should be:</p>\n\n<pre><code>$class = ucfirst($this-&gt;autoMap($command[0], $this-&gt;classAliases));\n</code></pre>\n\n<p>The closing <code>)</code> is in the wrong place.</p>\n\n<p>Besides that I like your router, maybe it would be even better if it had a module control (so you could have something like: module/controller/method). This way you can have separated modules for admin, debug, default, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T16:26:23.863", "Id": "28169", "ParentId": "20539", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T12:16:22.610", "Id": "20539", "Score": "2", "Tags": [ "php", "object-oriented", "mvc", "url-routing" ], "Title": "Good, flexible and secure MVC router PHP" }
20539
<p>I recently created an extension which detects the type of credit card based on the numbers entered in and formats it. I am using Luhn Algorithm for validating credit card numbers and I am using jQuery masking for formatting the credit card numbers (for reference: jquery.maskedinput-1.3.min).</p> <p>You can play with the demo <a href="http://frontendprojects.com/monkdetect/" rel="nofollow noreferrer">here</a>.</p> <p>How can I make this extensive? What should I be thinking about and what might not be so good in my current code?</p> <pre><code>jQuery(function($) { // hiding the status as the user focuses on the credit card input field $('.card input').bind('focus', function() { $("#ccard_number").unmask();//unmasking the text field as user starts typing $('.card .status').hide(); }); // showing the status when the user tabs or clicks away from the credit card input field $('.card input').bind('blur', function() { $('.card .status').show(); }); // checking input value entered using jquery.cardchecker $('.card input').cardchecker({ callback: function(result) { var status = (result.validLen &amp;&amp; result.validLuhn) ? 'valid' : 'invalid', message = '', types = '', i; // Getting the names of all accepted card types. for (i in result.option.types) { types += result.option.types[i].name + ", "; } types = types.substring(0, types.length-2); // Set the status message if (result.len &lt; 1) { message = 'Please enter a credit card number.'; } else if (!result.cardClass) { message = 'We accept the following card types: ' + types + '.'; } else if (!result.validLen) { message = 'It appears to be wrong number of digit. Please check that this number matches your "' + result.cardName + '" card'; } else if (!result.validLuhn) { message = 'Did you mistype a digit as this number matches your "' + result.cardName + '" card '; } else { message = 'It looks like a valid ' + result.cardName + '.'; if ( result.validLen ) { if ( result.cardName === 'Visa' ) { //if the card is Visa $("#ccard_number").mask("9999-9999-9999-9?999"); } if ( result.cardName === 'American Express' ) { //if the card is American Express $("#ccard_number").mask("999-999999-999999"); } if ( result.cardName === 'MasterCard' ) { //if the card is MasterCard $("#ccard_number").mask("9999-9999-9999-9999"); } if ( result.cardName === 'Discover' ) { //if the card is Discover $("#ccard_number").mask("9999-9999-9999-9999"); } if ( result.cardName === 'JCB' ) { //if the card is JCB $("#ccard_number").mask("9999-9999-9999-9999"); } if ( result.cardName === 'Diners Club' ) { //if the card is Diners Club $("#ccard_number").mask("999-999999-99999"); } } } // Show credit card icon $('.card .card_icon').removeClass().addClass('card_icon ' + result.cardClass); // Show status message $('.card .status').removeClass('invalid valid').addClass(status).children('.status_message').text(message); } }); }); /* * function for validating and formatting credit cards */ (function($, window, document) { var defaultvalue; // Plugin Core $.cardchecker = function(option) { var ccard = defaultvalue.types || [], num = (typeof option === "string") ? option : option.num, len = num.length, type, validLen = false, validLuhn = false; // Get matched type based on credit card number $.each(ccard, function(index, card) { if (card.checkType(num)) { type = index; return false; } }); // If number, ccard, and a matched type if (num &amp;&amp; ccard &amp;&amp; ccard[type]) { // Check card length validLen = ccard[type].checkLength(len); // Check Luhn Algorithm validLuhn = defaultvalue.checkLuhn(num); } return { type: type, validLen: validLen, validLuhn: validLuhn }; }; // Plugin Helper $.fn.cardchecker = function(option) { // Allow for just a callback to be provided or extend method that merges the contents of two or more objects, storing the result in the first object. if (option &amp;&amp; $.isFunction(option)) { var _option = $({}, defaultvalue); _option.callback = option; option = _option; } else { option = $.extend({}, defaultvalue, option); } // Fire on keyup return this.bind('keyup', function() { var ccard = option.types || {}, num = this.value.replace(/\D+/g, ''), // strip all non-digits name = '', className = '', // Check card check = $.cardchecker({ num: num }); // Assign className based on matched type if (typeof check.type === "number") { name = ccard[check.type].name; className = ccard[check.type].className; } // Invoke callback option.callback.call(this, { num: num, len: num.length, cardName: name, cardClass: className, validLen: check.validLen, validLuhn: check.validLuhn, option: option }); }); }; // Plugin Options defaultvalue = $.fn.cardchecker.option = { checkLuhn: function(num) { // http://en.wikipedia.org/wiki/Luhn_algorithm var len = num.length, total = 0, i; if (!num || !len) { return false; } num = num.split('').reverse(); for (i = 0; i &lt; len; i++) { num[i] = window.parseInt(num[i], 10); total += i % 2 ? 2 * num[i] - (num[i] &gt; 4 ? 9 : 0) : num[i]; } return total % 10 === 0; }, // http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers types: [ { name: 'Visa', className: 'visa', checkType: function(num) { return num.charAt(0) === '4'; }, checkLength: function(len) { return len === 13 || len === 16; } }, { name: 'American Express', className: 'amex', checkType: function(num) { return num.substr(0, 2) === '34' || num.substr(0, 2) === '37'; }, checkLength: function(len) { return len === 15; } }, { name: 'MasterCard', className: 'mastercard', checkType: function(num) { if (num.charAt(0) === '5') { return num.charAt(1) &gt;= 1 &amp;&amp; num.charAt(1) &lt;= 5; } return false; }, checkLength: function(len) { return len === 16; } }, { name: 'Discover', className: 'discover', checkType: function(num) { if (num.charAt(0) === '6') { return num.substr(0, 2) === '65' || num.substr(0, 4) === '6011' || num.substr(0, 3) === '644' || (num.substr(0, 1) === '6' &amp;&amp; parseInt(num, 10) &gt;= '622126' &amp;&amp; parseInt(num, 10) &lt;= '622925'); } return false; }, checkLength: function(len) { return len === 16; } }, { name: 'JCB', className: 'jcb', checkType: function(num) { return num.substr(0, 2) === '35'; }, checkLength: function(len) { return len === 16; } }, { name: 'Diners Club', className: 'diners', checkType: function(num) { return num.substr(0, 2) === '36' || num.substr(0, 2) === '38'; }, checkLength: function(len) { return len === 14; } } ], callback: $.noop }; })(jQuery, window, document ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:08:07.750", "Id": "32906", "Score": "6", "body": "Why re-invent the wheel? http://paweldecowski.github.com/jQuery-CreditCardValidator/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:33:06.023", "Id": "32909", "Score": "0", "body": "yes, I am aware about this. I want to extend it by formatting the credit card numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-26T13:30:41.223", "Id": "96949", "Score": "2", "body": "The first thing that popped into my head in regards to \"extending\" it: localization. What if you want other messages? What if you want multiple languages?" } ]
[ { "body": "<p>One thing that comes to mind is you could remove many lines of code by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\" rel=\"nofollow\">regular expressions</a>:</p>\n\n<pre><code>name: 'Visa',\n className: 'visa',\n checkPattern: /^4\\d{12}\\d{3}?$/\n</code></pre>\n\n<p>This means:</p>\n\n<ul>\n<li>/ beginning of the search pattern, required by JavaScript.</li>\n<li>^ don't match if there's anything before this pattern.</li>\n<li>4 literal number 4</li>\n<li>\\d{12} exactly 12 digits</li>\n<li>\\d{3}? optionally followed by another 3 digits</li>\n<li>$ don't match if there's anything after this pattern.</li>\n<li>/ end of the search pattern, required by JavaScript.</li>\n</ul>\n\n<p>Using regular expressions would allow you to replace <code>checkLength</code> and <code>checkType</code> with a single method.</p>\n\n<p><strong>Edit:</strong> cleaned up regex, thanks to @Schism.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T05:10:13.270", "Id": "99306", "Score": "2", "body": "`\\d` exists, so why not use it instead of `[0-9]`? The capturing group is also not needed. The regex could be written as `^4\\d{12}\\d{3}?$`. Plus, I question using a string when Javascript has built-in regex support; something like `checkPattern: /^4\\d{12}\\d{3}?$/` might be nicer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-09T00:23:40.780", "Id": "99551", "Score": "0", "body": "Thanks - I don't know THAT much regex stuff. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T01:52:50.647", "Id": "56394", "ParentId": "20543", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T13:44:39.977", "Id": "20543", "Score": "8", "Tags": [ "javascript", "beginner", "jquery", "validation", "finance" ], "Title": "Validating a credit card" }
20543
<p>I have moved all my web-server code dealing with user management into a single Node.js module that I pasted below. I have spent time polishing it, and churned it through JSHint. I am generally happy with the code, except for the error handling. I find it clunky at best.</p> <p>How can I improve error handling in the following code? Are there design or API guidelines I have not followed?</p> <pre><code>// ??? // Deal with the case where an admin no longer has admin rights, but still has a session open var server = require('./server.js').server; var User = require('./database.js').User; // Define the user API var API = { list: [list, 'private'], login: [login, 'public'], logout: [logout, 'private'], add: [add, 'admin'], remove: [remove, 'admin'], edit: [edit, 'admin'] }; // Attach path handlers for(var label in API) { var denied = 'Permission denied'; var wrapper = (function (label) { return function (req, res) { var callback = API[label][0]; var permission = API[label][1]; if(!req.session) { if(permission !== 'public') { res.send(denied); return; } } else if((permission === 'admin') &amp;&amp; (req.session.rights !== 'Administrator')) { res.send(denied); return; } callback(req, res); }; }(label)); server.post('/user/' + label, wrapper); } function list(req, res) { User.find({}, null, {sort: {username: 1}}, function (err, users) { res.send(users); }); } function login(req, res) { var errorMessage = 'Invalid user/password combination'; find(req.body.username, function(err, user) { if(printError(err)) { return; } // Check we have a user if(!user) { res.send(errorMessage); return; } // Check for a username/password match user.comparePassword(req.body.password, function(err, isMatch) { if(printError(err)) { return; } if(isMatch) { // Populate the session cookie req.session.username = user.username; req.session.rights = user.rights; res.send('OK'); } else { res.send(errorMessage); } }); }); } function logout(req, res) { // Clear session req.session.username = undefined; req.session.rights = undefined; res.send('OK'); } function add(req, res) { find(req.body.username, function (err, user) { if(user) { res.send('The user already exists'); } else { new User(req.body).save(function (err) { if(printError(err)) { return; } res.send('OK'); }); } }); } function remove(req, res) { find(req.body.username, function (err, user) { user.remove(function (err) { if(printError(err)) { return; } res.send('OK'); }); }); } function edit(req, res) { find(req.body.username, function (err, user) { if(printError(err)) { return; } // Populate username and rights user.username = req.body.user.username; user.rights = req.body.user.rights; // Only update nonempty passwords if(req.body.user.password !== '') { user.password = req.body.user.password; } user.save(function(err) { if(printError(err)) { return; } res.send('OK'); }); }); } function find(username, callback) { User.findOne({ username: username }, callback); } function printError(err) { if(err) { console.error('ERROR: ', err.message); // console.trace(); } return err; } </code></pre>
[]
[ { "body": "<p>From a once over </p>\n\n<ul>\n<li><p>Not everybody in CR agrees, but I find tabular data best presented in an aligned format:<br></p>\n\n<pre><code>var API = { \n list: [list , 'private'], \n login: [login , 'public' ], \n logout: [logout, 'private'], \n add: [add , 'admin' ], \n remove: [remove, 'admin' ], \n edit: [edit , 'admin' ] \n}; \n</code></pre></li>\n<li><p>For your error handing, I would mention that using <a href=\"http://expressjs.com/\" rel=\"nofollow\">express</a> is very nice for error handling. If you insist on doing it yourself you could do something like </p>\n\n<pre><code>function handle( f ){\n return function( err ){\n if(err){\n console.error('ERROR: ', err.message);\n return;\n }\n f.apply( this , arguments );\n }\n}\n</code></pre>\n\n<p>Then you can </p>\n\n<pre><code>function remove(req, res) {\n find(req.body.username, handle( function (err, user) {\n user.remove( handle( function (err) {\n res.send('OK');\n }));\n }));\n}\n</code></pre></li>\n<li>For your error message constants, I would declare them all together on top</li>\n<li><p>I am ambivalent about using an array for your API config instead of an object, if you keep using that, I would suggest you use named constants declared on top:</p>\n\n<pre><code> var callback = API[label][CALLBACK]; //Where CALLBACK is earlier declared as 0\n var permission = API[label][PERMISSION]; //Where PERMISSION is earlier declared as 1\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T02:40:41.847", "Id": "41442", "ParentId": "20547", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T15:47:17.820", "Id": "20547", "Score": "4", "Tags": [ "javascript", "node.js" ], "Title": "User management in Node.js" }
20547
<p>I'm tasked with getting emails from a .csv file and using them to submit a form. I am using the csv and mechanize Python libraries to achieve this.</p> <pre><code>import re import mechanize import csv def auto_email(email): br = mechanize.Browser() br.open("URL") br.select_form(name="vote_session") br['email_add'] = '%s' % (email) #email address br.submit() def csv_emails(): ifile = open('emails.csv', "rb") reader = csv.reader(ifile) rownum = 1 for row in reader: auto_email(row[0]) print "%d - %s processed" %(rownum, row[0]) rownum += 1 print 'List processed. You are done.' ifile.close() print csv_emails() </code></pre> <p>The code works, but I am very much a beginner in Python.</p> <p>I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?</p>
[]
[ { "body": "<p>I would suggest to use</p>\n\n<pre><code>with open('emails.csv', \"rb\") as ifile\n</code></pre>\n\n<p>see here for details: <a href=\"http://www.python.org/dev/peps/pep-0343/\">http://www.python.org/dev/peps/pep-0343/</a>\nin this case you don't need to do <code>ifile.close</code> at the end</p>\n\n<p>instead of incrementing rownum by yourself, you can use</p>\n\n<pre><code>for row, rownum in enumerate(reader):\n</code></pre>\n\n<p>I don't see the reason to do this</p>\n\n<pre><code>br['email_add'] = '%s' % (email) #email address\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>br['email_add'] = email\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:03:04.940", "Id": "32921", "Score": "0", "body": "`email` comes from a row returned by `csv.reader` so it's always a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:04:55.650", "Id": "32922", "Score": "0", "body": "so in this case `br['email_add'] = email` is enough. I edited my answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:01:27.540", "Id": "20549", "ParentId": "20548", "Score": "6" } }, { "body": "<p><code>print csv_emails()</code> doesn't make sense. Since <code>csv_emails()</code> returns no value, there is nothing to print.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-06T02:38:43.857", "Id": "52566", "ParentId": "20548", "Score": "0" } } ]
{ "AcceptedAnswerId": "20549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:16:16.327", "Id": "20548", "Score": "3", "Tags": [ "python", "beginner", "python-2.x", "csv", "email" ], "Title": "CSV email script efficiency" }
20548
<p>Below are some of the classes I have written for a small space invaders game. It's not finished but it's at the bare bones stage. I am still learning how to properly use the Slick2D library. I know where there are some problems but that is due to my lack of full knowledge of how Slick2D works, so I had to think of a workaround for the time being.</p> <p>I have only created this code so you can all check it out and tell me where I am going wrong and what I am doing right. I'd also like some feedback on the code in general, such as if it is clean, if it is organized, if the naming conventions for methods and variables helpful, and other things like that. I don't know if I am a good programmer or not so hopefully this may shine some light on the situation.</p> <p><strong>Entity class</strong></p> <pre><code>package com.emeraldzonegames.jinvaders.entities; import java.awt.Rectangle; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Image; import org.newdawn.slick.Graphics; public abstract class Entity { public Image entityImage; public int x, y, width, height,speed; public Rectangle entityRect; /** * Method that loads an image for each entity * @param imageName */ public void loadImage(String imageName) { try { entityImage = new Image("Assets/Graphics/"+imageName+".png"); } catch(Exception e) { e.printStackTrace(); } } //Getters and setters public void setPosition(int x, int y) { this.x = x; this.y = y; } public void setDimenseions(int width, int height) { this.width = width; this.height = height; } public void setSpeed(int speed) { this.speed = speed; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public int getSpeed() { return speed; } public Image getImage() { return entityImage; } /** * Creates a rectangle for the entity */ public void createRectangle() { entityRect = new Rectangle(getX(),getY(), getWidth(), getHeight()); } /** * Method to carry out logic if input is required * @param gc * @param deltaTime */ public void entityLogic(GameContainer gc,int deltaTime){} /** * Method to render objects to the screen * @param g */ public void renderEntity(Graphics g){} } </code></pre> <p><strong>Player class</strong>.</p> <pre><code>package com.emeraldzonegames.jinvaders.entities; import java.util.ArrayList; import org.newdawn.slick.Input; import org.newdawn.slick.Graphics; import org.newdawn.slick.GameContainer; /** * * ClassName: Player.java * ------------------------------------- * Description: The purpose of this class is to * Define all of the operations that are carried * out by the Player Object * */ public class Player extends Entity { public ArrayList&lt;Bullet&gt; bulletList; private boolean firing; private final String ENTITY_ID = "ship"; public Player() { bulletList = new ArrayList&lt;Bullet&gt;(); this.setImage(ENTITY_ID); this.setPosition(350,450); this.setDimenseions(100, 100); this.setSpeed(5); this.createRectangle(); } @Override public void entityLogic(GameContainer gc, int deltaTime) { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_A)) { this.x -= speed; this.entityRect.x -= speed; } if(input.isKeyDown(Input.KEY_D)) { this.x += speed; this.entityRect.x -= speed; } if(input.isKeyDown(Input.KEY_W)) { this.y -= speed; this.entityRect.y -= speed; } if(input.isKeyDown(Input.KEY_S)) { this.y += speed; this.entityRect.y += speed; } if(input.isKeyPressed(Input.KEY_SPACE)) { firing = true; addToList(); } checkBounds(); fireBullet(); destroyBullets(); } @Override public void renderEntity(Graphics g) { g.drawImage(this.getImage(), this.getX(), this.getY()); if(firing) { for(Bullet b : bulletList) { b.renderEntity(g); } } if(com.emeraldzonegames.jinvaders.main.JInvadersGame.debugModeEnabled) { g.drawRect(x, y, width, height); } } /** * Populates the arrayList with instances of the bullet object */ private void addToList() { Bullet bullet = new Bullet(this.x+40,this.y); bulletList.add(bullet); } /** * Moves the bullet when player is firing */ private void fireBullet() { if(firing) { for(Bullet b:bulletList) { b.moveBullet(); } } } /** * Destroys intances of the bullet once the bullet goes out of it's bounds */ private void destroyBullets() { for(int i = 0; i &lt; bulletList.size(); ++i) { Bullet bullet = bulletList.get(i); if(bullet.y &lt;= 0) { bulletList.remove(i); i--; } } } /** * Method to check if the player is on the screen at all times */ private void checkBounds() { if( this.x &gt; 720) { this.x = 720; } if( this.x &lt; 0) { this.x = 0; } if( this.y &gt; 450) { this.y = 450; } } } </code></pre> <p><strong>Bullet</strong></p> <pre><code>package com.emeraldzonegames.jinvaders.entities; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; public class Bullet extends Entity { private final String ENTITY_ID = "bullet"; public Bullet(int x , int y) { this.x = x; this.y = y; this.loadImage(ENTITY_ID); this.setDimenseions(15, 15); this.createRectangle(); } /** * Moves the bullet up the Y-Axis */ public void moveBullet() { this.setSpeed(3); this.y -= speed; this.entityRect.y -= speed; } @Override public void entityLogic(GameContainer gc, int deltaTime){} @Override public void renderEntity(Graphics g) { g.drawImage(this.getImage(), this.getX(), this.getY()); if(com.emeraldzonegames.jinvaders.main.JInvadersGame.debugModeEnabled) { g.drawRect(x, y, width, height); } } } </code></pre> <p><strong>Enemy</strong></p> <pre><code>package com.emeraldzonegames.jinvaders.entities; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; public class Enemy extends Entity { private final String ENTITY_ID = "testEnemy"; private final int CREATED = 1; private final int HIT_LEFT_WALL = 2; private final int HIT_RIGHT_WALL = 3; public int currentState; public Enemy(int x, int y) { this.x = x; this.y = y; this.speed = 3; this.currentState = CREATED; this.setDimenseions(40,35); this.loadImage(ENTITY_ID); this.createRectangle(); } @Override public void entityLogic(GameContainer gc, int deltaTime) { //TODO add enemy logic /*if(this.x &lt; 0) { currentState = HIT_LEFT_WALL; moveDown(); } if(this.x &gt; 720) { currentState = HIT_RIGHT_WALL; moveDown(); } switch(currentState) { case 1: moveLeft(); break; case 2: moveRight(); break; case 3: moveLeft(); break; }*/ } /*private void moveLeft() { this.x -= speed; this.entityRect.x -= speed; } private void moveRight() { this.x += speed; this.entityRect.x += speed; } private void moveDown() { this.y = y+10; this.entityRect.y = entityRect.y+10; }*/ @Override public void renderEntity(Graphics g) { g.drawImage(this.getImage(), x, y); if(com.emeraldzonegames.jinvaders.main.JInvadersGame.debugModeEnabled) { g.drawRect(x, y, width, height); } } } </code></pre> <p><strong>Main Game Class</strong></p> <pre><code>package com.emeraldzonegames.jinvaders.main; import java.util.ArrayList; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.Image; import org.newdawn.slick.Graphics; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import org.newdawn.slick.AppGameContainer; import com.emeraldzonegames.jinvaders.entities.Player; import com.emeraldzonegames.jinvaders.entities.Enemy; import com.emeraldzonegames.jinvaders.entities.Bullet; /** * * ClassName: JInvadersGame * ------------------------------------- * Description: The purpose of this class is to * create all of the assets and display them on screen * carry out logic if required * */ public class JInvadersGame extends BasicGame { private Player player; private ArrayList&lt;Enemy&gt; enemyList; private Music backgroundSong; private Image background; public static boolean debugModeEnabled = false; public JInvadersGame(String title) { super(title); } /** * Slick2D Method initialise components */ @Override public void init(GameContainer gc) throws SlickException { player = new Player(); enemyList = new ArrayList&lt;Enemy&gt;(); backgroundSong = new Music("Assets/Audio/DST-2ndBallad.ogg"); background = new Image("Assets/Graphics/background.jpg"); backgroundSong.loop(); //Creates the enemies createEnemies(10,3); } /** * Slick2D Method rendering */ @Override public void render(GameContainer gc, Graphics g) throws SlickException { g.drawImage(background, 0, 0); player.renderEntity(g); for(Enemy e : enemyList) { e.renderEntity(g); } } /** * Slick2D Method game loop */ @Override public void update(GameContainer gc, int deltaTime) throws SlickException { if(debugModeEnabled == false &amp;&amp; gc.getInput().isKeyPressed(Input.KEY_GRAVE)) { debugModeEnabled = true; } else if(debugModeEnabled == true &amp;&amp; gc.getInput().isKeyPressed(Input.KEY_GRAVE)) { debugModeEnabled = false; } player.entityLogic(gc,deltaTime); for(Enemy e : enemyList) { e.entityLogic(gc, deltaTime); } checkCollisions(); } /** * Creates a grid of enemies */ private void createEnemies(int row, int col) { for(int i = 1; i &lt;= row; i++) { for(int j = 1; j &lt;= col; j++) { Enemy enemy = new Enemy(i*50, j*50); enemyList.add(enemy); } } System.out.println(enemyList.size()); } /** * Check for collisions */ private void checkCollisions() { //Get the rectangles from each bullet and enemy from the respective ArralyLists for(int i = 0; i &lt; player.bulletList.size(); ++i) { Bullet b = player.bulletList.get(i); for(int j = 0; j &lt; enemyList.size(); ++j) { Enemy e = enemyList.get(j); //If a bullets rectangle connects with an enemies remove both objects from their lists if(b.entityRect.intersects(e.entityRect)) { player.bulletList.remove(i); enemyList.remove(j); i--; j--; } } } } public static void main(String[] args) { try { AppGameContainer jinvaders = new AppGameContainer(new JInvadersGame("EmeraldZoneGames - JInvaders")); jinvaders.setDisplayMode(800, 600, false); jinvaders.setVSync(true); jinvaders.setShowFPS(false); jinvaders.start(); } catch(SlickException se) { se.printStackTrace(); } } } </code></pre>
[]
[ { "body": "<p>Caveat: I am not a Java programmer. I am an ActionScript programmer. The two languages are somewhat related, and basic design principles should carry across.</p>\n\n<p>At first glance, I don't see anything that would scare me away from hiring you if it were my decision. I would say that most of this code is better/cleaner than code I have seen from Computer Science graduates who have been programming 10 or more years.</p>\n\n<p>So, what follows are just some observations that I have after 15 years or so of developing in AS + a few other languages.</p>\n\n<ol>\n<li>Your <code>Entity</code> looks to me like an Abstract Class. Doesn't Java have formal support for these? You may or may not get brownie points for making this an Abstract Class.</li>\n<li><code>setDimenseions</code>--typo. Your IDE is clearly helping you here, but if you are using this for portfolio code, why make mistakes you don't need to make?</li>\n<li>Your <code>entityLogic</code> method is getting information it doesn't need. Your <code>Player</code> Entity is the only one where you've fully fleshed out and used this method, and all you need there is the input, not the full <code>GameContainer</code>. If you need the full GameContainer, why not store it, rather than pushing it in every loop? I think at some level you realize how bad this is, since you're completely ignoring the method on <code>Bullet</code>. Yes, I know you built this off Slick2D's example code, but if Slick2D jumped off a cliff, would you?</li>\n<li>Having <code>renderEntity</code> on Entity violates <a href=\"http://codebetter.com/karlseguin/2008/12/05/get-solid-single-responsibility-principle/\">Single Responsibility Principle</a> IMO. This Class reads more to me like a Value Object than a View Object, so it should <em>not</em> be performing View type activities. Again, you've followed less than stellar example code. Instead, just have your Main Class do something like <code>g.drawImage(e.getImage(), e.getX(), e.getY())</code>, or you could even have an <code>EntityGraphics</code> Class that can take an entity and draw it. Either of these solutions handily eliminates the unneccessary dependency both on <code>Graphics</code> and that <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/\">horrible</a> static <code>debugMode</code> throughout the Entity inheritance chain.</li>\n<li>In <code>Entity</code>, sometimes you refer internally to the private storage variables, and sometimes you call the \"getters.\" Why?</li>\n<li>If you can't come up with a more descriptive JavaDoc comment for Player than what you used, you're probably better off leaving it off. We all know what Classes are for.</li>\n<li>I'd go with a constructor argument for the image name, rather than a static constant in your Entity SubClasses. What if you want a Player that's a submarine? Consider this idea for the other values you're coming up with \"out of thin air\" in the constructor.</li>\n<li>As I said, I see your <code>Entity</code> more as a VO, so <code>Player</code> shouldn't be responsible for creating its own bullets. What if you wanted to have more than one <code>Player</code>, with a global <a href=\"http://mindprod.com/jgloss/objectpooling.html\">Object Pool</a> of <code>Bullets</code> that recycles when they are taken off screen? I think you need to think a bit more about who should be responsible for what, where the Bullets are concerned. You have a mish-mash where some of it is handled by the Player and some of it is handled by the Main game, yet <em>none</em> of it goes through the \"official\" channel Entity should use for updating itself, <code>entityLogic</code>. Since your Main Class <em>already</em> concerns itself with looping through the Bullets, I'd probably relegate Player to simply storing the list of Bullets, and allow Main or some new Class to handle that.</li>\n<li><code>Enemy</code>--all that commented out code implies you're not a confident user of version control. Either fix it or take it out.</li>\n<li>All those try/catch statements. Is there something specific that you expect could cause an error here? If so, test for that and fix it if possible (for example, null values).</li>\n</ol>\n\n<p>Keep in mind, these are the type of suggestions I would offer to a very experienced developer, if I thought he/she was open to hearing it. I suspect that for most jobs, especially entry-level jobs, these points would be completely irrelevant. Note that if you take my suggestions that would have you deviating from the Slick2D example code, you might wind up shooting yourself in the foot with developers who feel it's better to stick to established norms for a variety of reasons, some of them good.</p>\n\n<p>I think your code shows solid competence, and I wouldn't hesitate to hire you if all the other parts of the interview and hiring process lined up. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:22:44.583", "Id": "32992", "Score": "0", "body": "Thanks for the comments. my initial goal for this game was to have as little logic and rendering code in the main game class as possible. I made a pong clone in the past. The way I did that was by using an abstract entity class and create objects from that, Then in the main game class I wrote all of the logic and rendering code. For this game, I thought that if I tried to keep the logic and rendering to the relevant classes it would make the code more suitable. From the advice given here I will modify the code and upload to GitHub. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T02:08:10.480", "Id": "20565", "ParentId": "20551", "Score": "7" } }, { "body": "<p>First of all, all 10 points made by @Amy Blankenship is valid points as far as I can see.\nMy comments are as follows:</p>\n\n<ol>\n<li><p>These fields should be protected. As a rule, if a field is not <code>final</code> it should not be <code>public</code> also. </p>\n\n<pre><code>public Image entityImage;\npublic int x, y, width, height,speed;\npublic Rectangle entityRect;\n</code></pre></li>\n<li><p><code>x, y, width, height</code> and <code>entityRect</code> contain duplicate information. This duplication complicates your code elsewhere and is a probable source of bugs.</p></li>\n<li><p><code>entityImage</code>,<code>x, y, width, height</code> are dependencies of <code>Entity</code>. That is an <code>Entity</code> is not in a valid state unless all these are supplied. Therefore these should go into the constructor. Since <code>Entity</code> is abstract, its constructor should be protected. Something like this:</p>\n\n<pre><code>protected Entity(Image image, Rectangle rect, int speed)\n</code></pre>\n\n<p>As it is the code betrays your limited Java knowledge/experience. </p></li>\n<li><p>Another rule of thumb: Do not repeat the name of the class in the fields. <code>Entity.entityImage</code> should be <code>Entity.image</code> and <code>Entity.entityRect</code> should be <code>Entity.rect</code></p></li>\n<li><p><code>setPosition(int x, int y)</code> and <code>setDimenseions(int width, int height)</code> are called only from the constructors of its subclasses, therefore they are not needed once you implement <code>protected Entity(Image image, Rectangle rect, int speed)</code>.</p></li>\n<li><p>Rule of thumb: Avoid setters in your core domain objects. Their names are usually meaningless and hide some other message in you domain. For example something like</p>\n\n<pre><code> object.setX(object.getX() - object.sped)\n</code></pre>\n\n<p>hides something like</p>\n\n<pre><code> object.moveLeft()\n</code></pre>\n\n<p>In the case of <code>setSpeed</code>; it is used in <code>moveBullet</code> each time you try to move the bullet because you forgot to supply speed in the constructor of <code>Bullet</code>. If you had created <code>protected Entity(Image image, Rectangle rect, int speed)</code> the compiler would have warned you.</p></li>\n<li><p><code>createRectangle()</code> is called in each of the subclass constructors, and nowhere else. It is a sign that it should go into the super class constructor. doing anything other than an assignment in constructor is suspect. In this case it is related to the duplication in <code>x,y,width,height</code> and <code>entityRectangle</code>. </p></li>\n<li><p><code>entityLogic</code> and <code>renderEntity</code> has empty method body. They could be declared <code>abstract</code>. </p></li>\n<li><p>On <code>Player</code> class <code>entityLogic</code> method does input handling, reads and modifies the states of other classes and only implemented in <code>Player</code> class. These are signs that it does not belong here. It belongs to your Game class. It needs to know all the entities and more suitable place to handle input. This also removes the responsibility of bullets from <code>Player</code> object.</p></li>\n<li><p>Rule of thumb: Method names should describe what the method does, not how it does what it does. Therefore <code>addToList</code> should be <code>addBullet</code>, even <code>fireABullet</code>.</p></li>\n<li><p><code>fireBullet</code> method name is misleading. Name is \"Fire bullet\" but \"moving the bullets if firing\" is what it does. <code>moveBulletsIfFiring</code> <em>could be</em> a better name, at least it allows one to ask \"Why are the bullets are moving only when the player is firing?\"</p>\n\n<pre><code> private void fireBullet() {\n if(firing)\n</code></pre></li>\n<li><p>Repeating of <code>g.drawImage(this.getImage(), this.getX(), this.getY());</code> in all the sub classes of <code>Entity</code> is a sign that this behavior belongs to the <code>Entity</code> class.</p></li>\n<li><p>Hard coded constants are source of problems. They decrease the maintainability of your programs. </p></li>\n<li><p>Checking for negative y coordinate is conspicuously missing in <code>checkBounds</code> method. Also note it does not just <code>check</code>. maybe something like <code>keepPlayerWithinBounds</code>. Name might be verbose but if you had a method like <code>Player.keepWithin(Rectangle rect)</code> than it would be less verbose as well as removing hard coded game are size constants from player class.</p></li>\n<li><p>Loading <code>Bullet</code> image from file each time player fires a bullet is wrong. This is true for all your entities as doing more than field assignment in constructors is a sign something fishy is going on. You can have a look at Object Factory pattern. Or object pooling as described by @Amy Blankenship.</p></li>\n<li><p>Try to use most abstract type you can get away with in declarations. Instead of <code>ArrayList bulletList</code> <code>Collection bullets</code>. This also enables you to ask yourself which implementation I should choose. In your case for example, using <code>HashSet</code> <strong><em>might</em></strong> allow some performance gains.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:09:05.807", "Id": "33039", "Score": "0", "body": "+1 for adding some sort of Factory or Builder in there. In his comments, Crispy talks about wanting to make entities based off his abstract Class. Using a Factory or Builder would allow him to get full leverage out of that idea. One thing I tend to do is have \"shell\" Factory that contains a hash inside it of other Factories, and it calls out the right one based on some condition. So, here, you could have a config section that says what Entities should be built, then loop through and build them all. Player Factory could contain a Bullet factory..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:10:55.433", "Id": "33040", "Score": "0", "body": "And potentially the group of Enemies could be considered an Entity containing the Enemy Entities, much like Bullet and Player work. You could substitute different Enemy Grid factories to create different grid patterns. Or this might be a good use for Strategy Pattern---that's one I only barely \"get.\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T08:42:51.797", "Id": "20573", "ParentId": "20551", "Score": "7" } }, { "body": "<p>These are the first impression I got skimming through your code.</p>\n\n<p><code>Entity</code></p>\n\n<ul>\n<li>Why do you have public fields?</li>\n<li>\"Catching\" an exception by only printing its stack trace is a bad practice.\nWhat happens to your code if I provide a wrong image name? I guess something bad, so please fail as early and as visibly as possible.</li>\n<li>I'd prefer to have a new class <code>Position</code> rather than having to keep the <code>x</code>, <code>y</code> pair.</li>\n</ul>\n\n<p><code>Player</code></p>\n\n<ul>\n<li>replace <code>ArrayList&lt;Bullet&gt;</code> with <code>List&lt;Bullet&gt;</code> on the field definition.\nYou do not need to know how the list is implemented. And keep that variable private too.</li>\n</ul>\n\n<p><code>Enemy</code></p>\n\n<ul>\n<li>Remove the commented code. If you do not need it you should remove it. Otherwise you should keep it and fix it.</li>\n</ul>\n\n<p>I also read the other replies you got so far and I agree with what they suggest to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:06:19.477", "Id": "20575", "ParentId": "20551", "Score": "3" } } ]
{ "AcceptedAnswerId": "20565", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T19:30:00.457", "Id": "20551", "Score": "3", "Tags": [ "java", "game" ], "Title": "Classes for a small space invaders game" }
20551
<p><strong>User specification</strong></p> <ul> <li>"<code>var_dump($GLOBALS)</code> is ugly as <code>...</code> without wamp"</li> </ul> <p><strong>General specification</strong></p> <ul> <li>Produce a PHP function to display the contents of <code>$GLOABLS</code> in a user-friendly manner</li> <li>Must produce properly indented HTML</li> <li>Must include appropriate CSS classes for customisability</li> </ul> <p>So far, this is what I've got:</p> <pre><code>function __printRow($key, $value, $row) { $type = gettype($value); $typeAndValue = __valueAndString($type, $value); $typeLabel = $typeAndValue['type']; $value = $typeAndValue['value']; echo _tab(5) . "&lt;tr class=\"_v_row_alt_" . $row % 2 . "\"&gt;\n" . _tab(6) . "&lt;td class=\"_v_key\"&gt;$key&lt;/td&gt;\n" . _tab(6) . "&lt;td class=\"_v_type _v_typelabel_$type\"&gt;$typeLabel&lt;/td&gt;\n" . _tab(6) . "&lt;td class=\"_v_value _v_type_$type\"&gt;$value&lt;/td&gt;\n" . _tab(5) . "&lt;/tr&gt;\n"; }//End __printRow() function _tab($num) { $tabs = ""; for($i = 0; $i &lt; $num; $i++) { $tabs .= "\t"; }//End for return $tabs; }//End _tab() function __valueAndString($type, $value) { $return = ['type' =&gt; $type, 'value' =&gt; $value]; if($value === null) { $return['type'] = $return['value'] = 'null'; return $return; }//End if switch($type) { case 'array': $return['value'] = '['; $count = count($value); $return['type'] = "$type &lt;font class=\"_v_length\"&gt;($count)&lt;/font&gt;"; for($i = 0; $i &lt; $count; $i++) { $subType = $value[$i] === null ? 'null' : gettype($value[$i]); $subTypesAndValues = __valueAndString($subType, $value[$i]); $subValue = $subTypesAndValues['value']; $return['value'] .= "&lt;font class=\"_v_type_$subType\"&gt;$subValue&lt;/font&gt;"; if(($i + 1) &lt; $count) { $return['value'] .= ', '; }//End if }//End for $return['value'] .= ']'; break; case 'boolean': $return['value'] = $value ? 'true' : 'false'; break; case 'string': $return['type'] = "$type &lt;span class=\"_v_length\"&gt;(" . strlen($value) . ')&lt;/span&gt;'; $return['value'] = "'$value'"; break; }//End switch return $return; }//End __valueAndString() function ___v() { $globals = $GLOBALS; unset($globals['GLOBALS']); //Remove reference to $GLOBALS if(!isset($globals['_SERVER'])) { //Didn't appear when run on a VM, not 100% sure that's why $globals['_SERVER'] = $_SERVER; } ksort($globals); echo "\n" . _tab(2) . "&lt;div class=\"_v_container\"&gt;\n"; if(empty($_SESSION)) { echo _tab(2) . "&lt;div class=\"_v _v_info\"&gt;&lt;span class=\"_v_info_var_name\"&gt;" . "Session&lt;/span&gt; is " . (!isset($_SESSION) ? 'not set' : 'empty') . ".&lt;/div&gt;&lt;br /&gt;\n"; }//End if foreach($globals as $varName =&gt; $super) { if(!is_array($super)) { __printRow($varName, $super, 0); }//End if elseif(!empty($super)) { ksort($super); $varName = ucfirst(strtolower(substr($varName, 1))); echo _tab(3) . "&lt;div class=\"_v_table\"&gt;\n" . _tab(4) . "&lt;span class=\"_v _v_title\" id=\"_v_$varName" . "_title\"&gt;$varName&lt;/span&gt;\n" . _tab(5) . "&lt;table class=\"_v _v_properties\" id=\"_v$varName\"&gt;\n"; $row = 0; foreach($super as $key =&gt; $value) { __printRow($key, $value, $row++); }//End foreach echo _tab(4) . "&lt;/table&gt;\n" . _tab(3) . "&lt;/div&gt;\n"; }//End if }//End foreach echo _tab(2) . "&lt;/div&gt;\n"; }//End __v() </code></pre> <p>Which I've been testing using:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;style&gt; ._v { font-family: 'Tw Cen MT', serif; } ._v_container { clear: both; } ._v_key { text-align: right; } ._v_length { font-style: italic; } ._v_properties { column-width: auto; } ._v_row_alt_0 { background-color: rgba(99, 184, 230, 0.15); } ._v_table { float: left; } ._v_title, ._v_info_var_name { font-weight: bold; } ._v_type { width: 1px; white-space: nowrap; color: #575757; text-align: center; } ._v_type_boolean, ._v_type_null { color: #0000E6; } ._v_type_double { color: #f57900; } ._v_type_integer { color: #4e9a06; } ._v_type_string { color: #cc0000; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;?php /* include statement for file containing the above PHP code */ session_start(); $_SESSION['myArray'] = [true, [3.14159, 'Bishop'], [null], 42]; ___v(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Issues</strong></p> <ul> <li>Table is improperly formed if the first element is not an array (although doesn't happen in this case)</li> <li>No handling for <code>object</code> nor <code>resource</code> types, which I've yet to decide how to represent (suggestions welcome)</li> </ul> <p>What I have so far seems to work fine, apart from the aforementioned issue, though the amount of code for what sounds like such a simple function is far above what I'd hoped, so I'd really appreciate any ideas on how to reduce it.</p>
[]
[ { "body": "<p>Have a look at <a href=\"http://krumo.sourceforge.net/\" rel=\"nofollow\">http://krumo.sourceforge.net/</a>, maybe reinventing the wheel is not necessary :)</p>\n\n<p>Even if you don't want to use it directly, reviewing the code might help you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T07:51:49.520", "Id": "20620", "ParentId": "20557", "Score": "1" } } ]
{ "AcceptedAnswerId": "20620", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T21:35:42.650", "Id": "20557", "Score": "1", "Tags": [ "php", "html", "php5" ], "Title": "Suggestions for improvement of HTML table building function" }
20557
<p>I have written a function to handle post data received from a web page. The Emphasis is on making getting post data easy: using the function allows the coder to specify the required data, type, and default value all in one line.</p> <p>I'm using django and it provides a nice dict of post data. this will be passed to the function.</p> <p>All the post data values is str. I want the str values converted to required types, and for default values to be used if the keys were not in the post data. </p> <p>The required types include int, uuid, long, and str.</p> <p>here is what I have:</p> <pre><code> def handler(post_data, transforms): """ Generator function that takes dict of post_data and treats in way specified by transforms Arguments: post_data - post data to be transformed to type required - dict transforms - tuple of tuples of how to treat the post data. - tuple 'schema' of transforms: ( (key in post_data to get, type to convert the vale to e.g, int or uuid, boolean of if value is required or not, default value to return if no key not exist ), ... ) example of transforms: ( ('key1', uuid, True), ('from', str, False, 'UK'), 'user', 'address' ) annotated example : ( ('key1', uuid, True), # convert val at 'key1' to uuid. required. ('from', str, False, 'UK'), # 'convert' val at 'from' to str. not required. Default value = 'UK' 'user', # get value at 'user' 'address', # get value at 'address' ) """ def defaults(key, to_type=str, required=True, default_value=None): """gives default values to any values not specified in the transform""" return key, to_type, required, default_value for transform in transforms: #if transform is a string then encapsulate transform = transform if isinstance(transform, tuple) else [transform] #unpack but provide default values for absent keys key, to_type, required, fallback = defaults(*transform) try: #try to convert the value to the format required by transform raw = request.POST.get(key) yield fallback if not raw else to_type(raw) except (ValueError, KeyError): #if key not exists or value cannot be converted if required: return #bailout yield fallback </code></pre> <p>example usage:</p> <pre><code>post_data = {'name':'richard', 'age':'23', 'from':'UK', 'key1': '330c48a4-3664-11e2-982e-fda51ac77194'} [in ] name, age = handler(post_data, transforms=('name', 'age')) [in ] print name, age [out] 'richard', '23'#notice 23 as string [in ] name, age = handler(post_data, transforms=('name', ('age', int))) [in ] print name, age [out] 'richard', 23 #notice 23 as int [in ] key1, brother = handler(post_data, transforms=(('key1', uuid), ('brother', str, False))) [in ] print key1, brother [out] UUID('330c48a4-3664-11e2-982e-fda51ac77194') #notice string has been converted to uuid and absense of brother value [in ] key1, brother = handler(post_data, transforms=(('key1', uuid), ('brother', str, False, 'Abe'))) [in ] print key1, brother [out] UUID('330c48a4-3664-11e2-982e-fda51ac77194'), 'Abe' #notice default value for brother used </code></pre> <p>I'm looking to make the code even more consise.</p>
[]
[ { "body": "<p>I think the code is great.</p>\n\n<p>Some comments:</p>\n\n<ol>\n<li>Transform is a tuple of 4 elements (key, type, is_default, default_value). I think is too many, it is hard to remember which means what.</li>\n<li>Since it is a tuple - if you want to provide a \"default_value\" - you need to provide everything else. But in real life the most common scenario for me is to use <code>request.GET.get('param1', 'default_value')</code></li>\n<li>I'm not sure about the version of python, but in python 2.* it would not cover unicodes <code>isinstance(transform, str)</code></li>\n<li>function name <code>def handler(post_data, transforms)</code> should be a verb probably.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T09:43:34.787", "Id": "33073", "Score": "0", "body": "thanks. I will do the following:\n\n1: combine \"is_default\" and \"default_value\"\n2: I will do\nraw = request.POST.get(key)\nyield fallback if not raw else to_type(raw)\n3: I will use not isinstance(transform, list)\n4: I will rename accordingly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T19:02:49.287", "Id": "33124", "Score": "0", "body": "`not isinstance(transform, list)` will not work, because you are using tuples.\nIf you want to check for unicode + str , you can use `isinstance(transform, basestring)`. if you want to check for collections you need to use collections module it has base classes for collections." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T06:01:45.193", "Id": "20618", "ParentId": "20564", "Score": "2" } } ]
{ "AcceptedAnswerId": "20618", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T01:47:25.057", "Id": "20564", "Score": "1", "Tags": [ "python", "django" ], "Title": "POST data handler" }
20564
<p>I have the following method that will take the car parts I searched for and match them to my car object in array. Then it tells me the percent match.</p> <p>Example:</p> <p>Car.h has NSSet toCarParts. toCarParts has may car parts.</p> <p>My array contains 5,000 or so matches.</p> <p>I will go through each one and match my parts to the car parts and calculate a percent match. If I search for wheel, tire, rim, and Car X has wheel, tire, rim, seat, my % should be 75%. </p> <p>The method does this, but take about 30 seconds on an iPhone 5 (double or triple on iPhone 4)</p> <p>How can I optimize it?</p> <p>I think what slows it down is that I need to open each car object, fire the faults, access the <code>toCarParts</code> set, for each part compare if it matches a part in my search array.</p> <p>I also think it is slow when doing division (<code>counter/[carPartsArrayFaulted count]=%</code>).</p> <pre><code>-(NSMutableArray*)calculatePercentagePerFind:(NSMutableArray*)CarArray:(NSMutableArray*)partsArray{ NSArray*defaultParts =[NSArray arrayWithArray:[[[HelperMethods alloc]init]getObjectUserDefault:@"AvailableDefaultParts"]]; int lowestPercentMatchInt=[[[HelperMethods alloc]init]getIntegerUserDefault:@"lowestPercentageMatch"]; NSMutableArray*partsFromCarArray=[[NSMutableArray alloc]init]; NSMutableArray*returnArray=[[NSMutableArray alloc]init]; NSMutableArray *partsWithDefaultParts =[NSMutableArray arrayWithArray:partsArray]; [partsWithDefaultParts addObjectsFromArray:defaultParts]; for (int i=0; i&lt;[CarArray count]; i++) { double matchCount=0; Car *CarResult =(Car*)[CarArray objectAtIndex:i]; //Check if it will at least be 30% match double number1 = [partsWithDefaultParts count]; number1 =(number1/[CarResult.numberOfParts doubleValue])*100; if (number1&gt;lowestPercentMatchInt) { partsFromCarArray =[NSMutableArray arrayWithArray:[[CarResult toParts]allObjects]]; NSMutableArray *faultedParts=[[NSMutableArray alloc]init]; for (int i =0; i&lt;[partsFromCarArray count]; i++) { CarPart*part = (CarPart*)[partsFromCarArray objectAtIndex:i]; [faultedParts addObject:part.name]; } // for each part in the Car for (NSString *partInCar in partsWithDefaultParts){ //if the search parts contain that part, add one to count if ([faultedParts containsObject:partInCar]) { matchCount++; } } //Calculate percent match double percentMatch = matchCount; percentMatch =(percentMatch/[CarResult.numberOfParts doubleValue])*100; //if at least 30%(user default) then add the percent match to Car result if (percentMatch &gt;lowestPercentMatchInt) { if (percentMatch&gt;100) { CarResult.percentMatch = [NSNumber numberWithDouble:100.00]; }else{ CarResult.percentMatch = [NSNumber numberWithDouble:percentMatch]; } [returnArray addObject:CarResult]; } } } NSLog(@"Percent Matched Cars = %i",[returnArray count]); return [self arrangeByHighestPercentMatch:returnArray]; } </code></pre>
[]
[ { "body": "<p>Currently you are comparing all part against all parts, so you have a squared complexity which causes trouble for bigger numbers.</p>\n\n<p>In the case that you can create your part list as <strong>sorted list</strong> (i.e. TreeSet in Java, not sure what is available in your language ) you can do the comparison in linear time by stepping through both lists in parallel.</p>\n\n<p>An other idea is to use something like the <strong>HashSet</strong> in Java where the containsObject don't cost linear time as with the array or a simple list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T12:22:07.357", "Id": "20582", "ParentId": "20567", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T03:53:50.977", "Id": "20567", "Score": "1", "Tags": [ "optimization", "objective-c", "ios" ], "Title": "Optimization of percent match code" }
20567
<p>I am working on projecteuler # 14, <a href="http://projecteuler.net/problem=14" rel="nofollow">http://projecteuler.net/problem=14</a> and my code takes too long to run. Any tips, or hints for a beginner?</p> <p>Code:</p> <pre><code>//////////////////////// /// ProjectEuler # 14/// //////////////////////// #include &lt;iostream&gt; #include &lt;tuple&gt; //New, shaky on tuple using namespace std; bool tester(int n) //Even number tester//It works 100% { bool result = false; if (n%2 == 0) result = true; return result; } int collatz_counter (int collatz_number) //Collatz sequence counter//It works 100% { int j = collatz_number; int total = 0; do { if (tester(j)) { j /=2; total ++; } else { j = 3*j +1; total ++; } }while (j!=1); total +=1; // To account for the original number itself return total; } pair &lt;int n, int m&gt; value_finder (int n) { int max = 0; int max_number = 0; for (int i = n; i&gt;1; i--) { if(collatz_counter(i) &gt; max) { max_number = i; max = collatz_counter(i); } } max_number++; return{max, max_number}; } int main (void) { int starter; int x; cout&lt;&lt;"Enter value :"&lt;&lt;endl; cin&gt;&gt;starter; cout&lt;&lt;endl; int Max = 0; int Max_Number = 0; for (x = starter; x&gt;= starter/2 ; x--) { int m, n; tie(m, n) = value_finder(x); if ( m&gt; Max) { Max_Number = n; Max = m; } } cout&lt;&lt;" The maximum numbers in the collatz sequence is "&lt;&lt;m&lt;&lt;endl; cout&lt;&lt;" The starting number of the collatz sequence is "&lt;&lt;n&lt;&lt;endl; system ("pause"); return 0; } </code></pre>
[]
[ { "body": "<p><strong>Hint</strong></p>\n\n<p>Taking the example from the Project Euler page, if you have computed the Collatz number for 5 in the past and you know it's 6, then when computing Collatz number for 10, you probably don't need to go through the whole chain. You can stop when you reach 5.</p>\n\n<p>It might be interesting to cache the computed value to be able to reuse them.</p>\n\n<p>(Disclaimer : I solved this problem a long time ago and cannot really remember how I did it)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:12:36.773", "Id": "33002", "Score": "0", "body": "I would vote up If I had enough rep points" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T06:49:03.203", "Id": "20570", "ParentId": "20568", "Score": "2" } }, { "body": "<p>You need to cache already computed values. That's all:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define sz 1000000\n#define UL unsigned long\n\nUL tb[sz+1];\n\nUL calc(UL n){\n if(n &lt; sz){\n if(tb[n]) return tb[n];\n if(n &amp; 1) return tb[n] = 1 + calc( n + (n &lt;&lt; 1) + 1);\n return tb[n] = 1 + calc( n &gt;&gt; 1);\n }\n if(n &amp; 1) return 1 + calc( n + (n &lt;&lt; 1) + 1); \n return 1 + calc( n &gt;&gt; 1);\n}\n\nint main(){\n UL max,a,b,i;\n max = 0;\n tb[1] = 1;\n max = 0;\n for( i = 1; i &lt;= sz; i++)\n if( max &lt; calc(i)) max = tb[i];\n printf(\"%lu\\n\",max);\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:16:25.170", "Id": "20578", "ParentId": "20568", "Score": "1" } }, { "body": "<p>The other answers have dealt with the important stuff regarding optimisation, I just want to make a couple of more general comments on your code. Firstly, please give your functions more meaningful names: i.e. prefer <code>isEven</code> to <code>tester</code>; secondly, your tester function is needlessly verbose, instead of</p>\n\n<pre><code>bool tester(int n) //Even number tester//It works 100%\n{\n bool result = false;\n if (n%2 == 0) result = true;\n return result;\n}\n</code></pre>\n\n<p>where you're checking a boolean and then assigning a boolean value based on the value of the boolean, you can simply do this:</p>\n\n<pre><code>bool isEven(int n)\n{\n return (n%2 == 0);\n}\n</code></pre>\n\n<p>it's cleaner, more compact and less error prone. Depending on your compiler, it may even be faster although most modern compilers are smart enough to figure it out when you've got optimisation turned on. As an even more minor point, I'd personally explicitly inline this kind of function and a faster check for the evenness of an integer is to check if the least significant bit is set:</p>\n\n<pre><code>inline bool isEven(int n)\n{\n return !(n &amp; 1);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:14:24.497", "Id": "20591", "ParentId": "20568", "Score": "1" } } ]
{ "AcceptedAnswerId": "20578", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T04:12:09.220", "Id": "20568", "Score": "1", "Tags": [ "c++", "project-euler" ], "Title": "Tips on projecteuler code optimization" }
20568
<p>I wrote a solution to the <a href="http://en.wikipedia.org/wiki/Knapsack_problem">Knapsack problem</a> in Python, using a bottom-up dynamic programming algorithm. It correctly computes the optimal value, given a list of items with values and weights, and a maximum allowed weight.</p> <p>Any critique on code style, comment style, readability, and best-practice would be greatly appreciated. I'm not sure how Pythonic the code is; filling in a matrix seems like a natural way of implementing dynamic programming, but it doesn't "feel" Pythonic (and is that a bad thing, in this case?).</p> <p>Note that the comments are a little on the verbose side; as I was writing the algorithm, I tried to be as explicit about each step as possible, since I was trying to understand it to the fullest extent possible. If they are excessive (or just plain incorrect), feel free to comment (hah!) on it.</p> <pre><code>import sys def knapsack(items, maxweight): # Create an (N+1) by (W+1) 2-d list to contain the running values # which are to be filled by the dynamic programming routine. # # There are N+1 rows because we need to account for the possibility # of choosing from 0 up to and including N possible items. # There are W+1 columns because we need to account for possible # "running capacities" from 0 up to and including the maximum weight W. bestvalues = [[0] * (maxweight + 1) for i in xrange(len(items) + 1)] # Enumerate through the items and fill in the best-value table for i, (value, weight) in enumerate(items): # Increment i, because the first row (0) is the case where no items # are chosen, and is already initialized as 0, so we're skipping it i += 1 for capacity in xrange(maxweight + 1): # Handle the case where the weight of the current item is greater # than the "running capacity" - we can't add it to the knapsack if weight &gt; capacity: bestvalues[i][capacity] = bestvalues[i - 1][capacity] else: # Otherwise, we must choose between two possible candidate values: # 1) the value of "running capacity" as it stands with the last item # that was computed; if this is larger, then we skip the current item # 2) the value of the current item plus the value of a previously computed # set of items, constrained by the amount of capacity that would be left # in the knapsack (running capacity - item's weight) candidate1 = bestvalues[i - 1][capacity] candidate2 = bestvalues[i - 1][capacity - weight] + value # Just take the maximum of the two candidates; by doing this, we are # in effect "setting in stone" the best value so far for a particular # prefix of the items, and for a particular "prefix" of knapsack capacities bestvalues[i][capacity] = max(candidate1, candidate2) # Reconstruction # Iterate through the values table, and check # to see which of the two candidates were chosen. We can do this by simply # checking if the value is the same as the value of the previous row. If so, then # we say that the item was not included in the knapsack (this is how we arbitrarily # break ties) and simply move the pointer to the previous row. Otherwise, we add # the item to the reconstruction list and subtract the item's weight from the # remaining capacity of the knapsack. Once we reach row 0, we're done reconstruction = [] i = len(items) j = maxweight while i &gt; 0: if bestvalues[i][j] != bestvalues[i - 1][j]: reconstruction.append(items[i - 1]) j -= items[i - 1][1] i -= 1 # Reverse the reconstruction list, so that it is presented # in the order that it was given reconstruction.reverse() # Return the best value, and the reconstruction list return bestvalues[len(items)][maxweight], reconstruction if __name__ == '__main__': if len(sys.argv) != 2: print('usage: knapsack.py [file]') sys.exit(1) filename = sys.argv[1] with open(filename) as f: lines = f.readlines() maxweight = int(lines[0]) items = [map(int, line.split()) for line in lines[1:]] bestvalue, reconstruction = knapsack(items, maxweight) print('Best possible value: {0}'.format(bestvalue)) print('Items:') for value, weight in reconstruction: print('V: {0}, W: {1}'.format(value, weight)) </code></pre> <p>The input file that it expects is as follows:</p> <pre><code>165 92 23 57 31 49 29 68 44 60 53 43 38 67 63 84 85 87 89 72 82 </code></pre> <p>The first line contains the maximum weight allowed, and subsequent lines contain the items, represented by value-weight pairs.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T00:18:33.647", "Id": "52860", "Score": "5", "body": "An old post, I know, but if you haven't run into it already `enumerate` allows you to specify the starting index (e.g. `for i,item in enumerate(items,1):` would have `i` begin at 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T04:44:36.323", "Id": "52869", "Score": "0", "body": "@SimonT: Fantastic! I've programmed in Python for 2+ years now, and I had never seen `enumerate` used that way. I'll definitely keep it in mind." } ]
[ { "body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>The function <code>knapsack</code> lacks a docstring that would explain what arguments the function takes (what kind of things are in <code>items</code>? must <code>items</code> be a sequence, or can it be an iterable?) and what it returns.</p></li>\n<li><p>This kind of function is ideal for <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctests</a>.</p></li>\n<li><p>The comments say things like \"Create an (N+1) by (W+1) 2-d list\". But what is N and what is W? Presumably N is <code>len(items)</code> and W is <code>maxweight</code>, so it would be a good idea to use the same names in the comments and the code:</p>\n\n<pre><code>N = len(items)\nW = maxweight\n</code></pre></li>\n<li><p>The comment above <code>bestvalues</code> fails to explain what the values in this table mean. I would write something like this:</p>\n\n<pre><code># bestvalues[i][j] is the best sum of values for any\n# subsequence of the first i items, whose weights sum\n# to no more than j.\n</code></pre>\n\n<p>This makes it obvious why <span class=\"math-container\">\\$0 ≤ i ≤ N\\$</span> and why <span class=\"math-container\">\\$0 ≤ j ≤ W\\$</span>.</p></li>\n<li><p>In a loop like:</p>\n\n<pre><code>bestvalues = [[0] * (maxweight + 1)\n for i in xrange(len(items) + 1)]\n</code></pre>\n\n<p>where the loop variable (here <code>i</code>) is unused, it's conventional to name it <code>_</code>.</p></li>\n<li><p>These lines could be omitted:</p>\n\n<pre><code># Increment i, because the first row (0) is the case where no items\n# are chosen, and is already initialized as 0, so we're skipping it\ni += 1\n</code></pre>\n\n<p>and then in the rest of the code, use <code>i + 1</code> instead of <code>i</code> and <code>i</code> instead of <code>i - 1</code>.</p></li>\n<li><p>The reconstruction loop:</p>\n\n<pre><code>i = N\nwhile i &gt; 0:\n # code\n i -= 1\n</code></pre>\n\n<p>can be written like this:</p>\n\n<pre><code>for i in reversed(range(1, N + 1)):\n # code\n</code></pre></li>\n<li><p>The code prints an error message like this:</p>\n\n<pre><code>print('usage: knapsack.py [file]')\n</code></pre>\n\n<p>Error messages ought to go to standard error (not standard output). And it's a good idea not to hard-code the name of the program, because it would be easy to rename the program but forget to update the code. So write instead:</p>\n\n<pre><code>sys.stderr.write(\"usage: {0} [file]\\n\".format(sys.argv[0]))\n</code></pre></li>\n<li><p>The block of code that reads the problem description and prints the result only runs when <code>__name__ == '__main__'</code>. This makes it hard to test, for example from the interactive interpreter. It's usually best to put this kind of code in its own function, like this:</p>\n\n<pre><code>def main(filename):\n with open(filename) as f:\n # etc.\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('usage: knapsack.py [file]')\n sys.exit(1)\n main(sys.argv[1])\n</code></pre>\n\n<p>and now you can run <code>main('problem.txt')</code> from the interpreter to test it.</p></li>\n<li><p>The code reads the whole of the file into memory as a list of lines:</p>\n\n<pre><code>lines = f.readlines()\n</code></pre>\n\n<p>this is harmless here because the file is small, but it's usually better to process a file one line at a time, like this:</p>\n\n<pre><code>with open(filename) as f:\n maxweight = int(next(f))\n items = [[int(word) for word in line.split()] for line in f]\n</code></pre></li>\n</ol>\n\n<h3>2. Recursive approach</h3>\n\n<p>Any dynamic programming algorithm can be implemented in two ways: by building a table of partial results from the bottom up (as in the code in the post), or by recursively computing the result from the top down, using <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"noreferrer\">memoization</a> to avoid computing any partial result more than once.</p>\n\n<p>The top-down approach often results in slightly simpler and clearer code, and it only computes the partial results that are needed for the particular problem instance (whereas in the bottom-up approach it's often hard to avoid computing all partial results even if some of them go unused).</p>\n\n<p>So we could use <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"noreferrer\"><code>@functools.lru_cache</code></a> to implement a top-down solution, like this:</p>\n\n<pre><code>from functools import lru_cache\n\ndef knapsack(items, maxweight):\n \"\"\"Solve the knapsack problem by finding the most valuable subsequence\n of items that weighs no more than maxweight.\n\n items must be a sequence of pairs (value, weight), where value is a\n number and weight is a non-negative integer.\n\n maxweight is a non-negative integer.\n\n Return a pair whose first element is the sum of values in the most\n valuable subsequence, and whose second element is the subsequence.\n\n &gt;&gt;&gt; items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]\n &gt;&gt;&gt; knapsack(items, 15)\n (11, [(2, 1), (6, 4), (1, 1), (2, 2)])\n\n \"\"\"\n @lru_cache(maxsize=None)\n def bestvalue(i, j):\n # Return the value of the most valuable subsequence of the first\n # i elements in items whose weights sum to no more than j.\n if j &lt; 0:\n return float('-inf')\n if i == 0:\n return 0\n value, weight = items[i - 1]\n return max(bestvalue(i - 1, j), bestvalue(i - 1, j - weight) + value)\n\n j = maxweight\n result = []\n for i in reversed(range(len(items))):\n if bestvalue(i + 1, j) != bestvalue(i, j):\n result.append(items[i])\n j -= items[i][1]\n result.reverse()\n return bestvalue(len(items), maxweight), result\n</code></pre>\n\n<p>To see how many partial solutions this needs to compute, print <code>bestvalue.cache_info()</code> just before returning the result. When solving the example problem in the docstring, this outputs:</p>\n\n<pre><code>CacheInfo(hits=17, misses=42, maxsize=None, currsize=42)\n</code></pre>\n\n<p>The 42 entries in the cache are fewer than the 96 partial solutions computed by the bottom up approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T22:19:40.947", "Id": "33033", "Score": "0", "body": "Thanks for your response (especially points 3 and 9)! I can't believe I forgot to consider the memoized recursive method. I'll apply some of your suggestions later today, hopefully. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-08T15:13:04.237", "Id": "75769", "Score": "0", "body": "Beware of recursion depth limit issues with this proposed solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T08:26:54.240", "Id": "76661", "Score": "1", "body": "@Frank: yes, this solution uses `len(items)` levels of stack." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-17T13:43:07.993", "Id": "288734", "Score": "0", "body": "@GarethRees Do you need to define `bestvalue()` inside `knapsack()`? I would tend to avoid defining a function inside a function to make things clearer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-17T18:06:25.343", "Id": "288795", "Score": "4", "body": "@greendiod: I defined `bestvalue` inside `knapsack` because (i) it's only used there; (ii) it uses `items` from the outer scope (it would be a pain to have to pass this down through all the recursive calls); (iii) it's memoized so it has an associated cache that we don't want to keep around when `knapsack` has returned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T03:53:32.457", "Id": "456708", "Score": "0", "body": "```value, weight = items[i - 1]``` present above the return value of ```bestvalue``` function returns an error: ```ValueError: not enough values to unpack (expected 2, got 0)```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T10:42:30.217", "Id": "456720", "Score": "0", "body": "@Saurabh: Check your `items` argument: is it a list of pairs as required?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T00:07:04.523", "Id": "456791", "Score": "0", "body": "@GarethRees: Sorry I got the error because I didn't fully implement your review in the original post." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-16T12:15:56.747", "Id": "20581", "ParentId": "20569", "Score": "61" } }, { "body": "<p>Following problem can be solved using <em>Dynamic Programming</em> in a much efficient way, in term of lines of code and fastest time to perform computation. On top that , following code perform <em>memoization</em> to cache previously computed results.</p>\n\n<pre><code>try:\n from functools import lru_cache\nexcept ImportError:\n # For Python2\n # pip install backports.functools_lru_cache\n from backports.functools_lru_cache import lru_cache\nclass knapsack:\n \"\"\"\n Maximize sum of selected weight.\n Sum of selected size is less than capacity.\n Algorithm: Dynamic Programming\n ----\n &gt;&gt;&gt;items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]\n &gt;&gt;&gt;weight, size = zip(*items)\n &gt;&gt;&gt;weight = list(weight)\n &gt;&gt;&gt;size = list(size)\n &gt;&gt;&gt;capacity = 15\n &gt;&gt;&gt;knapsack(size, weight).solve(capacity)\n\n &gt;&gt;&gt;(11, [1, 2, 3, 4])\n\n \"\"\"\n def __init__(self, size, weight):\n self.size = size\n self.weight = weight\n @lru_cache()\n def solve(self, cap, i=0):\n if cap &lt; 0: return -sum(self.weight), []\n if i == len(self.size): return 0, []\n res1 = self.solve(cap, i + 1)\n res2 = self.solve(cap - self.size[i], i + 1)\n res2 = (res2[0] + self.weight[i], [i] + res2[1])\n return res1 if res1[0] &gt;= res2[0] else res2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T07:54:18.683", "Id": "395421", "Score": "1", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T03:07:20.467", "Id": "204981", "ParentId": "20569", "Score": "1" } }, { "body": "<p>For the first section of code involving nested loops, if you should choose to<br>\n - use <code>curr</code> instead of <code>i</code>,<br>\n - assign <code>prev = curr - 1</code> and<br>\n - use <code>enumerate(items, 1)</code>, </p>\n\n<p>the code will literally document itself.</p>\n\n<pre><code>for curr, (value, weight) in enumerate(items, 1):\n prev = curr - 1\n for capacity in range(maxweight + 1):\n if weight &gt; capacity:\n bestvalues[curr][capacity] = bestvalues[prev][capacity]\n else:\n candidate1 = bestvalues[prev][capacity]\n candidate2 = bestvalues[prev][capacity - weight] + value\n\n bestvalues[curr][capacity] = max(candidate1, candidate2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T18:46:13.557", "Id": "237793", "ParentId": "20569", "Score": "2" } } ]
{ "AcceptedAnswerId": "20581", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-16T05:52:50.383", "Id": "20569", "Score": "56", "Tags": [ "python", "algorithm", "dynamic-programming", "knapsack-problem" ], "Title": "Dynamic programming knapsack solution" }
20569
<p>My script finds all factors of an integer. First it finds all prime integers using trial division then it uses the prime factors to find all other factors of the integer.</p> <p>I would like to know how I can improve and simplify it. I think the code that prevents duplicate factors such as 4 x 5 and 5 x 4 probably could be improved but this is the simplest way I could think of.</p> <p>Also, I am hoping that this is accurate and works for integers up to 99,999 but I have no idea how I could even test for that?</p> <p>My script on JS Bin: <a href="http://jsbin.com/arucuy/1/edit" rel="nofollow">http://jsbin.com/arucuy/1/edit</a></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;All Factors 1&lt;/title&gt; &lt;script&gt; window.onload = function() { // Find all factors var n = 20; // Save the inputted number above for later use var n2 = n; // Store prime factors in array var primeFactorsArray = new Array(); // Store all factors in array var allFactorsArray = new Array(); var addFactor = true; // Prime numbers list - saves time - currently goes up to 1,000 - not sure how high I should go if I plan on finding prime factors of integers up to 99,999? var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; // Trial division algorithm to find all prime factors of inputted number for (var i = 0, p = primeNumbers[i]; i &lt; primeNumbers.length &amp;&amp; p * p &lt;= n; i++, p = primeNumbers[i]) { while (n % p == 0) { primeFactorsArray.push(p); n /= p; } } if (n &gt; 1) { primeFactorsArray.push(n); } ///////////////////////////////////////////////////////////////////////////// // Use the prime factors above to find all the factors of the inputted number for (var i = 0, p = primeFactorsArray[i]; i &lt; primeFactorsArray.length; i++, p = primeFactorsArray[i]) { // Check that the prime number isn't a duplicate // Example: 20 = 2 x 2 x 5 --- We only want to try 2 once if (primeFactorsArray[i] !== primeFactorsArray[i-1]) { while (n2 % p == 0) { otherFactor = n2 / p; // Prevent duplicate factors // Example: 20 --- 4 x 5 and 5 x 4 are duplicate factors of 20 for (var t = 0; t &lt; primeFactorsArray.length; t++) { if (otherFactor == primeFactorsArray[t]) { // if otherFactor is a prime number don't add it addFactor = false; } else { addFactor = true; } } if (addFactor == true) { allFactorsArray.push(p + " x " + otherFactor); } p *= p; } } } // Display stuff document.getElementById("divOutput").innerHTML += "&lt;b&gt;Prime factors of " + n2 + "&lt;/b&gt;&lt;br /&gt;"; for (var i = 0; i &lt; primeFactorsArray.length; i++) { document.getElementById("divOutput").innerHTML += primeFactorsArray[i]; // Prevent extra x if (i + 1 &lt; primeFactorsArray.length) { document.getElementById("divOutput").innerHTML += " x "; } }; document.getElementById("divOutput").innerHTML += "&lt;br /&gt;&lt;b&gt;All factors of " + n2 + "&lt;/b&gt;&lt;br /&gt;"; for (var i = 0; i &lt; allFactorsArray.length; i++) { document.getElementById("divOutput").innerHTML += allFactorsArray[i] + "&lt;br /&gt;"; }; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="divOutput"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Have you considered using Pollard's Rho algorithm? It's insanely fast on small integers, and really easy to implement: <a href=\"http://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Algorithm\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Algorithm</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T09:03:46.033", "Id": "32972", "Score": "0", "body": "I want to stick with trial division for now as I am new to this and it's what I used in my script." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T08:38:00.787", "Id": "20572", "ParentId": "20571", "Score": "1" } }, { "body": "<p>A few comments :</p>\n\n<ul>\n<li><p>Something is wrong with the way you generate the different factors. If you try with n=300. You'll see that you miss (at least) : 300 = 6 * 50.</p></li>\n<li><p>It's not quite clear to me what you are trying to achieve with the <code>for (var t = 0; t &lt; primeFactorsArray.length; t++)</code> loop. Indeed, as you keep looping, the value of the <code>addFacotr</code> variable will be the one you would get on the <code>primeFactorsArray.length - 1</code>th item. Thus, your loop is doing the same as <code>if (otherFactor == primeFactorsArray[primeFactorsArray.length - 1])</code> (given the fact that <code>primeFactorsArray.length</code> is greater than 0, which will always be the case).</p></li>\n<li><p>As a general rule, always define in the smallest possible scope to make the reading easier.</p></li>\n<li><p>You could store only the prime factors to make the second part of the processing easier. Also, you could generate the output string during the process.</p></li>\n</ul>\n\n<p>You'll find my version of the code <a href=\"http://jsbin.com/arucuy/7/\" rel=\"nofollow\">here</a>, I have just taken my stylistic comments into account. The algorithm is still wrong here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T23:24:33.093", "Id": "33036", "Score": "0", "body": "Yeah... I tried 18 and I got 2 x 9, 3 x 6, 9 x 2. I'm trying to figure out why 2 x 9 was outputted twice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T23:26:04.803", "Id": "33037", "Score": "0", "body": "I've updated my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T16:25:01.507", "Id": "74584", "Score": "0", "body": "I think `300` is not equal to `6 * 500`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:11:20.700", "Id": "20576", "ParentId": "20571", "Score": "3" } }, { "body": "<p>This function is pretty fast and simple</p>\n\n<pre><code>function getFactors(integer){\n var factors = [],\n quotient = 0;\n\n for(var i = 1; i &lt;= integer; i++){\n quotient = integer/i;\n\n if(quotient === Math.floor(quotient)){\n factors.push(i); \n }\n }\n return factors;\n}\n</code></pre>\n\n<p>getFactors(900) \nreturns: [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 25, 30, 36, 45, 50, 60, 75, 90, 100, 150, 180, 225, 300, 450, 900] </p>\n\n<p>you could easily retrieve matched pairs such as 1x900, 2x450, 3x300 by matching from each end.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T15:07:39.133", "Id": "31621", "ParentId": "20571", "Score": "1" } }, { "body": "<p>The number to be factored is hard-coded into your script, making it inflexible. I added a user input so you don't have to rewrite the code.</p>\n\n<pre><code>var userInput = prompt(\"What number do you want factored?\")\nwindow.onload = function() {\n // Find all factors\n var n = userInput;\n // etc.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T05:20:10.717", "Id": "45802", "ParentId": "20571", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T08:03:41.890", "Id": "20571", "Score": "2", "Tags": [ "javascript", "primes" ], "Title": "Find all factors of an integer" }
20571
<p>I have a program that calculates some values and saves them to an array. Before save a value, program checks if there is already an identical value in array:</p> <pre><code> string someData = GetData(); bool newItem = true; int arrayDataLength = arrayData.Length; for (int x = 0; x &lt; arrayDataLength; x++) { if (arrayData[x] == someData) { newItem = false; arrayDataCount[x]++; break; } } if (newItem == true) { Array.Resize(ref arrayData, (arrayDataLength + 1)); Array.Resize(ref arrayDataCount, (arrayDataLength + 1)); arrayData[arrayDataLength] = someData; arrayDataCount[arrayDataLength]++; } </code></pre> <p>Sometimes arrays with data become big, and program works a bit slow. How can I optimize perfomance of this action?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T14:00:50.917", "Id": "32986", "Score": "1", "body": "I would strongly suggest waiting at least a day before accepting an answer (even if it is *very* helpful), as you are likely to get more feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T05:41:49.150", "Id": "33063", "Score": "0", "body": "Yes, I see it now." } ]
[ { "body": "<p><strong>1. Resizing.</strong> </p>\n\n<pre><code>Array.Resize(ref arrayData, (arrayData.Length+1);\n</code></pre>\n\n<p>It's not a good way to resize an array. You copy the whole array every time you need add just one value. You might want to consider the approach which is used in .NET collections. If you need to add something to an array and there is not enough space - double it's size. However, in this case you need to distinguish between capacity (allocated memory) and length (the real number of stored elements)</p>\n\n<pre><code>int newRealLength = realLength + 1;\nif (arrayData.Length &lt; newRealLength) {\n Array.Resize(ref arrayData, arrayData.Length*2);\n}\nrealLength = newRealLength;\n</code></pre>\n\n<p>Then, in the end, just drop everything above realLegth in your array by resizing it again.</p>\n\n<pre><code>Array.Resize(ref arrayData, realLength);\n</code></pre>\n\n<p>Otherwise, you might want to consider List - it uses an array underneath and employs the strategy I've described above - you don't have to write anything on your own in this case. </p>\n\n<p><strong>2. Search</strong> </p>\n\n<p>Search in the whole array is also a problem. If order doesn't matter and you can deal with duplicates later. You can do the trick. </p>\n\n<pre><code>Dictionary&lt;string,int&gt; d = new Dictionary&lt;string,int&gt;();\nif (false == d.ContainsKey(someData)) { \n d.Add(someData, 0);\n} else {\n int count = d[someData];\n d[someData] = count + 1; \n}\n//later you can convert keys and values to the 2 independent arrays\n//1st - added items\n//2nd - number of duplicates \nString[] arrayData = d.Keys.ToArray();\nint[] arrayDataCount = d.Values.ToArray(); \n</code></pre>\n\n<p>Please notice that this approach also covers the problem of resizing but doesn't preserve processing order.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:38:21.563", "Id": "32976", "Score": "0", "body": "Thanks very much for your reply! The way of using `Dictionary` is good for my task because I really have key-value pairs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T14:04:14.980", "Id": "32987", "Score": "2", "body": "Instead of `false == something`, write just `!something`. Also [Yoda contions](http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html) are usually not used in C#, because they are not needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:12:34.220", "Id": "32990", "Score": "0", "body": "In .NET, `Dictionary` doesn't have a `Get` method. And `Contains` won't compile because it expects a `KeyValuePair`. See my answer for the correct version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:25:30.747", "Id": "33009", "Score": "0", "body": "Not quite. `Add` throws an `ArgumentException` if the key already exists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:44:00.600", "Id": "33010", "Score": "0", "body": "@codesparkle There is a ContainsKey() on the line above to check that it doesn't exist." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:46:24.443", "Id": "33012", "Score": "0", "body": "Run your code. The else branch will try to add a key that is already present to the dictionary - and fail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:58:15.903", "Id": "33014", "Score": "0", "body": "@codesparkle - good catch." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:30:49.083", "Id": "20579", "ParentId": "20574", "Score": "2" } }, { "body": "<p>If you don't need to count the number of occurences, use a <code>Set</code>:</p>\n\n<pre><code>private readonly ISet&lt;string&gt; data = new HashSet&lt;string&gt;();\n\npublic void AddNewData()\n{\n string someData = GetData();\n data.Add(someData);\n}\n</code></pre>\n\n<hr>\n\n<p>If you need to count the occurences, you should use a <code>Dictionary</code>:</p>\n\n<pre><code>private readonly IDictionary&lt;string, int&gt; data = new Dictionary&lt;string, int&gt;();\n\npublic void AddNewData()\n{\n string someData = GetData();\n if (data.ContainsKey(someData))\n {\n data[someData]++;\n }\n else\n {\n data[someData] = 1;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Alternatively, you could just use a <code>List</code> and calculate the counts when you need them, using the LINQ <code>GroupBy</code> extension method:</p>\n\n<pre><code>private readonly ICollection&lt;string&gt; data = new List&lt;string&gt;();\n\npublic void AddNewData()\n{\n string someData = GetData();\n data.Add(someData); // data might contain duplicates\n}\n\npublic void PrintData() // use LINQ to count number of occurences\n{\n foreach (var entry in data.GroupBy(x =&gt; x))\n {\n Console.WriteLine(\"{0} {1}\", entry.Key, entry.Count());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T14:30:12.900", "Id": "20585", "ParentId": "20574", "Score": "4" } }, { "body": "<p>You should use <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"nofollow\"><code>List&lt;String&gt;</code></a> to replace your array to overcome resize problem.</p>\n\n<p>It will automatically resize the internal array to double the capacity when existing capacity becomes full.</p>\n\n<p>Your code will become</p>\n\n<pre><code> List&lt;String&gt; list = new List&lt;String&gt;(); // add values to it.\n if (!list.Contains(someData))\n {\n list.Add(someData);\n }\n</code></pre>\n\n<p>To efficiently search, You should use <a href=\"http://msdn.microsoft.com/en-in/library/xfhwa508.aspx\" rel=\"nofollow\"><code>Dictionary&lt;TKey, TValue&gt;</code></a></p>\n\n<pre><code> Dictonary&lt;String, String&gt; dict = new Dictionary&lt;String, String&gt;(); // add values to it.\n if (!dict.ContainsKey(someData)) // if you have key, use dict.ContainsKey(key)\n {\n dict.Add(someData, someData); // If you have key, use dict.Add(key,someData);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T16:12:14.797", "Id": "20589", "ParentId": "20574", "Score": "1" } } ]
{ "AcceptedAnswerId": "20585", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T10:34:51.923", "Id": "20574", "Score": "3", "Tags": [ "c#", "performance", "array" ], "Title": "Searching item in array" }
20574
<p>I have to display some set of:</p> <ul> <li>Data in serpentine order. In an experiment there are replication, range, and plot.</li> <li>Replications contains range a plot. A range contains a plot.</li> <li>If there are 2 replication, 4 ranges, and 8 plots, then each replication contains 2 ranges. Each range has 2 plot, so data to displayed in serpentine order.</li> </ul> <blockquote> <pre class="lang-none prettyprint-override"><code>Replication Range Plot 1 1 1 1 1 2 1 2 2 1 2 1 2 3 1 2 3 2 2 4 2 2 4 1 </code></pre> </blockquote> <p>The actual data I have to display is something like this:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Replication Range Plot Hybrid pedigree qty 1 1 1 HH1 HH1/HH1 1 1 1 2 HH2 HH2/HH2 1 1 2 2 HH3 HH3/HH3 3 1 2 1 HH4 HH4/HH4 4 2 3 1 HH1 HH1/HH1 1 2 3 2 HH2 HH2/HH2 1 2 4 2 HH3 HH3/HH3 3 2 4 1 HH4 HH4/HH4 4 </code></pre> </blockquote> <p>But in the database, data is scattered. In order to display, I have to do iteration. The serpentine data is stored in this format:</p> <pre class="lang-java prettyprint-override"><code>HashMap&lt;Integer, HashMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;&gt; </code></pre> <p>where hybrid information along with a pedigree, replication, range, plot, and quantity is stored in VO.</p> <p>This is the class for this:</p> <pre class="lang-java prettyprint-override"><code>public class HybridVo { private String hybridId; private String pedigree; private int replicaiton; private int range; private int plot; private String qty; public String getHybridId() { return hybridId; } public void setHybridId(String hybridId) { this.hybridId = hybridId; } public String getPedigree() { return pedigree; } public void setPedigree(String pedigree) { this.pedigree = pedigree; } public int getReplicaiton() { return replicaiton; } public void setReplicaiton(int replicaiton) { this.replicaiton = replicaiton; } public int getRange() { return range; } public void setRange(int range) { this.range = range; } public int getPlot() { return plot; } public void setPlot(int plot) { this.plot = plot; } public String getQty() { return qty; } public void setQty(String qty) { this.qty = qty; } } </code></pre> <p>This is where the logic resides:</p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.TreeMap; public class DisplayLogic { public static void main(String[] args) { // Lets assume that both the below variable are filled with data. TreeMap&lt;Integer, TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;&gt; serpentine = new TreeMap&lt;Integer, TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;&gt;(); List&lt;HybridVo&gt; hybridList = new ArrayList&lt;HybridVo&gt;(); // first iterate over the serpentine variable to diplay serpentine row. Iterator&lt;Integer&gt; serIt = serpentine.keySet().iterator(); while (serIt.hasNext()) { Integer replication = (Integer) serIt.next(); TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt; range = (TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;) serpentine .get(replication); Iterator ranIt = range.keySet().iterator(); int z=0; while (ranIt.hasNext()) { z++; List mapKeys = null; Integer rangeVal = (Integer) ranIt.next(); ArrayList&lt;Integer&gt; intData = range.get(rangeVal); mapKeys = intData; /* * the following is the code to display hybrid in serpentine order */ if (z % 2 == 0) { Collections.sort(mapKeys); Collections.reverse(mapKeys); } else { Collections.sort(mapKeys); } Iterator mainIt = mapKeys.iterator(); while (mainIt.hasNext()) { Integer plot = (Integer) mainIt.next(); // we have to repeat this iteration for each row of serpentine // which to costly Iterator&lt;HybridVo&gt; hybridVoIt = hybridList.iterator(); while (hybridVoIt.hasNext()) { HybridVo hybridVo = (HybridVo) hybridVoIt.next(); // this is logic where we get hybrid value which matches as per // serpentine order if (hybridVo.getReplicaiton() == replication &amp;&amp; hybridVo.getPlot() == plot &amp;&amp; hybridVo.getRange() == rangeVal) { } } } } } } } </code></pre> <p>As you can see, that the display algorithm will result into too many iterations. Specifically, the hybrid iterator has to be iterated for each iteration of the serpentine row. Can anybody think of a better design/pattern/OOP/algorithm?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T13:52:55.247", "Id": "32985", "Score": "0", "body": "Are the two last lines in the correct order in your example ? Same question for lines 3 & 4 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:16:43.907", "Id": "33003", "Score": "0", "body": "Ever heard about the [**for-each loop**](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html)? I see no reasons to use iterators explicitly. It makes your code a lot more complicated than it needs to be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T06:51:16.817", "Id": "33066", "Score": "0", "body": "TreeMap<Integer, TreeMap<Integer, ArrayList<Integer>>> serpentine = new TreeMap<Integer, TreeMap<Integer, ArrayList<Integer>>>();\n List<HybridVo> hybridList = new ArrayList<HybridVo>();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T06:51:40.997", "Id": "33067", "Score": "0", "body": "are the above two line which i commented you mean line 3,4" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T06:52:03.290", "Id": "33068", "Score": "0", "body": "last two line in my code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T09:00:08.303", "Id": "33147", "Score": "0", "body": "The lines in your example not in your code. Is it right that (2 4 2) comes before (2 4 1) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T09:21:36.890", "Id": "33148", "Score": "0", "body": "ya it is , it serpentine oder" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T09:22:49.527", "Id": "33149", "Score": "0", "body": "after every odd range , the plot oder reverses as you can see range 1 and 3 have same order while 2,4 have same" } ]
[ { "body": "<p>This is not a typical codereview question. It is not about reviewing code for code quality, it is asking for an algorithm improvement.</p>\n\n<p>But anyway, here we go:</p>\n\n<blockquote>\n <p>serpentine order</p>\n</blockquote>\n\n<p>I did not found any explanation on google what this is exactly.</p>\n\n<blockquote>\n <p>As you can see that the display algorithm will result into too many iterations which too bad specifically the hybrid iterator has to be iterated for each iteration of serpentine row.Can anybody think of better design/pattern/oop/algoritm</p>\n</blockquote>\n\n<p>Well, you just need the element with the suitable replication, plot and rangeval. So one thing you could do to get rid of this loop is to put all HybridVo in a HashMap and use replication, plot and rangeval as a (unique!) key and access them in this way.</p>\n\n<p>Example (I have cleaned up the source a bit, too):</p>\n\n<pre><code>public class DisplayLogic {\n public static void main(final String[] args) {\n // Lets assume that both the below variable are filled with data.\n final TreeMap&lt;Integer, TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;&gt; serpentine = new TreeMap&lt;Integer, TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;&gt;();\n final Map&lt;String, HybridVo&gt; mapForHybridVo = new HashMap&lt;&gt;();\n\n // first iterate over the serpentine variable to display serpentine row.\n for (final Integer replication : serpentine.keySet()) {\n final TreeMap&lt;Integer, ArrayList&lt;Integer&gt;&gt; range = serpentine.get(replication);\n boolean reverseIntData = true;\n\n for (final Integer rangeVal : range.keySet()) {\n final ArrayList&lt;Integer&gt; intData = range.get(rangeVal);\n // the following is the code to display hybrid in serpentine order\n if (reverseIntData)\n Collections.sort(intData, comparatorIntReverse);\n else\n Collections.sort(intData);\n reverseIntData = !reverseIntData;\n\n for (final Integer plot : intData) {\n final HybridVo hybridVo = mapForHybridVo.get(getHashForReplicationRangePlot(replication, rangeVal, plot));\n if (hybridVo != null) {\n // start here\n }\n }\n }\n }\n }\n\n private static Comparator&lt;Integer&gt; comparatorIntReverse = new Comparator&lt;Integer&gt;() {\n @Override\n public int compare(Integer arg0, Integer arg1) {\n return -Integer.compare(arg0, arg1);\n }\n };\n\n static String getHashForReplicationRangePlot(final int replication, final int range, final int plot) {\n return replication + \"#\" + range + \"#\" + plot; //hash must be unique for different inputs\n }\n}\n</code></pre>\n\n<p>I would further suggest to use better names and submethods to reduce the brackets depth.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T18:11:06.483", "Id": "20910", "ParentId": "20580", "Score": "2" } } ]
{ "AcceptedAnswerId": "20910", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T11:57:04.043", "Id": "20580", "Score": "1", "Tags": [ "java", "algorithm", "sorting", "collections", "iteration" ], "Title": "Displaying plotted data in serpentine order" }
20580
<p>I have created a drop-down to populate a list of cities. Everything works fine, but I would like to know better ways of doing this. Also, please let me know if it is possible to create the same drop down using <code>&lt;Select&gt;</code> instead of HTML helpers.</p> <pre><code>//ViewModel public class LocationDTO { public IEnumerable&lt;CityDTO&gt; Cities { get; set; } public LocationDTO() { this.Cities = new CityDTO[] { }; } } public class CityDTO { public string CityId { get; set; } public string CityName { get; set; } } </code></pre> <p>I've used entity framework database first approach to get the data back from database. Please address improvements that need to be done.</p> <pre><code>//Controller Models.LocationDTO Loc = new Models.LocationDTO(); EF.LocationEntities locCtx = new EF.LocationEntities(); public Action Result Index() { using(locCtx) { var locResults = (from q in locCtx.usp_GetAllCities() Select new Models.CityDTO { CityId = q.Id, CityName = q.Name }); loc.Cities = locResults.ToList(); } List&lt;Models.CityDTO&gt; citiesList = new List&lt;Models.CityDTO&gt;(); Models.CityDTO city = new Models.CityDTO() { CityId = "-1", CityName = "Select City" }; citiesList.Add(city); citiesList.AddRange(Loc.Cities.ToList()); ViewBag.CitiesDropDown = citiesList; return view(loc); } </code></pre> <p>I'd also like to know how the lamdba expression works in this scenario:</p> <pre><code>//View @{ List&lt;TestApp.Models.CityDTO&gt; citiesList = ViewBag.CitiesDropDown; var cityItems = new SelectList(citiesList, "CityId", "CityName"); } &lt;div&gt; Cities: @Html.DropDownListFor(x =&gt; x.Cities.SingleOrDefault().CityID, @cityItems) &lt;/div&gt; </code></pre>
[]
[ { "body": "<p><strong>View Model</strong></p>\n\n<p>Looks fine to me, although I'd recommend that if all your DTO classes are to be appended with 'DTO' you instead put them inside a namespace named 'DTO' and leave the 'DTO' characters off the class names entirely.</p>\n\n<p><strong>Controller</strong></p>\n\n<p>Use <code>var</code> when the Right Hand Side (RHS) is obvious.</p>\n\n<p>Also, I don't like the indentation in your LINQ statement. It makes it difficult to discern between LINQ and constructor.</p>\n\n<p>There is no point in calling <code>ToList</code> so much. AddRange is going to enumerate the whole collection anyway, so you don't actually need any <code>ToList</code> calls at all.</p>\n\n<pre><code>var Loc = new Models.LocationDTO();\nvar locCtx = new EF.LocationEntities();\n\npublic Action Result Index() {\n using(locCtx) { \n var locResults = (from q in locCtx.usp_GetAllCities()\n Select new Models.CityDTO \n {\n CityId = q.Id, \n CityName = q.Name\n }); \n loc.Cities = locResults;\n }\n\n var citiesList = new List&lt;Models.CityDTO&gt;();\n var city = new Models.CityDTO()\n {\n CityId = \"-1\", \n CityName = \"Select City\" \n };\n citiesList.Add(city);\n citiesList.AddRange(Loc.Cities);\n\n ViewBag.CitiesDropDown = citiesList;\n return view(loc);\n}\n</code></pre>\n\n<p><strong>View</strong></p>\n\n<p>You make a call to <code>Cities.SingleOrDefault()</code>. <code>SingleOrDefault()</code> can return a null value if your <code>City</code> class' default operator returns null (which is the <em>err</em> default behaviour). If this happens, accessing <code>CityId</code> will fail.</p>\n\n<pre><code>//View\n\n@{\n List&lt;TestApp.Models.CityDTO&gt; citiesList = ViewBag.CitiesDropDown;\n var cityItems = new SelectList(citiesList, \"CityId\", \"CityName\");\n}\n&lt;div&gt;\n Cities: @Html.DropDownListFor(x =&gt; x.Cities.SingleOrDefault().CityID, @cityItems)\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-14T13:54:13.743", "Id": "66640", "ParentId": "20586", "Score": "2" } }, { "body": "<ul>\n<li>For the DTOs, namespace them and keep them at that level. It's hard to add more here without more context around what you are doing.</li>\n</ul>\n\n<p>View</p>\n\n<ul>\n<li>In your view, you should not be doing the code inside of your @. This should all take place at the controller level or lower. Also, you should have a strongly typed ViewModel that contains exactly what the view needs.</li>\n</ul>\n\n<p>Controller</p>\n\n<ul>\n<li>Too much logic here. That query should be contained inside of a service/repository and you should simply call _cityService.GetAllCities() in the controller.</li>\n<li>After that's done, you can create a class to map from the cities to whatever you need to have in your viewmodel.</li>\n<li>Remove the ViewBag use, create a strongly typed ViewModel that you pass to your view.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-12T18:50:17.777", "Id": "73490", "ParentId": "20586", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T14:54:08.387", "Id": "20586", "Score": "4", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Drop-down for populating a list of cities" }
20586
<p>I am trying to create a class to queue up a series of commands. (Not really a queue as events happen based on time). Each command has a callback (Action) that get's called. However, each Action has a different set of parameters (signature), so I am using an object[] to pass them and then have to do lots of casting.</p> <p>Example: the Queue class:</p> <pre><code>class RfxQueue { public enum CMD {DISPLAY, REPLACE_TMPLT, SCALE_DVE, etc }; private Dictionary&lt;CMD, Action&lt;object []&gt;&gt; actions = new Dictionary&lt;CMD,Action&lt;object[]&gt;&gt;(); // Struct to hold command info public struct QItem { public CMD cmd; // The CMD to exec public long ttd; // Time to be executed public object[] param; // Parameters to Action } private List&lt;QItem&gt; q = new List&lt;QItem&gt;(); // The queue of events // Create a new callback public void addAction(CMD cmd, Action&lt;object []&gt; action) { actions.Add(cmd, action); } // Add to Q public void pushEvent(CMD Cmd, float Delay, params object[] Param) { q.Add(new QItem() { cmd = Cmd, param = Param, ttd = DateTime.Now.AddMilliseconds(Delay * 1000).Ticks }); } // This is actually done in a thread. Simplified here private void execEvent() { QItem item; // item is pulled from q here actions[item.cmd].Invoke(item.param); } } </code></pre> <p>And the owner class creates events like this:</p> <pre><code>// "q" is a RfxQueue and the internal Invoke is required to run on main thread q.events.Add(RfxQueue.CMD.SCALE_DVE, new Action&lt;object[]&gt;(o =&gt; { dispatcher.Invoke(new Action&lt;string, string, bool&gt;((a,b,c) =&gt; { _cgManager.ScaleDVE(a, b, c); }), (string)o[0], (string)o[1], (bool)o[2]); })); q.events.Add(RfxQueue.CMD.PLAY_ANIMATION, new Action&lt;object[]&gt;(o =&gt; { dispatcher.Invoke(new Action&lt;VideoTemplate, string&gt;((v, s) =&gt; { _cgManager.playAnimation(v, s); }), (VideoTemplate)o[0], (string)o[1]); })); </code></pre> <p>Lastly, an event is added like this:</p> <pre><code>// Play animation "inserton" in 3 seconds q.add(RfxQueue.CMD.PLAY_ANIMATION, template, 3f, "inserton"); </code></pre> <p>Is there a way to do this without all that casting? Thanks!</p>
[]
[ { "body": "<p>Starting from minor issues - please follow naming conventions (variables should be camelCased and methods PascalCased, do add access modifiers, give variables meaningful names).</p>\n\n<p>Your design breaks <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\">Open-Closed principle</a>: Queue knows all the possible commands it can handle. In case when you need to add a new command you'll have to change the queue rather than add new code. </p>\n\n<p>Also it breaks <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a> since queue knows not only about scheduling the execution but also serves as a repository for all possible actions to be run for commands.</p>\n\n<p>Both issues as well as those you have mentioned (type casting, different signatures) can be easily solved if you create a separate class per command type. Command will encapsulate parameters required for execution as well as the action to be executed:</p>\n\n<pre><code>public interface ICommand\n{\n void Execute();\n}\n\npublic class ScaleDveCommand : ICommand\n{\n public CgManager CgManager { get; set; }\n public string FirstString { get; set; } //TODO:Rename to meaningful name\n public string SecondString { get; set; } //TODO:Rename to meaningful name\n public bool SomeBool { get; set; } //TODO:Rename to meaningful name\n\n public void Execute()\n {\n dispatcher.Invoke(() =&gt; CgManager.ScaleDVE(FirstString, SecondString, SomeBool));\n }\n}\n\npublic class PlayAnimationCommand : ICommand\n{\n public CgManager CgManager { get; set; }\n public VideoTemplate VideoTemplate { get; set; }\n public string SomeMeaningfulNameHere { get; set; } //TODO:Rename to meaningful name\n\n public void Execute()\n {\n dispatcher.Invoke(() =&gt; { CgManager.playAnimation(VideoTemplate, SomeMeaningfulNameHere); });\n }\n}\n</code></pre>\n\n<p>And your \"queue\" class will look like:</p>\n\n<pre><code>public class RfxQ\n{\n private readonly SortedList&lt;long, ICommand&gt; _queue = new SortedList&lt;long, ICommand&gt;(); // The queue of events\n\n public void PushEvent(ICommand command, TimeSpan delay)\n {\n _queue.Add(DateTime.Now.Add(delay).Ticks, command);\n }\n\n // This is actually done in a thread. Simplified here\n private void ExecEvent()\n {\n ICommand command;\n // item is pulled from _queue here\n command.Execute();\n }\n}\n</code></pre>\n\n<p>And usage will look like:</p>\n\n<pre><code>q.pushEvent(new PlayAnimationCommand\n {\n CgManager = _cgManager,\n VideoTemplate = template,\n SomeMeaningfulNameHere = \"inserton\"\n }, TimeSpan.FromSeconds(3));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T16:14:37.750", "Id": "32996", "Score": "0", "body": "So, basically you're saying that it's better to couple the action and its parameters? I'm not completely sure about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T16:24:50.323", "Id": "32997", "Score": "0", "body": "OOP defines class as a structure that combines state and behavior, so I don't see issue in coupling action (behavior) with parameters of that action (state)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T16:34:38.493", "Id": "32998", "Score": "0", "body": "Thanks for the nice answer. The only changes I will make are 1) making CgManager and dispatcher static vars in ICommand (making ICommand a class), and 2) have each command accept the parameters in their constructors. These will shorten calles to PushEvent. Will this break OO design?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:30:14.850", "Id": "33018", "Score": "0", "body": "Why would you make ICommand a class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T12:56:23.420", "Id": "33084", "Score": "0", "body": "@JohnnyMopp It's hard to suggest the best approach actually since I don't know how CgManager and Dispatcher are managed. I generally dislike static fields (except static readonly ones) as it is a possible headache in multithreading environment as well as makes unit testing harder. Accepting parameters in constructor is fine." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:56:26.800", "Id": "20588", "ParentId": "20587", "Score": "7" } } ]
{ "AcceptedAnswerId": "20588", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:03:50.933", "Id": "20587", "Score": "4", "Tags": [ "c#", "casting", "callback" ], "Title": "Collection of Actions" }
20587
<p>In order to create loose coupling architecture on my web applications, I have created my own implementation for ORM, in this case, NHibernate.</p> <p>I want you please to review the code and tell me if you think it can work in a real world on high traffic app.</p> <p>I have divided the API to transaction and session. There are some cases where I want to use session with out transaction, and there are times when I need multiple transaction in a single HTTP request. </p> <p>This is the session API:</p> <pre><code>public interface IDalSession : IDisposable { IDalSession Start(); IDalTransaction StartWithTransaction(); bool IsActive(); T Save&lt;T&gt;(T entity); IQueryOver&lt;T&gt; QueryOver&lt;T&gt;() where T : class; IQueryable&lt;T&gt; Query&lt;T&gt;() where T : class; T CreateQuery&lt;T&gt;(string query) where T : class; void ExecuteUpdate(string sqlQuery); } </code></pre> <p>This is the transaction API:</p> <pre><code>public interface IDalTransaction : IDisposable { bool IsActive { get; } void MarkForRollBack(); void Commit(); T Save&lt;T&gt;(T entity); IQueryOver&lt;T&gt; QueryOver&lt;T&gt;() where T : class; IQueryable&lt;T&gt; Query&lt;T&gt;() where T : class; T CreateQuery&lt;T&gt;(string query) where T : class; void ExecuteUpdate(string sqlQuery); } </code></pre> <p>This is the session factory (the session suppose to exist per HTTP request): <strong>I am aware that I am coupled with the MySQL call below; it will be removed.</strong></p> <pre><code>public class NHibernateSessionFactory { public static ISessionFactory SessionFactory; public static void Configure(DatabaseConnectionProperties database) { if (SessionFactory == null) { FluentConfiguration configuration; configuration = Fluently.Configure().Database( MySQLConfiguration.Standard.ConnectionString( mysql =&gt; mysql.Database(database.DatabaseName).Username(database.UserName).Password(database.Password). Server(database.Host) )); foreach (Type entity in database.Entities) { configuration.Mappings(m =&gt; m.FluentMappings.AddFromAssembly(entity.Assembly) .Conventions.Add(new LowerCaseWithUnderConvention()) ); } if (database.GenerateTables) { configuration.ExposeConfiguration(cfg =&gt; new SchemaExport(cfg).Create(true, true)); } else { configuration.ExposeConfiguration(cfg =&gt; new SchemaExport(cfg)); } configuration.ExposeConfiguration( c =&gt; c.SetProperty("current_session_context_class", "web")); SessionFactory = configuration.BuildSessionFactory(); } } public static ISession GetCurrentSession() { if (!CurrentSessionContext.HasBind(SessionFactory)) { CurrentSessionContext.Bind(SessionFactory.OpenSession()); } return SessionFactory.GetCurrentSession(); } public static IDalSession OpenSession() { return new DalSession(SessionFactory); } public static void CloseSession() { SessionFactory.Close(); } } </code></pre> <p>This is how I inject the session per request:</p> <pre><code> kernel.Bind&lt;IDalSession&gt;() .ToProvider&lt;HttpDalSessionProvider&gt;() .InRequestScope(); </code></pre> <p>This is how I provide it to Ninject:</p> <pre><code>public class HttpDalSessionProvider : Provider&lt;IDalSession&gt; { private static DatabaseConnectionProperties GetDatabaseConnectionProperties() { List&lt;Type&gt; entities = new List&lt;Type&gt; {typeof (BillingInfo)}; return new DatabaseConnectionProperties( ConfigurationManager.AppSettings["DbHost"], ConfigurationManager.AppSettings["DbName"], ConfigurationManager.AppSettings["DbUser"], ConfigurationManager.AppSettings["DbPassword"], entities,true ); } protected override IDalSession CreateInstance(IContext context) { NHibernateSessionFactory.Configure(GetDatabaseConnectionProperties()); return NHibernateSessionFactory.OpenSession().Start(); } } </code></pre>
[]
[ { "body": "<p>I've seen many attempts to abstract particular ORM from application, and all of them at a certain stage of maturity had to break this abstraction. One of the reasons for that is when you need to optimize certain use cases (like eager-loading related entities, or combining several round trips to server into one) you'll need to use ORM specifics that you're abstracting from. </p>\n\n<p>And another (more obvious) reason why I vote against abstracting ORMs from the code is that ORM is already an abstraction, so what you do is an abstraction on top of another abstraction that brings little benefits.</p>\n\n<p>There is a very good series of articles that describes best practices for managing NHibernate in ASP.NET:</p>\n\n<ul>\n<li><a href=\"http://ayende.com/blog/4803/refactoring-toward-frictionless-odorless-code-the-baseline\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: The baseline</a></li>\n<li><a href=\"http://ayende.com/blog/4804/refactoring-toward-frictionless-odorless-code-hiding-global-state\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: Hiding global state</a></li>\n<li><a href=\"http://ayende.com/blog/4805/refactoring-toward-frictionless-odorless-code-limiting-session-scope\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: Limiting session scope</a></li>\n<li><a href=\"http://ayende.com/blog/4806/refactoring-toward-frictionless-odorless-code-a-broken-home-controller\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: A broken home (controller)</a></li>\n<li><a href=\"http://ayende.com/blog/4807/refactoring-toward-frictionless-odorless-code-the-case-for-the-view-model\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: The case for the view model</a></li>\n<li><a href=\"http://ayende.com/blog/4808/refactoring-toward-frictionless-odorless-code-getting-rid-of-globals\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: Getting rid of globals</a></li>\n<li><a href=\"http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions\" rel=\"noreferrer\">Refactoring toward frictionless &amp; odorless code: What about transactions?</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T04:42:04.427", "Id": "33188", "Score": "0", "body": "Thank you, please note that this is not an abstract implementation, this is a wrapper. I just want to avoid external dependencies across my systems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T06:47:31.163", "Id": "33191", "Score": "0", "body": "I meant exactly that: you are trying to *abstract* your system from NHibernate" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T13:11:41.480", "Id": "20631", "ParentId": "20592", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:30:17.087", "Id": "20592", "Score": "2", "Tags": [ "c#", "database", "http", "session", "hibernate" ], "Title": "NHibernate session and transaction implementation" }
20592
<p>I have this code in a class that gets a string, parses it, and makes some adjustments to get a valid <code>datetime</code> format from the string.</p> <p>An input string for this function could be = "A0X031716506774"</p> <pre><code>import datetime def _eventdatetime(self, string): base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M") weeks = datetime.timedelta(weeks = int(string[5:9])) days = datetime.timedelta(days = int(string[9])) seconds = datetime.timedelta(seconds = int(string[10:15])) stamp = base_date + weeks + days + seconds adjustUTC = datetime.timedelta(hours = 3) stamp = stamp - adjustUTC return str(stamp) </code></pre> <p>Total time: 0.0483931 s</p> <p>How can I improve the performance for this? The third line seems to be the slowest.</p>
[]
[ { "body": "<pre><code>import datetime\ndef _eventdatetime(self, string):\n base_date = datetime.datetime.strptime(\"1980-1-6 0:0\", \"%Y-%m-%d %H:%M\")\n</code></pre>\n\n<p>Why are you specifying the date as a string only to parse it? Just do: <code>base_date = datetime.datetime(1980,1,6,0,0)</code>. You should also make it a global constant so as not to recreate it all the time.</p>\n\n<pre><code> weeks = datetime.timedelta(weeks = int(string[5:9]))\n days = datetime.timedelta(days = int(string[9]))\n seconds = datetime.timedelta(seconds = int(string[10:15]))\n</code></pre>\n\n<p>There is no need to create several timedelta objects, you can do <code>datetime.timedelta(weeks = ..., days = ..., seconds = ...)</code></p>\n\n<pre><code> stamp = base_date + weeks + days + seconds\n\n adjustUTC = datetime.timedelta(hours = 3) \n stamp = stamp - adjustUTC\n</code></pre>\n\n<p>I'd use <code>stamp -= datetime.timedelta(hours = 3) # adjust for UTC</code></p>\n\n<pre><code> return str(stamp)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:10:25.343", "Id": "33015", "Score": "0", "body": "Thanks for your time Winston! Your advise is very useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:22:42.437", "Id": "20595", "ParentId": "20593", "Score": "3" } } ]
{ "AcceptedAnswerId": "20595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:45:56.693", "Id": "20593", "Score": "1", "Tags": [ "python", "performance", "datetime", "formatting" ], "Title": "Getting a valid datetime format from a string" }
20593
<p>We have a rule that all of our validation messages must be in a summary, and thus the default "this field is required" doesn't cut it because the messages lose their context in a summary and therefore need specific field indicators.</p> <p>I have a solution that I like rather well, but it soon became clear that there was a need for messages outside of just the required field (email, URL, custom methods like phoneUS, etc), so I made some additions to my function.</p> <p>I've been using jQuery for a while, but I'm not an expert in the optimization area, so I wanted to get some expert help on whether the function below could be optimized...my question is, "is there actually a better way to handle custom error messages in a summary?"</p> <pre><code>$('.required, .email').each(function(index) { var $this = $(this); var label = ( $this.is(':radio') ? $("label[data-name='"+$this.attr('name')+"']") : label = $("label[for='"+$this.attr('id')+"']") ); var customMessages = [{}]; if($this.hasClass('required')){ customMessages.required = "'" + label.text() + "' is required."; } if($this.hasClass('email')){ customMessages.email = "'" + label.text() + "' has an invalid email address."; } $this.rules("add", { messages: customMessages }); }); </code></pre> <p>Here is the jsFiddle: <a href="http://jsfiddle.net/GD5nw/1/" rel="nofollow">http://jsfiddle.net/GD5nw/1/</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-03T16:26:23.240", "Id": "118404", "Score": "0", "body": "In general, you should provide a wrapping element to run your selectors on, rather than traversing the entire DOM. Also, why are you adding an empty object literal to `customMessages`? You are adding properties to an array. It would make more sense to use a plain object." } ]
[ { "body": "<p>This looks fine to me.</p>\n\n<p>I only have 2 minor points:</p>\n\n<ol>\n<li>You could assign the <code>.text()</code> once in the <code>var</code> statements so that your string concats look like <code>customMessages.email = \"'\" + label + \"' has an invalid email address.\";</code> This way you are not repeating <code>text()</code> all over the place.</li>\n<li><code>var customMessages = [{}];</code> looks odd, because you are afterwards assigning straight to the array instead of the empty object. Simply replacing that with <code>var customMessages = {};</code> works in the fiddle.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-03T15:49:28.967", "Id": "64661", "ParentId": "20594", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:21:11.047", "Id": "20594", "Score": "4", "Tags": [ "javascript", "jquery", "validation" ], "Title": "Custom jQuery validation error messages" }
20594
<p>I've inherited a class which has a bunch of properties defined as:</p> <pre><code>public int ID { get { return m_nOID; } set { m_nOID = value; } } public int ConxnDetail { get { LoadDetails(); return m_nConxnDetail; } set { m_nConxnDetail = value; } } public bool ConxnConstraints { get { LoadDetails(); return m_bConxnConstraints; } set { m_bConxnConstraints = value; } } public bool IsShowCables { get { LoadDetails(); return m_bIsShowCables; } set { m_bIsShowCables = value; } } public int DefaultQueue { get { LoadDetails(); return m_nDefaultQueue; } set { m_nDefaultQueue = value; } } private User LoadDetails() { if (!IsLoaded &amp;&amp; !IsNew) { Logger.InfoFormat("Loading user details. UserID: [{0}]", m_nOID); User user = RemoteActivator.Create&lt;RemoteUser&gt;().GetUserById(m_nOID); if (user != null) { CopyDetails(user); MarkLoaded(); } else ClearDetails(); } return this; } </code></pre> <p>I would absolutely love to clean up the conventions here a bit and use only automatic getters/setters. Is this possible to do? If not, any other suggestions on reducing the boilerplate needed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:44:20.433", "Id": "33011", "Score": "0", "body": "Is there a reason the data isn't loaded when the object is constructed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:55:01.363", "Id": "33013", "Score": "0", "body": "Retrieving the ID property does not incur loading of all details. I assume that this was an optimization made at some point to lazy-load everything except the ID." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:12:04.900", "Id": "33016", "Score": "0", "body": "@SeanAnderson What is your intention? To keep that optimization in or to remove it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:14:31.687", "Id": "33017", "Score": "0", "body": "My intention is to not alter the function of the code, but to improve its readability. At the very least, is there a way to listen for properties being retrieved and execute LoadDetails only if the loading property isn't ID? This would allow me to replace all of this with automatic properties." } ]
[ { "body": "<p>There is the <a href=\"http://msdn.microsoft.com/en-us/library/ms743695.aspx\" rel=\"nofollow\">INotifyPropertyChanged</a> event handler, but I'm not sure why you would need that in this case? Instead why not just load the details when the ID changes as that seems to be the only value that will change between LoadDetails calls.</p>\n\n<p>Perhaps something like:</p>\n\n<pre><code>public int ID\n{\n get { return m_nOID; }\n set {\n\n if(m_NOID != value) {\n InitialiseUserDetails(m_nOID);\n }\n\n m_nOID = value; \n }\n}\n</code></pre>\n\n<p>If this was ok, you could remove the private backing fields as I believe you wish to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T23:05:00.170", "Id": "20602", "ParentId": "20596", "Score": "3" } } ]
{ "AcceptedAnswerId": "20602", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:25:53.477", "Id": "20596", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Calling tries to lazy load in every properties getter" }
20596
<p>I have a model <code>section</code> with a column <code>parent_id</code> - the only thing identifying a parent/child relationship. I wrote a helper method to output all sections, all their possible subsections and include their "depth".</p> <p>This is the helper method:</p> <pre><code># Calls itself for each section recursively to fetch all possible children def fetch_all_sections(standard, section = nil, depth = 0) all_sections = [] if section.nil? rootsections = roots(standard.sections.sorted) if ! rootsections.nil? rootsections.each do |section| all_sections.push(fetch_all_sections(standard, section)) end end else all_sections.push({:id =&gt; section.id, :sortlabel =&gt; section.sortlabel, :title =&gt; section.title, :depth =&gt; depth}) section.children.sorted.each_with_index do |section, index| all_sections.push(fetch_all_sections(standard, section, (depth += 1) - index)) end end return all_sections end </code></pre> <p><code>sorted</code> is a module method which sorts based on the <code>sort_key</code> column using regular expressions. The output of <code>debug(fetch_all_sections(@standard))</code> is:</p> <pre><code>- - "1 Collaborase Test Document depth: 0" - - "1.1 Section One Dot One depth: 1" - - "1.a Testing 123 depth: 1" - - "1.b Section One dot B depth: 1" - - "1.b.1 Testing One B One depth: 2" - - "2 Identify Project GHG Sources, Sinks, and Reservoirs (SSRs) depth: 0" - - "2.a Section Two dot A depth: 1" - - "3 Identify the Baseline depth: 0" - - "4 Identify the Baseline GHGs depth: 0" - - "5 Identify SSRs Relevant for Quantification depth: 0" - - "5.1 Section Five Dot One depth: 1" - - "6 GHG Quantification depth: 0" - - "7 Monitoring depth: 0" - - "8 Data and Information Retention depth: 0" - - "9 QA/QC depth: 0" </code></pre> <p><strong>My questions is this:</strong></p> <p>In this loop:</p> <pre><code>&lt;% fetch_all_sections(@standard).each do |section| %&gt; &lt;%= debug section %&gt; &lt;% end %&gt; </code></pre> <p>I want each section and all their children to be separated. Instead, each section in the above loop contains their children.</p> <p>Instead of this:</p> <pre class="lang-none prettyprint-override"><code>--- - - :id: 122 :sortlabel: "5" :title: Identify SSRs Relevant for Quantification :depth: 0 - - - :id: 412 :sortlabel: "5.1" :title: Section Five Dot One :depth: 1 </code></pre> <p>I want this:</p> <pre class="lang-none prettyprint-override"><code>--- - - :id: 122 :sortlabel: "5" :title: Identify SSRs Relevant for Quantification :depth: 0 --- - - :id: 412 :sortlabel: "5.1" :title: Section Five Dot One :depth: 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:38:29.840", "Id": "33019", "Score": "0", "body": "Derp. The syntax is `all_sections.push([section.sortlabel, section.title, depth])`. I'll leave the question open to see if anyone comes up with something better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:39:59.187", "Id": "33024", "Score": "0", "body": "I opted for pushing keys for easier retrieval: `all_sections.push({:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth})`" } ]
[ { "body": "<p>What I needed was the pipe operator! It was of course just doing what I was telling it to - pushing the results of itself onto the current element in the array. Only when the rootsections loop completes does it start a new array element.</p>\n\n<p>The 'pipe' (<code>|</code>) is a different array merge operator which appends what's to the right of it onto the end of the array on the left.</p>\n\n<pre><code>all_sections | fetch_all_sections(standard, section, depth)\n</code></pre>\n\n<p>The pipe operator changed how depth worked so instead I just counted the number of \".\" in sortlabel:</p>\n\n<pre><code>depth = section.sortlabel.split('.').length -1\n</code></pre>\n\n<p>The full method:</p>\n\n<pre><code># Calls itself for each section recursively to fetch all possible children\ndef fetch_all_sections(standard, section = nil, depth = 0)\n all_sections = []\n\n if section.nil?\n rootsections = standard.sections.sorted\n if ! rootsections.nil?\n rootsections.each_with_index do |section, i|\n depth = section.sortlabel.split('.').length - 1\n all_sections &lt;&lt; fetch_all_sections(standard, section, depth).first\n end\n end\n else\n\n all_sections &lt;&lt; {:id =&gt; section.id, :sortlabel =&gt; section.sortlabel, :title =&gt; section.title, :depth =&gt; depth}\n\n section.children.sorted.each do |section|\n all_sections | fetch_all_sections(standard, section)\n end\n end\n\n return all_sections\nend\n</code></pre>\n\n<p>If someone seeing this is considering something similar but starting from scratch, consider an Active Record Nesting gem: <a href=\"https://www.ruby-toolbox.com/categories/Active_Record_Nesting\" rel=\"nofollow\">https://www.ruby-toolbox.com/categories/Active_Record_Nesting</a></p>\n\n<p>UPDATE: I added .first within the rootsections loop. This is because I inadvertently built an array of arrays, each containing 1 hash. What I wanted was an array of hashes. Much easier retrieval now!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T17:25:54.470", "Id": "20651", "ParentId": "20597", "Score": "1" } } ]
{ "AcceptedAnswerId": "20651", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:21:16.550", "Id": "20597", "Score": "3", "Tags": [ "ruby", "array", "ruby-on-rails" ], "Title": "Retrieve all parents, all possible children, sorted and with their \"depth\"" }
20597
<p>I'm trying to work with forms, and just getting a grasp on JavaScript. Basically I'm unsure if there is a more reusable way to handle forms with Meteor/jQuery.</p> <pre><code>// Creating a new prayer, including the preview Template.newPrayer.events({ 'click input.save' : function() { var title = $("#prayer_title"); var prayer = $("#prayer"); var preview_container = $("#prayer_preview"); var currentUser = Meteor.userId(); if( currentUser !== null ) { Prayers.insert({ title: title.val(), prayer: prayer.val(), user: currentUser }); title.val(''); prayer.val(''); preview_container.fadeOut(); } }, // Auto-updating the preview 'keyup #prayer' : function() { var preview_container = $("#prayer_preview"); preview_container.fadeIn(); var preview_formatted = prayer.value.replace(/\n/g,'&lt;br/&gt;'); $(".preview_text").html(preview_formatted); } }); </code></pre> <p>Is there a better way to do this, should my template be laid out in a different way?</p> <pre><code>&lt;template name="newPrayer"&gt; &lt;h1&gt;{{title}}&lt;/h1&gt; &lt;form id="new_prayer"&gt; &lt;label for="prayer_title" class="item"&gt;Title&lt;/label&gt; &lt;input id="prayer_title" class="item" type="text" tabindex="1"/&gt; &lt;textarea id="prayer" class="item" name="prayer" tabindex="2" required="true" wrap="soft" autofocus="true" cols="60" rows="10"&gt;&lt;/textarea&gt; &lt;input type="button" class="save item" value="Save Prayer" tabindex="3" /&gt; &lt;/form&gt; &lt;div id="prayer_preview"&gt; &lt;h2&gt;Preview&lt;/h2&gt; &lt;p class="preview_text"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p>Is there a better way to handle form data and form display, without having selectors for every form element, and then having to clear each one?</p> <p>It seems like I'm not utilizing the full potential of Meteor's reactivity and templating features. Also open to any other pointers/tips with my code. The code works as is.</p> <p>P.S. This code is just me learning Meteor/JS and the beginning of a small project.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T16:37:03.687", "Id": "70855", "Score": "0", "body": "I think you'll want to take a look at https://github.com/awatson1978/forms-kitchen-sink" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-12T09:49:54.520", "Id": "139935", "Score": "1", "body": "while this may not answer your question directly,\nI would advise people visiting this post to check out the autoForm package (https://github.com/aldeed/meteor-autoform) being dependent on the SimpleSchema package, it allows you to bind forms to model schemas in a declarative way, cutting down the repetitive form building work" } ]
[ { "body": "<p>As far as I know, Meteor's reactivity is one-way: changes in data are reflected in the DOM. To go the other way (DOM to data) there's two common methods: 1) grabbing data directly from the DOM when it's needed (i.e. to save it) as you've done above and 2) binding DOM elements to data models, and using the data models for CRUD operations.</p>\n\n<p>1 is simpler to implement, but 2 gives you more control over data-flow, subscriptions, and life-cycles. 2 has plenty of great libraries you can use, so you don't have to reinvent the wheel just to leverage these benefits. <a href=\"http://backbonejs.org/\" rel=\"nofollow\">Backbone.js</a> is probably the most well known plain-JavaScript library for this sort of thing (also check out <a href=\"http://lodash.com/\" rel=\"nofollow\">Lo-Dash</a> and <a href=\"http://exosjs.com/\" rel=\"nofollow\">Exoskeleton</a> if you haven't), but the Meteor ecosystem may have a preferred library for this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-19T19:40:06.747", "Id": "39603", "ParentId": "20598", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T21:11:37.613", "Id": "20598", "Score": "4", "Tags": [ "javascript", "template", "meteor" ], "Title": "Working with forms in Meteor, using selectors for every input" }
20598
<p>I have a model class that contains 3 <code>ArrayList</code> which are in order by parallel of the same size. <code>&lt;Object&gt;&lt;Calendar&gt;&lt;Long&gt;</code> I want to sort it by the <code>&lt;Long&gt;</code> Is this the most clean? is there a better way? This doesn't seem memory efficient.</p> <pre><code> public class ResultModel{ private ArrayList&lt;Object&gt; sets = new ArrayList&lt;Object&gt;(); private ArrayList&lt;Calendar&gt; dates=new ArrayList&lt;Calendar&gt;(); private ArrayList&lt;Long&gt; unixtimes=new ArrayList&lt;Long&gt;(); private class WinningSet implements Comparable&lt;WinningSet&gt;{ private long unixtime; private Object set; private Calendar date; WinningSet(Object set,Calendar date,long unixtime){ this.unixtime=unixtime; this.set=set; this.date=date; } @Override public int compareTo(WinningSet another) { return (int) (this.unixtime-another.getUnixtime()); } public long getUnixtime() { return unixtime; } public Object getSet() { return set; } public Calendar getDate() { return date; } } public void sortSelf(){ ArrayList&lt;WinningSet&gt; list=new ArrayList&lt;WinningSet&gt;(); for(int i=0;i&lt;this.unixtimes.size();i++){ list.add(new WinningSet(this.sets.get(i),dates.get(i),unixtimes.get(i))); } Collections.sort(list,Collections.reverseOrder()); demap(list); } private void demap(ArrayList&lt;WinningSet&gt; list) { ArrayList&lt;Object&gt; tSets = new ArrayList&lt;Object&gt;(); ArrayList&lt;Calendar&gt; tDates=new ArrayList&lt;Calendar&gt;(); ArrayList&lt;Long&gt; tUnixtimes=new ArrayList&lt;Long&gt;(); for(WinningSet temp:list){ tDates.add(temp.getDate()); tSets.add(temp.getSet()); tUnixtimes.add(temp.getUnixtime()); } this.sets=tSets; this.dates=tDates; this.unixtimes=tUnixtimes; } } </code></pre>
[]
[ { "body": "<p><strong>1. Correctnes.</strong></p>\n\n<p>compareTo() method of the WinningSet class is not correct. As of now Integer.MAX_VALUE &lt; System.currentTimeMillis(). Consider the following example:</p>\n\n<pre><code> long time1 = System.currentTimeMillis();\n System.out.println(time1 &gt; 3*Integer.MAX_VALUE);\n System.out.println(time1 - 3*Integer.MAX_VALUE);\n System.out.println((int)(time1 - 3*Integer.MAX_VALUE));\n</code></pre>\n\n<p>It could be the case that your events are generated around the same time and it will not result in any error but in general - e.g. in future, if you restore some serialized objects, it could lead to a possible problem. You can rewrite it int the following way:</p>\n\n<pre><code> @Override\n public int compareTo(WinningSet another) {\n if (this.unixtime &gt; another.getUnixtime()) return 1;\n if (this.unixtime &lt; another.getUnixTime()) return -1;\n return 0;\n }\n</code></pre>\n\n<p><strong>2. Performance</strong></p>\n\n<p>Copy of the 3 lists is indeed a bad thing. You can use set() method from ListIterator to traverse through the lists and replace values in place.</p>\n\n<pre><code>private void demap(ArrayList&lt;WinningSet&gt; list) { \n Iterator li = list.iterator();\n Iterator si = sets.iterator();\n Iterator di = dates.iterator();\n Iterator ui = unixtimes.iterator();\n //you can add iterators for other lists here. \n while (li.hasNext()) {// we assume number is the same\n WinningSet temp = li.next();\n si.next(); //need to advance to the right element; \n di.next(); //need to advance to the right element; \n ci.next(); //need to advance to the right element; \n si.set(temp.getSet());\n di.set(temp.getDate());\n ui.set(temp.getUnixTime());\n }\n }\n</code></pre>\n\n<p><strong>3. Design</strong></p>\n\n<p>Are you sure that instead of a 3 lists you can't consider <em>TreeMap<code>&lt;Long, SomeClass</code>></em> where SomeClass is pair or Calendar and Object ? In this case you will always have the right order of items to work with - there is no need to sort lists on demand and do an extra work. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T20:26:39.213", "Id": "33133", "Score": "0", "body": "I agree with point 2 and 3, but I am not understanding 1. If the two unixtime is very close then it should give a small Integer (less than 10 secs) . So how does Integer.MAX_VALUE have anything to do with this. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T03:18:05.857", "Id": "33146", "Score": "0", "body": "@wtsang02, if you have 100% guarantee that they are close and will always be this close - it's not a problem. However, if by some accident you decide to compare two WinningSets by Unix time (month or so apart, if I recall correctly) you could have a problem. For example, if you decide in future to accumulate them somewhere for a long time then this way of comparison can result in a wrong behaviour. I just always prefer a usual way to write comparison just not to think about such cases." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T05:53:12.950", "Id": "20617", "ParentId": "20599", "Score": "1" } } ]
{ "AcceptedAnswerId": "20617", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T21:38:56.990", "Id": "20599", "Score": "2", "Tags": [ "java", "optimization", "android", "sorting" ], "Title": "Sorting parallel ArrayList" }
20599
<p>This code allows calling a method while redirecting the IO to strings. This is useful for unit testing where you have to direct something to the console or examine output that comes from it. I assume these have been written a lot, but I couldn't find examples.</p> <p>I'd like advice on how to make them generally useful and whether the style seems decent. There are two methods-- one sends a string to System.in while leaving the output alone, the other redirects both input and output, with the option that if the input string passed is null, it leaves the input alone. This covers all three cases.</p> <p>Invocations look like this:</p> <pre><code>enterInput(inputString, callingClassString, methodString, typeStrings[], argsForCall ...); captureIO(inputString, callingClassString, methodString, typeStrings[], argsForCall ...); </code></pre> <p>Code:</p> <pre><code>/** * Invoke the specified method using the specified string as console input. * Note that the calling class and types must be fully qualified. * * @param inputString Console input to be fed to the method * @param callingClassString Class of the method to invoke * @param method Name of the method to invoke * @param typeStrings Types the method takes (to distinguish it) * @param args Arguments to pass to the method * @return The console output captured */ public static void enterInput(String inputString, String callingClassString, String method, String[] typeStrings, Object... args) { try { Class&lt;?&gt;[] typeClasses = new Class&lt;?&gt;[typeStrings.length]; for (int i = 0; i &lt; typeStrings.length; i++) { typeClasses[i] = Class.forName(typeStrings[i]); } Method m = Class.forName(callingClassString).getMethod(method, typeClasses); InputStream origIn = System.in; System.setIn(new ByteArrayInputStream(inputString.getBytes())); m.invoke(null, args); System.setIn(origIn); } catch (Exception e) { throw new Error(e); } } /** * Invoke the specified method and return its console output as a string. * If inputString is not null, it is used as console input. * Note that the calling class and types must be fully qualified. * * @param inputString Console input to be fed to the method. * If null, leaves this input stream alone * @param callingClassString Class of the method to invoke * @param method Name of the method to invoke * @param typeStrings Types the method takes (to distinguish it) * @param args Arguments to pass to the method * @return The console output captured */ public static String captureIO(String inputString, String callingClassString, String method, String[] typeStrings, Object ... args) { String output = null; try { Class&lt;?&gt;[] typeClasses = new Class&lt;?&gt;[typeStrings.length]; for (int i=0; i&lt;typeStrings.length; i++) { typeClasses[i] = Class.forName(typeStrings[i]); } Method m = Class.forName(callingClassString).getMethod(method, typeClasses); InputStream origIn = System.in; PrintStream origOut = System.out; if (inputString != null) System.setIn(new ByteArrayInputStream(inputString.getBytes())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); m.invoke(null, args); output = baos.toString(); System.setOut(origOut); if (inputString != null) System.setIn(origIn); } catch (Exception e) { throw new Error(e); } return output; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T12:13:36.337", "Id": "33082", "Score": "0", "body": "I think the code you try to test with these methods would also benefit from a review. If you have a method that prints some output that needs to be tested than pass in the System.out as a parameter. You can then pass in your byte output stream when you want to test." } ]
[ { "body": "<p>In any case you should add the resetting of the <em>in</em> and <em>out</em> in the finally block, otherwise you will have problem in case an exception is thrown.</p>\n\n<hr>\n\n<p>Nevertheless, did you ever thought of using <a href=\"http://logging.apache.org/log4j\" rel=\"nofollow\">Log4J</a> or any other framework for logging? There you can easily define an <a href=\"http://logging.apache.org/log4j/2.x/manual/appenders.html\" rel=\"nofollow\">Appender</a> and decide where the log message will be written to.</p>\n\n<p>In addition to that, your tests shouldn't check the logging. (Except you are testing the logging.) Try to create smaller method, where you can easily test the return values instead of the log output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T18:40:45.983", "Id": "33290", "Score": "0", "body": "`you should add the resetting of the in and out in the finally block, otherwise you will have problem in case an exception is thrown.` There is a `System.exit(1)`, as long as there is only one thread, it does not matter. But the statement is still true in the general case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T20:01:36.200", "Id": "33304", "Score": "0", "body": "You are right, I missed that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T04:36:28.563", "Id": "33390", "Score": "0", "body": "Throwing an Error directly is even worst than throwing a raw Exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T19:03:59.620", "Id": "33590", "Score": "0", "body": "By throwing the error, I mean to be doing the equivalent of System.exit(), but just for this one program. System.exit() kills the JVM. What should I be doing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T04:49:13.490", "Id": "33600", "Score": "0", "body": "Throw an IOException and handle the program exit at the calling location, not in your library." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T11:07:50.860", "Id": "20629", "ParentId": "20600", "Score": "1" } }, { "body": "<p>This (and reflection in general) completely breaks refactoring, static code analysis and many more things and should therefore be avoided. (Imagine what happens if you find out a better naming for a function or you change the arguments.)</p>\n\n<p>If you really need this behavior, you could use (I assume jUnit 4+) hooks before and after class/test case:</p>\n\n<pre><code>@BeforeClass\npublic static void setUpBeforeClass() throws Exception {\n}\n\n@AfterClass\npublic static void tearDownAfterClass() throws Exception {\n}\n\n@Before\npublic void setUp() throws Exception {\n}\n\n@After\npublic void tearDown() throws Exception {\n}\n</code></pre>\n\n<p>and do whatever is necessary.<br>\nBesides this, as already written, I would suggest to modify your methods, too. It could be a better approach to separate the view (prints) from model/controller (functions doing something).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T12:16:47.680", "Id": "33399", "Score": "0", "body": "+1 for recognizing that OP was trying to reinvent some functionality of JUnit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T18:38:48.877", "Id": "20770", "ParentId": "20600", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T22:07:09.143", "Id": "20600", "Score": "3", "Tags": [ "java", "unit-testing" ], "Title": "Code to redirect console IO to strings" }
20600
<p>I'm a beginner Python coder and this is the first program that I have ever programmed. Please suggest improvements/bugs. <a href="http://paste2.org/p/2756692" rel="nofollow">Here's</a> the link to the code.</p> <pre><code>global hp hp = 20 global dice import random dice = random.randint(3,5) global beardamage import random beardamage = random.randint(1,9) global hunger hunger = 5 global spiderhp spiderhp = 5 global bearhp bearhp = 10 global potion potion = 0 global xp xp = 0 # |Data storage for part 1| #_______________________________________________________________________________ # x = ("attack") passwordcode = ("5665598") road =("left") key = ("key") choicekey = ("yes") hutchoice = ("gotoit") menucheat = ("cheat menu") menureadme = ("readme") menustart = ("start game") death = 1 menuhelp = ("help") potionadd = 1 examinationyes = ("examine") SmallHealing = random.randint(8,15) cheat01 = ("cheat_01") cheat02 = ("shutdown") bearxp = 100 spiderxp = 350 bow = random.randint(5,10) passwordcheat = ("password") # |End of data storage for adventure part 1.| #_______________________________________________________________________________ text = ("Loading files....") import time import sys from random import randrange for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.5) time.sleep(0.01) text = ("-1%||||||||||||||||100%-") print("") import time import sys from random import randrange for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.01) time.sleep(0.01) print("") import time time.sleep(1) import os import sys os.system("CLS") print("") print("") print(" ") print(" _ _ _ _ _ ") print(" / \ __| |_ _____ _ __ | |_ _ _ _ __ ___ _ __ _ _| |_| |__ ___ _ __ ") print(" / _ \ / _` \ \ / / _ \ '_ \| __| | | | '__/ _ \ | '_ \| | | | __| '_ \ / _ \| '_ \ ") print(" / ___ \ (_| |\ V / __/ | | | |_| |_| | | | __/ | |_) | |_| | |_| | | | (_) | | | |") print("/_/ \_\__,_| \_/ \___|_| |_|\__|\__,_|_| \___| | .__/ \__, |\__|_| |_|\___/|_| |_|") print(" |_| |___/ ") print(" //|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\") print(" // || Main menu || \\") print("||______________________________||_____________||________________________||") print("|| || HELP || ||") print("||______________________________||_____________||________________________||") print("|| || README || ||") print("||______________________________||_____________||________________________||") print("|| || START GAME || ||") print("||______________________________||_____________||________________________||") print(" \\ || CHEAT MENU || //") print(" \\|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//") thing = 2 thini = 1 print(" Enter the selected command") commandprompt = input("") while thing &gt; thini: if commandprompt == menucheat: print("Enter the password") commandprompt = input("") if commandprompt == passwordcheat: print("Access granted") print("") print("Cheat list") print("",(cheat01)," - Walkthrough") print("",(cheat02)," - You should know what that one does") commandprompt = input("") if commandprompt == cheat01: print("Cheat activated") print("") print("") import time time.sleep(2) print("WALKTHROUGH") print("HIT/RUN") print("Examine") print("Left") print("yes") print("go") print("5665598") print("HIT/RUN") elif commandprompt == cheat02: yes = ("yes") no = ("no") print("Are you sure?") commandprompt = input("") if commandprompt == yes: print("Shut down in 10 seconds") import os os.system("shutdown -r -t 10 ") elif commandprompt == no: print("Terminated") break else: print("Unknown command!") if commandprompt == menustart: print("Press enter to start") input("") break commandprompt = input("") if commandprompt == menureadme: print("_________________________________") print("Made by AO") print("Version 1.8") print("Dice system inplemented") print("Global system") print("Part 2 done") print("900+ lines of coding") print("_________________________________") import time time.sleep(5) if commandprompt == menuhelp: print("Help") print("Type commands exactly, no caps") else: print("Invalid command!") import time time.sleep(5) import os import sys os.system("CLS") import time import sys from random import randrange text = ("This is a story which set's back long before golden age...") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) import time time.sleep(1) print("") text = ("In a time of witchcraft, mysteries and myths.") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) import time time.sleep(1) print("") import time time.sleep(1) print("") text = ("!||SLENDER THE GAME||!") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") print("You have 20 hitpoints.") print("You have 5 hunger bars.") import time time.sleep(3) print("") import time time.sleep(1) text = ("You - Where I'm i?") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") print("You stand up") import time time.sleep(1) text = ("You - Hmm.") import os import sys os.system("CLS") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") print("You approach the door") print("But you hear a growling noise.") import time time.sleep(2) print("The door is smashed in half as a monster sees you.") import time time.sleep(2) print("It's a giant bear!") import time time.sleep(2) text = ("You - Ahhhh! Wait, It's so small!") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") text = ("You - What could possibly go wrong?") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") print("The bear looks agressive. The bear has",(bearhp)," hp. Type attack or run") y =input("") if (y) == (x): while (bearhp &gt; death): print("You hit the bear") print("") import time time.sleep(3) print("You do",(dice),"damage") print("") import time time.sleep(2) import os import sys os.system("CLS") bearhp = bearhp - dice if bearhp &lt; death: print("You do a final blow against the bear") print("") print("The bear has died") import os import sys os.system("CLS") break import time time.sleep(3) print("The bear does ",(beardamage),"damage") hp = hp - beardamage import time time.sleep(2) import os import sys os.system("CLS") print("") if hp &lt; death: print("OW! The bear does final blow against you!") print("You have died") import time time.sleep(2) print("Game over") import time time.sleep(99999) break import time time.sleep(3) if bearhp &lt; death: print("You do a final blow against the bear") print("") print("The bear has died") break import time print("You have",(hp),"left") print("") import time time.sleep(1) print("The bear has",(bearhp),"left") import time time.sleep(1) import os import sys os.system("CLS") else: print("You run away.") import time time.sleep(2) print("You have wasted your hunger bar") hungerbar = 1 hunger = hunger - hunger print("Hunger is",(hungerbar)," ") import time time.sleep(3) time.sleep(2) import time import sys from random import randrange text = ("You are in a strange room") for c in text: sys.stdout.write(c) sys.stdout.flush() seconds = "0." + str(randrange(1, 4, 1)) seconds = float(0.1) time.sleep(0.1) print("") print("You see a shelf") import time time.sleep(2) print("Hint - try examining it.","examine") examination = input("") if (examination) == (examinationyes): print("You find a small vial") import time time.sleep(2) print("It's a potion of healing!") import time time.sleep(2) print("You take the potion") potion = potion + potionadd import time time.sleep(2) print("You have",(potion),"in your inventury") import time time.sleep(2) print("You walk out of the door and you see a path") import time time.sleep(2) print("You go down the road") else: print("You walk out of the door and you see a path") import time time.sleep(2) print("You go down the road") print("You see a road which splits into 2 paths.") print("Do you wish to go left or right?") roadchoice = input("") if (roadchoice) == (road): print("You go left") else: print("You go right") import time time.sleep(5) print("You are walking slowly down the road.") import time time.sleep(3) print("You see a slender man.") import time time.sleep(3) import webbrowser webbrowser.open('http://www.google.co.uk/imgres?q=slender+screen&amp;um=1&amp;hl=en&amp;safe=active&amp;sa=N&amp;tbo=d&amp;tbm=isch&amp;tbnid=evaUdI26IM5C9M:&amp;imgrefurl=http://templardigital.blogspot.com/2012/07/video-game-review-slender.html&amp;docid=gV0cU5I4FRgbLM&amp;imgurl=http://3.bp.blogspot.com/-_BUhzLBaxQM/UBMEEXFKthI/AAAAAAAABa8/Miacjv_EtQs/s1600/Slender%252B2.png&amp;w=474&amp;h=348&amp;ei=wpy0UNv_IsWy0QXKvoD4CA&amp;zoom=1&amp;iact=rc&amp;dur=1&amp;sig=117123526119168881900&amp;page=1&amp;tbnh=145&amp;tbnw=202&amp;start=0&amp;ndsp=26&amp;ved=1t:429,r:17,s:0,i:135&amp;tx=140&amp;ty=96&amp;biw=1280&amp;bih=876') print("GAME OVER") time.sleep(3) print("SLENDER MAN HAS GOT YOU") import time time.sleep(5) print("END OF GAME! SLENDER TEXT. THE GAME") import time time.sleep(60) print("As you are walking down the misty road...") import time time.sleep(3) print("You see a small, old note.") print("Do you want to look at it?") keychoices = input("") if (keychoices) == (choicekey): print("Note - To open the ancient door, you must say 5665598") import time time.sleep(5) print("Remember not to forget it, otherwise you will die!") import time time.sleep(2) print("SteveXI - If you are reading this, then i am dead.") import time time.sleep(2) print("SteveXI - Good luck!") import time time.sleep(10) import os import sys os.system("CLS") else: print("You leave the note alone.") import os import sys os.system("CLS") import time time.sleep(3) print("In the distance, you see a small hut. It stands on a small hill.") import time time.sleep(3) print("You make a camp") import time time.sleep(2) print("What do you want to do now?") print(" 1) go 2) or do nothing") hutchoices = input("") something = 10 somethings = 1 hutchoiceyes = ("go") while something &gt; somethings: if (hutchoices) == (hutchoiceyes): print("You walk to the hut.") import time time.sleep(5) break else: print("You do nothing.") hutchoices = input("") import time time.sleep(3) import time time.sleep(5) print("You find an ancient sandstone door.") import time time.sleep(5) print("Say the inscription, if you know it.") password = input("") if (password) == (passwordcode): print("The door slides slowly out of the way.") print("You go down a cobweb filled passage") import time time.sleep(3) print(" You have completed the game, Welldone!") else: print("A trapdoor opens beneath you!") print("You fall down to your doom.") import webbrowser webbrowser.open('http://www.google.co.uk/imgres?q=slender+screen&amp;um=1&amp;hl=en&amp;safe=active&amp;sa=N&amp;tbo=d&amp;tbm=isch&amp;tbnid=evaUdI26IM5C9M:&amp;imgrefurl=http://templardigital.blogspot.com/2012/07/video-game-review-slender.html&amp;docid=gV0cU5I4FRgbLM&amp;imgurl=http://3.bp.blogspot.com/-_BUhzLBaxQM/UBMEEXFKthI/AAAAAAAABa8/Miacjv_EtQs/s1600/Slender%252B2.png&amp;w=474&amp;h=348&amp;ei=wpy0UNv_IsWy0QXKvoD4CA&amp;zoom=1&amp;iact=rc&amp;dur=1&amp;sig=117123526119168881900&amp;page=1&amp;tbnh=145&amp;tbnw=202&amp;start=0&amp;ndsp=26&amp;ved=1t:429,r:17,s:0,i:135&amp;tx=140&amp;ty=96&amp;biw=1280&amp;bih=876') import time time.sleep(5) print("You die, End of game.") import time time.sleep(5) print("SLENDERTEXT THE GAME") import time time.sleep(60) def clearscreen(): if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') print("Adventure part 2") import time time.sleep(4) print("Adventure start's now!") import time time.sleep(2) #This is part 2 of the adventure. All data must be below. #All data will be stored and loaded below. #_____________________________________________________________________________ spiderchoiseyes = ("hit") spiderchoiseno = ("no") reservespace = ("") roadchoice1exec = ("1") roadchoice2exec = ("2") villager = ("yes") hammerchoiceexec = ("yes") hungertakeaway = 1 spiderdamage = random.randint(1,8) global acid acid = 0 global portion potion = 0 global queenhp queenhp = 30 queendamage = random.randint(3,6) #_____________________________________________________________________________ print("You start the adventure") print("As you walk to the entrance, you see a giant spider!") import time time.sleep(3) print("You need to hit it") import time time.sleep(3) print("Hit it as many times as it takes to kill it.") import time time.sleep(2) spider = input("") if (spider) == (spiderchoiseyes): while (spiderhp &gt; death): print("You hit the spider") print("") import time time.sleep(3) print("You do",(dice),"damage") print("") spiderhp = spiderhp - dice if spiderhp &lt; death: print("You do a final blow against the spider") print("") print("The spider has died") break import time time.sleep(3) print("The spider does ",(spiderdamage),"damage") print("") if hp &lt; death: print("OW! The spider does final blow against you!") print("You have died") import time time.sleep(120) break hp = hp - spiderdamage import time time.sleep(3) if spiderhp &lt; death: print("You do a final blow against the spider") print("") print("The spider has died") break import time print("You have",(hp),"left") import time time.sleep(1) print("The spider ",(spiderhp),"left") else: print("You run away!") import time time.sleep(2) print("As you walk down the read slowly.") import time time.sleep(2) print("You see 2 roads again.") import time time.sleep(2) print("There's two roads.") import time time.sleep(2) #Road choices start's from here! print("There's 2 choises") print("Press enter to see the roads") input("") print("2 There's a road leading to a cave") input("") print("1 There's second road, it's leading to a dark forest") import time time.sleep(2) print("Which road do you want to go to? 1 or 2.") roadchoice2 = input("") if (roadchoice2) == (roadchoice2exec): print("You have gone left") import time time.sleep(3) print("You are walking to the cave") import time time.sleep(2) print("You see a muddy footsteps leading to a massive cave.") import time time.sleep("1") print("You see a pickaxe, do you want to examine and add it to your inventury?") hammerchoice = input("") if (hammerchoice) == (hammerchoiceexec): print("You examine the pickaxe") import time time.sleep(2) print("The axe looks a bit rusty") import time time.sleep(2) print("It might have a use later on.") else: print("You walk past it") import time time.sleep(2) print("You continue to walk towards the cave") import time time.sleep print("Your hunger level",hunger) import time time.sleep(1) print("You - You feel hungry, try seaching for a food source") elif (roadchoice2) == (roadchoice1exec): print("You have gone right") import time time.sleep(3) print("As are walking to the dark forest.") import time time.sleep(2) print("Mist slowly decends down to the forest floor") import time time.sleep(3) print("You are a bit lost") import time time.sleep(3) print("There's a full moon, but the mist is blinding your view.") import time time.sleep(3) print("There's a villager") import time time.sleep(3) print("Do you wish to talk to him?") villagertalk = input("") else: print("Slenderman killed you") print("End of the game") import time time.sleep(60) if (villagertalk) == (villager): print("You start a conversation with him") import time time.sleep(3) print("Villagersteve - Watch out for those woods") import time time.sleep(3) print("Villagersteve - These woods contain the most brutal undead.") import time time.sleep(2) print("Villagersteve - Here, Take this bow.") import time time.sleep(3) print("You - Item aquired.") import time time.sleep(2) print("Villagersteve - Wait, I must tell you...") import time time.sleep(3) print("You - You hear a screeching noise.") import time time.sleep(3) print("Villagerbob - I must runnnnnn.......THEY ARE COMING FOR ME!") import time time.sleep(3) print("Villagersteve runs away.") import time time.sleep(3) value = 0 print("Suddenly, You blacked out") time.sleep(2) print("You find yourself in a strange cave...") import time time.sleep(2) if value &lt; potion: print("You think, you need to use a portion now.") import time time.sleep(2) print("Do you want to use potion now?") rawinput = input("") boolean = ("yes") if rawinput == boolean: decreasevalue = 1 print("You have used the potion!") potion = potion - decreasevalue import time time.sleep(2) print("You have",(potion),"left") import time time.sleep(2) print("You gain",(SmallHealing),"hp") hp = hp + SmallHealing import time time.sleep(2) print("You have now",(hp),"left") import time time.sleep(2) print("Suddenly, you see a gigantic spider!") import time time.sleep(2) print("The queen has",(queenhp),"hp") import time time.sleep(2) print("The battle beggins!") while queenhp &gt; death: print("You hit queen spider") print("") import time time.sleep(3) print("You do",(dice),"damage") print("") import time time.sleep(2) print("Spider queen has",(queenhp),"left") print("") queenhp = queenhp - dice if queenhp == death: print("You do a final blow against the queen!") print("") print("The queen spider has died") import time time.sleep(2) print("You finish the game!") import time time.sleep(2) print("To be continued....") break import time time.sleep(3) print("The spider does ",(queendamage),"damage") queendamage = queendamage - hp print("You have",(hp),"left") hp = hp - queendamage print("") if hp == death: print("OW! The spider rips you in half.") print("You have died") import time time.sleep(120) break </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T23:54:12.767", "Id": "33038", "Score": "1", "body": "For a start, please put all the import at the beginning of your file." } ]
[ { "body": "<pre><code>global hp\nhp = 20\n</code></pre>\n\n<p>Global only has an effect inside a function. It does absolutely nothing here. At any rate you should avoid using global.</p>\n\n<pre><code>global dice\nimport random\ndice = random.randint(3,5)\nglobal beardamage\nimport random\nbeardamage = random.randint(1,9)\n</code></pre>\n\n<p>You only need to import things once. Here you have imported <code>random</code> twice, the second time doesn't do anything. Instead, just import everything that you need at the beginning.</p>\n\n<pre><code>x = (\"attack\")\npasswordcode = (\"5665598\")\nroad =(\"left\")\nkey = (\"key\")\n</code></pre>\n\n<p>The parentheses do nothing here. Also, if these are global constants, they should be named in ALL_CAPS.</p>\n\n<pre><code>text = (\"Loading files....\")\nimport time\nimport sys\nfrom random import randrange\nfor c in text:\n sys.stdout.write(c)\n sys.stdout.flush()\n seconds = \"0.\" + str(randrange(1, 4, 1))\n seconds = float(0.5)\n time.sleep(0.01)\ntext = (\"-1%||||||||||||||||100%-\")\nprint(\"\")\nimport time\nimport sys\nfrom random import randrange\nfor c in text:\n sys.stdout.write(c)\n sys.stdout.flush()\n seconds = \"0.\" + str(randrange(1, 4, 1))\n seconds = float(0.01)\n time.sleep(0.01)\n</code></pre>\n\n<p>See you've done the exact same thing twice. This means you should write a function like this:</p>\n\n<pre><code>def slow_print(text):\n for character in text:\n sys.stdout.write(character)\n time.sleep(0.01)\n\nslow_print(\"Loading Files...\")\nslow_print(\"-1%||||||||||||||||100%-\")\n</code></pre>\n\n<p>That way you only need one copy of the actual logic.</p>\n\n<pre><code>def clearscreen():\n if os.name == \"posix\":\n # Unix/Linux/MacOS/BSD/etc\n os.system('clear')\n elif os.name in (\"nt\", \"dos\", \"ce\"):\n # DOS/Windows\n os.system('CLS')\n</code></pre>\n\n<p>You define this, but don't actually use it above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:12:33.703", "Id": "20604", "ParentId": "20601", "Score": "12" } }, { "body": "<pre class=\"lang-py prettyprint-override\"><code>y =input(\"\")\nif (y) == (x):\n</code></pre>\n\n<p>That part, among others, is unclear. Here's my version that's also backward compatible with Python 2. I've only done the bear part.</p>\n\n<pre><code># Imports\nfrom __future__ import print_function # Makes Python 2 support Python 3 print().\nimport os\nimport sys\nfrom random import randint\nfrom time import sleep\n\n# Definitions\n\n# Use raw input in Python 2. Pass for Python 3.\ntry: input = raw_input\nexcept: pass\n\nDEATH = 0\n\ndef clear_screen():\n if os.name == \"posix\":\n # Unix/Linux/MacOS/BSD/etc\n os.system('clear')\n elif os.name in (\"nt\", \"dos\", \"ce\"):\n # DOS/Windows\n os.system('cls')\n\n\n# Other code\n\n# Player stats\nhp = 20\nhunger = 0\nfood_bars = 5\n\n# Bear stats\nbear_hp = 10\n\nprint(\"The bear looks aggressive. The bear has\", bear_hp, \"hp. Type attack or run\")\ncommand = input()\nif command == \"attack\":\n while bear_hp &gt; DEATH:\n print(\"You hit the bear\")\n print()\n sleep(3)\n damage = randint(3, 5)\n print(\"You do\", damage, \"damage\")\n print()\n sleep(2)\n clear_screen()\n bear_hp -= damage\n if bear_hp &lt;= DEATH:\n print(\"You do a final blow against the bear\")\n print()\n print(\"The bear has died\")\n break\n\n sleep(3)\n bear_dmg = randint(1, 9)\n print(\"The bear does\", bear_dmg, \"damage\")\n hp -= bear_dmg\n sleep(2)\n clear_screen()\n print()\n if hp &lt;= DEATH:\n print(\"OW! The bear does final blow against you!\")\n print(\"You have died\")\n sleep(2)\n print(\"Game over\")\n sleep(5)\n sys.exit()\n\n sleep(3)\n print(\"You have\", hp, \"hp left\")\n print()\n sleep(1)\n print(\"The bear has\", bear_hp, \"hp left\")\n sleep(1)\n clear_screen()\nelif command == \"run\":\n print(\"You run away.\")\n sleep(2)\n if food_bars &gt; 0:\n print(\"You have wasted a food bar\")\n food_bars -= 1\n else:\n print(\"You grow hungry\")\n hunger += 1\n print(\"Hunger is\", hunger)\n sleep(3)\nelse:\n print(command, \"is not an option.\")\n</code></pre>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python Style Guide</a> has more tips. If you're on Windows, i recommend using <a href=\"https://gist.github.com/CTimmerman/3fc259d7867c38f6919e\" rel=\"nofollow noreferrer\">Notepad++</a> to write Python.</p>\n\n<p>Since Python 3.6, you can use formatted string literals (a.k.a. \"<a href=\"https://cito.github.io/blog/f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>\"), like so:</p>\n\n<pre><code>&gt;&gt;&gt; name = 'Fred'\n&gt;&gt;&gt; seven = 7\n&gt;&gt;&gt; f'''He said his name is {name.upper()}\n... and he is {6 * seven} years old.'''\n'He said his name is FRED\\n and he is 42 years old.'\n</code></pre>\n\n<p>That snippet also demonstrates Python's triple-quoted strings that can span multiple lines, which can clean up parts like this:</p>\n\n<pre><code> print(f\"\"\"Access granted\n\n Cheat list\n {cheat01} - Walkthrough\n {cheat02} - You should know what that one does\"\"\")\n</code></pre>\n\n<p>Tested via the <a href=\"https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop\" rel=\"nofollow noreferrer\">REPL</a>:</p>\n\n<pre><code>&gt;&gt;&gt; cheat01 = 1\n&gt;&gt;&gt; cheat02 = \"two\"\n&gt;&gt;&gt;\n&gt;&gt;&gt; print(f\"\"\"Access granted\n...\n... Cheat list\n... {cheat01} - Walkthrough\n... {cheat02} - You should know what that one does\"\"\")\nAccess granted\n\nCheat list\n1 - Walkthrough\ntwo - You should know what that one does\n&gt;&gt;&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2015-07-07T16:39:05.213", "Id": "96110", "ParentId": "20601", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T22:30:52.453", "Id": "20601", "Score": "7", "Tags": [ "python", "beginner", "game", "dice", "adventure-game" ], "Title": "Python Adventure game" }
20601
<p><strong>Code Review</strong> is a question and answer site for seeking peer review of your code. It's built and run <em>by you</em> as part of the <a href="https://stackexchange.com">Stack Exchange</a> network of Q&amp;A sites. We're working together to improve the skills of programmers worldwide by taking working code and making it better.</p> <p>Before posting a question, please read <a href="https://codereview.stackexchange.com/help/on-topic"><em>What topics can I ask about here?</em></a> and <a href="https://codereview.stackexchange.com/help/how-to-ask"><em>How do I ask a good question?</em></a>.</p> <p>To get you the best answers, we’ve provided some guidance:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td>1. Code <strong>must</strong> produce the desired output</td> </tr> <tr> <td>2. Code <strong>must not</strong> error or contain known bugs</td> </tr> <tr> <td>3. Titles <strong>should</strong> describe what the code does</td> </tr> <tr> <td>4. The <strong>more</strong> code you provide the <strong>more</strong> we can help</td> </tr> <tr> <td>5. After an answer is posted, you <strong>must not</strong> edit your question to invalidate any advice.</td> </tr> </tbody> </table> </div>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-17T00:19:54.120", "Id": "20605", "Score": "0", "Tags": null, "Title": null }
20605
<p>The quality of your working code with regards to:</p> <ul> <li>Best practices and design pattern usage</li> <li>Security issues</li> <li>Performance</li> <li>Correctness in unanticipated cases</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:20:31.763", "Id": "20606", "Score": "0", "Tags": null, "Title": null }
20606
<ul> <li>Troubleshooting, debugging, or understanding code snippets</li> <li>How to add a feature</li> <li>How to fix compile-time errors, runtime errors, or incorrect results</li> <li>Best practices in general (that is, it's okay to ask "Does this code follow common best practices?", but not "What is the best practice regarding X?")</li> <li>Tools, improving, or conducting code reviews</li> <li>Higher-level architecture and design of software systems</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:20:56.520", "Id": "20607", "Score": "0", "Tags": null, "Title": null }
20607
<p>I found an example of <a href="http://www.obviex.com/samples/Encryption.aspx" rel="nofollow">how to implement Rijndael</a>.</p> <p>This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and decrypt data. As long as encryption and decryption routines use the same parameters to generate the keys, the keys are guaranteed to be the same. The class uses static functions with duplicate code to make it easier to demonstrate encryption and decryption logic. In a real-life application, this may not be the most efficient way of handling encryption, so - as soon as you feel comfortable with it - you may want to redesign this class.</p> <p>Is this code secure enough for production systems?</p> <pre><code>using System; using System.IO; using System.Text; using System.Security.Cryptography; public class RijndaelSimple { /// &lt;summary&gt; /// Encrypts specified plaintext using Rijndael symmetric key algorithm /// and returns a base64-encoded result. /// &lt;/summary&gt; /// &lt;param name="plainText"&gt; /// Plaintext value to be encrypted. /// &lt;/param&gt; /// &lt;param name="passPhrase"&gt; /// Passphrase from which a pseudo-random password will be derived. The /// derived password will be used to generate the encryption key. /// Passphrase can be any string. In this example we assume that this /// passphrase is an ASCII string. /// &lt;/param&gt; /// &lt;param name="saltValue"&gt; /// Salt value used along with passphrase to generate password. Salt can /// be any string. In this example we assume that salt is an ASCII string. /// &lt;/param&gt; /// &lt;param name="hashAlgorithm"&gt; /// Hash algorithm used to generate password. Allowed values are: "MD5" and /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes. /// &lt;/param&gt; /// &lt;param name="passwordIterations"&gt; /// Number of iterations used to generate password. One or two iterations /// should be enough. /// &lt;/param&gt; /// &lt;param name="initVector"&gt; /// Initialization vector (or IV). This value is required to encrypt the /// first block of plaintext data. For RijndaelManaged class IV must be /// exactly 16 ASCII characters long. /// &lt;/param&gt; /// &lt;param name="keySize"&gt; /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. /// Longer keys are more secure than shorter keys. /// &lt;/param&gt; /// &lt;returns&gt; /// Encrypted value formatted as a base64-encoded string. /// &lt;/returns&gt; public static string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize) { // Convert strings into byte arrays. // Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); // Convert our plaintext into a byte array. // Let us assume that plaintext contains UTF8-encoded characters. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // First, we must create a password, from which the key will be derived. // This password will be generated from the specified passphrase and // salt value. The password will be created using the specified hash // algorithm. Password creation can be done in several iterations. PasswordDeriveBytes password = new PasswordDeriveBytes( passPhrase, saltValueBytes, hashAlgorithm, passwordIterations); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(keySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate encryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform encryptor = symmetricKey.CreateEncryptor( keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. string cipherText = Convert.ToBase64String(cipherTextBytes); // Return encrypted string. return cipherText; } /// &lt;summary&gt; /// Decrypts specified ciphertext using Rijndael symmetric key algorithm. /// &lt;/summary&gt; /// &lt;param name="cipherText"&gt; /// Base64-formatted ciphertext value. /// &lt;/param&gt; /// &lt;param name="passPhrase"&gt; /// Passphrase from which a pseudo-random password will be derived. The /// derived password will be used to generate the encryption key. /// Passphrase can be any string. In this example we assume that this /// passphrase is an ASCII string. /// &lt;/param&gt; /// &lt;param name="saltValue"&gt; /// Salt value used along with passphrase to generate password. Salt can /// be any string. In this example we assume that salt is an ASCII string. /// &lt;/param&gt; /// &lt;param name="hashAlgorithm"&gt; /// Hash algorithm used to generate password. Allowed values are: "MD5" and /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes. /// &lt;/param&gt; /// &lt;param name="passwordIterations"&gt; /// Number of iterations used to generate password. One or two iterations /// should be enough. /// &lt;/param&gt; /// &lt;param name="initVector"&gt; /// Initialization vector (or IV). This value is required to encrypt the /// first block of plaintext data. For RijndaelManaged class IV must be /// exactly 16 ASCII characters long. /// &lt;/param&gt; /// &lt;param name="keySize"&gt; /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. /// Longer keys are more secure than shorter keys. /// &lt;/param&gt; /// &lt;returns&gt; /// Decrypted string value. /// &lt;/returns&gt; /// &lt;remarks&gt; /// Most of the logic in this function is similar to the Encrypt /// logic. In order for decryption to work, all parameters of this function /// - except cipherText value - must match the corresponding parameters of /// the Encrypt function which was called to generate the /// ciphertext. /// &lt;/remarks&gt; public static string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize) { // Convert strings defining encryption key characteristics into byte // arrays. Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); // Convert our ciphertext into a byte array. byte[] cipherTextBytes = Convert.FromBase64String(cipherText); // First, we must create a password, from which the key will be // derived. This password will be generated from the specified // passphrase and salt value. The password will be created using // the specified hash algorithm. Password creation can be done in // several iterations. PasswordDeriveBytes password = new PasswordDeriveBytes( passPhrase, saltValueBytes, hashAlgorithm, passwordIterations); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(keySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform decryptor = symmetricKey.CreateDecryptor( keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(cipherTextBytes); // Define cryptographic stream (always use Read mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. byte[] plainTextBytes = new byte[cipherTextBytes.Length]; // Start decrypting. int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. // Let us assume that the original plaintext string was UTF8-encoded. string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); // Return decrypted string. return plainText; } } /// &lt;summary&gt; /// Illustrates the use of RijndaelSimple class to encrypt and decrypt data. /// &lt;/summary&gt; public class RijndaelSimpleTest { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main(string[] args) { string plainText = "Hello, World!"; // original plaintext string passPhrase = "Pas5pr@se"; // can be any string string saltValue = "s@1tValue"; // can be any string string hashAlgorithm = "SHA1"; // can be "MD5" int passwordIterations = 2; // can be any number string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes int keySize = 256; // can be 192 or 128 Console.WriteLine(String.Format("Plaintext : {0}", plainText)); string cipherText = RijndaelSimple.Encrypt(plainText, passPhrase, saltValue, hashAlgorithm, passwordIterations, initVector, keySize); Console.WriteLine(String.Format("Encrypted : {0}", cipherText)); plainText = RijndaelSimple.Decrypt(cipherText, passPhrase, saltValue, hashAlgorithm, passwordIterations, initVector, keySize); Console.WriteLine(String.Format("Decrypted : {0}", plainText)); } } </code></pre>
[]
[ { "body": "<p>This code uses obsolete <code>PasswordDeriveBytes</code> class, use <code>Rfc2898DeriveBytes</code> class instead (Thanks @tom for highlighting this issue):</p>\n\n<pre><code>Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(\n passPhrase,\n saltValueBytes,\n passwordIterations);\n</code></pre>\n\n<p>Also, even though <code>IV</code> (initVectorBytes) may be publicly stored it should not be reused for different encryptions. You can derive it from pseudo-random bytes:</p>\n\n<pre><code>byte[] initVectorBytes = password.GetBytes(symmetricKey.BlockSize / 8);\n</code></pre>\n\n<p>Other than that encryption/decryption looks properly implemented, and I completely agree with original code writer that initialization/duplicate steps should be taken to constructor. It will reduce the number of parameters in Encrypt/Decrypt methods to one - actual payload.</p>\n\n<p>Depending on your specifics you can also expose methods accepting and returning encrypting/decrypting streams for large encryption volumes if necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:39:37.573", "Id": "33102", "Score": "0", "body": "what about the obselete GetBytes method? and the constant IV?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:45:06.667", "Id": "33105", "Score": "0", "body": "Oops, missed this part. Will update the answer, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T17:26:41.497", "Id": "33120", "Score": "0", "body": "In order to properly decrypt previously encrypted string you need to pass the same `IV` that was used during encryption. In addition different encryptions should use different `IV`s. You can store `IV` the same way you store salt, but since it functions similarly to salt I would rather derive it from password+salt dependent random bytes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T17:46:57.407", "Id": "33121", "Score": "0", "body": "Deleted my previous comment. Question should have been - if I am going to use a unique IV for every string that I encrypt, how do get that back when I decrypt?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T19:18:41.287", "Id": "33129", "Score": "0", "body": "You should store the salt along with encrypted text in order to decrypt it. Same stands for `IV` - you should have it at the time of decryption, but since it's redundant to store 2 \"salting\" fields I suggested to build it from password+salt." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T19:51:11.447", "Id": "33131", "Score": "0", "body": "I'm not quite following. Could you point me to an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T21:02:04.953", "Id": "33142", "Score": "0", "body": "In order to encrypt and decrypt the payload you need: password, salt, IV. Password is provided by user, salt and IV should be generated by your application and stored next to encrypted text. In my answer I have shown how you can generate IV instead of storing it along with encrypted text and salt." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T20:11:52.203", "Id": "34627", "Score": "0", "body": "Symmetric encryption should only be used for certain types of data to be encrypted. For passwords, a hash is generally sufficient and is preferred as you shouldn't be sending around passwords, hence no reason to be able to retrieve them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T21:59:40.540", "Id": "34631", "Score": "0", "body": "@Shelakel The code under review does not specify the purpose of encryption, so not sure why you mentioned that passwords should be hashed (which is true though)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:34:16.263", "Id": "20641", "ParentId": "20608", "Score": "3" } } ]
{ "AcceptedAnswerId": "20641", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:26:19.773", "Id": "20608", "Score": "3", "Tags": [ "c#", "security", "aes" ], "Title": "Rijndael for use in production systems" }
20608