body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Before going out and learning a full fledged framework I'm trying to understand the MVC pattern coding basic stuff, at the moment I'm testing with MVC applied to form validation.</p> <p>After reading a good amount of articles and code examples I came out with my own version, nothing too elaborate as it's mostly for learning, so I need advice in the structure.</p> <p>For this example I have a basic form which inserts a Category into a database, so I divided it like this:</p> <ul> <li>class Category extends Operations: This class only deals with database management stuff CRUD operations (the business logic), defines which fields are required and the table name. I call this my model.</li> <li>abstract class Operations: Will be extended by other classes that I'll make in the future such as Products, Clients, etc. Contains common properties (id, attributes). Again part of the model.</li> <li>class CategoryControl: The controller, deals with $_POST data, setting the corresponding attributes for the Category object and gets its status (insert success/failed, for example).</li> <li>abstract class Controller: Generic class which contains form submit status and executes the corresponding CRUD operation.</li> <li>Finally the view which is the form, only requesting for the object status to display a sucess/failure message to the user.</li> </ul> <p>Here's the code for each:</p> <p><strong>view.php</strong></p> <pre><code>&lt;?php require('clases/Database.php'); require('clases/CategoryControl.php'); $category = new CategoryControl($database); ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="view.php" method="post"&gt; &lt;label&gt;Name &lt;/label&gt;&lt;input type="text" name="name" maxlength="80" /&gt;&lt;br /&gt; &lt;label&gt;Parent &lt;/label&gt;&lt;input type="text" name="parent" maxlength="80" /&gt;&lt;br /&gt; &lt;input type="submit" name="submit" value="Insert" /&gt; &lt;/form&gt; &lt;?php if ($category-&gt;getStatus() == 1): ?&gt; &lt;p&gt;Inserted Sucess&lt;/p&gt; &lt;?php elseif ($category-&gt;getStatus() == 0) : ?&gt; &lt;p&gt;Null fields&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Category.php</strong></p> <pre><code>&lt;?php require("Operations.php"); class Category extends Operations { const TABLE = 'category'; private $reqFields = array('name', 'parent'); public function __construct($pdo_link) { parent::__construct($pdo_link); } public function insert() { if ($this-&gt;checkNullFields($this-&gt;reqFields)) { $stmt = $this-&gt;database-&gt;prepare("INSERT INTO ". self::TABLE ." (name, parent) VALUES (:name, :parent)"); foreach ($this-&gt;attribs as $field =&gt; $value) $stmt-&gt;bindValue(':'.$field, $value); $stmt-&gt;execute(); $stmt = NULL; return true; } else return false; } public function update() { if ($this-&gt;checkNullFields($this-&gt;reqFields)) { $stmt = $this-&gt;database-&gt;prepare("UPDATE ". self::TABLE ." SET name = :name, parent = :parent WHERE id = :id"); foreach ($this-&gt;attribs as $field =&gt; $value) $stmt-&gt;bindValue(':'.$field, $value); $stmt-&gt;bindValue(':id', $this-&gt;id); $stmt-&gt;execute(); $stmt = NULL; return true; } else return false; } public function delete() { if (!empty($this-&gt;id)) { $stmt = $this-&gt;database-&gt;prepare("DELETE FROM ". self::TABLE ." WHERE id = :id"); $stmt-&gt;bindValue(':id', $this-&gt;id); $stmt-&gt;execute(); $stmt = NULL; return true; } else return false; } } ?&gt; </code></pre> <p><strong>Operations.php</strong></p> <pre><code>&lt;?php abstract class Operations { protected $database; // PDO link public $id; public $attribs; public $status; protected function __construct($pdo_link) { $this-&gt;database = $pdo_link; } abstract protected function insert(); abstract protected function update(); abstract protected function delete(); protected function checkNullFields($reqFields) { foreach ($reqFields as $i =&gt; $value) { if (empty($this-&gt;attribs[$value])) return false; } return true; } } ?&gt; </code></pre> <p><strong>CategoryControl.php</strong></p> <pre><code>&lt;?php require('Category.php'); require('Controller.php'); class CategoryControl extends Controller { public function __construct($pdo_link) { $this-&gt;model = new Category($pdo_link); if ($this-&gt;checkSubmit()) { $this-&gt;initAttribs(); $this-&gt;processPostData(); } } public function initAttribs() { $this-&gt;model-&gt;id = isset($_GET['id']) ? $_GET['id'] : ''; $this-&gt;model-&gt;attribs = array( 'name' =&gt; isset($_POST['name']) ? $_POST['name'] : '', 'parent' =&gt; isset($_POST['parent']) ? $_POST['parent'] : '' ); } } ?&gt; </code></pre> <p><strong>Controller.php</strong></p> <pre><code>&lt;?php abstract class Controller { protected $model; protected function checkSubmit() { if (isset($_POST['submit'])) { return true; } else { $this-&gt;model-&gt;status = -1; return false; } } protected function processPostData() { if ($_POST['submit'] == 'Insert') $this-&gt;model-&gt;status = $this-&gt;model-&gt;insert(); else if ($_POST['submit'] == 'Update') $this-&gt;model-&gt;status = $this-&gt;model-&gt;update(); else if ($_POST['submit'] == 'Delete') $this-&gt;model-&gt;status = $this-&gt;model-&gt;delete(); } abstract protected function initAttribs(); public function getStatus() { return $this-&gt;model-&gt;status; } } ?&gt; </code></pre>
[]
[ { "body": "<p><strong>Directory Structure</strong></p>\n\n<p>When implementing a heavy design pattern like MVC, the best thing to do is set up your directory structure to support it. For example, you currently have, at the very least, your Model and Controller in the same directory. When dealing with just a few files this may seem fine, but once you start expanding you will soon realize that this will quickly become a mess. Look around at how different MVC frameworks set up their directory structure and adapt yours to whichever fits your needs. For example, I've adapted something pretty similar to Zend's, which looks something like this:</p>\n\n<pre><code>application\n config\n models\n views\n controllers\ndata\n cache\n logs\npublic\n js\n css\n images\n</code></pre>\n\n<p>Not saying you have to adopt this structure, just saying its the one I like and have found to meet all of my needs. You can also create your own. Don't limit yourself to prefab solutions, but don't dismiss them either. There was a lot of thought put behind those solutions, so they are likely to be pretty efficient.</p>\n\n<p><strong>Views and Index</strong></p>\n\n<p>Your Views should not be knowledgeable of the type of framework you are using. This makes it easier to change the framework should it ever become necessary. So, including the Model and Controller in the View is the wrong way to go about this. A View should only have simple templating variables, and maybe a header or footer inclusion.</p>\n\n<p>Remember, the index is not a view. It is the first page of your website and should be the page all requests are made from. The Controller should be included in the index via some get variable, or some default value when first run. The Model is always associated with the Controller, so it is the Controller's job to load it, not the index's or the View's. So, a link to mywebsite.com should result in a default Model, Controller, and View being loaded, or just a Controller or View, depending on what default page or implementation you end up using. Similarly, a link to <code>mywebsite.com?controller=Controller&amp;view=View</code> or rewritten to use modrewrite (think its modrewrite) as <code>mywebsite.com/Controller/View</code> should load the correct Controller and pass the View to that Controller to be loaded. So your index should look something like this.</p>\n\n<pre><code>&lt;?php\nrequire 'classes/Database.php';\nrequire 'clases/CategoryControl.php';\n$category = new CategoryControl( $database );\n$category-&gt;render( $view );\n?&gt;\n</code></pre>\n\n<p>Notice the render method. It doesn't have to be called render, but typically a controller has such a method that extracts all of the template data into the local variable scope and includes the view. This is the implementation I use, but it is not the only one. Some people don't like using <code>extract()</code> and instead use a foreach loop to make variable-variables, some use the class implementation as you are, but I find the extract cleaner. However, I would stick to one of the first two implementations. Using a class instance requires a dependency on the framework, which we've already established was bad, and makes your code less non-PHP user friendly. Meaning a pure HTML programmer will have some difficulties interfacing the PHP and HTML. Its better to abstract those class methods to variables to help those non-PHP users and because it just cleans up the HTML. Even if you aren't in a group, it is still a good idea to program like you are. This gets you in the right frame of mind for future group projects, and typically makes your code more reusable.</p>\n\n<pre><code>//In Controller\npublic function render( $view ) {\n extract( $this-&gt;data );\n include $view;\n}\n\n//In View\n&lt;?php if( $status == 1 ) : ?&gt;\n</code></pre>\n\n<p>By the way, where did $database come from? You just dumped it into the category constructor without defining it. Normally I would assume this came from the controller, but you don't appear to be following this method. I would hate to assume this is a global.</p>\n\n<p><strong>Models</strong></p>\n\n<p>The structure of your Models are fine, but there are a few of things I would like to point out.</p>\n\n<p>First, you don't need to redeclare a method that has been defined in a parent class unless you are planning on doing something extra with it. Inheritance declares that any non-private methods and properties are automatically included in any children without the express need of declaring it so. In other words, defining a constructor in a child just to declare it to use the parent constructor is redundant. If you did something before or after calling the parent constructor, then that would be different, that's a form of polymorphism.</p>\n\n<p>The second thing is that abstract classes cannot be instantiated, therefore they should not, and can not have constructors. You are likely getting warnings about this in the background. Instead use an <code>init()</code> method and in each child constructor call it, or explicitly define the constructors in the child classes.</p>\n\n<p>Another thing I want to point out, though I'm sure some will disagree, is that you shouldn't use the \"braceless\" syntax. PHP inherently requires braces for its statements. It allows you to ignore this requirement so long as you promise not to use more than one line. But that's where it ends. It would be different if there was not that limitation, but that's not the case. Once you have two lines, you have to go back and add those braces, and this is where many people make mistakes. Besides, having to go back and add those braces just distracts from the task at hand. I would much rather just add them to begin with and later only have to start typing. PHP , in my opinion, should not allow this syntax unless they plan to change their syntax to allow for full bracless coding. Sorry for the mini rant, I just figured I'd do my best to warn you off of it. If you like braceless code, try Python :)</p>\n\n<p>There is no need to NULL out a variable, or anything really. This kind of micro-memory management just leads to sloppy code and the minute increase in performance is so negligible as to not be worth it. I know some people have been pushing this on reddit and in some blog posts, but the benefits do not outweigh the costs.</p>\n\n<p>Your <code>insert()</code> and <code>update()</code> methods are violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, you can combine these methods into a third shared method. Then each specific method would pass the proper MySQL statement to the shared method. The only catch would be adding the \"id\" to the <code>$attribs</code> property before running the shared method so that it will be bound, and you may need to remove it after. But this is still better.</p>\n\n<p><strong>Controllers</strong></p>\n\n<p>The structure of your Controllers are also fine. There's only one thing I would like to point out here: Sanitize your user input. You are validating it, at least in as much as you are ensuring it exists, but you don't validate it. If your PHP version is >= 5.2, you can check out <code>filter_input()</code> function. This also makes checking if an index is set unnecessary as it will return FALSE if not.</p>\n\n<p>All in all, I'm very impressed. The implementation is sound and just needs some minor tweaks. Most people don't take to it so quickly. I had a whole disclaimer about how MVC was hard to learn but I had to remove it because you didn't need it :P Anyways, I hope this helps. If you have any questions, just leave me a comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:06:48.153", "Id": "25239", "Score": "0", "body": "That's what I call an asnwer! Nice piece of advice there, I sure will be re-reading this from time to time. Now about the directory structure I already had in mind something like that, that was basically a stub. The thing i still find difficult to grasp is the single entry point, I guess it's just matter of more reading and practice, can't get it right at the first try. About $database, yes it's a global instance of the PDO class which is inside the 'Database.php' code and every page includes it (I found it easier to implement it that way while I learn the single entry point concept." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:13:31.610", "Id": "25240", "Score": "0", "body": "About the model, i recognize there are indeed some redundancies in the CRUD methods, in fact I first programmed them like you mentioned (a general insert/upd method), but then changed it since I found it kinda clunky (as you said, separating the ID from the attribs, etc). About the php braces, I've found myself adding braces now and then since I'm too lazy to add braces for one liners which then grow to be more complicated, it's just matter of discipline. About the micro-optimizations, it's a result of reading a lot of opinions, i guess php garbage collector takes care of those trivial things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:15:55.723", "Id": "25241", "Score": "0", "body": "@user1647798: The single entry point is a bit hard to grasp. For a while there my mind refused to accept it was possible and I kept trying to do extra stuff on the index. I don't know what finally clicked, but something did, and its relatively simple once you get past the barrier. Anyways, don't use globals, they are evil and should be completely removed from the language. If you need to keep a single instance, do so through injection. In this case, the first time you should need it is in the index when injecting it into the controller. Just create it then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:17:43.650", "Id": "25242", "Score": "0", "body": "I'm going slow and steady, I programmed a website procedurally and just recently I've started to learn the OOP paradigm and MVC to rewrite it, since It's a nightmare to maintain a site coded like that. All in all thanks for taking the time to formulate that answer, I appreciate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T01:40:05.840", "Id": "417201", "Score": "0", "body": "`and the minute increase in performance is so negligible as to not be worth it` In fact these days you might even cause more resources usage bypassing PHP being efficient in the background by forcing something that is not really necessary. Like manual garbage collection from days gone." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T17:29:05.600", "Id": "15546", "ParentId": "15530", "Score": "6" } } ]
{ "AcceptedAnswerId": "15546", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T05:06:31.340", "Id": "15530", "Score": "5", "Tags": [ "php", "design-patterns", "mvc", "form" ], "Title": "Correct MVC pattern implementation for form validation" }
15530
<p>This is just my simple structure. I want to know if there is a better way than this because I have so many lines of code already.</p> <pre><code> &lt;?php $p1speed = 5; $p2speed = 3; //way for next turn: 1 for turn $p1 = 0; $p2 = 0; if($p1speed&gt;$p2speed) { $p1 = 1; $p2 = 0; } else if($p2speed&gt;$p1speed) { $p1 = 0; $p2 = 1; } $count=0; //begin while($count&lt;5){ if($p1==1) { echo 'P1 turns &lt;br&gt;'; //adjust $p1 = 0; $p2 = 1; } else if($p2==1) { echo 'P2 turns &lt;br&gt;'; //adjust $p1 = 1; $p2 = 0; } $count++; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:09:47.347", "Id": "25206", "Score": "0", "body": "What are you trying to achieve? Is the 5 in the while loop fixed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:13:12.027", "Id": "25208", "Score": "0", "body": "yes, A battle game" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T12:38:18.587", "Id": "25221", "Score": "0", "body": "Why are you giving the choice of PHP, C, and C++? The languages are utterly different." } ]
[ { "body": "<p>If the 5 in the while loop is fixed you can simply unroll it as: [C code, but I hope you get the idea]</p>\n\n<pre><code>void turn(int player);\n\nvoid foo(){\n int p1speed = 3;\n int p2speed = 5;\n\n int first_player;\n int second_player\n\n if(p1speed &gt; p2speed){\n first_player = 1;\n second player = 2;\n }\n else{\n first_player = 2;\n second_player = 1;\n }\n\n //now, instead of the while loop you can have:\n turn(first_player);\n turn(second_player);\n turn(first_player);\n turn(second_player);\n turn(first_player);\n}\n\nvoid turn(int player){\n printf(\"Player %d turn\", player);\n int other = 3 - player; // Nice trick\n //Do something\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:43:58.130", "Id": "25209", "Score": "0", "body": "fix but not 5 , 30 instead :) thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T08:06:14.810", "Id": "25211", "Score": "0", "body": "well, unrolling a 30 loop makes less sense, but you could still use a `for(int i = 0; i < 15; i++){turn(first_player);turn(second_player);}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T14:38:52.613", "Id": "152619", "Score": "0", "body": "This does not sound like a very portable alternative... Can you please expand on why you would do it this way?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:22:45.737", "Id": "15532", "ParentId": "15531", "Score": "-1" } }, { "body": "<p>This is a refactoring of the original code. It picks the starting player and then uses a simple toggle <code>($currentPlayer = ($currentPlayer == 1) ? 2 : 1;)</code> to determine which player goes next for 5 rounds. </p>\n\n<pre><code>$currentPlayer = 1;\n\nif ($player2speed &gt; $player1speed) {\n\n $currentPlayer = 2;\n\n}\n\n$count = 0;\n\nwhile ($count &lt; 5) {\n\n echo $currentPlayer . \" turns&lt;br/&gt;\";\n\n $currentPlayer = ($currentPlayer == 1) ? 2 : 1;\n\n $count ++;\n}\n</code></pre>\n\n<p>Note, the current code fails if both player's speeds are the same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T14:41:57.330", "Id": "152620", "Score": "0", "body": "Would you please add more detail to your answer as to how you would improve the code? As it stands this answer is mostly just a code dump..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T15:39:54.440", "Id": "152635", "Score": "0", "body": "@Phrancis It's just a re-factoring of the original code mainly to redress the 'I want to know if there is a better way than this because I have so much of line code already please help'\n\nIt picks the starting player and then uses a simple toggle ($currentPlayer = ($currentPlayer == 1) ? 2 : 1;) to determine which player goes next for 5 rounds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T16:13:03.920", "Id": "152644", "Score": "1", "body": "Thanks for clarifying. Also just noticed you posted this 3 years ago, nice to see you're still around!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T11:00:57.267", "Id": "15535", "ParentId": "15531", "Score": "2" } }, { "body": "<p>Why have to tagged this as C and C++? There is nothing here to do with either language, this is all PHP.</p>\n\n<p>Why are you explicitly declaring an elseif statement when comparing speed? The only reason I can think of is if you are also going to compare for equality (going same speed). But you aren't, so an else statement would serve a better purpose here by comparing for both equality and less-than. Unless the initial \"turn\" variable values of 0 are supposed to cover this eventuality, but then they should be defined in a final else, otherwise this just looks odd. Besides, the while loop makes me think this is not the case.</p>\n\n<pre><code>if( $p1speed &gt; $p2speed ) {\n //change turns\n} else {\n //equivalent to if( $p2speed &gt;= $p1speed ) \n}\n//OR\nif( $p1speed &gt; $p2speed ) {\n //change turns\n} elseif( $p2speed &gt; $p1speed ) {\n //change turns\n} else {\n //default turns\n}\n</code></pre>\n\n<p><strong>Extending Player Pool</strong></p>\n\n<p>Some of the following might be beyond the scope of your project, but figured I'd mention it anyways, as its something to think about when developing a game, or any kind of application. Does my code allow for expansion? Is expansion necessary? Richard has already pointed out a better way to treat turns (+1), but the problem with his implementation is that it does not easily allow for more than two players. To accomplish this, you will need a counter, which you could reuse from the loop, and some sort of operation to reset the index when the counter has exceeded maximum number of players, I'm thinking modulo. So for example, using Richard's example we can easily determine who's turn it is on every iteration by using the following bit of code inside the loop.</p>\n\n<pre><code>$currentPlayer = $counter % $numberOfPlayers;\n</code></pre>\n\n<p>How then do we determine which player is first with a larger player pool? Which is second? We can't manually write each comparison. Well, we could, but that would be a bit much. Instead, if we get all the player speeds into an array, we can sort it and use the array indices to determine the order. Of course, that means we will have to tweak the above algorithm to use the array positions instead of a sequential incremental to ensure players going faster are not behind players going slower, but that's simple enough.</p>\n\n<pre><code>$speeds = array(\n 5,//player 1\n 3,//player 2\n 2//player 3\n);\n$numberOfPlayers = count( $speeds );\nasort( $speeds );\n//do other things and eventually start loop\n$position = $counter % $numberOfPlayers;\n$currentPlayer = $speeds[ $position ];\n</code></pre>\n\n<p>The problem with the above example is that the players are already in order, so it does not demonstrate this very well. But take my word for it, those numbers could easily be mixed up and still work. <code>asort()</code> is the key here. It sorts an array and keeps the array's indices in tact.</p>\n\n<p><strong>Loops</strong></p>\n\n<p>While loops are for testing a condition until otherwise (dis)proven. In other words, \"is this statement TRUE?\" Loop until it is. Typically this is done for things that already have this kind of boolean type associated with it and just need certain conditions to be met before it is passed. Such as when reading from a file. The problem with these kinds of loops is that it is very easy to accidentally create an infinite loop and crash the program. The need for a while loop should be rare.</p>\n\n<p>For loops are for looping over a set of sequential data using an explicit counter.</p>\n\n<p>Foreach loops are for looping over a set of non-sequential data using an internal (invisible) counter.</p>\n\n<p>So, the question here is: Why are you recreating a for loop with a while loop? As miniBill pointed out, a for loop is better here. Hopefully the above explanations can help you figure out why. If your concern is speed, know that PHP has come a long way since the early days and for loops are now much better.</p>\n\n<pre><code>for( $i = 0; $i &lt; 5; $i++ ) {\n</code></pre>\n\n<p><strong>Cleaning Up</strong></p>\n\n<p>The main problem you seem to be having right now is that you are using procedural code, which, as you have noticed, results in a lot of bulky, repetitive code. The only cure for this is to start using a class or functions. I'd lean more towards a class here, but if you are unfamiliar with the concept, learning how to implement functions properly might be a better first step. Just for the sake of example, here is a turn toggle as I would write it in a class method. Of course, there is a better way to do this, as we have already discussed, but it serves to demonstrate the point quite well.</p>\n\n<pre><code>public function toggleTurns() {\n $this-&gt;p1 = $this-&gt;p1 == 1 ? 2 : 1;\n $this-&gt;p2 = $this-&gt;p2 == 1 ? 2 : 1;\n}\n\n//in some other method\nfor( $i = 0; $i &lt; 5; $i++ ) {\n if($p1==1) {\n echo 'P1 turns &lt;br&gt;';\n } else {\n echo 'P2 turns &lt;br&gt;';\n }\n\n $this-&gt;toggleTurns();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T15:15:14.013", "Id": "15540", "ParentId": "15531", "Score": "2" } }, { "body": "<p>From:\n<a href=\"http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html\" rel=\"nofollow\">Intel 64 and IA-32 Architectures Optimization Reference Manual</a></p>\n\n<blockquote>\n <p>Intel 64 and IA-32 Architectures Optimization Reference Manual<br>\n Chapter 3 GENERAL OPTIMIZATION GUIDELINES<br> \n 3.4.1 Branch Prediction Optimization <br><br>\n Eliminate branches whenever possible.</p>\n</blockquote>\n\n<pre><code>$toggle = array(1,0);\n$turns = array(0=&gt; array(0=&gt;'P1 Turns&lt;br/&gt;',1=&gt;''),\n 1=&gt; array(0=&gt;'P2 Turns&lt;br/&gt;',1=&gt;''));\n\n\n\nfor( $i = 0; $i &lt; 5; $i++ ) {\n $p1 = toggle[$p1];\n $p2 = toggle[$p2];\n echo $turns[$p1][$p2];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T17:44:13.977", "Id": "84821", "ParentId": "15531", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T06:58:56.220", "Id": "15531", "Score": "2", "Tags": [ "php" ], "Title": "\"P1 attacks P2\" and \"P2 attacks P1\"" }
15531
<p>I have a java based server application that needs to support multiple clients. In the main class I have a method that runs in an infinite loop and waits for client connection. Following is this method:</p> <pre><code>public void listen() { try { serverSocket = new ServerSocket(portNo); while (true) { clientSocket = serverSocket .accept(); ClientMgr client = new ClientMgr(clientSocket); client.start(); //start a separate thread to manage client } } catch (Exception e) { //handle any exceptions } finally { close(); //close any open sockets } } </code></pre> <p>I would like to know how I can design (change) this method such that it can be tested by a unit test. If it is already testable then suggest how this can be tested?</p>
[]
[ { "body": "<p>I think it's possible to test this method with another threads and some helper code which passes fix requests to your server and checks the server's answer. It definitely requires some work and I'm not sure how should we call this test: unit test, module test or integration test? Anyway, make sure that the checks happens on the the test method's thread, otherwise JUnit won't detect the uncatched exceptions.</p>\n\n<p>To make it more testable I'd separate the <code>ClientManager</code> creation to an <code>IncomingConnectionHandler</code> interface and implementation and pass an instance of this object to the class of the <code>listen</code> method.</p>\n\n<pre><code>public interface IncomingConnectionHandler {\n void handle(Socket socket);\n}\n\npublic final class IncomingConnectionHandlerImpl {\n\n public IncomingConnectionHandlerImpl {\n }\n\n public void handle(final Socket socket) {\n final ClientManager client = new ClientManager(clientSocket);\n client.start();\n }\n}\n\n\npublic class MySocketListener {\n\n private final IncomingConnectionHandler incomingConnectionHandler;\n\n public MySocketListener(final IncomingConnectionHandler incomingConnectionHandler) {\n this.incomingConnectionHandler = checkNotNull(incomingConnectionHandler, \n \"incomingConnectionHandler cannot be null\");\n }\n\n public void listen() {\n try {\n serverSocket = new ServerSocket(portNo);\n while (true) {\n final Socket clientSocket = serverSocket.accept();\n incomingConnectionHandler.handle(clientSocket);\n }\n } catch (Exception e) {\n //handle any exceptions\n } finally {\n close(); //close any open sockets\n }\n }\n</code></pre>\n\n<p>After this in the unit test you could do the following:</p>\n\n<ul>\n<li>create a <code>MySocketListener</code> instance with a mocked <code>IncomingConnectionHandler</code>,</li>\n<li>start an new thread which connects to the port of <code>MySocketListener</code>,</li>\n<li>check that the handle method of the mocked <code>IncomingConnectionHandler</code> was called with a live/proper <code>Socket</code> instance,</li>\n<li>shutdown the helper thread and the <code>MySocketListener</code>.</li>\n</ul>\n\n<hr>\n\n<p>Consider not using using abbreviation like <code>Mgr</code>. It would make the code readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T15:16:56.223", "Id": "15541", "ParentId": "15534", "Score": "3" } } ]
{ "AcceptedAnswerId": "15541", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T10:04:00.810", "Id": "15534", "Score": "3", "Tags": [ "java", "unit-testing", "junit" ], "Title": "Designing a listener method and making it Testable" }
15534
<pre><code>/* Create a random maze */ package main import ( "fmt" "math/rand" "time" ) const ( mazewidth = 15 mazeheight = 15 ) type room struct { x, y int } func (r room) String() string { return fmt.Sprintf("(%d,%d)", r.x, r.y) } func (r room) id() int { return (r.y * mazewidth) + r.x } // whetwher walls are open or not. // There are (num_rooms * 2) walls. Some are on borders, but nevermind them ;) type wallregister [mazewidth * mazeheight * 2]bool var wr = wallregister{} // rooms are visited or not type roomregister [mazewidth * mazeheight]bool var rr = roomregister{} func main() { rand.Seed(time.Now().Unix()) stack := make([]room, 0, mazewidth*mazeheight) start := room{0, 0} // mark start position visited rr[start.id()] = true // put start position on stack stack = append(stack, room{0, 0}) for len(stack) &gt; 0 { // current node is in top of the stack current := stack[len(stack)-1] // Slice of neighbors we can move availneighbrs := current.nonvisitedneighbors() // cannot move. Remove this room from stack and continue if len(availneighbrs) &lt; 1 { stack = stack[:len(stack)-1] continue } // pick a random room to move. next := availneighbrs[rand.Intn(len(availneighbrs))] // mark next visited rr[next.id()] = true // open wall between current and next: first, second := orderrooms(current, next) // second is either at the right or bottom of first. if second.x == first.x+1 { wr[first.id()*2] = true } else if second.y == first.y+1 { wr[first.id()*2+1] = true } else { // probably impossible or maybe not... panic("Wot?!?") } // push next to stack stack = append(stack, next) } // print maze // print upper border for x := 0; x &lt; mazewidth; x++ { if x == 0 { fmt.Printf(" ") } else { fmt.Printf("_ ") } } fmt.Println() for y := 0; y &lt; mazeheight; y++ { fmt.Printf("|") // left border for x := 0; x &lt; mazewidth; x++ { id := room{x, y}.id() right := "|" bottom := "_" if wr[id*2] { right = " " } if wr[id*2+1] { bottom = " " } if x == mazewidth-1 &amp;&amp; y == mazeheight-1 { right = " " } fmt.Printf("%s%s", bottom, right) } fmt.Println() } } // return slice of neighbor rooms func (r room) neighbors() []room { rslice := make([]room, 0, 4) if r.x &lt; mazewidth-1 { rslice = append(rslice, room{r.x + 1, r.y}) } if r.x &gt; 0 { rslice = append(rslice, room{r.x - 1, r.y}) } if r.y &lt; mazeheight-1 { rslice = append(rslice, room{r.x, r.y + 1}) } if r.y &gt; 0 { rslice = append(rslice, room{r.x, r.y - 1}) } return rslice } // return rooms that are not visited yet func (r room) nonvisitedneighbors() []room { rslice := make([]room, 0, 4) for _, r := range r.neighbors() { if rr[r.id()] == false { rslice = append(rslice, r) } } return rslice } // order to rooms by closeness to origin (upperleft) func orderrooms(room1, room2 room) (room, room) { dist1 := room1.x*room1.x + room1.y*room1.y dist2 := room2.x*room2.x + room2.y*room2.y if dist1 &lt; dist2 { return room1, room2 } return room2, room1 } </code></pre> <p><a href="http://play.golang.org/p/8W_FbBfUjb">http://play.golang.org/p/8W_FbBfUjb</a> (You can run it here. But since time.Now() is fixed there, you will always get same maze.)</p> <p>In any aspect of it, how does it look?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T14:12:36.663", "Id": "25222", "Score": "2", "body": "Looks very good to me. To be perfect you could produce the test and benchmark files too..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-09T08:20:06.393", "Id": "336660", "Score": "0", "body": "very nice, what algorithm are you using?" } ]
[ { "body": "<p>General notes:</p>\n\n<ul>\n<li>the code would benefit from splitting it into more methods,</li>\n<li>go uses camelCaseConvention, not onlylowerletters.</li>\n</ul>\n\n<p>Now, some particulars.</p>\n\n<pre><code>stack = append(stack, room{0, 0})\n</code></pre>\n\n<p>You can use <code>start</code> variable here.</p>\n\n<pre><code>func (r room) neighbors() []room {\n</code></pre>\n\n<p>In this function, it'd be more idiomatic to use <code>switch { ... }</code> instead of sequence of ifs. Same for the if-elses in the <code>main()</code>.</p>\n\n<p>Also it may be more efficient to have a single global re-used <code>[4]room</code> array and have <code>neighbors</code>/<code>nonvisitedneighbors</code> returns slices on it instead of <code>make</code>-ing a new one each call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T15:35:55.620", "Id": "15710", "ParentId": "15539", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T13:57:54.650", "Id": "15539", "Score": "11", "Tags": [ "random", "go" ], "Title": "Creating random maze in Go" }
15539
<p>This is my C# class, which takes 2.6s:</p> <pre><code>class Snake { readonly Symbol _mySymbol; readonly int _multiplier; readonly int _hit; readonly int _payout; readonly Snake _bestSnake; public Symbol MySymbol { get { return _mySymbol; } } public int Multiplier { get { return _multiplier; } } public int Hit { get { return _hit; } } public int Payout { get { return _payout; } } public Snake BestSnake { get { return _bestSnake; } } public Snake(Apple myApple) { this._mySymbol = myApple.MySymbol; this._multiplier = myApple.Multiplier; this._hit = 1; this._payout = _mySymbol.Payout_[0] * (_multiplier == 0 ? 1 : _multiplier); this._bestSnake = this; } Snake(Symbol mySymbol, int multiplier, int hit) { this._mySymbol = mySymbol; this._multiplier = multiplier; this._hit = hit; this._payout = _mySymbol.Payout_[hit - 1] * (multiplier == 0 ? 1 : multiplier); this._bestSnake = this; } Snake(Symbol mySymbol, int multiplier, int hit, Snake bestRecentSnake) : this(mySymbol, multiplier, hit) { if (_payout &lt; bestRecentSnake._payout) { this._bestSnake = bestRecentSnake; } else if (_payout == bestRecentSnake._payout) { if (bestRecentSnake._mySymbol.Type == 1 &amp;&amp; mySymbol.Type != 1) { this._bestSnake = bestRecentSnake; } } } public Snake Eat(Apple nextApple) { var resultSymbol = Symbol.Add(_mySymbol, nextApple.MySymbol); if (resultSymbol == null) return null; var newSnake = new Snake(resultSymbol, Math.Max(_multiplier, nextApple.Multiplier), Hit + 1, _bestSnake); return newSnake; } </code></pre> <p>This is my F# class, which takes 5s:</p> <pre><code>type Snake (mySymbol: Symbol, multiplier, hit, best: Option&lt;Snake&gt;) = let payout (mySymbol: Symbol) hit multiplier = match multiplier with | 0 -&gt; mySymbol.Payout_.[hit-1] | a -&gt; mySymbol.Payout_.[hit-1] * a new (myApple: Apple) = Snake (myApple.MySymbol, myApple.Multiplier, 1, None) member this.BestSnake = match best with | Some a when this.Payout &lt; a.Payout -&gt; a | Some a when this.Payout = a.Payout &amp;&amp; a.MySymbol.Type = 1 &amp;&amp; mySymbol.Type &lt;&gt; 1 -&gt; a | _ -&gt; this member this.MySymbol = mySymbol member this.Payout = payout mySymbol hit multiplier member this.Multiplier = multiplier member this.Hit = hit member this.Eat (myApple: Apple) = let tmp = Symbol.Add mySymbol myApple.MySymbol match tmp with | None -&gt; Operators.Unchecked.defaultof&lt;Snake&gt; | Some a -&gt; Snake (a, (max multiplier myApple.Multiplier), hit+1, Some this.BestSnake) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T16:00:49.010", "Id": "25223", "Score": "2", "body": "Could you also provide the code that you used to measure the performance? What exactly did you measure?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T16:00:56.623", "Id": "25224", "Score": "0", "body": "This doesn't address your question, but the whole point of using underscores before member variable names is so that you don't have to use `this.`. The underscore is a convention so that you always know what is a member variable instead of a method variable. It also allows you to never have to worry about a method variable shadowing a member variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T16:43:32.337", "Id": "25225", "Score": "0", "body": "On underscores: I strongly prefer `this.` over an underscore; so does Stylecop. I would also use auto-properties such as `public int Multiplier {get; private set;}` or have `readonly` fields (those can still be set inside of the constructor)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T16:46:03.940", "Id": "25226", "Score": "0", "body": "@svick sry it is too complicated if i attach the complete code. I measured the whole project which reference this class (before switch to F# is 2.6s vs after is 5s)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T17:49:42.110", "Id": "25229", "Score": "0", "body": "If you measured the whole project, how do you know this one class is the part that's slow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T17:54:09.630", "Id": "25230", "Score": "1", "body": "One obvious difference I can see is that the F# version of the BestSnake property does work every time you call it, while the C# version simply returns a pre-calculated value every time you call it. Whether this matters or not to your performance measurement depends entirely on code that's not included here." } ]
[ { "body": "<p>There are a few small differences in your translation. I would start with as literal a translation possible, then optimize/make idiomatic from there. If done incrementally it should be easy to spot performance problems as they occur. Here's a starting point:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>(* stub *)\n[&lt;AllowNullLiteral&gt;]\ntype Symbol =\n member x.Payout = [|0|]\n member x.Type = 0\n static member Add(sym1, sym2) : Symbol = null\n\n(* stub *)\ntype Apple =\n abstract MySymbol : Symbol\n abstract Multiplier : int\n\ntype private BestSnake =\n | This\n | RecentSnake of Snake\n\nand [&lt;AllowNullLiteral&gt;] Snake private (mySymbol: Symbol, multiplier, hit, bestSnake) as this =\n let payout = mySymbol.Payout.[hit - 1] * (match multiplier with 0 -&gt; 1 | m -&gt; m)\n let bestSnake =\n match bestSnake with\n | This -&gt; this\n | RecentSnake bestRecentSnake -&gt;\n if payout &lt; bestRecentSnake.Payout || \n (payout = bestRecentSnake.Payout &amp;&amp; bestRecentSnake.MySymbol.Type = 1 &amp;&amp; mySymbol.Type &lt;&gt; 1) \n then bestRecentSnake\n else null\n\n member val MySymbol : Symbol = mySymbol\n member val Multiplier = multiplier\n member val Hit = hit\n member val BestSnake = bestSnake\n member val Payout = payout\n\n new (mySymbol, multiplier, hit, bestRecentSnake) = Snake(mySymbol, multiplier, hit, RecentSnake bestRecentSnake)\n new (mySymbol, multiplier, hit) = Snake(mySymbol, multiplier, hit, This)\n new (myApple: Apple) = Snake(myApple.MySymbol, myApple.Multiplier, 1, This)\n\n member this.Eat(nextApple: Apple) =\n match Symbol.Add(this.MySymbol, nextApple.MySymbol) with\n | null -&gt; null\n | resultSymbol -&gt; Snake(resultSymbol, max this.Multiplier nextApple.Multiplier, this.Hit + 1, this.BestSnake)\n</code></pre>\n\n<p>The performance of this should be on par with C#.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T20:33:36.647", "Id": "25236", "Score": "0", "body": "I notice u used member val, is there any difference between to use/not to use val if the property is readonly of a default parameter? e.g. member val Hit = hit vs member Hit = hit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T20:47:36.623", "Id": "25237", "Score": "0", "body": "I used it because it guarantees (and therefore makes explicit) that the right-hand side is only evaluated once. If the right-hand side is a constant (as in this case) there is no difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T11:13:34.543", "Id": "25287", "Score": "0", "body": "new (myApple: Apple) as this = Snake(myApple.MySymbol, myApple.Multiplier, 1, this) at runtime raises {\"The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.\"}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T14:28:27.937", "Id": "25299", "Score": "0", "body": "Oops—I didn't test it. It doesn't like passing `this` to another constructor. An alternate solution is to use a discriminated union to represent the different values that can be assigned to `bestSnake`. I've updated the code to demonstrate. I tested this time and it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T21:05:13.743", "Id": "25337", "Score": "0", "body": "thx, i have updated my question with latest improved F# code, still it is a bit slower than C#, I also attached some results from profiling tool. Even if I inline Symbol.Add, it would take 3 s which is longer than 2.6s" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T21:14:57.173", "Id": "25338", "Score": "0", "body": "Hmm, your code doesn't even compile. Without your _complete_ source there's no way to help you further. I advise decompiling your F# and comparing it to the C# version." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T18:51:18.603", "Id": "15547", "ParentId": "15542", "Score": "5" } } ]
{ "AcceptedAnswerId": "15547", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T15:39:15.317", "Id": "15542", "Score": "5", "Tags": [ "c#", "performance", "f#" ], "Title": "Rewriting C# implementation of Snake class in F#" }
15542
<p>For something I'm doing, it would just make things so much easier, quicker, and cleaner to have C# style events. I've written a class I believe should replicate a C# style event using reflection. Since I've never actually used reflection before in any meaningful sense, I'm very much not happy using it without, at the very least, a second opinion.</p> <p>I want to declare an event with:</p> <pre><code>public Event SomeEvent = new Event(); </code></pre> <p>Raise the event (presumably within the declaring class) with (where SomeArguments is whatever class that may be specified in the Javadocs boxed in an Object):</p> <pre><code>SomeEvent.Raise(this, SomeArguments); </code></pre> <p>Add a method to be called when the event is raised with:</p> <pre><code>SomeEvent.AddListener(this, "onSomeEvent"); </code></pre> <p>Stop a method being called when an event is raised with:</p> <pre><code>SomeEvent.RemoveListener(this, "onSomeEvent"); </code></pre> <p>And cancel all listeners with:</p> <pre><code>SomeEvent.ClearListeners(); </code></pre> <p>Methods to listen to the event should be formatted like:</p> <pre><code>public void onSomeEvent(object Sender, object SomeArguments) { } </code></pre> <p>And this is my class:</p> <pre><code>package puppy.hanii.library; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; public class Event { public Event() { Methods = new ArrayList&lt;Method&gt;(); DeclaringClasses = new ArrayList&lt;Object&gt;(); } ArrayList&lt;Method&gt; Methods; ArrayList&lt;Object&gt; DeclaringClasses; public boolean AddListener(Object Class, String MethodName) { try { Method MTR = Class.getClass().getMethod(MethodName, Object.class, Object.class); // MTR = Method To Register. if(Methods.contains(MTR)) return false; else { Methods.add(MTR); DeclaringClasses.add(Class); return true; } } catch (NoSuchMethodException error) { throw new RuntimeException("No such method, or correct overloads of method, exists."); } } public boolean RemoveListener(Object Class, String MethodName) { try { DeclaringClasses.remove(Class); return Methods.remove(Class.getClass().getMethod(MethodName, Object.class, Object.class)); } catch (NoSuchMethodException error) { throw new RuntimeException("No such method, or correct overload of method, exists."); } } public void ClearListeners() { Methods.clear(); DeclaringClasses.clear(); } public void Raise(Object Sender, Object Arguments) { for(int i = 0; i &lt; Methods.size(); i++) { try { Methods.get(i).invoke(DeclaringClasses.get(i), Sender, Arguments); } catch(IllegalAccessException error) { } catch(InvocationTargetException error) { throw new RuntimeException("Error in event handler"); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T20:05:13.083", "Id": "25234", "Score": "0", "body": "Have you considered creating an anonymous class that call the event handler instead of string method names?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T14:00:06.747", "Id": "25296", "Score": "0", "body": "That seems like it would make it somewhat more fiddly when registering listeners than it needs to be :X Plus I like keeping the listener method separate from its assignment to an event. What if I wanted to register, deregister, and re-register the same method to an event multiple times? I'd have to either type the same method multiple times or create a method in the listener's class for the sole purpose of registering the event.\n\nAlthough I'm not too experienced with anonymous classes either ^^;; so maybe I've picked something up wrong." } ]
[ { "body": "<p>Your listener is pair {object, method name}.\nIn Java, typical approach is to represent listener as a single object, which implements specific interface. This way we do not need reflection, things work faster, and errors are discovered at compile time, not run time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T04:14:09.927", "Id": "25349", "Score": "0", "body": "As an object that implements a specific interface? That brings up a number of the reasons C#-style events would be better for me in the first place. If I wanted to have a class that listens to multiple events, I'd have to create multiple interfaces for each event. That would entail creating different event classes for each event that might be declared. I don't think I'd be much better off than just implementing the observer normally :\\" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T15:59:51.907", "Id": "25382", "Score": "0", "body": "°Observer pattern normally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T16:32:35.150", "Id": "25385", "Score": "0", "body": "What I have described earlier in the answer is normal java implementation of observer pattern. Creating different event classes for each event is not that hard - you can use anonymous inner classes based on handler interface. As for event handler interfaces, you can use single interface, or different interfaces - its up to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:07:49.320", "Id": "25394", "Score": "0", "body": "It's not hard, but it's not certainly not clean and would likely result in problems down the road in what I'm doing. C#-style events vastly simplifies everything." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T03:41:51.757", "Id": "15598", "ParentId": "15549", "Score": "0" } }, { "body": "<pre><code> ArrayList&lt;Method&gt; Methods;\n ArrayList&lt;Object&gt; DeclaringClasses;\n</code></pre>\n\n<p>Two things: firstly, you're using C# naming conventions rather than Java. Secondly, code to the interface: the fields should be <code>List&lt;XYZ&gt;</code> rather than <code>ArrayList&lt;XYZ&gt;</code>.</p>\n\n<pre><code> public boolean AddListener(Object Class, String MethodName)\n</code></pre>\n\n<p><code>Class</code> isn't an obvious name for something which isn't a class. And given that you're using <code>java.lang.Class</code> inside the method without fully qualifying the name, it has even more potential to confuse.</p>\n\n<pre><code> Method MTR = Class.getClass().getMethod(MethodName, Object.class, Object.class); // MTR = Method To Register.\n</code></pre>\n\n<p>If you have to add a comment explaining the name, perhaps you chose the wrong name? What's wrong with <code>Method method = ...</code>?</p>\n\n<pre><code> if(Methods.contains(MTR))\n return false;\n</code></pre>\n\n<p>So I can't have the event notify two different objects of the same class?</p>\n\n<pre><code> public boolean RemoveListener(Object Class, String MethodName)\n {\n try\n { \n DeclaringClasses.remove(Class);\n return Methods.remove(Class.getClass().getMethod(MethodName, Object.class, Object.class)); \n }\n</code></pre>\n\n<p>Buggy. <code>Collection.remove</code> removes one instance of the object, but you're making no attempt to ensure it's the right one. If I register two methods on the same object, this could remove the wrong instance of the object, which would then make objects and methods not line up correctly.</p>\n\n<p>In fact, it's even worse than that: if I register a method on one object and then remove it on another, or register one method on an object and then remove a different one, I'll end up with <code>Methods</code> and <code>DeclaringClasses</code> not even being the same size.</p>\n\n<p>Also, why would you want to call <code>getMethod</code> again unless the method hasn't been registered? If the method has been registered, you've already resolved it; if it hasn't, you don't need to resolve it except to check for typos.</p>\n\n<p>The best way to store the resolved methods is probably <code>Map&lt;Tuple&lt;Object, String&gt;, Method&gt;</code>: that allows you to iterate through the entry set in the <code>Raise</code> method and to efficiently implement <code>RemoveListener</code>.</p>\n\n<pre><code> catch(IllegalAccessException error)\n { }\n</code></pre>\n\n<p>No. Swallowing exceptions like that is bad, especially when you've done nothing to prevent them occurring. You should check in <code>AddListener</code> whether the method is accessible, and throw an exception there if it isn't. Then here you should log an error for debugging purposes.</p>\n\n<p>Other issues to consider:</p>\n\n<ol>\n<li><p>Thread-safety. This has no thread-safety whatsoever.</p></li>\n<li><p>Typing. If you're going to emulate C#'s events then don't just emulate the ungenericised <code>EventHandler</code>. At the very least, emulate <code>EventHandler&lt;T&gt;</code>. Because Java's generics aren't reified this requires a bit of boilerplate:</p>\n\n<pre><code>public class Event&lt;T&gt;\n{\n private final Class&lt;T&gt; typeParam;\n\n public Event(Class&lt;T&gt; typeParam)\n {\n this.typeParam = typeParam;\n }\n</code></pre>\n\n<p>You can now use <code>typeParam</code> in the <code>Class.getMethod</code> call.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:01:21.307", "Id": "25392", "Score": "0", "body": "1: I don't understand. I'm using the ArrayLists to store the class' data, not store other ArrayLists external to the class. Also, What would make those member names adhere to Java conventions? I thought they did.\n\n2: Noted, I'll change it to ListeningClass. I could see how that could become a problem XD\n\n3: I'm a fan of self-documenting code. The only reason I abbreviated it was because I thought such a long variable name would make method calls needlessly long. Although since I only actually use it twice after declaring it, I'll change that ^^;;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:01:55.633", "Id": "25393", "Score": "0", "body": "4: That was a mistake that I only noticed last night. I could have sworn that I'd updated the post when I fixed that, but I guess I must have forgotten. >.<\n\n5: 1: See above. 2: Where I've used getMethod again, I'm getting the method from the methods list to remove. There's probably a better way to go about that actually. 3: I hadn't thought about that. (@ the map bit)\n\n6: I had no idea how to handle that exception, thankyou.\n\n7: I'll look into those, thankyou.\n\nI'll post another comment once I've modified my class accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:19:14.987", "Id": "25395", "Score": "0", "body": "On 1: Eek, I see what you meant about the Lists/ArrayLists, I misunderstood you, sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:18:03.887", "Id": "25403", "Score": "0", "body": "@HaniiPuppy, Java naming conventions are that the only names which start with an upper case letter are types and static final fields (which are only upper case). http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T22:29:11.680", "Id": "25424", "Score": "0", "body": "<See my edit on the question.>\n\nI thought creating an inner-class for my method/class pairing would solve some of my problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T22:40:41.420", "Id": "25425", "Score": "0", "body": "<See my edit on the question.>\n\nI thought creating an inner-class for my method/class pairing would solve some of my problems.\n\nAs for generics, I was thinking I could get around not being able to get the class of a generic type by declaring the event with Event<SomeType> SomeEvent = new Event<SomeType>() and then using the class object for a List<SomeType> rather than the generic type itself. This would also make listener methods implement a List<Sometype> as the arguments rather than a Sometype. Does this sound wrong or like it could cause problems?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T22:43:19.423", "Id": "25426", "Score": "0", "body": "i.e.\n\nMethodClassPairing method = new MethodClassPairing(ListeningClass, ListeningClass.getClass().getMethod(MethodName, Object.class, Object.class)); would become MethodClassPairing method = new MethodClassPairing(ListeningClass, ListeningClass.getClass().getMethod(MethodName, Object.class, List<ArgType>.class)); and public void Raise(Object Sender, Object Arguments) { } would become \npublic void Raise(Object Sender, List<ArgType> Arguments) { }\n\nEDIT: I really wish the comments on here would retain line breaks and indentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T08:57:11.773", "Id": "25439", "Score": "0", "body": "@HaniiPuppy, I was thinking more along the lines of http://pastebin.com/E7sDAmAb . That also depends on an old library of mine, which used to be online but apparently got lost when Oracle absorbed Sun, so I've posted it at http://pastebin.com/NmddGusL" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T08:58:19.757", "Id": "25440", "Score": "0", "body": "The thing with generics is that they're not reified. What that means is that at runtime they don't exist. You can't tell whether a `List` is a `List<SomeType>` at runtime. This is a very big difference to C#'s generics." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T07:33:57.380", "Id": "15602", "ParentId": "15549", "Score": "3" } }, { "body": "<p>C# events are only privately raisable and clearable. This could be achieved with a nested class:</p>\n\n<pre><code>// Wrapper for a method and possible instance\npublic class EventHandlerDelegate\n{\n /** for wrapping static methods */\n public EventHandlerDelegate(Class clazz, string methodName)\n {\n if(clazz == null)\n throw new RuntimeException(\"clazz was null.\");\n\n try\n {\n Method method = clazz.getMethod(methodName, Object.class, Object.class);\n if(!method.isAccessible())\n throw new RuntimeException(MethodName + \"(Object, \" + \"); is not accessible.\");\n else\n this(null, method);\n }\n catch (NoSuchMethodException error) { throw new RuntimeException(\"No such method, or correct overloads of method, exists.\"); }\n }\n\n public EventHandlerDelegate(Object instance, string methodName)\n {\n if(instance == null)\n throw new RuntimeException(\"instance was null.\");\n try\n {\n Method method = instance.getClass().getMethod(MethodName, Object.class, Object.class);\n if(!method.isAccessible())\n throw new RuntimeException(MethodName + \"(Object, \" + \"); is not accessible.\");\n else\n this(instance, method);\n }\n catch (NoSuchMethodException error) { throw new RuntimeException(\"No such method, or correct overloads of method, exists.\"); }\n }\n\n public EventHandlerDelegate(Object instance, Method method)\n {\n if(passedMethod == null)\n throw new RuntimeException(\"passedMethod were null.\");\n else\n {\n _instance = instance;\n _method = method;\n }\n }\n\n private Object _instance;\n private Method _method;\n\n @Override\n public boolean equals(Object obj)\n {\n if(obj instanceof EventHandlerDelegate)\n {\n EventHandlerDelegate other = (EventHandlerDelegate)obj;\n\n return (_instance == other._instance) &amp;&amp; _method.equals(other._method);\n }\n else\n return false;\n }\n\n @Override\n public int hashCode()\n {\n int hash = 5;\n hash = 37 * hash + (_instance != null ? _instance.hashCode() : 0);\n hash = 37 * hash + (_method != null ? _method.hashCode() : 0);\n return hash;\n }\n\n public void invoke(Object sender, Object args)\n {\n _method.invoke(_instance, sender, arguments);\n }\n}\n</code></pre>\n\n<p>Event class implementing the event registration</p>\n\n<pre><code>public class Event\n{\n public Event()\n {\n _handlers = new ArrayList&lt;EventHandlerDelegate&gt;();\n _registrator = new Registrator();\n }\n\n List&lt;EventHandlerDelegate&gt; _handlers;\n Registrator _registrator;\n\n public Registrator getRegistrator()\n {\n return registrator;\n }\n\n public void ClearListeners() { _handlers.clear(); }\n\n public void Raise(Object sender, Object arguments)\n {\n for(EventHandlerDelegate handler : _handlers)\n {\n try { handler.invoke(sender, arguments); }\n catch (IllegalAccessException error)\n { throw new RuntimeException(\"This shouldn't have happened ?_?\", error); }\n catch (InvocationTargetException error)\n { throw new RuntimeException(\"Error in event handler\", error); }\n }\n }\n\n public class Registrator\n {\n public boolean addListener(EventHandlerDelegate eventhandler)\n {\n _handlers.add(eventhandler);\n }\n\n public boolean RemoveListener(EventHandlerDelegate eventhandler)\n {\n handlers.remove(eventhandler);\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>class ClassWithEvent\n{\n public Event()\n {\n _somethingChangedEvent = new Event();\n }\n\n private Event _somethingChangedEvent;\n\n public Registrator getSomethingChangedEvent()\n {\n return _somethingChangedEvent.getRegistrator();\n }\n}\n\n{\n ClassWithEvent obj = ...;\n obj.getSomethingChangedEvent().addListener(new EventHandlerDelegate(this, \"myHandler\"));\n}\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li><code>EventHandlerDelegate</code> is usable on its own and instances can be reused to save on reflection.</li>\n<li><code>EventHandlerDelegate</code> can wrap static methods.</li>\n</ul>\n\n<p>TODO:</p>\n\n<ul>\n<li>the <code>Event</code> and <code>EventhandlerDelegate</code> could be made generic to have typesafe methods.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:16:36.587", "Id": "28558", "ParentId": "15549", "Score": "0" } } ]
{ "AcceptedAnswerId": "15602", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T19:27:50.853", "Id": "15549", "Score": "5", "Tags": [ "java", "event-handling" ], "Title": "Replicating C#-style events in Java using reflection" }
15549
<p>Recently I have written an <code>SslStream</code> class asynchronously authenticate clients and receive message from them. I still would like anyone to suggest improvements for my code.</p> <pre class="lang-c# prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.IO; public class Wrapper { public byte[] buffer; public SslStream sslStream; public object connector; } public class Sock { private Dictionary&lt;string, byte&gt; Connections; public event Action&lt;Wrapper&gt; AnnounceNewConnection; public event Action&lt;Wrapper&gt; AnnounceDisconnection; public event Action&lt;byte[], Wrapper&gt; AnnounceReceive; private Socket _sock; private X509Certificate certificate = X509Certificate.CreateFromCertFile("exportedcertificate.cer"); public Sock(int port) { try { Connections = new Dictionary&lt;string, byte&gt;(); _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _sock.Bind(new IPEndPoint(IPAddress.Any, port)); _sock.Listen(500); _sock.BeginAccept(AcceptConnections, new Wrapper()); } catch (Exception e) { Console.WriteLine(e); } } private void AcceptConnections(IAsyncResult result) { Wrapper wr = (Wrapper)result.AsyncState; try { wr.sslStream = new SslStream(new NetworkStream(_sock.EndAccept(result), true)); wr.sslStream.BeginAuthenticateAsServer(certificate, EndAuthenticate, wr); _sock.BeginAccept(AcceptConnections, new Wrapper()); } catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); } } private void EndAuthenticate(IAsyncResult result) { Wrapper wr = (Wrapper)result.AsyncState; try { try { wr.sslStream.EndAuthenticateAsServer(result); } catch { } if (wr.sslStream.IsAuthenticated) { AnnounceNewConnection.Invoke(wr); if (wr.sslStream.CanRead) { wr.buffer = new byte[5]; wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr); } } else { AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); } } catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); } } private void ReceiveData(IAsyncResult result) { Wrapper wr = (Wrapper)result.AsyncState; try { AnnounceReceive.Invoke(wr.buffer, wr); SocketError error = SocketError.Disconnecting; int size = wr.sslStream.EndRead(result); if (error == SocketError.Success &amp;&amp; size != 0) { wr.buffer = new byte[size]; wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr); } else { wr.sslStream.Close(); wr.sslStream.Dispose(); AnnounceDisconnection.Invoke(wr); } } catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); } } } </code></pre> <p>Also, how can I verify server authentication?</p>
[]
[ { "body": "<p>I like the layout</p>\n\n<p>First thing, move your using statements out of the namespace declaration, and remove unused references (I use Resharper, but there is a command in VS that will do this for you, I just can't remember it):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Net.Security;\nusing System.Security.Cryptography.X509Certificates;\n</code></pre>\n\n<p>I don't see Wrapper used enough to comment on the class, but the names, if public should begin with capital letters.</p>\n\n<p>In the Sock class:</p>\n\n<p>Connections does not follow C# naming conventions. It should be named _connections;</p>\n\n<p>_sock can be made readonly. This will prevent accidental overwrite, and I believe uses less resources when compiled. I would also rename it to _socket to avoid confusion in your class.</p>\n\n<p>certificate could be made readonly, and I'd initialize it in the constructor like all your other class variables. It should also be renamed to _certificate. The alternative is to make it static, which might be a better idea because it looks like it needs to stay in memory. In which case, it should be renamed Certificate.</p>\n\n<p>I would move the initialzation of _sock into it's own method. This will clean up your constructor a little, and portray intent much better.</p>\n\n<pre><code>_socket = InitializeSocket(port);\n\n....\n\nprivate static InitializeSocket(int port)\n{\n var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n socket.Bind(new IPEndPoint(IPAddress.Any, port));\n socket.Listen(500);\n socket.BeginAccept(AcceptConnections, new Wrapper());\n\n return socket;\n}\n</code></pre>\n\n<p>The listen value should be put into a class constant instead of using a magic number. This will allow for easier changes later, and makes the initialization easier to read.</p>\n\n<pre><code>private const int ListenLength = 500;\n\n...\n\nsocket.Listen(ListenLength);\n</code></pre>\n\n<p>In AcceptConnections, wr should be named to resultWrapper. I would also use the var keyword because of the boxing. This can be done in all your methods.</p>\n\n<pre><code>var resultWrapper= (Wrapper)result.AsyncState;\n</code></pre>\n\n<p>Add line breaks and whitespace to your catch statement. Makes it easier to debug.</p>\n\n<p>I don't like that you have to inject a Wrapper into the call within a Wrapper:</p>\n\n<pre><code>resultWrapper.sslStream.BeginAuthenticateAsServer(certificate, EndAuthenticate, resultWrapper);\n</code></pre>\n\n<p>I would put a method in the Wrapper class call BeginAuthenticateAsServer:</p>\n\n<pre><code>public void BeginAuthenticateAsServer(X509Certificate certificate, AsyncCallback endAuthenticate)\n{\n sslStream.BeginAuthenticateAsServer(certificate, endAuthenticate, this);\n}\n</code></pre>\n\n<p>Then your call will be</p>\n\n<pre><code>resultWrapper.BeginAuthenticateAsServer(Certificate, EndAuthenticate);\n</code></pre>\n\n<p>Your call to AnnounceDisconnection will fail if AccounceDisconnection is null. Instead, add a method called Disconnect:</p>\n\n<pre><code>private void Disconnect(Wrapper wrapper)\n{\n if (AnnounceDisconnection == null)\n {\n return;\n }\n AnnounceDisconnection.Invoke(wrapper);\n}\n</code></pre>\n\n<p>Then in your code where its needed, call Disconnect</p>\n\n<p>This line</p>\n\n<pre><code>try { wr.sslStream.EndAuthenticateAsServer(result); }\ncatch { }\n</code></pre>\n\n<p>Hides an exception. Not a very good idea. Either log it, retry, or let the application error handling deal with it. This will cause confusion in the future.</p>\n\n<p>AnnounceReceive - See solution for AnnounceDisconnection;</p>\n\n<p>Try this and see how it looks. I have a few more ideas, but this is a good start.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I have taken CodeSparkle's suggestions and updated the code, with some of my ideas</p>\n\n<p>The old Wrapper class:</p>\n\n<pre><code>public class SslSocketEventArgs : EventArgs\n{\n private static readonly X509Certificate Certificate =\n X509Certificate.CreateFromCertFile(\"exportedcertificate.cer\");\n\n private SslStream _sslStream;\n\n public byte[] Buffer { get; private set; }\n\n public void ReplaceSslStream(IAsyncResult result, Socket socket)\n {\n if (_sslStream != null)\n {\n CloseAndDispseSslStream();\n }\n\n _sslStream = new SslStream(new SslStream(new NetworkStream(socket.EndAccept(result), true)));\n }\n\n public void CloseAndDispseSslStream()\n {\n if (_sslStream == null)\n {\n return;\n }\n\n _sslStream.Close();\n _sslStream.Dispose();\n }\n\n public void BeginAuthenticateAsServer(AsyncCallback endAuthenticate)\n {\n _sslStream.BeginAuthenticateAsServer(Certificate, endAuthenticate, this);\n }\n\n public void EndAuthenticateAsServer(IAsyncResult result)\n {\n _sslStream.EndAuthenticateAsServer(result);\n }\n\n public void CreateBuffer(int size)\n {\n Buffer = new byte[size];\n }\n\n public void BeginRead(AsyncCallback receiveData)\n {\n if (Buffer == null)\n {\n throw new ApplicationException(\"Buffer has not been set.\");\n }\n\n _sslStream.BeginRead(Buffer, 0, Buffer.Length, receiveData, this);\n }\n\n public int EndRead(IAsyncResult result)\n {\n return _sslStream.EndRead(result);\n }\n\n public bool IsAuthenticated()\n {\n return _sslStream.IsAuthenticated;\n }\n\n public bool CanRead()\n {\n return _sslStream.CanRead;\n }\n}\n</code></pre>\n\n<p>The old Sock class:</p>\n\n<pre><code>public class SslSocketMonitor\n{\n private const int ListenLength = 500;\n\n public event EventHandler&lt;SslSocketEventArgs&gt; Connected;\n public event EventHandler&lt;SslSocketEventArgs&gt; Disconnected;\n public event EventHandler&lt;SslSocketEventArgs&gt; ReceivedData;\n\n private readonly Socket _socket;\n\n public SslSocketMonitor(int port)\n {\n try\n {\n _socket = InitializeSocket(port);\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n }\n\n private Socket InitializeSocket(int port)\n {\n var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n socket.Bind(new IPEndPoint(IPAddress.Any, port));\n socket.Listen(ListenLength);\n socket.BeginAccept(AcceptConnections, new SslSocketEventArgs());\n\n return socket;\n }\n\n private void AcceptConnections(IAsyncResult result)\n {\n var resultWrapper = (SslSocketEventArgs) result.AsyncState;\n try\n {\n resultWrapper.ReplaceSslStream(result, _socket);\n resultWrapper.BeginAuthenticateAsServer(EndAuthenticate);\n\n _socket.BeginAccept(AcceptConnections, new SslSocketEventArgs());\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n Disconnected.InvokeSafely(this, resultWrapper);\n resultWrapper.CloseAndDispseSslStream();\n }\n }\n\n private void EndAuthenticate(IAsyncResult result)\n {\n var resultWrapper = (SslSocketEventArgs) result.AsyncState;\n try\n {\n try\n {\n resultWrapper.EndAuthenticateAsServer(result);\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex);\n }\n\n if (resultWrapper.IsAuthenticated())\n {\n Connected.InvokeSafely(this, resultWrapper);\n if (resultWrapper.CanRead())\n {\n resultWrapper.CreateBuffer(5);\n resultWrapper.BeginRead(ReceiveData);\n }\n }\n else\n {\n Disconnected.InvokeSafely(this, resultWrapper);\n resultWrapper.CloseAndDispseSslStream();\n }\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n Disconnected.InvokeSafely(this, resultWrapper);\n resultWrapper.CloseAndDispseSslStream();\n }\n }\n\n private void ReceiveData(IAsyncResult result)\n {\n var resultWrapper = (SslSocketEventArgs) result.AsyncState;\n try\n {\n ReceivedData.InvokeSafely(this, resultWrapper);\n\n var size = resultWrapper.EndRead(result);\n if (size != 0)\n {\n resultWrapper.CreateBuffer(size);\n resultWrapper.BeginRead(ReceiveData);\n }\n else\n {\n resultWrapper.CloseAndDispseSslStream();\n Disconnected.InvokeSafely(this, resultWrapper);\n }\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n Disconnected.InvokeSafely(this, resultWrapper);\n resultWrapper.CloseAndDispseSslStream();\n }\n }\n}\n</code></pre>\n\n<p>Extensions:</p>\n\n<pre><code>public static class EventHandlerExtensions\n{\n public static void InvokeSafely&lt;T&gt;(this EventHandler&lt;T&gt; eventHandler,\n object sender, T eventArgs) where T : EventArgs\n {\n if (eventHandler != null)\n {\n eventHandler(sender, eventArgs);\n }\n }\n}\n</code></pre>\n\n<p>Like CodeSparkle, I don't like the CloseAndDisposeSslStream method, but I'm not clear on a good solution for it right now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T22:48:26.333", "Id": "15552", "ParentId": "15550", "Score": "2" } }, { "body": "<p>I can't comment on how secure your code is, however there are a couple of other problems that I would like to point out. </p>\n\n<h2>Clutter</h2>\n\n<p>Your using directives can be cut down to:</p>\n\n<pre><code>using System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Net.Security;\nusing System.Security.Cryptography.X509Certificates;\n</code></pre>\n\n<h2>Naming</h2>\n\n<ul>\n<li><p>Let me show you what I think of when I see a class called <code>Sock</code>:<br>\n<img src=\"https://i.imgur.com/alb8e.png\" alt=\"socks\"><br>\nYou need to give that class a better name, for instance <code>SslSocketMonitor</code>. Actually, I don't know enough about your class to find a good name; use your brain to find a better one.</p></li>\n<li><p>Let me show you what I think of when I see a class called <code>Wrapper</code>:<br>\n<img src=\"https://i.stack.imgur.com/1jzBU.jpg\" alt=\"enter image description here\"><br>\nBecause you are using it as a parameter to an event, this ought to be called something like <code>SslSocketEventArgs</code>, but certainly <em>not</em> <code>Wrapper</code>.</p></li>\n<li><p><strong>Decide on one naming convention and stick to it.</strong> You are using <em>three</em> different conventions for naming private fields:</p>\n\n<pre><code>private Dictionary&lt;string, byte&gt; Connections; // UpperCase\nprivate Socket _sock; // _lowerCasePrefixed\nprivate X509Certificate certificate; // lowerCase\n</code></pre></li>\n<li>Your event names are nonstandard and not particularly clear.<br>\nInstead of <code>AnnounceNewConnection</code> try <code>Connected</code>,<br>\ninstead of <code>AnnounceDisconnection</code> try <code>Disconnected</code>,<br>\nand instead of <code>AnnounceReceive</code> use <code>ReceivedData</code>.</li>\n</ul>\n\n<h2>API problems</h2>\n\n<ul>\n<li><p>.NET programmers are familiar with events. Therefore, it makes sense to implement the pattern <em>properly</em>:</p>\n\n<ol>\n<li><code>SslSocketEventArgs</code> (formerly <code>Wrapper</code>) needs to be derived from <a href=\"http://msdn.microsoft.com/en-us/library/system.eventargs.aspx\" rel=\"nofollow noreferrer\"><code>System.EventArgs</code></a> </li>\n<li><p>Instead of using <code>Action</code>:</p>\n\n<pre><code>public event Action&lt;Wrapper&gt; AnnounceNewConnection;\npublic event Action&lt;Wrapper&gt; AnnounceDisconnection;\npublic event Action&lt;byte[], Wrapper&gt; AnnounceReceive;\n</code></pre>\n\n<p>use the more expressive and conventional <code>EventHandler&lt;T&gt;</code>:</p>\n\n<pre><code>public event EventHandler&lt;SslSocketEventArgs&gt; Connected;\npublic event EventHandler&lt;SslSocketEventArgs&gt; Disconnected;\npublic event EventHandler&lt;SslSocketEventArgs&gt; ReceivedData;\n</code></pre></li>\n<li><p>It's not safe to directly invoke event handlers as they could easily be null. So define the following extension method to safely invoke the event handlers:</p>\n\n<pre><code>public static class EventHandlerExtensions\n{\n public static void InvokeSafely&lt;T&gt;(this EventHandler&lt;T&gt; eventHandler, \n object sender, T eventArgs) where T : EventArgs\n {\n if (eventHandler != null)\n {\n eventHandler(sender, eventArgs); // syntactic sugar for .Invoke\n }\n }\n}\n</code></pre></li>\n</ol>\n\n<p>and replace all the usages:</p>\n\n<pre><code>Disconnected.InvokeSafely(this, wr);\nReceived.InvokeSafely(this, wr); // etc...\n</code></pre></li>\n<li><p>I'm not a fan of beginning listening in the constructor. It would be better to invoke that explicitly in a separate method.</p></li>\n<li><p>There should be a way to cancel listening. Write a public method to enable this.</p></li>\n</ul>\n\n<h2>Programming errors</h2>\n\n<ul>\n<li><p>Your field <code>Dictionary&lt;string, byte&gt; Connections</code> is initialized but never used. Delete it.</p></li>\n<li><p>You have lines like these spread throughout your code:</p>\n\n<pre><code>wr.sslStream.Close();\nwr.sslStream.Dispose();\n</code></pre>\n\n<p>That scares me. What if you forgot to close it somewhere? It would be best to enclose all uses of the class in <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">using statements</a> where possible.</p></li>\n<li><p>In <code>ReceiveData</code>, you make the following (constant) assignment:</p>\n\n<pre><code>SocketError error = SocketError.Disconnecting;\n</code></pre>\n\n<p>So the following condition <strong>will always be <code>false</code>:</strong></p>\n\n<pre><code>if (error == SocketError.Success &amp;&amp; size != 0)\n</code></pre>\n\n<p>What you are probably trying to do is instead of <code>catch (Exception)</code>:</p>\n\n<pre><code>catch (SocketException e)\n{\n // handle properly!\n Console.WriteLine(e.SocketErrorCode);\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T01:50:04.213", "Id": "25344", "Score": "0", "body": "haha sock indeed" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T22:58:26.883", "Id": "15553", "ParentId": "15550", "Score": "8" } }, { "body": "<p>Very good, but this only error is double invoke 'SslStream()'</p>\n\n<pre><code>_sslStream = new SslStream(NetworkStream(socket.EndAccept(result), true));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-12T19:01:15.160", "Id": "216633", "Score": "1", "body": "Please elaborate on what you think the problem is and how it should be fixed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-12T18:00:34.353", "Id": "116591", "ParentId": "15550", "Score": "-3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:37:55.913", "Id": "15550", "Score": "3", "Tags": [ "c#", "asynchronous", "console", "socket", "authentication" ], "Title": "Asynchronous SSLSTREAM" }
15550
<p>I have recently received some feedback on a project I did called <a href="https://github.com/rlemon/Notifier.js" rel="nofollow">Notifier.js</a>, in which you can see I have included all of the source images and styles in the JavaScript file. The feedback I received was that having it all bundled up together may be <em>cool</em>, but it is in fact not as performant and harder to maintain (which, if you know JS and CSS is not true... but that is to be debated later).</p> <p>My reasoning for doing the script this way was two parts:</p> <ol> <li>fewer requests </li> <li>single file include means no mucking about with "<em>where did I store the images, ohh now I have to alter the CSS file... and the JS file..</em>" kind of business.. the KISS principal (<em>Keep It Simple, Stupid!</em>). </li> </ol> <p>Have I in fact taken the wrong approach? Are the downfalls of doing it my way worse than the benefits? I can't see how it would be <em>that</em> much slower just to load the base64 images and style the elements with JS (am I wrong?).</p> <p>While you are looking, any other feedback would be greatly appreciated. </p> <pre><code>var Notifier = (function() { var apply_styles = function(element, style_object) { for (var prop in style_object) { element.style[prop] = style_object[prop]; } }; var fade_out = function(element) { if (element.style.opacity &amp;&amp; element.style.opacity &gt; 0.05) { element.style.opacity = element.style.opacity - 0.05; } else if (element.style.opacity &amp;&amp; element.style.opacity &lt;= 0.1) { if (element.parentNode) { element.parentNode.removeChild(element); } } else { element.style.opacity = 0.9; } setTimeout(function() { fade_out.apply(this, [element]); }, 1000 / 30); }; var config = { /* How long the notification stays visible */ default_timeout: 5000, /* container for the notifications */ container: document.createElement('div'), /* container styles for notifications */ container_styles: { position: "fixed", zIndex: 99999, right: "12px", top: "12px" }, /* individual notification box styles */ box_styles: { cursor: "pointer", padding: "12px 18px", margin: "0 0 6px 0", backgroundColor: "#000", opacity: 0.8, color: "#fff", font: "normal 13px 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif", borderRadius: "3px", boxShadow: "#999 0 0 12px", width: "300px" }, /* individual notification box hover styles */ box_styles_hover: { opacity: 1, boxShadow: "#000 0 0 12px" }, /* notification title text styles */ title_styles: { fontWeight: "700" }, /* notification body text styles */ text_styles: { display: "inline-block", verticalAlign: "middle", width: "240px", padding: "0 12px" }, /* notification icon styles */ icon_styles: { display: "inline-block", verticalAlign: "middle", height: "36px", width: "36px" } }; apply_styles(config.container, config.container_styles); document.body.appendChild(config.container); return { notify: function(message, title, image) { var notification = document.createElement('div'); apply_styles(notification, config.box_styles); notification.onmouseover = function() { apply_styles(this, config.box_styles_hover); }; notification.onmouseout = function() { apply_styles(this, config.box_styles); }; notification.onclick = function() { this.style.display = 'none'; }; var icon = document.createElement('img'); icon.src = image; apply_styles(icon, config.icon_styles); notification.appendChild(icon); var text = document.createElement('div'); apply_styles(text, config.text_styles); notification.appendChild(text); if (title) { var title_text = document.createElement('div'); apply_styles(title_text, config.title_styles); title_text.appendChild(document.createTextNode(title)); text.appendChild(title_text); } if (message) { var message_text = document.createElement('div'); message_text.appendChild(document.createTextNode(message)); text.appendChild(message_text); } config.container.insertBefore(notification, config.container.firstChild); setTimeout(function() { fade_out(notification); }, config.default_timeout); }, info: function(message, title) { this.notify(message, title, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxIKNf3BRpoAAAfvSURBVFjDnZddjGRVEcd/59zbt6ene3fWXXaGcWd3YRlcZpnVCAReyEIIKmOCMZFoJIEXfTAxPGhCfAD1SRNjxAf1SWJi9smNkYSP7PqgkoAJASLifuCEkcXJjPNB90zPbHdP972nqny4t2eagXWRSk5u376nqv7nf6rq1HF8RFlbW2P//v3930eAE8BE8XkBuLR///753XOvJfG1JjQaDQ4cOICZPVCv1x8Fvuqci6IownsPgKoiItTrdQHOmNlp4Gxf92NJo9HoP0/V6/X5ZrNp3W5XRcTMzFT1fcPMTESs2+1qs9m0er0+32g0Tg3a+shSr9f7zxfW1tYsTVPtOzVTa3bELi6LvTqfj4vLwTa2xMx2wKRpqmtra1av118YtLlb3O4/3nvvPcxsDPhHpVIZrVarmCm9AH96W3htAVqZI4kc3ufqokYalGrJuPOw4/6bI8oxOOdpt9tsbW2tAp92zq0cPHjw6gBWV1dxzo2a2fyePXuSJEmc98a5twLPvyUMJZ7Ye6LIEzmP9w4zQ80QUUSVTJRuJjx4ImZmqoSqI01Tu3LlSuqcO2Jmq6Ojo1dnYGVl5d1arXYkKZcdZvz0L10WNo0kjoijHQA4TyV2GEYnMzAlFCCCKL1MODzi+N59FXCOtNezVqs1PzY2dsOgP7/L+c/K5fLRcrnsnCk/PNfi303BOcDADAwIYtx/DJ64z/HkfZ4HJh1B8jn5MLyDd9cDT569gjOlXC67crl8dGVl5akPAFhaWmJ5efmTZvbdWq2GR/jly23+symYWU4ztk23qXHvpENVUVVO3eRInGHk39Uo9GBpQ/jFSy08Qq1Ww8y+s7y8fGhpaWkHwPj4OKr642q1SgiBNxcz/nq5BwaquUHVnF5Vo9fTD0RzLxVEDTUtRg7YMF5+p8ffF1JCCFSrVVT1R+Pj4zsAilU+UqlUSCJ4+pUWsadYjaGiiOXvokKqyu9fS/EevIc/X0ppbuUARUG10C0Axx5+/coVkggqlQpm9oiZ5UG4sLAA8ODQ0NCztVqNy42Mx59tUi3HedBFEbH3xJHHR57Igfee5qZClhvfAq7b5wuAeUYEFYIoQfJnqys89eV93HggodVq0e12vwQ85ycmJjCzLyRJYiKBl9/ZIvZs0y2qSD/CgxDUCCIMD8Nnb4o4eUPE3prLnQVFQsGE7DAgqpQ8vPSvLUQCSZKYmX1hYmIiPwtU9fY4jp1HubSU5orOEZxuJ6p5MBzeDDHHt+4qc8eRCIB/rgg/ebFLKdqJFREj9BeghqpwYalH5Kq4OHaqesf2YaSqR53LjS80M0QdDDhnO6o93jkiU+48WqGb5cF44nrPvpKwke1irgChqgSFxWaGxzDnUNUbtwGYWdU5B2a0eoKa/4DzyPI99s4hQbfTMy/FEKNkYnnWFKt+HwhTWj0tCkXucxBAW1X3okYSGe1MIQBRUVTMY2Z4dTjviHYBUDVCFgjitle/A8K2K2Q1yecS5T4HAcyr6riIMlrzzNUF8wbOUHNEZmhBvzdQke0Ay+PD5dEeXFELcibEBplQxmoRQRQQzOydwVL8epqmlolyy2hMkLyoZNJPJSUEIRMhC3lq0S80xQgipCJF2smAruQpqcLUaIlUlCzLDPgbgJ+bm8PM/tjtdp33EaeOlemkuaKEnL6sbzDsGLYPARBCfhoOOpcgiBidVDh1rIz3EVtbW87Mzs3NzeEnJyeZmZl5bnNzU5Mk4ZaDMYdGfFFMilEYzETJQg5EBwGoIQXIrADSB9S3cXgk4pbRmCRJ2Nzc1JmZmecmJyfzLZibmwM43el06AbjsbtrtNOCziDbLISBle3eAtUBp/1t07xwdXrCY3fvpRuMTqcDcLrwmQOYnZ3FzJ6o1+sMDw9z+0TCPcfKhZEBgwWIZjsrikse7ZGH2aUtsoE5+XwjBOGeY2VuP1xieHiYer2OmT05Ozu7A+D48eNMTU0tqupT6+vr4Et8/3MjXL/HDTjv769iJc9jT19GxRAxHv/tZbI4yrdHlEzz1Yso43s9P/j8CPgS6+vrqOrPp6amFo4fP/7hHdGFCxfmx8fHJ0TEiQjf/kODt+sZsXM45woNR+gFlhc2wGD00F7KlbhoWPI+IKjxqetifvWV64iiiCiKbGlpaWF6evrIVXvCS5cuoaqjZjZ/6NChRFWd04zfvHqFp1+5QlLyuEJpB8xAqS6O9l4wvnHXHr551x7Ml/De2+LiYuqcO+K9Xz1x4sTVe8KLFy8CjInImwcOHBir1Wp02i06mXH69RbPv9VhvaOUIk/RFKMGmSj7Kp4HTwzz6B01KiXHcLVGq9Wi0WisRFH0GWDl1ltv/d9tebENTE9Pc/78+bNJkjwwNjZmIuK63S2GS475pjC7mrFRdEYjZc/NB0vc8ImITmYMDVWIoshWVlZcmqbnTp48OdO3ec17QV/Onz/PyZMnuXDhwr0icrparU6MjIzY0NCQy7KMEAIiAkAURcRxTKlUotvt2sbGhmu32wtRFD0yPT39Yt/WR7qY7JJoeHi43Ol0umfOnPn6+Pj412q12her1WqUJAlxnF8tQwikaUq73ZbNzc2zi4uLZx5++OHflcvlpNfr9ciPNvt/ATigBJSBSvEsAfrQQw9N33bbbcf37dt3vZm5RqOx+sYbb8w+88wzFwu9APTIu7UukALycRjYLb4A4QZ0o8J4/1YgA+/XlP8CEfRY6kDvcEYAAAAASUVORK5CYII="); }, warning: function(message, title) { this.notify(message, title, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILGKEFK64AAAZZSURBVFjDvZdbjFVXGcd/39qXc+Ywl9LQYdoCji0XhbRorVOVXnRKShUjSmPB2KT2yUaa2AeTYqyJDanxAR5UHiRqJZEUaRS1AS+Q0KLcxGCpBVMwaUIphRYYcGbOzD57r/V9PuztjLEoZQBXsnPOWdlrff/1v6x1Fkyw2YH7L/j9Uls8kUG6fxFqdr3+eeEq0HY1exp4ZSJzyaUXvw/ErjULZ2XGCiPuwo59T0SzWzAOub5tXPUW9vX/So+vNz39J9O3dpme3aVh710nJzKXu6TCe+8l7Fv4AeKOJdK5AJEYiRuImyx09fWEfQu/dtUl8LvuPORuXjmXZKpI1AbiQHPMOfTQo4VJrSNZ8ELrijPQ3PFx/O5PLKP9/fOk3isiUVlcYsAhvoVMfSAR0+9cNQbyF/uyeN7qlKAicQPiNhCBUGB+FEnaKQ4/jliYjtkbyd1/uOic0bsuvvOuVe66hf0u6REB1Bxff/qH/HHPS4yONJndex1kZ6B9ptm5/R9K79m9/orsA60dH0NEukz9k27KvTByCuIGrt7Oxs3b6Whv0Nk5iU/dPQu0RVTrFU177slfuPOjZrq31r/n8jxQ69+DBb/O3fB55Nxh0Az8CMQeVcV7T1saYfkQ+BFs6AjRjctNi+bPL1b8ogCy3/eRbbtjrkXty+LaNAij4JvghyEfJE1TvPfUU0GKYfBNxLdwrfMikz98Q7b9I1+9LAD1Rfsxn/0snv4Fs4GDZfFiuALwD9I0KQHEBn4IiiHww1jzDZLu+9C8ubr529ujCQEY+cVcRn5z+wN0zLnF5cOCKYSipL8YgnyQei2lKDxtKVAMgm9imoEFOPsXohuXxGK6ekIAGg/8DSuGNiTXLzYG/w4hxyzHNIfQgmKYNIkofEFbYhAyCHkZSc2hGCFpn4WpPT6yZX538/n5lwag+etbn4p6PlmXswfELJS7XSgfDS3wo9RShy88bTUt+7UF2kIqsHpqJ0nvQ6a+2DjpMy+/uxgObZ6HiHRpyL9R65qDvb0bcQnqFLHA2A7oR2lLHXnhaaQKoYVglGADpgEsEIWWSG1q//Avoz4z3d+x9PD/ZqBj6WHU+7VJ7/LITmwrqQ8V7aGFVg/FCGlieB9oSwqs6rfqPTQr+07vJ5mxxLRobvzP4u9gYHDTbBCZK3H7QxFAaGGmYIqYxyQCiRBx4I1GzSgKTyMtSg9goIpaQCyAeswCcu6QRFPuuGnwufSxzgdfXftfGehcdhTz2U+T3s+avrmt0ryFhQzz5SchQ0MGxQj11NAQaKQ56lvgs8qM1TshA22hg0dJp9yGFc015zbNjC7IwPkNN4G4RdI56zY3eAQzxbQF5hFLMPGIRqg4RBxmBdd0CLW2lEaUQTGKYhVbWq3eg3owj77+PMl7Ppfmx7Z8G3jigqfhwE96sknzV6T22rNCVEeipDxuXVSZrzIgDkRIerrhmi78a8ewvFVKYIqZIhX9ph6xgIUcN30xzSPPYeaniHJ28sPHxgGcWz/jyWRa/6po+BUohhCXgItAYkRicG5cfwRDiF053CuIGJiNecYqH5j+C4THwig2YxnZqxu2XvvIiU+PSTDwzLRJ6vOnko5uwtsnIUrBFCxCJGDiQcviJg4TIQuOVZsLAL65NKUeKWBIxQAW0IoJLKDqEVWi7DhSn7p44Bn5oJm9FAOo99+vz3nQ+SM/AhcjBriAaQwujK1cxYE4ksixcqNn+4Gs3LRaddZ+McYHQ6k8YAoaxhNRyeFf30p9zgprHvzBpimPDsyOz6ybOpO48UgcTuPVIxiIosSIBLBSd/03+okiMs0ZGhouT001oIaFMCaDjQHxmI5LAmAnfydRd9+sM+sOPhybz7/V9r7l5o9+V4jbsKDgqhVUqx7//ycgjnxUWPNYO5q2MIM1X26QnxoqDWWGUY5XKwGJBqBiQwM68Fdqc75iwyd2r4w1FL2cf1lMHKIeEcVUQcK46yUAUkkggNB2MufHX0oBKE4OgNpYDIFxGSogUjFSbtHAqR1iuPfGkGzJ3jy0oBYBrsBwCKGMmpWaW6W9mFQxFDAo3srLIBulAbEqilUaMLAwBmYsIQrZwGlQ2SoAO59of/bm7mhxPZFOswteRS/jHiXv+OkDxfGB8GLfqqH7pYrirUAOBP4/zQE1kYldaK9o+yfo49dpgHxFaAAAAABJRU5ErkJggg=="); }, success: function(message, title) { this.notify(message, title, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILCcu1C1wAAAW3SURBVFjD7Zd/kFVlGcc/z/uec/fe3b33suwPoDZN1qWtBcnQAdH8kTA12CSp0yCpQwwRpcbsiPnHbtDyY6IlTNOZ0koDm2myoXJmCRBFCDJnsJZgEdp2QPyxl5i9d3/fe88957xvf+xCi6ABRn84PjPPnOd9zx+f55znPd/nOfChfeBt1ah4w5m31UVPoJOJi59b3NH4QmMXh/js//fpFzGp+aVm25nuNB3dHWbXkV22dn3tcgCaLjZ8CdPW7Fpj96X2mbZUm91/fL89eOKgbU8dsDOemN4KQCPIRYE38Ll1t7e8eM3HZloRES0arTRaNEo0pZFiFvz+awf3LNoz+X+fwHe4peXWta1XTrjSilUionFGJRBzo7x0dCeNWxrIGqrOPISNo+KlfOK84E18Zd3c1a314yZZP8xJweTxwzz5ME8+yKOUYsO+DazZ1kDCBUJ8dQZ0iFuu21C/dcn2W+1tN848zCJKzoWtlsvCh7/U/JvaikttYPLiWw/fDHsh9Ig4ER5/5VGe/esjxKPQHfAka+l1AOjnisk/vWTpFdUfX3htTT3xaLE1BmJFtfzu5ZeXAc3vBXdWOA/+aG5Ty4TScTbAEzEaQYPVBFZRFi2nZfcaXnt7G7EIHB2kJVzJQywdOYTTnokPfHPm/JLA+nKyVlo0Ra7Lk7u39u+Ydzj5bvD46uLV6+Y+0Dg2VgZWg9FYOwzHapKRsTTvWEnPQJsNDHKkn4fMSlpOE6L2YwP5o95OUdpHtIfSHsrxCGyOL0ypT3Afs/WK/0CTI/G4H4758fo77mscUxLBiIfBIxSPEI+APBFH88CWBoZybTYA6exj8Wj4qQTMIMG+4/+gxxxG6wLieIj20K7Hp6or7aT6smXhSBFqn4a+Zpjyi/KnfnDbgvuTxQ6oAhbvVBKGPEoMD/5xGVH1us0ZpDPDHaziZ+98gxogdgPX+iF11TVd4mpIuOVoJ0CUIbC+xKK2pn1S12Of+Tq5/XfBjZvGbmq4ad78IkeDGLAGKwZrDRZDLszTvHUtFcW9tr+AdHQzm9VsPlsJNY3gC11eLwtnXAWBc4KCShF3K3C1RmnDxKoK9qfaS16dx5bbXyh/cdE1X56jFHASOnI1NqDHS7N++xOMjw/Z3gLSkWEGzex+tzN0Sogqv0f209OJzZoOSg0XJ6HGk1Q1lMpH2NHxajjkZ3fOqbv55jAQrHUwocKEGhNqvCCgJzfAxj3PUaI9m8khh9NMNk0cfK8vSJ8Mim6iqifD9M/fAFpD1AWcQXL6TQbkNcqSVurGT5iIhDjKReMAFrBkTQ8Dfi+b9rZShG8zHsE/09SGTXT8N/1wAC5dAcd8Hi/WfPtYCi6v1mhxERwEsBiMk5Us7fgBFCwEAKYUE0Ypk2m0tj2PCq1NF8h29lBTkeRfqXMQMA3Qtwv4E5n4LO5Wyi27urZSXJK4JHCJoylBSwwHF6UNWocgEFKg2r2OZ//yPPkhbMYj/UYvE5NRulP3n5t669GL8HoMBTNn1lWXEZExREjiEMehGIcoWiIILiIWUT6XRWazced2hgawaY+3unqpTRTT/9a9594+TmtG2T5+ks3BodcLxKgixrhRXkURlUQpJ2orqZGv8vNt2xkagEyBjjcz1CRKGDq25Pya5+nd8GHCbMAfDnSmbJyPjoDHE6OKKJUUUU7MTuCScD6Pbv4tQ1lIF2hru4e68jj+kcXn372d0Qv3u3BikEeOdPXP1baChFQCCoOPz+Cw1HoJVm1bTmAKZArs/ttdXP/JX8KhBRc2Ppx1ILn8MbJX142JlZckiRYJsYimSMqwxuHPna+AQDrP5r138sUpG+HAPRc+vzhn28xbnnr7eO+9KdWL0iACSg8LlFLQnefXe+9k/tRn4O93v78BSr9zI/l9yFneKI3yLSMQAlaG3Qj0+azfO49vTP3V+4dfsE19+sP/rQ+Q/RtTFlmk7odnzwAAAABJRU5ErkJggg=="); }, error: function(message, title) { this.notify(message, title, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILEdjZkwoAAAdESURBVFjDnZddbFTHFcd/M9f75V2vlw+bAMqCHYysUkXNRyHEEpRQsEj7gOzUgEiJkgdHSlAek5cAolUlniIRUFJQnnCqhDQ4ICWNBXESoKKpIlAIpaCYQmRsYj5sr3e93nv3zp3pw91ddsE2hJGOZnfm3PP/z5kzc84I7qPlOjuJ7N8PQH779rWyunoFwWCTCAQiSAlK5XDdPm3bJwJvvnkUwN66lfDevfe0LaabTK1fT+LwYca3bHnCikR2yurq31mLFiGSSUQiAaEQQgiMUpBKofv70ZcvoycmPtO53I7q9947ne7oIP7RRw9G4Nazz86vCga7AnV1q0KrVhk5d64Q4+OYTAYRDEI4DEKAUhjXRdTUQDSKvnbNOF9/LdTNm1/pfP6PiSNHBn82gaHVqzutQGBfTWurCdXXC/P99wjPgxkzoK7O72MxsCywbRgbg1u3IJXCCIFYsoT80JDJ9vQI5bov1x89un8yHDnZ4NWWlr0yGt03s72d0OnTgq4uxE8/+ZOWBVL6YlkQCFT+NwZx/Tp8+CHBs2dF7XPPIaLRfYMrV+65LwL/e/LJnVYi8ersp59GvP02nD8PWoNSvngeuC7k8/7Ks1lwHP+/Uv6c1r5cuIB4911mt7RgxeNbf1y2bOeUW3CuuZlAILAsEIt9s6C1FfHOO8hg0Hf1rFnwzDMwMuK7PZGAeBwiEX/l+bxPZHQUmpr87Th82NcfHsY4Dqazk/6eHvLZ7FOe6/77F+fPV3ogMzoq3VzuxEOtrcbbvRuTyfircRzf6LZt8NJLkMtBOg2pVAmA0VFfHnkENmyAzk5oaYHxcYzrQiaDt3s3c9asMWpi4sRwJlPCtYo/Xq2v/8uMpUt/Ezt1SpgrV5BCIKSEpUsR778PxsCcOdDQAF9+6W+F49wmtHgxbN7s6wGsWAE3biBOnsTk8+ixMUQ6LbxHH7W8oaHgX0dGekse+D3gOs4bs+rrcc+cwQDadTGPPYbo7vaNCuH3TU3w+uswNAQ3b8L169DYCM8/f1uvqLtjB+aVV9COgwHUmTPMrKvDdZw3flVc+fHZs/nnnDkb/9vaalLNzSYFZhyMvWiRMcYYo7WZtF26ZExbmzFvvTWlni6MOWAmwKTBpJubzcV168ypefM2nqyv90l8lUh8OrBli74OZqSgOFFba9SBA2badvr0PcHzDz9sJgqLSoG5BWbwhRf08ZkzPy1tgcrn14WUEh5QkrEx8i++iD5yZOqr8vHHb7u9rBljEIC7YAHe1avocrtAWCmhHGcNgPxHJFJjJRJS9fXhAapc2fOw16/HO3ZsmmwyNbjq78eDuwioH35AxuPBnkikWmqt51uxGM7ISAm8nIQGnLVr0V98cc/MVgR3kklU2cpVmU0XcEZGsGpr0bBQGq1jxrJQjnOXoiqTiTVr8Hp7p0+tQmA3NKAGBiq+LbfpAcpxQEo8raulp3VW2TZKCFRBKV/4yC0jIjo6sFavvqcXAh98gLKsuwiU21RC4No2Rqms1J43aI+O4oXDFYBumVgdHUQPHrx9yUzTrOXLqe7tRYVCFTbKbepIhNzwMK7W/bIN0rlUSnvRaEkhXxAXCHR0UFsEF+J+CigCK1dS88knqGi0ZKvcpqquxh4bc9uNycpCRurJWZZx7lh5eNMm6g4exExx1HQ2OyWJ8Lp1zDx0CFfKCpt5IGtZBjgGILv9y6Ark0oJT8oSUxuYvWtXKbgmi/ZrixeTK5wOc8f2GGOobm1l3uefY5d5QElJJpUSErq6i+m4GzCgH2pqEm5fH1VAFRCIxfjluXMEFy68C/xyMokaGABg3scfE2tv9+cKZI0xmIkJ/tPYiHPjRikYA01NDPb1GQmyrXgTtvm2d00oVRED9vg43y1eTL4AVAS/kEySHRgo6f24cSOjXV13gX+XTJK9cQOnbP/HlULArrY7C5JusDRkZzQ2Bt3Ll0VVgV2xf+LSJUKNjZxNJnEHBhB3FpTBIAsPHGDWhg142Synk0nyIyMVN2CgocEMX7mSlxBt84cqCAA8JcPhf4WjUbzh4RK4BQRrawnNnUvu4sUK8GJvACMES3p6uLBpUwW4BqxZs8hls3i2vRz4pm2qqrgbdlbFYtullOh0GqugJMuqFznJx6YgXmG8CKwBKx7H1RpvfPxPbbDjnmX5IdhjRSJbZSiESqUqSIgyYRICxbNQzANViQSe4+Dlcnva4bX7fhd0Q6ewrH0yHjduJiNQqoLAZB4o9hqgqopATY3x0mlhPO/lNtj/s19G3TDfwN+scHilCYWMsm3hOc60WyBDIarCYSMcR3i2fVzA5jYYfKCnWbH9HX4t4c8S1sh4XOZzOWTxWeafO7RtE4pE8NJpreGYhm1/gG8f9HEqgQAQBsICwsaPwdBr8NsGWBaFBgmRwn7bGbhyBb7dC72AI0Ab/0KdKFysxYR43x4QhcCvKpAJFggFC+PFuJSFeKMs6dnF2qOsHNCTgfwfl5gsFvMgXIgAAAAASUVORK5CYII="); } }; }()); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T22:27:28.797", "Id": "25246", "Score": "1", "body": "At the very least for option 1) you can use tools to bundle all your js into one minified file when loading onto the live site, and for test sites leave them separated for debuggin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T05:45:54.113", "Id": "25276", "Score": "0", "body": "@rlemon putting images in base 64 is not simpler. Editing them makes it harder and there is the whole separation of concerns. IMHO it works well for small images or in situations where multiple requests are very very bad. Usually you just have one sprite image and your css looks after the rest. Having to decide where to put images or changing css is normal, this is what css was made for." } ]
[ { "body": "<p>Site loading performance depends on the number of HTTP request in many cases. The less of them, the better. This rule justify your reasoning to keep everything in one file that is being loaded with one request.</p>\n\n<p>There are, however, two things that should also be considered:</p>\n\n<ol>\n<li><p>Caches. In normal case, your CSS and image files will be cached and\nthis should prevent browser from doing too much requests. This, of\ncourse, needs some server side configuration but if anybody cares\nabout performance, ensuring proper cache configuration is probably\none of the most important things anyway. Of course javascript file\ncan be cached too but it's not always possible so it just depends on\nyour workload.</p></li>\n<li><p>Dynamic change of styles and DOM. When all the styles are in single\nfile, browser may read, parse and apply them all at the same time,\ncausing only one reflow. When you set them individually, it may do\nreflow each time you do the change. Now, in most cases, browsers\nwill queue some changes before doing reflow, letting changes to be\napplied in groups. But this is browser specific and you have no\ncontrol over this. Since you are changing styles using properties,\nyou are actually doing a lot of small changes. It is why it is\ngenerally faster to switch CSS classes instead of changing\nindividual properties but you can't do this with your approach. You\ncan, however, use CSS classes as I mentioned still having whole CSS\nembedded in your code. Here's how:</p>\n\n<pre><code>var style = document.createElement('style');\nstyle.type = 'text/css';\nstyle.innerHTML = \"YOUR WHOLE CSS\";\ndocument.getElementsByTagName('head')[0].appendChild(style);\n</code></pre>\n\n<p>Just replace \"YOUR WHOLE CSS\" with your values. This way whole CSS is loaded at once, you have CSS classes and can apply them easily at once instead of changing each property one by one.</p></li>\n</ol>\n\n<p>All this is theoretical. You may get different performances on different browsers (or even on different versions of one browser) sine each of them implement some other optimisations techniques. So the only proper way of optimising your scripts is to try and measure. On as many browsers as you can.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T06:59:14.923", "Id": "15560", "ParentId": "15551", "Score": "6" } }, { "body": "<p>A few observations:</p>\n\n<ol>\n<li>If a specific part of the file is supposed to change a lot, then refer to Krzysztof Adamski's answer.</li>\n<li>You also need to look at the size of base64 images: storing an image in base64 takes more space than in a file since (about 33%). For large images, it can be a problem. This is where CSS sprites can help: you only use one file to store multiple iamges.</li>\n<li>If your project is going to get bigger, then you should use the module pattern and a tool like RequireJS to manage depedencies. This is explained in the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">Learning JavaScript Design Patterns</a> online book.</li>\n</ol>\n\n<p>My conclusion is that for this example it's OK: it's small enough to be easy to understand and edit, you will only need one HTTP request which is great for performance, and it's easy to send to your users (eg. other developers).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T09:22:56.153", "Id": "15563", "ParentId": "15551", "Score": "3" } }, { "body": "<p>Embedding images inside the source makes the images hard to maintain but there is almost always a trade for performance.</p>\n\n<p>Here are a few tips after reviewing your code.</p>\n\n<h1>1) Use <code>Notifier</code> as a namespace.</h1>\n\n<p>The module design pattern doesn't go well with this project because Notifier doesn't have anything to hide.\nAlso you should create functions inside the closure, then attach the functions to the returned object literal. </p>\n\n<h1>2) Expose as much as possible to prevent hard-coding values.</h1>\n\n<p>What are you hiding the <code>config</code> variable? It's best if you attach it as a property to <code>Notifier</code>.\nAlso attach the image values to the config variable. \nTry something like this, <code>Notifier.config.imgs.warning</code>.</p>\n\n<p>Old Code:</p>\n\n<pre><code>//...\ninfo: function(message, title) {\n this.notify(message, title, \"data:image/png;base64,i...\");\n},\n//...\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Notifier.config = {\n //...\n imgs = {\n //...\n info: \"data:image/png;base64,i...\"\n //...\n }\n //...\n};\n//...\ninfo: function(message, title) {\n this.notify(message, title, Notifier.config.imgs.info );\n},\n//...\n</code></pre>\n\n<h1>3) Rewrite <code>fade_out</code></h1>\n\n<p>The function <code>fade_out</code> contains multiple problems:</p>\n\n<ul>\n<li><code>fade_out</code> is a recursive functions without a break condition, meaning this function is never ending once called.\nTo fix this, add a simple condition to that will clear the timeout or return from the function.</li>\n<li>Too many <code>if</code> and <code>else</code> conditions are used. Reduce the logic to simplify to conditions.</li>\n<li><code>setTimeout</code> is used to create an interval, when setInterval is more appropriate.</li>\n</ul>\n\n<p>Old Code:</p>\n\n<pre><code>var fade_out = function(element) {\n if (element.style.opacity &amp;&amp; element.style.opacity &gt; 0.05) {\n element.style.opacity = element.style.opacity - 0.05;\n } else if (element.style.opacity &amp;&amp; element.style.opacity &lt;= 0.1) {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n } else {\n element.style.opacity = 0.9;\n }\n setTimeout(function() {\n fade_out.apply(this, [element]);\n }, 1000 / 30);\n};\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>fade_out = function (element) {\n if (!element || !element.style) {\n return;\n }\n var fn = function(){\n if (0.05 &lt; element.style.opacity) {\n element.style.opacity -= 0.05;\n return;\n }\n element.style.opacity = 0;\n if( element.parentNode ){\n element.parentNode.removeChild(element);\n }\n clearInterval(t);\n }, t = setInterval(fn, 1000 / 30);\n};\n</code></pre>\n\n<h1>4) Expose the events</h1>\n\n<p>For further flexible, provide access to the mouse events by attaching them to the <code>config</code> or <code>Notifier</code> object.</p>\n\n<p>Old Code:</p>\n\n<pre><code>//...\nnotification.onclick = function() {\n this.style.display = 'none';\n};\n//...\n</code></pre>\n\n<p>New code:</p>\n\n<pre><code>//...\nNotifier.event.onclick = function () {\n this.style.display = 'none';\n};\n//...\nnotification.onclick = Notifier.event.onclick;\n//...\n</code></pre>\n\n<h1>5) Split up functions that are 8 - 12 lines into smaller units</h1>\n\n<p><code>notify</code> has high complexity because it's handling too much. Try to abstract the logic into smaller units that only perform one task.</p>\n\n<p>Old Code:</p>\n\n<pre><code>notify: function(message, title, image) {\n\n var notification = document.createElement('div');\n apply_styles(notification, config.box_styles);\n\n notification.onmouseover = function() {\n apply_styles(this, config.box_styles_hover);\n };\n notification.onmouseout = function() {\n apply_styles(this, config.box_styles);\n };\n //... more code\n //... more code\n setTimeout(function() {\n fade_out(notification);\n }, config.default_timeout);\n },\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Notifier.notify = function (message, title, image) {\n var notification = Notifier.element.createNotification(image);\n notification.appendChild(Notifier.element.getTextNotice(title, message));\n Notifier.container.insertBefore(notification, Notifier.container.firstChild);\n setTimeout(function () {\n Notifier.element.fade_out(notification);\n }, Notifier.config.default_timeout);\n};\n</code></pre>\n\n<h1>6) Create a setup function that auto-starts</h1>\n\n<p>It's good to have an <code>setup</code> or <code>init</code> function with a script that's more than 50 lines of code.</p>\n\n<p>Additional code:</p>\n\n<pre><code>Notifier.setup = (function () {\n Notifier.element.apply_styles(Notifier.container, Notifier.config.container_styles);\n document.body.appendChild(Notifier.container);\n}());\n</code></pre>\n\n<h2>Final Result:</h2>\n\n<pre><code>var Notifier = {\n container : document.createElement('div'),\n element : {},\n event : {}\n};\nNotifier.config = {\n default_timeout : 5000,\n container : Notifier.container,\n container_styles : {\n position : \"fixed\",\n zIndex : 99999,\n right : \"12px\",\n top : \"12px\"\n },\n box_styles : {\n cursor : \"pointer\",\n padding : \"12px 18px\",\n margin : \"0 0 6px 0\",\n backgroundColor : \"#000\",\n opacity : 0.8,\n color : \"#fff\",\n font : \"normal 13px 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif\",\n borderRadius : \"3px\",\n boxShadow : \"#999 0 0 12px\",\n width : \"300px\"\n },\n box_styles_hover : {\n opacity : 1,\n boxShadow : \"#000 0 0 12px\"\n },\n title_styles : {\n fontWeight : \"700\"\n },\n text_styles : {\n display : \"inline-block\",\n verticalAlign : \"middle\",\n width : \"240px\",\n padding : \"0 12px\"\n },\n icon_styles : {\n display : \"inline-block\",\n verticalAlign : \"middle\",\n height : \"36px\",\n width : \"36px\"\n },\n imgs : {\n error : \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILEdjZkwoAAAdESURBVFjDnZddbFTHFcd/M9f75V2vlw+bAMqCHYysUkXNRyHEEpRQsEj7gOzUgEiJkgdHSlAek5cAolUlniIRUFJQnnCqhDQ4ICWNBXESoKKpIlAIpaCYQmRsYj5sr3e93nv3zp3pw91ddsE2hJGOZnfm3PP/z5kzc84I7qPlOjuJ7N8PQH779rWyunoFwWCTCAQiSAlK5XDdPm3bJwJvvnkUwN66lfDevfe0LaabTK1fT+LwYca3bHnCikR2yurq31mLFiGSSUQiAaEQQgiMUpBKofv70ZcvoycmPtO53I7q9947ne7oIP7RRw9G4Nazz86vCga7AnV1q0KrVhk5d64Q4+OYTAYRDEI4DEKAUhjXRdTUQDSKvnbNOF9/LdTNm1/pfP6PiSNHBn82gaHVqzutQGBfTWurCdXXC/P99wjPgxkzoK7O72MxsCywbRgbg1u3IJXCCIFYsoT80JDJ9vQI5bov1x89un8yHDnZ4NWWlr0yGt03s72d0OnTgq4uxE8/+ZOWBVL6YlkQCFT+NwZx/Tp8+CHBs2dF7XPPIaLRfYMrV+65LwL/e/LJnVYi8ersp59GvP02nD8PWoNSvngeuC7k8/7Ks1lwHP+/Uv6c1r5cuIB4911mt7RgxeNbf1y2bOeUW3CuuZlAILAsEIt9s6C1FfHOO8hg0Hf1rFnwzDMwMuK7PZGAeBwiEX/l+bxPZHQUmpr87Th82NcfHsY4Dqazk/6eHvLZ7FOe6/77F+fPV3ogMzoq3VzuxEOtrcbbvRuTyfircRzf6LZt8NJLkMtBOg2pVAmA0VFfHnkENmyAzk5oaYHxcYzrQiaDt3s3c9asMWpi4sRwJlPCtYo/Xq2v/8uMpUt/Ezt1SpgrV5BCIKSEpUsR778PxsCcOdDQAF9+6W+F49wmtHgxbN7s6wGsWAE3biBOnsTk8+ixMUQ6LbxHH7W8oaHgX0dGekse+D3gOs4bs+rrcc+cwQDadTGPPYbo7vaNCuH3TU3w+uswNAQ3b8L169DYCM8/f1uvqLtjB+aVV9COgwHUmTPMrKvDdZw3flVc+fHZs/nnnDkb/9vaalLNzSYFZhyMvWiRMcYYo7WZtF26ZExbmzFvvTWlni6MOWAmwKTBpJubzcV168ypefM2nqyv90l8lUh8OrBli74OZqSgOFFba9SBA2badvr0PcHzDz9sJgqLSoG5BWbwhRf08ZkzPy1tgcrn14WUEh5QkrEx8i++iD5yZOqr8vHHb7u9rBljEIC7YAHe1avocrtAWCmhHGcNgPxHJFJjJRJS9fXhAapc2fOw16/HO3ZsmmwyNbjq78eDuwioH35AxuPBnkikWmqt51uxGM7ISAm8nIQGnLVr0V98cc/MVgR3kklU2cpVmU0XcEZGsGpr0bBQGq1jxrJQjnOXoiqTiTVr8Hp7p0+tQmA3NKAGBiq+LbfpAcpxQEo8raulp3VW2TZKCFRBKV/4yC0jIjo6sFavvqcXAh98gLKsuwiU21RC4No2Rqms1J43aI+O4oXDFYBumVgdHUQPHrx9yUzTrOXLqe7tRYVCFTbKbepIhNzwMK7W/bIN0rlUSnvRaEkhXxAXCHR0UFsEF+J+CigCK1dS88knqGi0ZKvcpqquxh4bc9uNycpCRurJWZZx7lh5eNMm6g4exExx1HQ2OyWJ8Lp1zDx0CFfKCpt5IGtZBjgGILv9y6Ark0oJT8oSUxuYvWtXKbgmi/ZrixeTK5wOc8f2GGOobm1l3uefY5d5QElJJpUSErq6i+m4GzCgH2pqEm5fH1VAFRCIxfjluXMEFy68C/xyMokaGABg3scfE2tv9+cKZI0xmIkJ/tPYiHPjRikYA01NDPb1GQmyrXgTtvm2d00oVRED9vg43y1eTL4AVAS/kEySHRgo6f24cSOjXV13gX+XTJK9cQOnbP/HlULArrY7C5JusDRkZzQ2Bt3Ll0VVgV2xf+LSJUKNjZxNJnEHBhB3FpTBIAsPHGDWhg142Synk0nyIyMVN2CgocEMX7mSlxBt84cqCAA8JcPhf4WjUbzh4RK4BQRrawnNnUvu4sUK8GJvACMES3p6uLBpUwW4BqxZs8hls3i2vRz4pm2qqrgbdlbFYtullOh0GqugJMuqFznJx6YgXmG8CKwBKx7H1RpvfPxPbbDjnmX5IdhjRSJbZSiESqUqSIgyYRICxbNQzANViQSe4+Dlcnva4bX7fhd0Q6ewrH0yHjduJiNQqoLAZB4o9hqgqopATY3x0mlhPO/lNtj/s19G3TDfwN+scHilCYWMsm3hOc60WyBDIarCYSMcR3i2fVzA5jYYfKCnWbH9HX4t4c8S1sh4XOZzOWTxWeafO7RtE4pE8NJpreGYhm1/gG8f9HEqgQAQBsICwsaPwdBr8NsGWBaFBgmRwn7bGbhyBb7dC72AI0Ab/0KdKFysxYR43x4QhcCvKpAJFggFC+PFuJSFeKMs6dnF2qOsHNCTgfwfl5gsFvMgXIgAAAAASUVORK5CYII=\",\n info : \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxIKNf3BRpoAAAfvSURBVFjDnZddjGRVEcd/59zbt6ene3fWXXaGcWd3YRlcZpnVCAReyEIIKmOCMZFoJIEXfTAxPGhCfAD1SRNjxAf1SWJi9smNkYSP7PqgkoAJASLifuCEkcXJjPNB90zPbHdP972nqny4t2eagXWRSk5u376nqv7nf6rq1HF8RFlbW2P//v3930eAE8BE8XkBuLR///753XOvJfG1JjQaDQ4cOICZPVCv1x8Fvuqci6IownsPgKoiItTrdQHOmNlp4Gxf92NJo9HoP0/V6/X5ZrNp3W5XRcTMzFT1fcPMTESs2+1qs9m0er0+32g0Tg3a+shSr9f7zxfW1tYsTVPtOzVTa3bELi6LvTqfj4vLwTa2xMx2wKRpqmtra1av118YtLlb3O4/3nvvPcxsDPhHpVIZrVarmCm9AH96W3htAVqZI4kc3ufqokYalGrJuPOw4/6bI8oxOOdpt9tsbW2tAp92zq0cPHjw6gBWV1dxzo2a2fyePXuSJEmc98a5twLPvyUMJZ7Ye6LIEzmP9w4zQ80QUUSVTJRuJjx4ImZmqoSqI01Tu3LlSuqcO2Jmq6Ojo1dnYGVl5d1arXYkKZcdZvz0L10WNo0kjoijHQA4TyV2GEYnMzAlFCCCKL1MODzi+N59FXCOtNezVqs1PzY2dsOgP7/L+c/K5fLRcrnsnCk/PNfi303BOcDADAwIYtx/DJ64z/HkfZ4HJh1B8jn5MLyDd9cDT569gjOlXC67crl8dGVl5akPAFhaWmJ5efmTZvbdWq2GR/jly23+symYWU4ztk23qXHvpENVUVVO3eRInGHk39Uo9GBpQ/jFSy08Qq1Ww8y+s7y8fGhpaWkHwPj4OKr642q1SgiBNxcz/nq5BwaquUHVnF5Vo9fTD0RzLxVEDTUtRg7YMF5+p8ffF1JCCFSrVVT1R+Pj4zsAilU+UqlUSCJ4+pUWsadYjaGiiOXvokKqyu9fS/EevIc/X0ppbuUARUG10C0Axx5+/coVkggqlQpm9oiZ5UG4sLAA8ODQ0NCztVqNy42Mx59tUi3HedBFEbH3xJHHR57Igfee5qZClhvfAq7b5wuAeUYEFYIoQfJnqys89eV93HggodVq0e12vwQ85ycmJjCzLyRJYiKBl9/ZIvZs0y2qSD/CgxDUCCIMD8Nnb4o4eUPE3prLnQVFQsGE7DAgqpQ8vPSvLUQCSZKYmX1hYmIiPwtU9fY4jp1HubSU5orOEZxuJ6p5MBzeDDHHt+4qc8eRCIB/rgg/ebFLKdqJFREj9BeghqpwYalH5Kq4OHaqesf2YaSqR53LjS80M0QdDDhnO6o93jkiU+48WqGb5cF44nrPvpKwke1irgChqgSFxWaGxzDnUNUbtwGYWdU5B2a0eoKa/4DzyPI99s4hQbfTMy/FEKNkYnnWFKt+HwhTWj0tCkXucxBAW1X3okYSGe1MIQBRUVTMY2Z4dTjviHYBUDVCFgjitle/A8K2K2Q1yecS5T4HAcyr6riIMlrzzNUF8wbOUHNEZmhBvzdQke0Ay+PD5dEeXFELcibEBplQxmoRQRQQzOydwVL8epqmlolyy2hMkLyoZNJPJSUEIRMhC3lq0S80xQgipCJF2smAruQpqcLUaIlUlCzLDPgbgJ+bm8PM/tjtdp33EaeOlemkuaKEnL6sbzDsGLYPARBCfhoOOpcgiBidVDh1rIz3EVtbW87Mzs3NzeEnJyeZmZl5bnNzU5Mk4ZaDMYdGfFFMilEYzETJQg5EBwGoIQXIrADSB9S3cXgk4pbRmCRJ2Nzc1JmZmecmJyfzLZibmwM43el06AbjsbtrtNOCziDbLISBle3eAtUBp/1t07xwdXrCY3fvpRuMTqcDcLrwmQOYnZ3FzJ6o1+sMDw9z+0TCPcfKhZEBgwWIZjsrikse7ZGH2aUtsoE5+XwjBOGeY2VuP1xieHiYer2OmT05Ozu7A+D48eNMTU0tqupT6+vr4Et8/3MjXL/HDTjv769iJc9jT19GxRAxHv/tZbI4yrdHlEzz1Yso43s9P/j8CPgS6+vrqOrPp6amFo4fP/7hHdGFCxfmx8fHJ0TEiQjf/kODt+sZsXM45woNR+gFlhc2wGD00F7KlbhoWPI+IKjxqetifvWV64iiiCiKbGlpaWF6evrIVXvCS5cuoaqjZjZ/6NChRFWd04zfvHqFp1+5QlLyuEJpB8xAqS6O9l4wvnHXHr551x7Ml/De2+LiYuqcO+K9Xz1x4sTVe8KLFy8CjInImwcOHBir1Wp02i06mXH69RbPv9VhvaOUIk/RFKMGmSj7Kp4HTwzz6B01KiXHcLVGq9Wi0WisRFH0GWDl1ltv/d9tebENTE9Pc/78+bNJkjwwNjZmIuK63S2GS475pjC7mrFRdEYjZc/NB0vc8ImITmYMDVWIoshWVlZcmqbnTp48OdO3ec17QV/Onz/PyZMnuXDhwr0icrparU6MjIzY0NCQy7KMEAIiAkAURcRxTKlUotvt2sbGhmu32wtRFD0yPT39Yt/WR7qY7JJoeHi43Ol0umfOnPn6+Pj412q12her1WqUJAlxnF8tQwikaUq73ZbNzc2zi4uLZx5++OHflcvlpNfr9ciPNvt/ATigBJSBSvEsAfrQQw9N33bbbcf37dt3vZm5RqOx+sYbb8w+88wzFwu9APTIu7UukALycRjYLb4A4QZ0o8J4/1YgA+/XlP8CEfRY6kDvcEYAAAAASUVORK5CYII=\",\n success : \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILCcu1C1wAAAW3SURBVFjD7Zd/kFVlGcc/z/uec/fe3b33suwPoDZN1qWtBcnQAdH8kTA12CSp0yCpQwwRpcbsiPnHbtDyY6IlTNOZ0koDm2myoXJmCRBFCDJnsJZgEdp2QPyxl5i9d3/fe88957xvf+xCi6ABRn84PjPPnOd9zx+f55znPd/nOfChfeBt1ah4w5m31UVPoJOJi59b3NH4QmMXh/js//fpFzGp+aVm25nuNB3dHWbXkV22dn3tcgCaLjZ8CdPW7Fpj96X2mbZUm91/fL89eOKgbU8dsDOemN4KQCPIRYE38Ll1t7e8eM3HZloRES0arTRaNEo0pZFiFvz+awf3LNoz+X+fwHe4peXWta1XTrjSilUionFGJRBzo7x0dCeNWxrIGqrOPISNo+KlfOK84E18Zd3c1a314yZZP8xJweTxwzz5ME8+yKOUYsO+DazZ1kDCBUJ8dQZ0iFuu21C/dcn2W+1tN848zCJKzoWtlsvCh7/U/JvaikttYPLiWw/fDHsh9Ig4ER5/5VGe/esjxKPQHfAka+l1AOjnisk/vWTpFdUfX3htTT3xaLE1BmJFtfzu5ZeXAc3vBXdWOA/+aG5Ty4TScTbAEzEaQYPVBFZRFi2nZfcaXnt7G7EIHB2kJVzJQywdOYTTnokPfHPm/JLA+nKyVlo0Ra7Lk7u39u+Ydzj5bvD46uLV6+Y+0Dg2VgZWg9FYOwzHapKRsTTvWEnPQJsNDHKkn4fMSlpOE6L2YwP5o95OUdpHtIfSHsrxCGyOL0ypT3Afs/WK/0CTI/G4H4758fo77mscUxLBiIfBIxSPEI+APBFH88CWBoZybTYA6exj8Wj4qQTMIMG+4/+gxxxG6wLieIj20K7Hp6or7aT6smXhSBFqn4a+Zpjyi/KnfnDbgvuTxQ6oAhbvVBKGPEoMD/5xGVH1us0ZpDPDHaziZ+98gxogdgPX+iF11TVd4mpIuOVoJ0CUIbC+xKK2pn1S12Of+Tq5/XfBjZvGbmq4ad78IkeDGLAGKwZrDRZDLszTvHUtFcW9tr+AdHQzm9VsPlsJNY3gC11eLwtnXAWBc4KCShF3K3C1RmnDxKoK9qfaS16dx5bbXyh/cdE1X56jFHASOnI1NqDHS7N++xOMjw/Z3gLSkWEGzex+tzN0Sogqv0f209OJzZoOSg0XJ6HGk1Q1lMpH2NHxajjkZ3fOqbv55jAQrHUwocKEGhNqvCCgJzfAxj3PUaI9m8khh9NMNk0cfK8vSJ8Mim6iqifD9M/fAFpD1AWcQXL6TQbkNcqSVurGT5iIhDjKReMAFrBkTQ8Dfi+b9rZShG8zHsE/09SGTXT8N/1wAC5dAcd8Hi/WfPtYCi6v1mhxERwEsBiMk5Us7fgBFCwEAKYUE0Ypk2m0tj2PCq1NF8h29lBTkeRfqXMQMA3Qtwv4E5n4LO5Wyi27urZSXJK4JHCJoylBSwwHF6UNWocgEFKg2r2OZ//yPPkhbMYj/UYvE5NRulP3n5t669GL8HoMBTNn1lWXEZExREjiEMehGIcoWiIILiIWUT6XRWazced2hgawaY+3unqpTRTT/9a9594+TmtG2T5+ks3BodcLxKgixrhRXkURlUQpJ2orqZGv8vNt2xkagEyBjjcz1CRKGDq25Pya5+nd8GHCbMAfDnSmbJyPjoDHE6OKKJUUUU7MTuCScD6Pbv4tQ1lIF2hru4e68jj+kcXn372d0Qv3u3BikEeOdPXP1baChFQCCoOPz+Cw1HoJVm1bTmAKZArs/ttdXP/JX8KhBRc2Ppx1ILn8MbJX142JlZckiRYJsYimSMqwxuHPna+AQDrP5r138sUpG+HAPRc+vzhn28xbnnr7eO+9KdWL0iACSg8LlFLQnefXe+9k/tRn4O93v78BSr9zI/l9yFneKI3yLSMQAlaG3Qj0+azfO49vTP3V+4dfsE19+sP/rQ+Q/RtTFlmk7odnzwAAAABJRU5ErkJggg==\",\n warning : \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wCBxILGKEFK64AAAZZSURBVFjDvZdbjFVXGcd/39qXc+Ywl9LQYdoCji0XhbRorVOVXnRKShUjSmPB2KT2yUaa2AeTYqyJDanxAR5UHiRqJZEUaRS1AS+Q0KLcxGCpBVMwaUIphRYYcGbOzD57r/V9PuztjLEoZQBXsnPOWdlrff/1v6x1Fkyw2YH7L/j9Uls8kUG6fxFqdr3+eeEq0HY1exp4ZSJzyaUXvw/ErjULZ2XGCiPuwo59T0SzWzAOub5tXPUW9vX/So+vNz39J9O3dpme3aVh710nJzKXu6TCe+8l7Fv4AeKOJdK5AJEYiRuImyx09fWEfQu/dtUl8LvuPORuXjmXZKpI1AbiQHPMOfTQo4VJrSNZ8ELrijPQ3PFx/O5PLKP9/fOk3isiUVlcYsAhvoVMfSAR0+9cNQbyF/uyeN7qlKAicQPiNhCBUGB+FEnaKQ4/jliYjtkbyd1/uOic0bsuvvOuVe66hf0u6REB1Bxff/qH/HHPS4yONJndex1kZ6B9ptm5/R9K79m9/orsA60dH0NEukz9k27KvTByCuIGrt7Oxs3b6Whv0Nk5iU/dPQu0RVTrFU177slfuPOjZrq31r/n8jxQ69+DBb/O3fB55Nxh0Az8CMQeVcV7T1saYfkQ+BFs6AjRjctNi+bPL1b8ogCy3/eRbbtjrkXty+LaNAij4JvghyEfJE1TvPfUU0GKYfBNxLdwrfMikz98Q7b9I1+9LAD1Rfsxn/0snv4Fs4GDZfFiuALwD9I0KQHEBn4IiiHww1jzDZLu+9C8ubr529ujCQEY+cVcRn5z+wN0zLnF5cOCKYSipL8YgnyQei2lKDxtKVAMgm9imoEFOPsXohuXxGK6ekIAGg/8DSuGNiTXLzYG/w4hxyzHNIfQgmKYNIkofEFbYhAyCHkZSc2hGCFpn4WpPT6yZX538/n5lwag+etbn4p6PlmXswfELJS7XSgfDS3wo9RShy88bTUt+7UF2kIqsHpqJ0nvQ6a+2DjpMy+/uxgObZ6HiHRpyL9R65qDvb0bcQnqFLHA2A7oR2lLHXnhaaQKoYVglGADpgEsEIWWSG1q//Avoz4z3d+x9PD/ZqBj6WHU+7VJ7/LITmwrqQ8V7aGFVg/FCGlieB9oSwqs6rfqPTQr+07vJ5mxxLRobvzP4u9gYHDTbBCZK3H7QxFAaGGmYIqYxyQCiRBx4I1GzSgKTyMtSg9goIpaQCyAeswCcu6QRFPuuGnwufSxzgdfXftfGehcdhTz2U+T3s+avrmt0ryFhQzz5SchQ0MGxQj11NAQaKQ56lvgs8qM1TshA22hg0dJp9yGFc015zbNjC7IwPkNN4G4RdI56zY3eAQzxbQF5hFLMPGIRqg4RBxmBdd0CLW2lEaUQTGKYhVbWq3eg3owj77+PMl7Ppfmx7Z8G3jigqfhwE96sknzV6T22rNCVEeipDxuXVSZrzIgDkRIerrhmi78a8ewvFVKYIqZIhX9ph6xgIUcN30xzSPPYeaniHJ28sPHxgGcWz/jyWRa/6po+BUohhCXgItAYkRicG5cfwRDiF053CuIGJiNecYqH5j+C4THwig2YxnZqxu2XvvIiU+PSTDwzLRJ6vOnko5uwtsnIUrBFCxCJGDiQcviJg4TIQuOVZsLAL65NKUeKWBIxQAW0IoJLKDqEVWi7DhSn7p44Bn5oJm9FAOo99+vz3nQ+SM/AhcjBriAaQwujK1cxYE4ksixcqNn+4Gs3LRaddZ+McYHQ6k8YAoaxhNRyeFf30p9zgprHvzBpimPDsyOz6ybOpO48UgcTuPVIxiIosSIBLBSd/03+okiMs0ZGhouT001oIaFMCaDjQHxmI5LAmAnfydRd9+sM+sOPhybz7/V9r7l5o9+V4jbsKDgqhVUqx7//ycgjnxUWPNYO5q2MIM1X26QnxoqDWWGUY5XKwGJBqBiQwM68Fdqc75iwyd2r4w1FL2cf1lMHKIeEcVUQcK46yUAUkkggNB2MufHX0oBKE4OgNpYDIFxGSogUjFSbtHAqR1iuPfGkGzJ3jy0oBYBrsBwCKGMmpWaW6W9mFQxFDAo3srLIBulAbEqilUaMLAwBmYsIQrZwGlQ2SoAO59of/bm7mhxPZFOswteRS/jHiXv+OkDxfGB8GLfqqH7pYrirUAOBP4/zQE1kYldaK9o+yfo49dpgHxFaAAAAABJRU5ErkJggg==\"\n }\n};\nNotifier.element.apply_styles = function (element, style_object) {\n for (var prop in style_object) {\n if (style_object.hasOwnProperty(prop)) {\n element.style[prop] = style_object[prop];\n }\n }\n};\nNotifier.element.fade_out = function (element) {\n if (!element || !element.style) {\n return;\n }\n var fn = function(){\n if (0.05 &lt; element.style.opacity) {\n element.style.opacity -= 0.05;\n return;\n }\n element.style.opacity = 0;\n if( element.parentNode ){\n element.parentNode.removeChild(element);\n }\n clearInterval(t);\n }, t = setInterval(fn, 1000 / 30);\n};\nNotifier.element.getTextNotice = function (title, message) {\n var text = document.createElement('div'),\n title_text = document.createElement('div'),\n message_text = document.createElement('div');\n Notifier.element.apply_styles(text, Notifier.config.text_styles);\n if (title) {\n Notifier.element.apply_styles(title_text, Notifier.config.title_styles);\n title_text.appendChild(document.createTextNode(title));\n text.appendChild(title_text);\n }\n if (message) {\n message_text.appendChild(document.createTextNode(message));\n text.appendChild(message_text);\n }\n return text;\n};\nNotifier.element.createNotification = function (image) {\n var el = document.createElement('div'),\n icon = document.createElement('img');\n icon.src = image;\n Notifier.element.apply_styles(icon, Notifier.config.icon_styles);\n el.appendChild(icon);\n Notifier.element.apply_styles(el, Notifier.config.box_styles);\n\n el.onmouseover = Notifier.event.onmouseover;\n el.onmouseout = Notifier.event.onmouseout;\n el.onclick = Notifier.event.onclick;\n return el;\n};\nNotifier.event.onmouseover = function () {\n Notifier.element.apply_styles(this, Notifier.config.box_styles_hover);\n};\nNotifier.event.onmouseout = function () {\n Notifier.element.apply_styles(this, Notifier.config.box_styles);\n};\nNotifier.event.onclick = function () {\n this.style.display = 'none';\n};\nNotifier.setup = (function () {\n Notifier.element.apply_styles(Notifier.container, Notifier.config.container_styles);\n document.body.appendChild(Notifier.container);\n}());\n// original API\nNotifier.notify = function (message, title, image) {\n var notification = Notifier.element.createNotification(image);\n notification.appendChild(Notifier.element.getTextNotice(title, message));\n Notifier.container.insertBefore(notification, Notifier.container.firstChild);\n setTimeout(function () {\n Notifier.element.fade_out(notification);\n }, Notifier.config.default_timeout);\n};\nNotifier.info = function (message, title) {\n Notifier.notify(message, title, Notifier.config.imgs.info);\n};\nNotifier.warning = function (message, title) {\n Notifier.notify(message, title, Notifier.config.imgs.warning);\n};\nNotifier.success = function (message, title) {\n Notifier.notify(message, title, Notifier.config.imgs.success);\n};\nNotifier.error = function (message, title) {\n Notifier.notify(message, title, Notifier.config.imgs.error);\n};\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/Lpuj2/\" rel=\"nofollow\">http://jsfiddle.net/Lpuj2/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T20:18:54.693", "Id": "25898", "Score": "0", "body": "Wow! thanks for the feedback (this is what I get for not checking back in a week :P) I just got your pull request I will review it when I get home from work :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T01:10:16.273", "Id": "15595", "ParentId": "15551", "Score": "2" } } ]
{ "AcceptedAnswerId": "15595", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T22:19:59.823", "Id": "15551", "Score": "5", "Tags": [ "javascript", "performance" ], "Title": "Single and multiple files" }
15551
<p>Totally new to MVP and Spring, and I have what seems to be typical MVP application that uses Spring, where the presenter is instantiated like: </p> <pre><code>IApplicationContext ctx = ContextRegistry.GetContext(); presenter = (clsPresenter)ctx.GetObject("clsPresenter"); </code></pre> <p>I hate using strings to call code, really, I hate it. So I'm thinking of putting something like</p> <pre><code>static private readonly string _clsName = typeof(ClsPresenter).Name.ToCamelCase(); public static ClsPresenter getNewPresenterFromSpring() { IApplicationContext ctx = ContextRegistry.GetContext(); return (ClsPresenter)ctx.GetObject(_clsName); } </code></pre> <p>into all of the presenters. So that instead of the the two lines above which use a string to find the presenter, it would be one line using the static method: </p> <pre><code>presenter = ClsPresenter.getNewPresenterFromSpring(); </code></pre> <p>I know this violates the SRP, and it might look to be introducing some coupling between the Presenter classes and Spring, but it seems to me that it's not really coupled any more than it was before, it's just now type (and typo) safe, while living in a somewhat weird place. If I stop using Spring, I simply replace this call with whatever else gets used instead.</p> <p>Am I missing something that makes this a really bad idea? Is there a better way of avoiding the usage of strings? Should I just suck it and make sure I don't spell "clsPresenter" as "classPresenter"?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T09:11:15.107", "Id": "25279", "Score": "0", "body": "Isn't Spring for Java? Or do you mean Spring.Net? Or something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T14:32:20.973", "Id": "25300", "Score": "0", "body": "I meant Spring.Net" } ]
[ { "body": "<ol>\n<li><p>Not sure if that is just the case in your example but it's rather uncommon in C# to prefix classes with <code>cls</code> or <code>class</code>. In fact the only commonly used type identifier as part of the type name is usually the <code>I</code> prefix for interfaces.</p></li>\n<li><p>Method names in C# are usually <code>PascalCase</code> naming convention. <code>camelCase</code> is used for local variables.</p></li>\n<li><p>Not entirely sure about the whole structure of your code but to me it looks like you should be able to easily move the code into a separate helper class like this:</p>\n\n<pre><code>public static class SpringHelper\n{\n public static T GetNewPresenter&lt;T&gt;()\n {\n IApplicationContext ctx = ContextRegistry.GetContext();\n return (T)ctx.GetObject(typeof(T).Name.ToCamelCase());\n }\n}\n</code></pre>\n\n<p>You would call it like this then:</p>\n\n<pre><code>SpringHelper.GetNewPresenter&lt;ClsPresenter&gt;();\n</code></pre>\n\n<p>If all your presenters have a base class your could also add a <code>where</code> clause to restrict the types.</p>\n\n<p>This would at least remove the dependency out of the presenter class.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T09:36:46.407", "Id": "36403", "ParentId": "15554", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T23:25:59.423", "Id": "15554", "Score": "4", "Tags": [ "c#", "spring" ], "Title": "Avoiding using strings when using Spring.Net by incorporating instantiation in class" }
15554
<p>I have written following code to find the minimum difference from a list of numbers.</p> <p>Because I am using a loop once and LINQ again to find the minimum, the algorithm is O(N<sup>2</sup>).</p> <p>Can you please tell me if I am using the framework in the most optimal way (speed and memory utilisation) to achieve this task:</p> <pre><code>using (StreamReader sr = new StreamReader("IN.in")) using (StreamWriter sw = new StreamWriter("OUT.out")) { int T = int.Parse(sr.ReadLine()); for (int i = 1; i &lt;= T; i++) { int N = int.Parse(sr.ReadLine()); List&lt;int&gt; intList = sr.ReadLine().Split(' ').Select(e =&gt; int.Parse(e)).ToList(); intList.Sort(); List&lt;int&gt; diff = new List&lt;int&gt;(); int leastDiff = int.MaxValue; for (int k = 0; k &lt; intList.Count - 1; k++) { int iDiff = intList[k + 1] - intList[k]; diff.Add(iDiff); leastDiff = Math.Min(leastDiff, iDiff); } sw.WriteLine(leastDiff); } } </code></pre> <h3>Benchmark</h3> <p>For 3 test case of 5 integers in each list where as for loop implementation takes 55±5 ms. Mr.Mindor LINQ implementation timing varies from 60±50 ms. Memory usage in both implementation is almost 8.3MB</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:26:31.783", "Id": "25249", "Score": "5", "body": "O(N2) == O(N) so don't worry. Your main cost here is I/O, not the calculations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:38:33.477", "Id": "25250", "Score": "3", "body": "Premature optimization is the root of all evil. If you have enough memory (you almost certainly have way more than you need) don't worry about it. If your program isn't taking too long (it almost certainly isn't) then don't worry about it. You should focus on making your code work correctly first, making it easily understandable and readable second (so it can be well maintained) and only look at performance last if your program is unacceptably slow or uses too much memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:40:50.163", "Id": "25251", "Score": "1", "body": "By O(N2) did you mean \"n squared\"? Cos that's a bit of an important distinction, and one worth editting your question to clarify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:41:09.633", "Id": "25252", "Score": "1", "body": "@Servy I guess it is some kind of homework, so here optimization is the root of good marks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:43:04.787", "Id": "25253", "Score": "2", "body": "@ie. I never had an assignment that encouraged excessive micro-optimization. If that is the case, all the more reason to assert that it's not a good idea because he is being taught bad principles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:45:56.780", "Id": "25254", "Score": "0", "body": "@Servy it is not about micro-optimizations, it is about finding of effective algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:48:24.767", "Id": "25255", "Score": "0", "body": "@ie. Well, the naive implementation of this particular problem is extraordinarily effective; there is not much room for improvement. If the goal was to focus on using the correct algorithms you would likely need a more complex (and time consuming) problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:54:41.557", "Id": "25256", "Score": "0", "body": "@Servy Brian had already suggested to use [Bucket sort](http://en.wikipedia.org/wiki/Bucket_sort) instead of standard quick sort. if it is acceptable according to input value conditions, it might be more effective then \"extraordinarily effective\" ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T17:00:40.097", "Id": "25257", "Score": "0", "body": "@ie. It would depend on a number of things, particularly the size of the data set. In any case, most classes usually discuss sorting algorithms specifically, and then when moving onto other algorithms there isn't, academically, a reason to use anything other than the language implemented sort. It's far more likely in my mind that the OP is just trying to optimize something that doesn't need to be optimized in the first place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T17:04:48.127", "Id": "25258", "Score": "0", "body": "@Servy thanks, but I was a student once and know how it works ;) anyway it is not reasonable to continue our discussion until OP clear some moments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T01:23:19.367", "Id": "25274", "Score": "2", "body": "At the risk of sounding like a broken record, wrap your `IDisposable` types (`StreamReader` and `StreamWriter`) in `using` blocks and get rid of the need to call `Close()` explicitly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T11:58:45.593", "Id": "25288", "Score": "1", "body": "Why is this marked C++?" } ]
[ { "body": "<p>First of all using LINQ method <code>Min</code> is not making this algorithm \\$O(n^2)\\$. If you want to avoid this call, you can calculate min \"in-place\":</p>\n\n<pre><code>//...\n\nvar min = int.MaxValue;\n\nfor (int k = 0; k &lt; intList.Count-1; k++)\n{\n min = Math.Min(min, intList[k + 1] - intList[k]);\n}\n\nsw.WriteLine(min); \n\n//...\n</code></pre>\n\n<p>Anyway, the most heavy operation here is <code>Sort</code>. It makes this algorithm \\$O(n*log n)\\$.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:29:02.180", "Id": "25259", "Score": "0", "body": "If you have a lot of numbers per list, it might be worth switching to an O(n) sorting algorithm (e.g., bucket sort)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:37:42.673", "Id": "25260", "Score": "1", "body": "@Brian agree! but we have no idea about input data restrictions, TS does not give us them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:44:38.293", "Id": "25261", "Score": "0", "body": "I was suggesting this to the OP as a means of fixing the bottleneck that you point out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T08:54:54.120", "Id": "25278", "Score": "0", "body": "Finding minimum in the same loop is definitely reasonable step. I wonder, how can we convert this loop to linq, and will there be any performance improvment ?\n for (int k = 0; k < intList.Count-1; k++)\n {\n int iDiff = intList[k + 1] - intList[k];\n diff.Add(iDiff); \n min = Math.Min(min, iDiff);\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T10:08:25.383", "Id": "25358", "Score": "0", "body": "@autrevo you will not get the performance improvement if you use LINQ instead of for-loop." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:17:04.913", "Id": "15556", "ParentId": "15555", "Score": "5" } }, { "body": "<p>For one thing, arrays are more efficient than Lists. If you know how big the collection is going to be you should opt for an array instead. This is the case for your diff collection.</p>\n\n<p>However, you can skip having a diff collection altogether and just keep track of the smallest diff so far:</p>\n\n<pre><code>int smallestDiff = int.MaxValue;\nfor(int k = 0;k &lt; intList.Count - 1; k++)\n smallestDiff = Math.Min(smallestDiff, intList[k + 1] - intList[k]);\n</code></pre>\n\n<p>You're also needlessly using a List for your intList collection:</p>\n\n<pre><code>int[] intList = sr.ReadLine().Split(new char[] { ' ' }, SplitOptions.None).Select(e =&gt; int.Parse(e)).ToArray();\nArray.Sort(intList);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:35:37.130", "Id": "25262", "Score": "5", "body": "The performance difference between using an array and a list is almost nothing. There is very, very little overhead involved in wrapping the array access with the List. Also note that you don't know the number of elements when creating the array, so the array creation will not be any more efficient than using a List." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:38:27.440", "Id": "25263", "Score": "0", "body": "\"Almost nothing\" is still something. Since this question was specifically about performance, I stand by my assertion. Are you suggesting that arrays have no use in the face of Lists? And where do I not know the number of elements? It's calculated at the time of collection creation in each case here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:43:56.377", "Id": "25264", "Score": "0", "body": "Why don't you actually measure the difference between the two. My guess is the randomness and noise of the processor will be greater than any performance difference between the two methods. If you want to optimize the code then look for real optimizations at an algorithmic level, rather than micro optimizations at the barely-even-measurable-by-a-computer level. As to knowing the number of elements, `ToArray` doesn't know how many items are in the `IEnumerable` it's passed, so it can't allocate an array of the correct size at first; it needs to create several successively larger arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:49:00.550", "Id": "25265", "Score": "0", "body": "Well at least you're not trying to defend your original comment. I agree that pre/micro optomizations aren't a great way to spend your effort, but you also shouldn't just willy nilly do things that you know will be less efficient. I also agree that, by far, the single largest bottleneck in this are the I/O operations. However, eliminating the I/O operations, I did benchmark the OP's algorithm vs. mine, and mine was 37% faster over 1000 iterations. Not exactly trivial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:54:10.583", "Id": "25266", "Score": "2", "body": "What about my original comment am I not defending? Using a List over an array isn't really \"less efficient\". From a performance point of view, in this context, they are effectively identical. It's pretty much entirely personal preference. My guess is most of your performance gains came from not performing a second pass over the data, which isn't really a micro-optimization (although probably isn't *needed* in this context)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:21:20.230", "Id": "15557", "ParentId": "15555", "Score": "2" } }, { "body": "<p>You're worrying about the wrong problems: there isn't a lot more performance to be squeezed out of your code, but you could make substantial improvements to readability.</p>\n\n<ul>\n<li><p><strong>Choose a better file format</strong><br>\nWhy are you encoding the number of lines to be read into the file itself? That seems like redundant information. Just read all the lines there are and use those. You are also redundantly encoding the number of numbers per line: <code>int N = int.Parse(sr.ReadLine());</code><br>\nYou aren't doing anything with the parsed value, which is an indication that it shouldn't be in the file to start with.</p></li>\n<li><p><strong>Make your code reusable</strong><br>\nWhy not define the algorithm for finding the smallest difference inside an extension method? This allows you to <strong>separate the concerns</strong> of I/O and your minimum difference finding logic.</p>\n\n<pre><code>public static int SmallestDifference(this IEnumerable&lt;int&gt; source)\n{\n var numbers = source as int[] ?? source.ToArray();\n Array.Sort(numbers);\n int difference = int.MaxValue;\n for (int i = 1; i &lt; numbers.Length; i++)\n {\n difference = Math.Min(difference, numbers[i] - numbers[i - 1]);\n }\n return difference;\n}\n</code></pre></li>\n<li><p><strong>Be expressive</strong><br>\nUsing the deferred execution streaming <code>File.ReadLines</code> method together with an expressive LINQ query, you can write code that reads fluently and makes sense rather than confusing the reader with details:</p>\n\n<pre><code>var minDifferences = from line in File.ReadLines(\"IN.in\")\n let numbers = from number in line.Split(' ')\n select int.Parse(number)\n select numbers.SmallestDifference().ToString();\nFile.WriteAllLines(\"OUT.out\", minDifferences);\n</code></pre></li>\n</ul>\n\n<p>Now here's a tiny surprise left for the end:</p>\n\n<blockquote>\n <p><strong>This solution consistently performs <em>at least</em> as well as your original code.</strong><br>\n <em>(On average, it's a couple of milliseconds faster per fifty thousand lines, but that's in the realm of microbenchmarking which should be avoided. Just trying to give you a rough idea.)</em><br>\n So stop worrying about performance; strive for clean code instead.</p>\n</blockquote>\n\n<p><em>EDIT</em>: I understand that you can't change the format (as per your comment), so I've added the code below to allow you to stick with your current file layout. The modification required is tiny: simply skip the first line, and only look for the smallest difference in lines that have more than one number.</p>\n\n<pre><code>var minDifferences = from line in File.ReadLines(\"IN.in\").Skip(1)\n let numbers = from number in line.Split(' ')\n select int.Parse(number)\n where numbers.Count() &gt; 1\n select numbers.SmallestDifference().ToString();\nFile.WriteAllLines(\"OUT.out\", minDifferences);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:41:58.550", "Id": "25324", "Score": "0", "body": "codesparkle, Last two points has been really helpful. But coming to first point unfortunately I can not play with file format and this has been created keeping in mind programmer may read file from C/C++ as well, where specifying, no. of items N, present on a particular line can simplify file i/o for the programmer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:46:35.660", "Id": "25325", "Score": "0", "body": "So deferred execution to read lines using LINQ, will not be make the code cleaner, as again I'll have to write if conditions inside LINQ to skip evaluating SmallestDifference() when reading T or N from file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T18:11:42.947", "Id": "25327", "Score": "0", "body": "@autrevo I understand your first comment, but I disagree with your second: As you can see, the change only adds a single line." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T14:16:14.173", "Id": "15573", "ParentId": "15555", "Score": "8" } }, { "body": "<p>As for using Linq, what you are looking for is a pairwise version of the Aggregate Extension method, which is not built in, but is not incredibly difficult to implement.</p>\n\n<p>As your question is about finding the minimum difference from a list of numbers, I'm not going to touch on the source of the list.</p>\n\n<p>I'm going to agree with codesparkle that you want reusability and readability. </p>\n\n<p>For the extension method:</p>\n\n<pre><code>public static class Extensions\n{\n public static TAccumulator PairwiseAggregate&lt;TAccumulator,TSource&gt;(this IEnumerable&lt;TSource&gt; source, TAccumulator seed, Func&lt;TAccumulator, TSource, TSource, TAccumulator&gt; aggregator ) \n {\n IEnumerator&lt;TSource&gt; e = source.GetEnumerator();\n e.MoveNext();\n TSource current = e.Current;\n while(e.MoveNext())\n {\n TSource next = e.Current;\n seed = aggregator(seed, current, next);\n current = next;\n }\n return seed;\n } \n}\n</code></pre>\n\n<p>Then the smallestDifference method:</p>\n\n<pre><code> public static int SmallestDifference(this IEnumerable&lt;int&gt; source)\n {\n return source.OrderBy(i =&gt; i).PairwiseAggregate(int.MaxValue, (seed, first, second) =&gt; Math.Min(seed, second-first));\n\n }\n</code></pre>\n\n<p><code>PairwiseAggregate</code> is \\$O(n)\\$. </p>\n\n<p>The \\$O(n log n)\\$ of SmallestDifference is ruled by the O(<a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">n log n</a>) of the OrderBy (<a href=\"https://stackoverflow.com/a/2792105/391656\">quick sort</a>).</p>\n\n<p>If you don't want to use the default Sorting Algorithm, then an extension can be written for that as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T19:28:11.113", "Id": "25331", "Score": "0", "body": "I am curious to know the difference between complexity of algorithm, thus advantage of using orderby. Please fill in above O() blank spaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T19:40:40.293", "Id": "25333", "Score": "0", "body": "Just to share results, for 3 test case of 5 integers in each list where as for loop implementation takes 55+-5 ms. LINQ implementation timing varies from 60+-50 ms. Memory usage in both implementation is almost 8.3MB" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T03:10:19.153", "Id": "25347", "Score": "1", "body": "@autrevo I used OrderBy over an in-place sort in my SmallestDifference method to not alter the original.\nI did not explicitly copy to an array as codesparkle did for simplicity and readability. What method are you using to get those numbers? And for very small arrays, any overhead in setting up a particular sorting algorithm is going to dominate the time it takes to sort and you are often better off sorting with some naive method. If you truely want to compare you are going to need much larger arrays." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T15:48:22.860", "Id": "15576", "ParentId": "15555", "Score": "4" } } ]
{ "AcceptedAnswerId": "15573", "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T16:12:22.530", "Id": "15555", "Score": "3", "Tags": [ "c#", "performance", "algorithm", "linq" ], "Title": "Finding the minimum difference in a list of numbers" }
15555
<p>In other languages, I prefer to arrange source files so that simpler and more widely useful concepts are introduced before implementation details, and I try where possible to make complex implementation details top-level functions so that I can separate them out and let the main function read like a high-level algorithm description.</p> <p>OCaml obviously has an interface/source distinction, but even with a sparse well-documented interface like</p> <pre><code>type t (** Blah blah blah *) val important_operator : t -&gt; t -&gt; t (** Blah blah blah *) </code></pre> <p>I've been tempted to do things like</p> <pre><code>let rec important_operator a b = let a', b' = foo a b in let a', b' = iterate_until_convergence (=) (fun (a, b) -&gt; bar (baz a b)) (a', b') in merge a', b' (* Implementation details *) and foo a b = ... and bar x = ... and baz a b = ... and merge a b = ... </code></pre> <p>Is this poor style? Does it affect the ability of IDE-users to navigate source files?</p>
[]
[ { "body": "<p>It's not idiomatic OCaml indeed.</p>\n\n<ol>\n<li>\"and\" is an effective way to say \"watch out for mutual recursion\".</li>\n<li>OCaml encourages you to use nested functions instead! As <a href=\"http://mirror.ocamlcore.org/ocaml-tutorial.org/the_structure_of_ocaml_programs.html\">The Structure of OCaml programs</a> says: \"Nested functions are, however, very useful and very heavily used in OCaml.\"</li>\n</ol>\n\n<p>You would write this code as follows:</p>\n\n<pre><code>let important_operator a b =\n let foo a b = ... in\n let bar x = ... in\n let baz a b = ... in\n let merge a b = ... in\n let a', b' = foo a b in\n let a', b' = iterate_until_convergence (=)\n (fun (a, b) -&gt; bar (baz a b))\n (a', b') in\n merge a', b'\n</code></pre>\n\n<p>Of course, you don't need to <em>only</em> use nested functions, you can also define <code>bar</code> or <code>baz</code> before defining <code>important_operator</code>. OCaml tends to only use functions that were defined \"earlier\", so using <code>and</code> for this is abusing the system.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T07:34:29.053", "Id": "15562", "ParentId": "15558", "Score": "5" } }, { "body": "<p>The code is incorrect as written. The declaration of important_operator\nneeds to start with \"let rec\" instead of just \"let\" in order to make the low-level functions visible when the main one is defined. And no, it's not idiomatic.</p>\n\n<p>Nested functions are common, but there's not much point in them when they don't share data. You still have to write them in bottom-up order in the body of the outer function unless you use the \"let rec\" trick.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T04:49:00.237", "Id": "25529", "Score": "0", "body": "I updated the code to include the missing `rec`. Thanks for pointing that out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T04:01:48.987", "Id": "15599", "ParentId": "15558", "Score": "3" } }, { "body": "<p>You would feel probably more at ease with a language like Haskell which follow that style. I think however that there is an camlp4 filter somewhere which provide a 'let .... where ...' syntactic construct allowing you to use that style. Still, while sometimes convenient, other comments above may have demonstrated how things are usually done in ocaml, and I think its usually efficient enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T11:52:30.120", "Id": "15612", "ParentId": "15558", "Score": "1" } } ]
{ "AcceptedAnswerId": "15562", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T23:46:27.463", "Id": "15558", "Score": "3", "Tags": [ "ocaml" ], "Title": "Is this use of (let ... and ...) in OCaml poor style?" }
15558
<p>The need is to get the possibility to differentiate between a Barcode-Scanner (which behaves like a keyboard) from a human pressing keys in a...let's say a Textbox (the use case would be all over everything, wherever I expect a barcode scanner).</p> <p>The basic idea was to create a buffer which holds the typed string (converted from the Keys-Enum, which I already have a function for) and "releases" it to a callback which then handles it. The problem with those scanners is that they behave like normal keyboards, there's no way to differentiate between them and the user except for the amount of time spend between keypresses. To minimize on-screen flickering, it is shoveled into a buffer instead of the control.</p> <p>Despite that I mostly need it to hold Strings, I wrote it as a generic method because I can imagine to stuff pretty much everything in there when I need it in a certain amount of time back.</p> <p>So, let's cut to the case:</p> <pre><code>public class TimeoutBuffer&lt;T&gt; { private Thread backgroundThread; private T buffer; private DateTime lastChange = DateTime.MaxValue; private Object syncObject = new Object(); public Action&lt;T&gt; Callback { get; set; } public int Timeout { get; set; } public TimeoutBuffer(int timeout) { this.Timeout = timeout; } /// &lt;summary&gt; /// Retrieves the value from the buffer (and clears the buffer). Resets the timer. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public T Get() { lock (syncObject) { T temp = buffer; buffer = default(T); lastChange = DateTime.MaxValue; return temp; } } /// &lt;summary&gt; /// Stores the value into the buffer. Resets the timer. /// &lt;/summary&gt; /// &lt;param name="buffer"&gt;&lt;/param&gt; public void Store(T buffer) { lock (syncObject) { this.buffer = buffer; lastChange = DateTime.Now; if (backgroundThread == null || backgroundThread.ThreadState == ThreadState.Stopped) { backgroundThread = new Thread(Check); backgroundThread.IsBackground = true; backgroundThread.Start(); } } } private void Check() { while (syncObject != null &amp;&amp; buffer != null) // Just to be sure...I think... { lock (syncObject) { if ((DateTime.Now - lastChange).TotalMilliseconds &gt;= Timeout) { if (Callback != null) { Callback.Invoke(Get()); } else { // Clear it anyway...their loss. buffer = default(T); lastChange = DateTime.MaxValue; } return; } } Thread.Sleep(1); } } } </code></pre> <p>What you're looking at here is a threaded-beast:</p> <ol> <li>It gets created</li> <li>Something gets stored in the buffer</li> <li>The background-thread is started</li> <li>[Optional]: Go back to 2</li> <li>The background-thread finds that it is time and calls the callback</li> <li>The buffer is cleared and the background-thread terminates</li> <li>Go back to 2</li> </ol> <p>The original design had a constantly running background-thread (with an <code>if(buffer != null)</code> right inside the lock), which I'm not very fond of...I'm not very fond of creating a thread every keypress, either.</p> <p>Example usage:</p> <pre><code>private TimeoutBuffer&lt;String&gt; buffer; // In the form constructor buffer = new TimeoutBuffer&lt;String&gt;(20); buffer.Callback = new Action&lt;String&gt;(buffer_TimedOut); // Keypress-Event buffer.Store((buffer.Get() ?? "") + keyData.ToString()); void buffer_TimedOut(String value) { if (this.InvokeRequired) { this.BeginInvoke(new Action&lt;String&gt;(buffer_TimedOut), new Object[] { value }); } else { if (value.Length == 13) { // Barcode! } else { // Typed text...append to Textbox f.e. } } } </code></pre> <p>What I feel odd about:</p> <ul> <li>The locking</li> <li>The handling of T</li> <li>The thread</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T03:13:40.220", "Id": "168217", "Score": "0", "body": "so i'm assuming this is a HID scanner. Is there a SDK that came with it? if there is you might have a better way of checking if the scanner was used. Another possibility is if you can use the SDK to fire the scanner. Our honeywell, and Newland scanners both had that possibility, and it worked reasonably well. as a tip for right now though, look into `Queue` and `Monitor` the Queue you can empty out and fill up as needed. The monitor will lock a background thread until you pulse (saving you lots of cycles and power)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T08:47:03.003", "Id": "168246", "Score": "0", "body": "@RobertSnyder Thanks for the suggestions, those scanners did not have an SDK, they simply reported as keyboard (quite cheap and simple scanners. Though, I'm not working there anymore, so I can't tell if the code was changed somehow or another solution was found." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T12:26:45.237", "Id": "168263", "Score": "0", "body": "Bummer. I just looked at the date stamp on this thread! WOW! 3 YEARS! hahaha. Well.. Do you want a review of your code becuse i'm fixing to throw it all in VS and see about improvments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T16:00:26.710", "Id": "168306", "Score": "0", "body": "Sure, I'd like to know what you think about (though, I'll have to read it again). Also don't worry, happened to me more often than I'd like to admit." } ]
[ { "body": "<p>Using DateTime to check the timespan is not as accurate or as good as just using the <code>System.Diagnostic.Stopwatch</code> class. Plus the stopwatch class has a <code>ElapsedMilliseconds</code> already. So you can switch out <code>LastChange</code> with a stopwatch, and everytime you set it to <code>DateTime.MaxValue</code> instead call <code>stopwatch.Reset()</code></p>\n\n<p>There are places when you use the Object version of an object instead of its primitive counterpart. I haven't seen much discussion on it lately, but most people would prefer to use the primitive counterpart unless using one of the static methods (such as <code>String.Format</code> and even then some people would argue...meh)</p>\n\n<p>What I don't get about your logic and your description is how this would differentiate between Barcode input and UserInput. I say that because if you follow your logic you check if your buffer is null (and actually since it is generic that isn't a good idea you should check if it is equal to <code>default(T)</code>, and even that isn't a great idea because you very well may want to pass in null/default value) after you check if it is null you call the callback. Essentially you are forcing your program to wait 20ms to return the data you want. Overall that isn't so bad, and yes, who has the ability to type 13 characters in 20ms??? but... wouldn't it be better to do a circular average of the time between when the buffer gets filled, and return that as part of your callback? You could then check that the AverageTimeBetweenKeyPresses is ???1ms??? and assume that it is a scanner. Meh.. I even see draw backs to that approach as well. </p>\n\n<p>One other thing I would prefer to see is the use of a Monitor pulse and wait system. You can create a timer that just does Monitor.Pulse on a object. In your background thread you would have your while loop but instead of continuasly looping you'd Lock the object to be Pulsed by Monitor. here is a good article that discuses it in length - <a href=\"https://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx\" rel=\"nofollow\">MSDN Article</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-05T18:59:50.617", "Id": "168531", "Score": "0", "body": "Thank you. Yes, the only difference between user input the scanner is the amount of time that it takes. As I said, I don't have access to that code anymore, but your suggestions sound very reasonable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-06T11:52:12.397", "Id": "168608", "Score": "0", "body": "@Bobby yeah, I had to do work with scanners and user input for a few years too. Fun work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-05T15:42:06.240", "Id": "92760", "ParentId": "15570", "Score": "2" } }, { "body": "<p>most of the barcode scanners enables the input of a prefix and a suffix to the data they will send to the computer.\nso, a solution in c# is to use the \"PreviewTextInput\" event to capture each letter as they go to the app (before they get to a specific control) in the form of strings.\nthen, if it is your prefixe, you take all the following letters as long as you don't reach your suffix and put them together in a string. for these letters, you can specify that they are \"handled\" so they won't make it trought to a textbox without your consentment.</p>\n\n<p>otherwise, if it is not your prefixe, you can assume it is a hand made entry and simply do nothing. the app will then handle it as usual...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-30T16:09:20.413", "Id": "291316", "Score": "0", "body": "Does this review the code in question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-30T22:01:55.537", "Id": "291388", "Score": "0", "body": "@Mast Well, I'd allow it because it \"reviews\" the basic ideas and assumptions of the code. Something which I have also done multiple times. But changing the scanner to have a prefix is/was not an option, as far as I remember." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-30T15:28:51.217", "Id": "153989", "ParentId": "15570", "Score": "0" } } ]
{ "AcceptedAnswerId": "92760", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T12:55:20.547", "Id": "15570", "Score": "3", "Tags": [ "c#" ], "Title": "Differentiate a Keyboard-Scanner from Keyboard: TimeoutBuffer" }
15570
<p>I've made a simple program that can calculate the area of various 2D shapes. I'd like your expereanced eyes to asses my code. Be as harsh as you want but please be <strong>specific</strong> and offer me ways in which I can improve my coding.</p> <pre><code>shape = ("triangle","square","rectangle","circle") # This is a tuple containing the string names of all the supported shapes so far. constants = (3.14) # An object containing the value of pi. I will add more constants in future and turn this into a tuple. start_up = input("Do you want to calculate a shape's area?: ") # Fairly self explainatory if start_up != "yes" or "no": # This is to prevent the program failing if the user answers the start_up question print("Sorry but I don't understand what your saying") # with an answer outside of the simple yes/no that it requires start_up = input("Do you want to calculate a shape's area?: ") # re-iterates the start up question. while start_up == "yes": # This is the condition that obviously contains the bulk of the program. target_shape = input("Choose your shape: ") # Once again, self explainatory. if target_shape == shape[0]: # Uses the shape tuple to bring forth the case for the first shape, the triangle. h = float(input("give the height: ")) # These Two lines allow the user to input the required values to calculate the area of the triangle. b = float(input("give the base length: ")) # They are using the float funtion to increase the accuracy of the answer. area_triangle = h * 1/2 * b # The formula we all learned in school. print("the area of the %s is %.2f" % (shape[0],area_triangle)) # This generates a format string which uses both the shape tuple and the area_triangle object # to display the answer. note the %.2f operand used to specify how many decimal places for the answer. if target_shape == shape[1]: # Square l = float(input("give the length: ")) area_square = l ** 2 print("the area of the %s is %.2f" % (shape[1],area_square)) if target_shape == shape[2]: # Rectangle l = float(input("give the length: ")) w = float(input("give the width: ")) area_rectangle = l * w print("the area of the %s is %.2f" % (shape[2],area_rectangle)) if target_shape == shape[3]: # Circle r = float(input("give the radius: ")) pi = constants # In this line we are calling forth the constants object to use the value of pi. area_circle = 2 * pi * r print("the area of the %s is %.2f" %(shape[3],area_circle)) start_up = input("Do you want to calculate another shape's area?: ") # This line allows the user the chance to do just what it says in the brackets. else: # This is to safegaurd against failure in the event of the user print("That shape's not in my database") # inputing a shape non-existant in the shape tuple. start_up = input("Do you want to calculate another shape's area?: ") if start_up == "no": #This is for when the user no longer wants to use the program. print("Goodbye then!") input("Press any key to close") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T16:55:24.913", "Id": "25319", "Score": "1", "body": "The `if start_up != (\"yes\" or \"no\"):` is still wrong; `('yes' or 'no')` is `'yes'`. You're looking for `not in` or 2 inequality tests." } ]
[ { "body": "<p>Since you're not using shape extensively I would get rid of that data structure all together. It would be easier to read inline then having to look to the margin for comments.</p>\n\n<p>For example:</p>\n\n<pre><code> if target_shape == 'square': \n l = float(input(\"give the length: \")) \n area_square = l ** 2\n print(\"the area of the square is %.2f\" % (area_square))\n</code></pre>\n\n<p>When comparing strings if you don't want to be strict you should normalize them before compare.</p>\n\n<p>For example:</p>\n\n<pre><code>'Square'.lower() == 'square'\n</code></pre>\n\n<p>so your code would become:</p>\n\n<pre><code> if target_shape.lower() == 'square': \n l = float(input(\"give the length: \")) \n area_square = l ** 2\n print(\"the area of the square is %.2f\" % (area_square))\n</code></pre>\n\n<p>You're not accounting for any errors. What if the user hits enter without giving a length?</p>\n\n<pre><code>ValueError: could not convert string to float\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T14:58:49.747", "Id": "15575", "ParentId": "15572", "Score": "4" } }, { "body": "<p>In addition to Justin's comments:</p>\n\n<p>You want to be more DRY. You have the line: </p>\n\n<pre><code>start_up = input(\"Do you want to calculate a shape's area?: \")\n</code></pre>\n\n<p>in your code 5 times (one of which is just completely broken because regardless of the answer it's asked again) when once would suffice:</p>\n\n<pre><code>while True:\n startup = None\n while startup not in (\"yes\", \"no\"):\n if startup is not None:\n print(\"Sorry but I don't understand what your saying\")\n startup = input(\"Do you want to calculate a shape's area?: \")\n if startup == \"no\":\n print(\"Goodbye then!\")\n input(\"Press enter to close\") # &lt;-- \"any key\" is a lie; will require return...\n break\n # do the rest of the stuff here.\n</code></pre>\n\n<p>The bit that prints the area is also repeated unnecessarily; call the results for each section \"area\" and use that; you already insert the correct shape name.</p>\n\n<p>Your indentation is also inconsistent; don't switch between 3 and 4 space indents; pick one.</p>\n\n<p>The <code>else</code> clause at the end also only applies to the last <code>if</code>; any shape but circle will be calculated <em>and</em> the user will be told the shape isn't in the \"database\". replace all the <code>if</code>s but the first with <code>elif</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:22:50.173", "Id": "25322", "Score": "0", "body": "Man I did say be as harsh as you like but you guys are tearing my code apart. I've also started to find more and more faults in my code my self. I'm thinking of completely rewriting this program from scratch because editing it is becoming a pain. Thanks again for the input!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:05:12.777", "Id": "25371", "Score": "0", "body": "I've used the above loop structure into my code with great success but I have to admit that I don't fully understand how it works. From my understanding \"None\" is some kind of placeholder object that doesn't have any properties and in this code is primarily used to prevent startup from continuously reiterating itself before I've even typed in an input. I don't understand the \"True\" object at all though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:46:42.940", "Id": "25374", "Score": "0", "body": "@RationalMystic: `while True:` simply creates an infinite loop which will run over and over until it reaches a `break`. It's used to avoid using the same code to set a loop control variable both before the loop and at its end." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:06:03.713", "Id": "15581", "ParentId": "15572", "Score": "4" } }, { "body": "<p>Your code is very good for a beginner! As you have noticed, there are always improvements to be done, so don't worry too much about this. Here's what I feel the other answers have missed:</p>\n\n<pre><code>constants = (3.14)\n</code></pre>\n\n<p>Use <code>math.pi</code> instead!</p>\n\n<pre><code>start_up = input(\"Do you want to calculate a shape's area?: \") # Fairly self explanatory.\n</code></pre>\n\n<p>I understand that those comments help you as a Python beginner, but they should be avoided in real code. As the <a href=\"http://www.python.org/dev/peps/pep-0008/#inline-comments\" rel=\"nofollow\">PEP 8 section on online comments</a> says, inline comments that state the obvious are distracting. You're also <a href=\"http://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow\">breaking the 79 characters rule</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T10:25:09.907", "Id": "25359", "Score": "1", "body": "As noted in the comments above, `if start_up != \"yes\" or \"no\"` will *not* work, because that's not how `or` works. For similar reasons, `start_up != (\"yes\" or \"no\")` won't work either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T10:31:16.030", "Id": "25360", "Score": "1", "body": "To be specific: The \"or\" will return the first truthy value, so `(\"yes\" or \"no\")` is simply \"yes\". In the other case, if `start_up = 'yes'`, then `start_up != \"yes\" or \"no\"` will be `False or \"no\"`, which is \"no\", which is a nonempty string and thus truthy, so the branch will still be taken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T11:05:41.613", "Id": "25361", "Score": "0", "body": "Thanks! For some reason, I was assuming there was the same magic than in 1 < x < 5. I removed the wrong bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:00:30.440", "Id": "25370", "Score": "0", "body": "Thank you. I've started rewritting the code and I think I've managed to iron out most of my syntaxial mistakes. There however is one thing which I can't seem to implement. How can you safeguard against someone inputting either nothing or an invalid value when it asks you to provide the values to carry out the area equations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T15:16:41.033", "Id": "25376", "Score": "1", "body": "You can catch the `ValueError` exception that `float()` is throws when the argument is empty or invalid, and ask for a value again. It's not really important, and if you want to do it, consider writing a function which you'll be able to call whenever you need this. eg. `get_float(\"I just need the length of a side: \")`. The function will be able to loop until the user gives an useful value. By the way, you should upvote questions that helped you (not only mine!), and decide on which question helped you the most. When you've rewritten your code, you can ask another question if you want to." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:58:39.423", "Id": "15610", "ParentId": "15572", "Score": "1" } } ]
{ "AcceptedAnswerId": "15581", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T13:48:37.777", "Id": "15572", "Score": "5", "Tags": [ "python", "beginner", "computational-geometry" ], "Title": "Calculating the area of various 2D shapes" }
15572
<p>I just figured out <a href="http://projecteuler.net/problem=12" rel="nofollow">Project Euler problem #12</a>. This the first one I've done in Python, so I'm putting my code out there to hopefully get some constructive criticism. </p> <p>If anyone is interested, would you mind looking over my solution and letting me know how I can improve on it, either through optimization or style?</p> <p>Thanks!</p> <pre><code>from math import* def divisorCount(n): nDivisors = 0 integerSqrt = int(sqrt(n)) if sqrt(n) == integerSqrt: nDivisors += 1 for i in range(1, integerSqrt - 1): if n % i == 0: nDivisors += 2 return nDivisors def main(): divisors = 0 incrementTriangle = 1 triangleNumber = 1 while True: divisors = divisorCount(triangleNumber) if divisors &lt; 500: incrementTriangle += 1 triangleNumber = triangleNumber + incrementTriangle elif divisors &gt;= 500: print "The first triangle number w/ 500+ divisors is", triangleNumber return 0 main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:02:03.143", "Id": "25305", "Score": "0", "body": "I quick run through the [`pep8`](http://pypi.python.org/pypi/pep8) program should point out any style improvements. [PEP-0008](http://www.python.org/dev/peps/pep-0008/) is the \"style guide\" for Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:04:51.760", "Id": "25306", "Score": "0", "body": "I think they're looking for feedback on the semantics and code design, not syntax. But yeah, this type of question is for codereview." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:05:17.573", "Id": "25307", "Score": "1", "body": ".. but before you take it over to `codereview`, you might want to test your `divisorCount` function a bit more.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:05:54.643", "Id": "25308", "Score": "1", "body": "a hint for you,take `24`, it's factors are `1,2,3,4,6,8,12,24`, i.e total `8`, and `24` can be represented in terms of it's prime factors as `24=2^3 * 3^1` , so the total number of factors are given by `(3+1)*(1+1)` i,e 8, where `3,4` are powers of the prime factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:08:42.097", "Id": "25309", "Score": "0", "body": "related: [Project Euler #12 in python](http://stackoverflow.com/q/571488/4279). See [the code that is linked](http://gist.github.com/68515) in the comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:44:23.640", "Id": "25310", "Score": "0", "body": "Thanks for the help everyone... will move over to codereview from now on. However, DSM- I'd love to know what's wrong with divisorCount... right now it's giving me the correct answer, but you must see something that can break." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:52:04.443", "Id": "25311", "Score": "0", "body": "@tjr226: try `divisorCount(2)` or `divisorCount(6)`, for example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T12:19:42.143", "Id": "25312", "Score": "0", "body": "@tjr226 Try `for i in range(1,10): print i`." } ]
[ { "body": "<pre><code>from math import*\n</code></pre>\n\n<p>Missing space?</p>\n\n<pre><code> for i in range(1, integerSqrt - 1):\n if n % i == 0:\n nDivisors += 2\n</code></pre>\n\n<p>I'm not saying it's better here, but you can achieve a lot with list comprehensions. For example, <code>2 * len([i for i in range(1, integerSqrt -1) if n % i == 0]</code> would be equivalent. And less readable, so don't use it here!</p>\n\n<pre><code> incrementTriangle += 1\n triangleNumber = triangleNumber + incrementTriangle\n</code></pre>\n\n<p>Be consistent with increments (<code>triangleCount += incrementTriangle</code>)</p>\n\n<pre><code> elif divisors &gt;= 500:\n print \"The first triangle number w/ 500+ divisors is\", triangleNumber\n return 0\n</code></pre>\n\n<p>Using returns or breaks in a loop is usually a bad idea if it can be avoided. It means that you need to scan the whole loop to see where the loop could end earlier than expected. In this case, what's preventing you from doing <code>while divisors &lt; 500</code>. As an added bonus, you would stop mixing output and actual logic.</p>\n\n<pre><code>print \"The first triangle number w/ 500+ divisors is\", triangleNumber\n</code></pre>\n\n<p>Use the <code>print()</code> function provided in Python 2.6. It will make your code Python 3 compatible and.. more pythonic. If you want more flexibly, also consider using format strings. This would give:</p>\n\n<pre><code>print(\"The first triangle number w/ 500+ divisors is %d\" % triangleNumber)\n</code></pre>\n\n<p>So, you have a main function and call it like this:</p>\n\n<pre><code>main()\n</code></pre>\n\n<p>You should instead use the <a href=\"https://codereview.meta.stackexchange.com/a/493/11227\"><code>__main__</code></a> idiom, as it will allow your file to be imported (for example to use divisorsCount).</p>\n\n<p>And last, but not least, you should really follow the PEP 8, as others said in the comments. Consistency is really important to make your code more readable!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:44:47.490", "Id": "15608", "ParentId": "15577", "Score": "0" } }, { "body": "<p>Cygal's answer covers style, but you also asked for optimisation so here goes.</p>\n\n<p>Your <code>divisorCount</code> can be a lot more efficient. The number of divisors can be calculated cia the following formula:</p>\n\n<pre><code>d(n) = prod((k + 1)) for a^k in the prime factorisation of n\n</code></pre>\n\n<p>For example, consider the prime factorisation of 360:</p>\n\n<pre><code>360 = 2^3 * 3^2 * 5^1\n</code></pre>\n\n<p>The exponents in the prime factorisation are 3, 2, and 1, so:</p>\n\n<pre><code>d(360) = (3 + 1) * (2 + 1) * (1 + 1)\n = 24\n</code></pre>\n\n<p>Note that 360 indeed has 24 factors: <code>[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360]</code>.</p>\n\n<p>Combine this with the fact that a number <code>n</code> can have at most one prime factor greater than <code>sqrt(n)</code>, and you get something like the following:</p>\n\n<pre><code># Calculates the number of positive integer divisors of n, including 1 and n\ndef d(n):\n divisors = 1\n stop = math.sqrt(n)\n\n primes = # Calculate prime numbers up to sqrt(n) in ascending order\n for prime in primes:\n if prime &gt; stop:\n break\n\n exponent = 0 \n while n % prime == 0:\n n /= prime\n exponent += 1\n\n if a != 0:\n divisors *= (a + 1)\n stop = max(stop, n)\n\n # At this point, n will either be 1 or the only prime factor of n &gt; root\n # in the later case, we have (n^1) as a factor so multiply divisors by (1 + 1)\n if n &gt; root:\n divisors *= 2\n\n return divisors\n</code></pre>\n\n<p>Since you are going to be calling this function many times consecutively, it makes sense to pre-calculate a list of primes and pass it to the divisor function rather than calculating it each time. One simple and efficient method is the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthanes</a> which can be implemented very easily:</p>\n\n<pre><code># Compute all prime numbers less than k using the Sieve of Eratosthanes\ndef sieve(k):\n s = set(range(3, k, 2))\n s.add(2)\n\n for i in range(3, k, 2):\n if i in s:\n for j in range(i ** 2, k, i * 2):\n s.discard(j)\n\n return sorted(s)\n</code></pre>\n\n<p>This function can also fairly easily be modified to compute a range in pieces, e.g. to calculate the primes to 1M and then to 2M without recalculating the first 1M.</p>\n\n<p>Putting this together your main loop will then look something like this:</p>\n\n<pre><code>primes = [2, 3, 5]\ntriangularNumber = 0\nincrement = 1\nmaxDivisors = 0\nwhile maxDivisors &lt; 500:\n triangularNumber += increment\n increment += 1\n\n if math.sqrt(triangularNumber) &gt; primes[-1]:\n primes = sieve(primes, primes[-1] * 4)\n\n divisors = d(triangularNumber, primes)\n maxDivisors = max(divisors, maxDivisors)\n\nprint triangularNumber, \"has\", maxDivisors, \"divisors.\"\n</code></pre>\n\n<p>As far as performance goes, here are the triangular numbers with the largest number of divisors and the times (in seconds) taken to get there (py1 is your code, py2 is using primes, c++ is the same as py2 but in c++):</p>\n\n<pre><code>TriNum Value d(n) py1 py2 c++\n 12375 76576500 576 0 0 0\n 14399 103672800 648 0 0 0\n 21735 236215980 768 1 0 0\n 41040 842161320 1024 4 0 0\n 78624 3090906000 1280 128 13 9\n 98175 4819214400 1344 350 23 15\n123200 7589181600 1512 702 38 23\n126224 7966312200 1536 749 41 24\n165375 13674528000 1728 - 74 42\n201824 20366564400 1920 - 107 61\n313599 49172323200 2304 - 633 153\n395199 78091322400 2880 - 790 259\n453375 102774672000 3072 - 910 358\n</code></pre>\n\n<p>There are probably other optimisations you can make based on the properties of triangular numbers, but I don't know the math. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T12:31:50.220", "Id": "15671", "ParentId": "15577", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T03:57:28.800", "Id": "15577", "Score": "2", "Tags": [ "python", "project-euler" ], "Title": "Python Code Review - Project Euler #12" }
15577
<p>Goal:</p> <ol> <li>Extract all Appendix Titles</li> <li>If Appendix Title is Answer Key call custom solutions template</li> <li>If Not Answer Key call default appendix template</li> </ol> <p>XML:</p> <pre><code>&lt;appendix&gt; &lt;title&gt;Appendix A&lt;/title&gt; &lt;section&gt;data&lt;/section&gt; &lt;/appendix&gt; &lt;appendix&gt; &lt;title&gt;Answer Key&lt;/title&gt; &lt;section&gt;data&lt;/section&gt; &lt;/appendix&gt; </code></pre> <p>XSLT:</p> <pre><code>&lt;xsl:template match="appendix/title"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="self::node()[text()='Answer Key']"&gt; &lt;div class="answer-key"&gt; &lt;xsl:call-template name="solutions"/&gt; &lt;/div&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:apply-templates select="appendix"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; </code></pre> <p>This template works correctly; however I am interested in gaining some ground when it comes to writing solid XSL templates. Particularly the XPATH expressions. There seem to be various ways to achieve the same results when using XPath. Is the following XPath expression best?</p> <pre><code>test="self::node()[text()='Answer Key']" </code></pre>
[]
[ { "body": "<p>I don't see how that <code>&lt;xsl:otherwise&gt;</code> would ever do anything based on your sample xml. The template matches on <code>appendix/title</code> so your context would be the title element. Applying templates to appendix children of title would be a no-op. I think something like this would be closer to what you want</p>\n\n<pre><code>&lt;xsl:template match=\"appendix[title = 'Answer Key']\"&gt;\n &lt;div class=\"answer-key\"&gt;\n &lt;xsl:call-template name=\"solutions\"/&gt;\n &lt;/div&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"appendix\"&gt;\n &lt;!-- Do something standard --&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Here, the first template has a higher implicit priority than the second template so it will match on the \"Answer Keys\". If the predicate evaluates to false, the second template will then match. Note though the code above will behave differently if the called template \"solutions\" depends on having a title element context node as it would in your code sample. In this sample the context would be the appendix element, which seems like possibly a more appropriate point in the document hierarchy to be performing whatever operations you intend to do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:34:22.213", "Id": "29177", "Score": "0", "body": "Thanks. Your code example was nice and clean and your explanation made me revisit this code and see that logically it was not sound, as you had mentioned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T05:44:45.530", "Id": "18279", "ParentId": "15582", "Score": "4" } }, { "body": "<blockquote>\n <p>Is the following XPath expression best? <code>\n test=\"self::node()[text()='Answer Key']\"</code></p>\n</blockquote>\n\n<p>You can simplify the XPath expression to <code>.='Answer Key'</code></p>\n\n<ul>\n<li><code>self::node()</code> is the context node, <a href=\"http://www.w3.org/TR/xpath/#path-abbrev\" rel=\"nofollow\">which can be abbreviated to <code>.</code></a></li>\n<li>the <a href=\"http://www.w3.org/TR/xpath/#booleans\" rel=\"nofollow\">equality of a node with a string is the boolean resulting from the comparison of the string-value with the string</a></li>\n<li>the <a href=\"http://www.w3.org/TR/xpath/#element-nodes\" rel=\"nofollow\">string-value of an element is the concatenation of all text nodes within</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:36:18.323", "Id": "29178", "Score": "0", "body": "Thanks for the XPath pointers and explanations your expression is much more clean and neat." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T10:10:47.483", "Id": "18281", "ParentId": "15582", "Score": "2" } } ]
{ "AcceptedAnswerId": "18279", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:21:21.780", "Id": "15582", "Score": "3", "Tags": [ "optimization", "beginner", "xml", "xslt" ], "Title": "Appendix answer key template" }
15582
<p>I'm in the process of doing some mapping of POCOs via IDataReader. I'd love to hear thoughts on the approach and if they are any good ways to improve what I have done. </p> <pre><code>public class Code { public int Id { get; set; } public string Type { get; set; } public string Value { get; set; } public string Description { get; set; } } public class CodeRepository : GenericRepository { public CodeRepository(IDbConnection connection) : base(connection) { } public IEnumerable&lt;Code&gt; GetCodesForDemographics() { var sql = @" Select CODE_TYPE, CODE, DESCRIPTION From Codes Where CODE_TYPE In ('language', 'lang_service', 'transfer', 'admit_type', 'Value', 'admit_src', 'state', 'county', 'ethnic', 'race', 'exempt_unit_code', 'alt_care_type_code')"; using (var manager = new DbCommandManager(this.Connection, sql)) { using (var reader = manager.GetReader()) return DbAutoMapper.MapReaderToList&lt;Code, CodeFactory&gt;(reader); } } public class CodeFactory : IFactory&lt;Code&gt; { public Code CreateTFromReader(IDataReader reader) { try { var code = new Code(); code.Type = (reader["CODE_TYPE"] as string) ?? String.Empty; code.Description = (reader["DESCRIPTION"] as string) ?? String.Empty; code.Value = (reader["CODE"] as string) ?? String.Empty; return code; } catch (Exception) { throw new Exception("Error creating Code objects from reader."); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T20:53:05.193", "Id": "25449", "Score": "0", "body": "I agree with the posted answer except you should only catch specific exceptions or at best ApplicationException. Wrapping a System exception such as insufficient permissions or an OutOfMemoryException as an inner exception obscures what is really going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T08:27:11.083", "Id": "62873", "Score": "0", "body": "How would you handle collections as mentioned in http://stackoverflow.com/questions/20699004/grouping-a-collection?" } ]
[ { "body": "<p>Most of it looks good. That is until I get to your catch statement:</p>\n\n<pre><code>catch (Exception)\n{\n throw new Exception(\"Error creating Code objects from reader.\");\n}\n</code></pre>\n\n<p>really does not explain why you are having. I would suggest either creating your own exception i.e. InvalidCodeDataException, or throwing an ApplicationException. Either of these should take the original exception as an inner exception:</p>\n\n<pre><code>catch (Exception ex)\n{\n throw new InvalidCodeDataException(\"Error creating Code objects from reader.\", ex);\n}\n</code></pre>\n\n<p>This way, you do not lose what cause the original exception.</p>\n\n<p>Two suggestions:</p>\n\n<ol>\n<li>don't use the this. statement, I find it overly clutters code up if\nyou are using standard naming conventions, which you are.</li>\n<li><p>Use the object initializer format when creating objects:</p>\n\n<pre><code>return new Code\n {\n Type = (reader[\"CODE_TYPE\"] as string) ?? String.Empty,\n Description = (reader[\"DESCRIPTION\"] as string) ?? String.Empty,\n Value = (reader[\"CODE\"] as string) ?? String.Empty\n }\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T18:59:11.977", "Id": "25329", "Score": "0", "body": "Good feedback. I appreciate it. Always trying to learn. : )" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:56:24.417", "Id": "15584", "ParentId": "15583", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T17:24:36.897", "Id": "15583", "Score": "3", "Tags": [ "c#", "asp.net" ], "Title": "Using C# generics and factory classes to map IDataReader to POCO?" }
15583
<p>One of the things I wanted to do was make it impossible to forget to initialise or forget to cleanup WSA. Often the network examples will return as soon as an error occurs (say an socket didn't bind) this means you have to remember to add <code>WSACleanup()</code> before each return and I don't like that.</p> <p>I also wanted to make it impossible to forget to close opened sockets (I believe this is the RAII idiom?)</p> <p>A quick rundown of the class structure:</p> <ul> <li><code>Socket</code> (abstract base class)</li> <li><code>ListeningSocket</code> (binds to a port and listens)</li> <li><code>AcceptingSocket</code> (accepts connections)</li> <li><code>TransmittingSocket</code> (connects to a remote machine to send data).</li> </ul> <p><strong>Socket.h:</strong></p> <pre><code>#ifndef SOCKET_H #define SOCKET_H #include &lt;iostream&gt; #include &lt;WinSock2.h&gt; class Socket { public: virtual ~Socket() = 0; static bool winsockInitialized(); bool isValid(); SOCKET getSocket(); protected: Socket(SOCKET socket); SOCKET socket_; sockaddr_in socketAddress_; private: Socket(); class WsaData { public: WsaData() { std::cout &lt;&lt; "Initializing WSA." &lt;&lt; std::endl; initSuccess_ = WSAStartup(MAKEWORD(2,2), &amp;wsaData_); if(initSuccess_ != 0) { std::cout &lt;&lt; "Error: " &lt;&lt; WSAGetLastError() &lt;&lt; " occured." &lt;&lt; std::endl; WSACleanup(); } } ~WsaData() { std::cout &lt;&lt; "Cleaning up WSA." &lt;&lt; std::endl; WSACleanup(); } bool isInitialized() { return !initSuccess_; } private: WSADATA wsaData_; int initSuccess_; }; static WsaData wsaData_; }; #endif </code></pre> <p><strong>Socket.cpp:</strong></p> <pre><code>#include "Socket.h" #include &lt;iostream&gt; Socket::WsaData Socket::wsaData_; // Pure virtual destructor Socket::~Socket() { if(socket_ != INVALID_SOCKET) { closesocket(socket_); } } // Accessor for WSA initialization status bool Socket::winsockInitialized() { return wsaData_.isInitialized(); } // Implicit conversion from Socket to underlying SOCKET bool Socket::isValid() { return socket_ != INVALID_SOCKET; } // Accessort for SOCKET member SOCKET Socket::getSocket() { return socket_; } // Custom constructor Socket::Socket(SOCKET socket) : socket_(socket) { } // Default constructor (hidden) Socket::Socket() { } </code></pre> <p><strong>ListeningSocket.h:</strong></p> <pre><code>#ifndef LISTENING_SOCKET_H #define LISTENING_SOCKET_H #include "Socket.h" class ListeningSocket : public Socket { public: ListeningSocket(int port); ~ListeningSocket(); bool bindAndListen(); private: ListeningSocket(); const int port_; }; #endif </code></pre> <p><strong>ListeningSocket.cpp:</strong></p> <pre><code>#include "ListeningSocket.h" // Custom Constructor ListeningSocket::ListeningSocket(int port): port_(port), Socket(socket(AF_INET, SOCK_STREAM, 0)) { socketAddress_.sin_port = htons(port); socketAddress_.sin_addr.s_addr = INADDR_ANY; socketAddress_.sin_family = AF_INET; } // Destructor ListeningSocket::~ListeningSocket() { std::cout &lt;&lt; "Listening socket closing." &lt;&lt; std::endl; } // Binds the socket to and listens on the specified port bool ListeningSocket::bindAndListen() { int bindError = bind(socket_, (sockaddr*)&amp;socketAddress_, sizeof(socketAddress_)); if(bindError == SOCKET_ERROR) { std::cout &lt;&lt; "Error: " &lt;&lt; WSAGetLastError() &lt;&lt; " while binding socket to port " &lt;&lt; port_ &lt;&lt; "." &lt;&lt; std::endl; return false; } std::cout &lt;&lt; "Socket bound on port " &lt;&lt; port_ &lt;&lt; "." &lt;&lt; std::endl; int listeningError = listen(socket_, SOMAXCONN); if(listeningError == SOCKET_ERROR) { std::cout &lt;&lt; "Error: " &lt;&lt; WSAGetLastError() &lt;&lt; " while trying to listen on port " &lt;&lt; port_ &lt;&lt; "." &lt;&lt; std::endl; return false; } std::cout &lt;&lt; "Socket listening on port " &lt;&lt; port_ &lt;&lt; "." &lt;&lt; std::endl; return true; } // Default Constructor (hidden) ListeningSocket::ListeningSocket(): port_(0), Socket(socket(AF_INET, SOCK_STREAM, 0)) { } </code></pre> <p><strong>AcceptingSocket.h:</strong></p> <pre><code>#ifndef ACCEPTING_SOCKET_H #define ACCEPTING_SOCKET_H #include "Socket.h" class AcceptingSocket: public Socket { public: AcceptingSocket(Socket&amp; socket); ~AcceptingSocket(); private: AcceptingSocket(); }; #endif </code></pre> <p><strong>AcceptingSocket.cpp:</strong></p> <pre><code>#include "AcceptingSocket.h" // Custom constructor AcceptingSocket::AcceptingSocket(Socket&amp; socket) : Socket(accept(socket.getSocket(), NULL, NULL)) { } // Destructor AcceptingSocket::~AcceptingSocket() { std::cout &lt;&lt; "Accepting socket closing." &lt;&lt; std::endl; } // Default constructor (hidden) AcceptingSocket::AcceptingSocket() : Socket(socket(AF_INET, SOCK_STREAM, 0)) { } </code></pre> <p><strong>TransmittingSocket.h:</strong></p> <pre><code>#ifndef TRANSMITTING_SOCKET_H #define TRANSMITTING_SOCKET_H #include "Socket.h" #include &lt;string&gt; class TransmittingSocket: public Socket { public: TransmittingSocket(std::string ip, int port); ~TransmittingSocket(); bool connectTo(); private: TransmittingSocket(); const std::string ip_; const int port_; }; #endif </code></pre> <p><strong>TransmittingSocket.cpp:</strong></p> <pre><code>#include "TransmittingSocket.h" #include &lt;iostream&gt; // Custom constructor TransmittingSocket::TransmittingSocket(std::string ip, int port): ip_(ip), port_(port), Socket(socket(AF_INET, SOCK_STREAM, 0)) { socketAddress_.sin_port = htons(port_); socketAddress_.sin_addr.s_addr = inet_addr(ip_.c_str()); socketAddress_.sin_family = AF_INET; } // Destructor TransmittingSocket::~TransmittingSocket() { std::cout &lt;&lt; "Transmitting socket closing." &lt;&lt; std::endl; } // Connects the socket to specified ip/port bool TransmittingSocket::connectTo() { int connectionError = connect(socket_, (sockaddr*)&amp;socketAddress_, sizeof(socketAddress_)); if(connectionError == INVALID_SOCKET) return false; else return true; } // Default constructor (hidden) TransmittingSocket::TransmittingSocket(): ip_(""), port_(0), Socket(socket(AF_INET, SOCK_STREAM, 0)) { } </code></pre> <p>And finally, here is a really simple client/server example using these classes:</p> <p><strong>Client:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "TransmittingSocket.h" int main(int argc, char* argv[]) { if(!Socket::winsockInitialized()) return -1; TransmittingSocket transmitSocket("127.0.0.1", 100); if(!transmitSocket.isValid()) return -1; if(!transmitSocket.connectTo()) return -1; std::string text = "Some sentence with whitespace in it."; int bytesSent = send(transmitSocket.getSocket(), &amp;text[0], sizeof(char)*text.size(), 0); std::cout &lt;&lt; "Sent " &lt;&lt; bytesSent &lt;&lt; " bytes." &lt;&lt; std::endl; system("pause"); return 0; } </code></pre> <p><strong>Server:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;WinSock2.h&gt; #include "ListeningSocket.h" #include "AcceptingSocket.h" int main(int argc, char* argv[]) { if(!Socket::winsockInitialized()) return -1; ListeningSocket listeningSocket(100); if(!listeningSocket.bindAndListen()) return -1; AcceptingSocket clientSocket(listeningSocket); if(!clientSocket.isValid()) return -1; std::vector&lt;char&gt; buffer = std::vector&lt;char&gt;(1024, 0); int recvBytes = recv(clientSocket.getSocket(), &amp;buffer[0], sizeof(char)*buffer.size(), 0); std::string text = std::string(&amp;buffer[0], &amp;buffer[recvBytes]); std::cout &lt;&lt; text &lt;&lt; std::endl; buffer.clear(); std::ofstream outfile("C:\\Users\\Borgleader\\Documents\\Visual Studio 2010\\Projects\\Hex\\Debug\\text.txt",'w'); if (outfile.is_open()) { outfile &lt;&lt; text; outfile.close(); } else { std::cout &lt;&lt; "Error opening file"; } std::cout &lt;&lt; "File was sucessfully received.\n"; system("pause"); return 0; } </code></pre>
[]
[ { "body": "<p>Without looking at the details, it seems that you have too many classes. A base class for all sockets that takes care of freeing the resources is fine. A listen socket that waits for incoming connections is fine, too.</p>\n\n<p>But I don't get the need for AcceptingSocket and TransmittingSocket, because once you've got a connection it doesn't really matter where it came from, you can use it to read and/or write data.</p>\n\n<p>So my suggestion is to use one ConnectionSocket that can be made to either accept an incoming connection from a listen socket, or actively open a connection to somewhere, depending on which constructor is used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T09:25:05.787", "Id": "15866", "ParentId": "15589", "Score": "3" } } ]
{ "AcceptedAnswerId": "15866", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T20:39:50.400", "Id": "15589", "Score": "5", "Tags": [ "c++", "classes", "networking", "socket" ], "Title": "Simple Socket class hierarchy" }
15589
<p>I've just coded a hex to integer converter in C and want my code criticized. I did not cover switch statements so I know that can be improved. I am also planning to truncate "0x" in the beginning of the input if the user enters that.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;math.h&gt; #define MAXCHAR 100 int htoi(char hexArray[], int srraySize); int main(void){ int userInput; int i = 0; char hexArray[MAXCHAR]; while((userInput = getchar()) != EOF){ if(userInput &gt;= '0' &amp;&amp; userInput &lt;= '9'){ hexArray[i] = userInput; ++i; } if((userInput &gt;= 'a' &amp;&amp; userInput &lt;= 'f') || (userInput &gt;= 'A' &amp;&amp; userInput &lt;= 'F')){ hexArray[i] = userInput; ++i; } } hexArray[++i] = '\0'; int ans = htoi(hexArray, i); printf("%d\n", ans); return 0; } int htoi(char hexArray[], int arraySize) typedef enum{ a = 10, b, c, d, e, f } hexValues; int intArray[MAXCHAR] = { 0 }; int i, j; int finalAns = 0; for(i = 0; i &lt; arraySize; ++i){ if(hexArray[i] &gt;= 'A' &amp;&amp; hexArray[i] &lt;= 'F'){ hexArray[i] = (char)tolower((int)hexArray[i]); } } for(i = 0; i &lt; arraySize; ++i){ if(hexArray[i] &gt;= '0' &amp;&amp; hexArray[i] &lt;= '9'){ intArray[i] = hexArray[i]; } else if(hexArray[i] &gt;= 'a' &amp;&amp; hexArray[i] &lt;= 'f'){ if(hexArray[i] == 'a'){ intArray[i] = a; } else if(hexArray[i] == 'b'){ intArray[i] = b; } else if(hexArray[i] == 'c'){ intArray[i] = c; } else if(hexArray[i] == 'd'){ intArray[i] = d; } else if(hexArray[i] == 'e'){ intArray[i] = e; } else if(hexArray[i] == 'f'){ intArray[i] = f; } } } j = arraySize-2; for(i = 0; i &lt; arraySize-1; ++i){ printf("J = %d\n", j); printf("Initial Value: %d\n", intArray[i]); intArray[i] = (intArray[i] * (pow(16, j))); printf("Processed Value: %d\n", intArray[i]); finalAns = finalAns + intArray[i]; --j; } return finalAns; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:31:10.597", "Id": "25405", "Score": "0", "body": "If you're going to include ctype.h, you might as well use isxdigit, or at least isdigit in the places where you do the '0' and '9' comparisons." } ]
[ { "body": "<ul>\n<li><p>Your <code>hexArray</code> has a static size of <code>MAXCHAR</code> but you never check if you didn't exceed this size when reading input. Consider what would happen if someone enters <code>MAXCHAR+1</code> characters at input.</p></li>\n<li><p>When you set last character in your <code>hexArray</code> to <code>'\\0'</code>, you do it on wrong position. In your while loop, you increment <code>i</code> after each write to <code>hexArray</code> so at the end <code>i</code> is an index of next free element. And you should write <code>'\\0'</code> here. But you use pre-increment (<code>++i</code>) so you write this <code>'\\0'</code> on next place.</p></li>\n<li><p>This '\\0' is not really needed at all since you pass array size as an argument to <code>htoi</code> anyway. But you pass wrong size as I already mentioned.</p></li>\n<li><p>You are using <code>tolower</code> function in your <code>htoi</code> function but you could do this already when getting input. This saves you one loop over all values. It means that htoi will be less general since it will only work with low capital letters, though.</p></li>\n<li><p>You could also use <code>tolower</code> function on all the input characters since if <code>tolower</code> gets argument that is not uppercase letter, it will return unchanged value. This would save you some ifs in your code for the price of overhead of running a function (and doing ifs in it since it has to do this).</p></li>\n<li><p><code>if(hexArray[i] &gt;= '0' &amp;&amp; hexArray[i] &lt;= '9') intArray[i] = hexArray[i];</code> is wrong. You set intArray[i] value to '0' (which is numerical value 48) instead of 0. So you should use <code>intArray[i]=hexArray[i]-'0';</code> instead.</p></li>\n<li><p>Your big if-elseif block for a-f characters can be much simpler. All ASCII letters have consecutive numbers so to convert 'a' to 10, 'b' to 11 etc you can use:</p>\n\n<blockquote>\n<pre><code> else if(hexArray[i] &gt;= 'a' &amp;&amp; hexArray[i] &lt;= 'f') {\n intArray[i] = hexArray[i] - 'a' + 10;\n }\n</code></pre>\n</blockquote>\n\n<p>This saves you a lot of ifs and you can even remove your <code>enum</code>.</p></li>\n<li><p>The whole <code>intArray</code> array is not really needed at all since you could do your computations inside of the loop in which you create it. This way you can have only one loop inside of your <code>htoi</code>.</p></li>\n<li><p>Yyou are using <code>int</code> type to hold computed integer. So you can really only convert <code>sizeof(int)*2</code> characters long hex value inside, and your <code>MAXCHAR=100</code>.</p></li>\n<li><p>You can eliminate the need of <code>pow</code> function if you will start your calculations from the end of <code>intArray</code> array. You can store powers of 16 in some variable and just multiply it by 16 (or shift left 4 bits) in each iteration.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T08:49:57.890", "Id": "15605", "ParentId": "15604", "Score": "5" } } ]
{ "AcceptedAnswerId": "15605", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T08:08:11.760", "Id": "15604", "Score": "2", "Tags": [ "c", "converting" ], "Title": "Hex to integer converter" }
15604
<p>I'm writing a monadic parser instance that transforms Data.Map.Map's:</p> <pre><code>instance (Ord a, FromEDN a, FromEDN b) =&gt; FromEDN (M.Map a b) where parseEDNv (E.Map m) = mapMmap parseEDNv parseEDN m parseEDNv v = typeMismatch "Map" v </code></pre> <p>Data.Map doesn't provide it's own mapM version like Data.Vector does, so i had to write it from scratch:</p> <pre><code>mapMmap :: (Ord a2, Monad m) =&gt; (a1 -&gt; m a2) -&gt; (b1 -&gt; m b2) -&gt; M.Map a1 b1 -&gt; m (M.Map a2 b2) mapMmap kf vf m = do let pairsIn = M.assocs m pairsOut &lt;- mapM fs pairsIn return $! M.fromList pairsOut where fs (k, v) = do newK &lt;- kf k newV &lt;- vf v return (newK, newV) </code></pre> <p>It works, but very verbose. How to trim into a more succinct INLINEable version without too much black^W monadic magic?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:51:53.413", "Id": "74212", "Score": "0", "body": "Have you considered traverseWithKey?" } ]
[ { "body": "<p>There is <code>keys</code> library which implements </p>\n\n<pre><code>mapWithKeyM_ :: (FoldableWithKey t, Monad m) =&gt; (Key t -&gt; a -&gt; m b) -&gt; t a -&gt; m ()\n</code></pre>\n\n<p>and related functions for <code>Data.Map</code>.</p>\n\n<p>There is also <code>Data.Traversable.mapM</code>, but it only maps over values. Mapping over both keys and values is not a <code>mapM</code> operation because there is <code>Ord</code> constraint.</p>\n\n<p>If you still consider implementing your function yourself, it can be written like this:</p>\n\n<pre><code>import qualified Data.Map as M\nimport Control.Monad\n\nmapMmap :: (Ord a2, Monad m) =&gt; \n (a1 -&gt; m a2) -&gt; (b1 -&gt; m b2) -&gt; M.Map a1 b1 -&gt; m (M.Map a2 b2)\nmapMmap kf vf = liftM M.fromList . mapM fs . M.assocs \n where\n fs (k, v) = liftM2 (,) (kf k) (vf v)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T16:40:29.987", "Id": "25386", "Score": "0", "body": "Ah, liftM2, that's how it is used!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:44:56.387", "Id": "15609", "ParentId": "15606", "Score": "5" } } ]
{ "AcceptedAnswerId": "15609", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T08:53:34.937", "Id": "15606", "Score": "3", "Tags": [ "haskell" ], "Title": "mapM for both keys and values of Data.Map" }
15606
<p>Consider the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; struct test { int j; test&amp; operator&gt;&gt;(int &amp; i) { i = ++j%26; return *this; } operator bool() { return j%26; } }; int main () { test t; int i; while (t &gt;&gt; i) { cout &lt;&lt; i &lt;&lt; endl; } } </code></pre> <p>I have implemented a simple class that can be used in a similar fashion as for example <code>std::cin</code>. I implemented it this way, because I wanted to have an object that hides some IO-operations from me and provide a nice interface to yield the data items each one-at-a-time.</p> <p>Although it does want I want, I know there is at least one issue with the implementation:</p> <ul> <li>ignorance w.r.t. the <a href="http://en.wikibooks.org/wiki/More_C++_Idioms/Safe_bool" rel="nofollow">safe bool idiom</a></li> </ul> <p>Are there probably any more?</p>
[]
[ { "body": "<p>For simple 10 lines 10 programs you can get away with this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Anything bigger and it starts to be a pest more than a help. Thus it best not to get into the habit of using it. Anyway it is simpler even in this case just to prefex cout with std:: (that is why standard is named std to make it short and easy to use).</p>\n\n<p>You don't initialize the value of j in your class.</p>\n\n<pre><code>int j;\n</code></pre>\n\n<p>Thus any usage is undefined behavior.</p>\n\n<p>You have two options:</p>\n\n<ol>\n<li>Add a constructor that initaizes j</li>\n<li>Always force zero-initialization of your class.</li>\n</ol>\n\n<p>In anything but this trivial program I would go with (1) and add a constructor. But just to show zero initialization the alternative is:</p>\n\n<pre><code> Test t = Test(); // The () brackets at the end of Test() force zero initialization;\n</code></pre>\n\n<p>Note: The equivalent for new is</p>\n\n<pre><code> Test* t = new Test(); // force zero-initialization (when no constructor)\n Test* t = new Test; // Use default-initialization (un-initialized)\n</code></pre>\n\n<p>Note 2: Normally you would think you could do this:</p>\n\n<pre><code> Test t(); // Unfortunately this is a forward declaration of a function.\n</code></pre>\n\n<p>Note 3: But you can get around the problems of (2) by using extra braces.\n As pointed out last time I tried to answer a question like this.</p>\n\n<pre><code> Test t(()); // Unfortunately this confuses people and maintainers have been\n // known to try and take out the extra braces. With mixed results.\n // This is why I still prefer method 1\n\n Test t = Test(); // This may look like there is an extra copy.\n // But every compiler implements the optimization to do construction\n // in place.\n // Thus I prefer method 1 (ie this method)\n</code></pre>\n\n<p>Described here: <a href=\"https://stackoverflow.com/questions/5914422/proper-way-to-initialize-c-structs/5914697#5914697\">https://stackoverflow.com/questions/5914422/proper-way-to-initialize-c-structs/5914697#5914697</a></p>\n\n<p>For such a simple class I don't think you need to worry about the safe bool idium. This just protects your class from being used in places where arithmatic would be done:</p>\n\n<pre><code> Test t;\n int x = 5 + t; // Here we get conversion to bool\n // which is then converted to int (0 or 1)\n // The safe bool idium would protect you from this:\n</code></pre>\n\n<p>To use it do this:</p>\n\n<pre><code> operator bool() { return j%26; }\n\n // Remove the above and replace with\n\n operator void*() {return j%26 ? &amp;j /* or this the value is not important as long as it is not NULL */ : NULL; } \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:41:02.557", "Id": "25397", "Score": "0", "body": "Thanks for your notes! Actually you're right, plus, in this case typing `std::` two times would've been less than one time `using ...`. Also no discussion about the value of `j` being indeterminate, but I can't believe this condition turns using this value undefined behavior (couldn't find a statement prohibiting this in C++03)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:51:16.840", "Id": "25400", "Score": "0", "body": "if I overload the `operator void*` this would add other unexpected behavior depending on the return value, wouldn't it? (e.g., `(test*)(void*)t`) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T22:58:52.553", "Id": "25427", "Score": "0", "body": "The value of j is indeterminate. That is fine up to the point where you try and use it (read it). At this point the behavior becomes undefined. http://stackoverflow.com/q/4279264/14065" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T23:08:19.450", "Id": "25428", "Score": "0", "body": "@moooeeeep: Yes if you want to explicitly cast something to void* then you may do so (though since you are using C++ you should probably do so with a C++ cast not a C cast). But casting it back is undefined behavior (since it was not a pointer to start with). And there are no implicit cast back (you must do it explicitly). The only legal thing you can do with a void pointer is check if it is NULL. (Note: You may cast it back to its original pointer type if you know the pointer type it originated from (but that information is not provided here))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T23:10:45.233", "Id": "25430", "Score": "0", "body": "There is no arithmetic on void pointers. They are not implicitly converted to anything else. The only valid operation is comparison against NULL or itself (any other test is invalid (and probably undefined behavior))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T23:42:28.690", "Id": "25438", "Score": "1", "body": "Admitadel. The link you provide is the fale-safe mechanism that is perfect (and should be used in real code). The one I did is a trick that works fine and good for code reviews like this (where you don't want to plow through 100 lines of code just to explain something trivial when it is not really needed). This article: http://www.artima.com/cppsource/safeboolP.html explains all the techniques; plus the advantages and disadvantages of each." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T16:30:46.850", "Id": "15624", "ParentId": "15613", "Score": "2" } } ]
{ "AcceptedAnswerId": "15624", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T12:44:04.517", "Id": "15613", "Score": "2", "Tags": [ "c++" ], "Title": "Custom stream-like classes" }
15613
<p>I have the following:</p> <pre><code> public class ContentsController : BaseController { private IContentService _content; private IPageService pageService; private IReferenceService _reference; private ISequenceService seqService; public ContentsController( IContentService contentService, IPageService pageService, IReferenceService referenceService, ISequenceService sequenceService) { this._content = contentService; this.pageService = pageService; this._reference = referenceService; this.seqService = sequenceService; } </code></pre> <p>Note that it's completely mixed up with different naming standards. </p> <p>Is there anything recommended for the naming of services that are used by my controller?</p>
[]
[ { "body": "<p>IMHO, member variables should begin with an underscore and be descriptive</p>\n\n<p>This is fine</p>\n\n<pre><code>private IContentService _content;\n</code></pre>\n\n<p>This is better</p>\n\n<pre><code>private IContentService _contentService;\n</code></pre>\n\n<p>BTW, using '<code>this.</code>' in your constructor is redundant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:42:54.923", "Id": "25368", "Score": "0", "body": "Using underscores is just one naming style and one that is not universally accepted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:59:57.073", "Id": "25369", "Score": "1", "body": "@svick You are correct, edited my answer. I do like this convention best as it visually differentiates a member variable, and I can have the exact same name for my parameters (without the underscore), making the code very readable. Again, just MHO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T00:29:54.973", "Id": "25525", "Score": "0", "body": "@Forty-Two underscores or no underscores, `this.` or none these are a matter of style. One that makes minimal difference. What is more important is that there is a **consistent** style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T00:38:37.240", "Id": "25526", "Score": "0", "body": "@james yes, huskey's answer above has already pointed that out, but thanks for your input." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:13:24.997", "Id": "15615", "ParentId": "15614", "Score": "4" } }, { "body": "<p>I don't think it matters as long as you are consistent. I personally prefer: _{servicename}Service format. ex. _referenceService</p>\n\n<pre><code>public class ContentsController : BaseController {\n private IContentService _contentService;\n private IPageService _pageService;\n private IReferenceService _referenceService;\n private ISequenceService _seqService;\n\n public ContentsController(\n IContentService contentService,\n IPageService pageService,\n IReferenceService referenceService,\n ISequenceService sequenceService) {\n this._contentService = contentService;\n this._pageService = pageService;\n this._referenceService = referenceService;\n this._seqService = sequenceService;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:11:37.787", "Id": "25412", "Score": "0", "body": "yes, I use this same standard for naming. I would also remove the this. reference as another standard (albiet off topic from OP question)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:14:54.430", "Id": "15616", "ParentId": "15614", "Score": "5" } }, { "body": "<p>I'd recommend to use <a href=\"http://msdn.microsoft.com/en-us/library/ms229002%28v=vs.100%29.aspx\" rel=\"nofollow\">Microsoft's Guidelines for Names</a>, so you can check your code with tools like FxCop.</p>\n\n<p>Here are guidelines for your case:</p>\n\n<ul>\n<li><p>Do not use underscores, hyphens, or any other nonalphanumeric characters (<code>contentService</code> instead of <code>_contentService</code>)</p></li>\n<li><p>Spell out all words used in a field name. Use abbreviations only if developers generally understand them. Do not use uppercase letters for field names (<code>sequenceService</code> instead of <code>_seqService</code>)</p></li>\n<li><p>Do use camel casing in parameter names (you did)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T13:35:41.977", "Id": "15681", "ParentId": "15614", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:01:02.493", "Id": "15614", "Score": "3", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "What standard should I use for the naming of my MVC controller services?" }
15614
<p>I have the following code:</p> <pre><code> public string GetRefStat(string pk) { return RefStat[pk.Substring(2, 2)]; } private readonly Dictionary&lt;String, int&gt; RefStat = new Dictionary&lt;string, int&gt; { {"00", REF.MenuType, } // Menu {"01", REF.ReferenceStatus,} // Article {"02", REF.ReferenceStatus,} // Favorites List {"03", REF.ReferenceStatus,} // Content Block {"06", REF.ReferenceStatus } // Topic }; </code></pre> <p>GetRefStat and the dictionary are always used together. </p> <p>Is there a way I could simplify and combine these? I was wondering if I could put the information in a static class and then have a get method that returned the information I needed. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:10:19.677", "Id": "25372", "Score": "2", "body": "Your code won't compile. The dictionary contains `int`s, but the method returns `string`s. Also, some commas in your definition of the dictionary are misplaced (they should outside the braces, not inside)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:06:31.850", "Id": "25409", "Score": "0", "body": "Does REF.ReferenceStatus have to be a integer or could it be an enumeration instead? If it could be an enumeration you could do something with attributes and enum parsing to get what you want?" } ]
[ { "body": "<p>Your code is short, readable and efficient, so I don't think it needs much improvement. And I don't think adding a static class would give you anything (although changing the field and the method to <code>static</code> could make sense).</p>\n\n<p>Another way to write your code would be to use <code>switch</code>, but I'm not sure whether it's more readable (although it could be slightly more efficient):</p>\n\n<pre><code>public string GetRefStat(string pk)\n{\n switch (pk.Substring(2, 2))\n {\n case \"00\":\n return REF.MenuType;\n case \"01\":\n case \"02\":\n case \"03\":\n case \"06\":\n return REF.ReferenceStatus;\n default:\n throw new InvalidOperationException();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:08:04.143", "Id": "25410", "Score": "0", "body": "Although people say to stay away from switches where you can, I actually think I prefer this given that so much of the cases use the same REF. It also lets you control the exception thrown with even a possible explicit message." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:17:56.217", "Id": "15619", "ParentId": "15617", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:42:02.587", "Id": "15617", "Score": "2", "Tags": [ "c#" ], "Title": "Simplifying dictionary of constant values" }
15617
<p>I am trying to figure out a better way to attach the icons based on the class id.</p> <p><a href="http://jsfiddle.net/fLZKc/2/" rel="nofollow">Here</a> is the link.</p> <pre><code>var bubble = "M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z", heart = "M24.132,7.971c-2.203-2.205-5.916-2.098-8.25,0.235L15.5,8.588l-0.382-0.382c-2.334-2.333-6.047-2.44-8.25-0.235c-2.204,2.203-2.098,5.916,0.235,8.249l8.396,8.396l8.396-8.396C26.229,13.887,26.336,10.174,24.132,7.971z", documentation = "M26.679,7.858c-0.176-0.138-0.404-0.17-0.606-0.083l-9.66,4.183c-0.42,0.183-0.946,0.271-1.486,0.271c-0.753,0.002-1.532-0.173-2.075-0.412c-0.194-0.083-0.356-0.176-0.471-0.259c0.042-0.021,0.09-0.042,0.146-0.064l8.786-3.804l1.31,0.561V6.612c0-0.244-0.106-0.475-0.283-0.612c-0.176-0.138-0.406-0.17-0.605-0.083l-9.66,4.183c-0.298,0.121-0.554,0.268-0.771,0.483c-0.213,0.208-0.397,0.552-0.394,0.934c0,0.01,0.003,0.027,0.003,0.027v14.73c0,0.006-0.002,0.012-0.002,0.019c0,0.005,0.002,0.007,0.002,0.012v0.015h0.002c0.021,0.515,0.28,0.843,0.528,1.075c0.781,0.688,2.091,1.073,3.484,1.093c0.66,0,1.33-0.1,1.951-0.366l9.662-4.184c0.255-0.109,0.422-0.383,0.422-0.692V8.471C26.961,8.227,26.855,7.996,26.679,7.858zM20.553,5.058c-0.017-0.221-0.108-0.429-0.271-0.556c-0.176-0.138-0.404-0.17-0.606-0.083l-9.66,4.183C9.596,8.784,9.069,8.873,8.53,8.873C7.777,8.874,6.998,8.699,6.455,8.46C6.262,8.378,6.099,8.285,5.984,8.202C6.026,8.181,6.075,8.16,6.13,8.138l8.787-3.804l1.309,0.561V3.256c0-0.244-0.106-0.475-0.283-0.612c-0.176-0.138-0.407-0.17-0.606-0.083l-9.66,4.183C5.379,6.864,5.124,7.011,4.907,7.227C4.693,7.435,4.51,7.779,4.513,8.161c0,0.011,0.003,0.027,0.003,0.027v14.73c0,0.006-0.001,0.013-0.001,0.019c0,0.005,0.001,0.007,0.001,0.012v0.016h0.002c0.021,0.515,0.28,0.843,0.528,1.075c0.781,0.688,2.091,1.072,3.485,1.092c0.376,0,0.754-0.045,1.126-0.122V11.544c-0.01-0.7,0.27-1.372,0.762-1.856c0.319-0.315,0.708-0.564,1.19-0.756L20.553,5.058z"; $('.chat').each(function(i) { chat = Raphael($(this)[0], 40, 40); var shape = chat.path(bubble).attr({ "fill": "#333" }); shape.hover(function() { this.attr({ "fill": "#fff" }); }, function() { this.attr({ "fill": "#333" }); }); }) $('.heart').each(function(i) { paper = Raphael($(this)[0], 40, 40) var shape = paper.path(heart).attr({ "fill": "#333" }); shape.hover(function() { this.attr({ "fill": "#fff" }); }, function() { this.attr({ "fill": "#333" }); }); }) $('.documentation').each(function(i) { paper = Raphael($(this)[0], 40, 40) var shape = paper.path(documentation).attr({ "fill": "#333" }); shape.hover(function() { this.attr({ "fill": "#fff" }); }, function() { this.attr({ "fill": "#333" }); }); })​ </code></pre> <p>HTML page:</p> <pre><code>&lt;div id="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#" class="chat"&gt;&lt;span&gt;Chat&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="heart"&gt;&lt;span&gt;Heart&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="documentation"&gt;&lt;span&gt;Documentation&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>​ What I am thinking is that for <code>id=menu</code>, loop every <code>li</code> element and create an icon based on the class. Is this correct or is there a better way to do this?</p>
[]
[ { "body": "<p>You could also create a utility function that takes a class selector and a path and then does the needful. Furthermore you repeat very much <code>{\"fill\": \"#fff\"}</code>, that should be well named variable.</p>\n\n<p>Given these 2 observations, you could write the code this way:</p>\n\n<pre><code>var bubble = \"M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z\",\n heart = \"M24.132,7.971c-2.203-2.205-5.916-2.098-8.25,0.235L15.5,8.588l-0.382-0.382c-2.334-2.333-6.047-2.44-8.25-0.235c-2.204,2.203-2.098,5.916,0.235,8.249l8.396,8.396l8.396-8.396C26.229,13.887,26.336,10.174,24.132,7.971z\",\n documentation = \"M26.679,7.858c-0.176-0.138-0.404-0.17-0.606-0.083l-9.66,4.183c-0.42,0.183-0.946,0.271-1.486,0.271c-0.753,0.002-1.532-0.173-2.075-0.412c-0.194-0.083-0.356-0.176-0.471-0.259c0.042-0.021,0.09-0.042,0.146-0.064l8.786-3.804l1.31,0.561V6.612c0-0.244-0.106-0.475-0.283-0.612c-0.176-0.138-0.406-0.17-0.605-0.083l-9.66,4.183c-0.298,0.121-0.554,0.268-0.771,0.483c-0.213,0.208-0.397,0.552-0.394,0.934c0,0.01,0.003,0.027,0.003,0.027v14.73c0,0.006-0.002,0.012-0.002,0.019c0,0.005,0.002,0.007,0.002,0.012v0.015h0.002c0.021,0.515,0.28,0.843,0.528,1.075c0.781,0.688,2.091,1.073,3.484,1.093c0.66,0,1.33-0.1,1.951-0.366l9.662-4.184c0.255-0.109,0.422-0.383,0.422-0.692V8.471C26.961,8.227,26.855,7.996,26.679,7.858zM20.553,5.058c-0.017-0.221-0.108-0.429-0.271-0.556c-0.176-0.138-0.404-0.17-0.606-0.083l-9.66,4.183C9.596,8.784,9.069,8.873,8.53,8.873C7.777,8.874,6.998,8.699,6.455,8.46C6.262,8.378,6.099,8.285,5.984,8.202C6.026,8.181,6.075,8.16,6.13,8.138l8.787-3.804l1.309,0.561V3.256c0-0.244-0.106-0.475-0.283-0.612c-0.176-0.138-0.407-0.17-0.606-0.083l-9.66,4.183C5.379,6.864,5.124,7.011,4.907,7.227C4.693,7.435,4.51,7.779,4.513,8.161c0,0.011,0.003,0.027,0.003,0.027v14.73c0,0.006-0.001,0.013-0.001,0.019c0,0.005,0.001,0.007,0.001,0.012v0.016h0.002c0.021,0.515,0.28,0.843,0.528,1.075c0.781,0.688,2.091,1.072,3.485,1.092c0.376,0,0.754-0.045,1.126-0.122V11.544c-0.01-0.7,0.27-1.372,0.762-1.856c0.319-0.315,0.708-0.564,1.19-0.756L20.553,5.058z\";\n\n\nattachIcon( '.heart' , heart );\nattachIcon( '.bubble' , heart );\nattachIcon( '.documentation' , documentation );\n\nfunction attachIcon( selector , path )\n{\n var normalAttributes = { fill: '#333' },\n hoverAttributes = { fill: '#fff' },\n\n $(selector).each(function(i) {\n var icon = Raphael($(this)[0], 40, 40),\n shape = icon.path(path).attr( normalAttributes );\n shape.hover(function() {\n this.attr( hoverAttributes );\n }, function() {\n this.attr( normalAttributes );\n });\n })\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T13:28:14.260", "Id": "44570", "ParentId": "15620", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:24:44.187", "Id": "15620", "Score": "3", "Tags": [ "javascript", "jquery", "raphael.js" ], "Title": "Generate Raphael icons on a page" }
15620
<p>I am making a query in mysql to import users in our marketing system and need for this a lot of data like for example :</p> <ul> <li>Date of last order</li> <li>Date of last cheque created</li> <li>...</li> </ul> <p>This are all left joins where I just want the last result with conditions. For the moment I do just a select for this field but I don't know if this is the best option. Here you have the query that I'm currently usign: </p> <pre><code>select u.first_name, u.last_name, u.email, u.birthdate, u.id, u.sex, c.name, u.facebook_id, u.created_at, u.last_active, u.referrer_id, IF(wants_email = 0, (select created_at from wants_email_logs where value = 0 and u.id = user_id order by id desc limit 1), NULL ) as DATEUNJOIN, (select max(o.created_at) from orders o where o.user_id = u.id and o.state in ('paid','processing', 'shipped', 'completed')) as DATE_LAST_ORDER, (select max(c.created_at) from cheques c where c.user_id = u.id and c.spent = 0) as cheque_date from users u left join countries c on u.country_id = c.id ; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:28:16.497", "Id": "62840", "Score": "0", "body": "Add this:\norder by left_table.required_field limit 1" } ]
[ { "body": "<p>Can you use temp tables? I think that's generally the best idea... using a lot of subqueries can get nasty real quick. Here's my version:</p>\n\n<p>(I'm not able to test it so use it at your own risk. Also if you use temp tables, you'll still probably want to define your datatypes in the CREATE TABLE sections)</p>\n\n<pre><code>DROP TABLE IF EXISTS temp_date_unjoin;\n\nCREATE TABLE temp_date_unjoin\nSELECT\n user_id,\n MAX(created_at) AS date_unjoin\nFROM wants_email_logs\nWHERE value = 0\nGROUP BY user_id;\n\nDROP TABLE IF EXISTS temp_date_last_order;\n\nCREATE TABLE temp_date_last_order\nSELECT\n user_id,\n MAX(created_at) AS date_last_order\nFROM orders o\nWHERE state IN ('paid', 'processing', 'shipped', 'completed')\nGROUP BY user_id;\n\nDROP TABLE IF EXISTS temp_cheque_date;\n\nCREATE TABLE temp_cheque_date\nSELECT\n user_id,\n MAX(created_at) AS cheque_date\nFROM cheques\nGROUP BY user_id;\n\nSELECT \n u.first_name, \n u.last_name, \n u.email, \n u.birthdate, \n u.id, \n u.sex, \n c.name, \n u.facebook_id, \n u.created_at, \n u.last_active, \n u.referrer_id,\n du.date_unjoin,\n lo.date_last_order,\n cd.cheque_date \nFROM \n users u\n LEFT JOIN temp_date_unjoin du\n ON du.user_id = u.id\n LEFT JOIN temp_date_last_order lo\n ON lo.user_id = u.id\n LEFT JOIN temp_cheque_date cd\n ON cd.user_id = u.id\n LEFT JOIN countries c \n ON u.country_id = c.id \n;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T06:38:54.243", "Id": "23607", "ParentId": "15622", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T15:30:39.670", "Id": "15622", "Score": "1", "Tags": [ "performance", "mysql", "sql" ], "Title": "Mysql left joins last row" }
15622
<p>I have the following function to confirm if a directory contains files:</p> <pre><code>/** * Check if the directory is empty * * Function to ascertain if the specified directory contains files. * Comparing to two, because parent and current are present inside * the returned array. Only 3+ denotes files on the target dir. * * @param str $dir Directory to scan. * @param bol $count Whether the return value should be the count result * * @return bool|int Integer with count, TRUE or FALSE for check */ public function directory_with_contents($dir, $count = false) { try { if (!is_readable($dir)) return NULL; if ($count) { return count(scandir($dir)); } else { return (count(scandir($dir)) == 2) ? false : true; } } catch(PDOException $e) { throw new userman_Exception("&lt;h1&gt;ups!&lt;/h1&gt;&lt;br/&gt;". $e-&gt;getMessage()); } } </code></pre> <p>The functions works well, but it is being used with directories that contain over one million files inside. The <code>scandir()</code> takes his time to return the results, and in turn this function with a large amount of files becomes slow.</p> <p>Is any optimization that can be done as to have this function performing any faster when dealing with directories that have a large number of files?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:20:18.087", "Id": "25404", "Score": "0", "body": "As a side note, depending on the file system, a million files in a directory might be a bad idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:48:07.857", "Id": "25406", "Score": "0", "body": "@Corbin It's a Debian based server and the files are temporarily stored inside the directory while the process queue takes care of them!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:10:42.343", "Id": "25411", "Score": "0", "body": "Depending on the file system and what order your processing files in, you may be better of breaking the files into separate directories. I can't remember for ext3 and ext4, but for ext2, a directory is essentially a linked list. In other words, to open a file requires iterating over all of the file nodes ordered before it. If you're not using ext2 though, I believe you should be fine. Just thought it might be worth mentioning :)." } ]
[ { "body": "<p>Why is there a catch for a PDOException? Also, why are you masking it with another exception? That doesn't make much sense. How is the final catch block supposed to know what it's actually catching?</p>\n\n<hr>\n\n<p>Anyway, you need to use a lower-level method than scandir. You could use a <a href=\"http://us2.php.net/directoryiterator\" rel=\"nofollow\"><code>DirectoryIterator</code></a> instance, but I would probably just go with <a href=\"http://php.net/opendir\" rel=\"nofollow\"><code>opendir</code></a>.</p>\n\n<p>For example:</p>\n\n<pre><code> function is_directory_empty($path)\n {\n $dir = opendir($path);\n while (($f = readdir($dir)) !== false) {\n if ($f !== '.' &amp;&amp; $f !== '..') {\n return true;\n }\n }\n return false;\n }\n</code></pre>\n\n<p>The important part here is that the loop bails upon finding the first file. Additionally, <code>.</code> and <code>..</code> will usually be the first two entries, so it should only have to run 3 times at maximum (though that is implementation specific, I believe, since the dots are not required to be first -- if the dots aren't first, it would run at most twice for an empty directory and once for a non-empty one).</p>\n\n<p>It's worth noting that this function has terrible error handling. In particular, there's no way to know if the directory is empty or the <code>opendir</code> call failed. You could throw an exception:</p>\n\n<pre><code>if ($dir === false) {\n //I chose UnexpectedValueException because it's what DirectoryIterator throws\n throw new UnexpectedValueException(\"Unable to open directory: {$path}\");\n}\n</code></pre>\n\n<p>Another way would be to take a more procedural, C-esque approach:</p>\n\n<pre><code>define('DIR_EMPTY', 0);\ndefine('DIR_NOT_EMPTY', 1);\ndefine('DIR_ERROR_OPEN', 2);\n\nfunction is_directory_empty($path)\n{\n $dir = opendir($path);\n if ($dir === false) {\n return DIR_ERROR_OPEN;\n }\n while (($f = readdir($dir)) !== false) {\n if ($f !== '.' &amp;&amp; $f !== '..') {\n return DIR_EMPTY;\n }\n }\n return DIR_NOT_EMPTY;\n}\n\n$dir_empty = is_directory_empty(\"/some/path\");\nif ($dir_empty == DIR_EMPTY) {\n echo 'Empty!';\n} else if ($dir_empty == DIR_NOT_EMPTY) {\n echo 'Not empty!';\n} else {\n //(Should arguably be an else-if to check the last condition)\n echo 'Error opening path';\n}\n</code></pre>\n\n<hr>\n\n<p>I would consider having your file-counting functionality, and your is-empty functionality be two separate functions. There's a definite relation possible between them (is_empty(x) === !file_count(x)), but they're really different functionalities.</p>\n\n<p>I'm not much a fan of a boolean flag changing the functionality of a function. It's an anti-pattern in my opinion (and quite a few other people's opinion, though I'm too lazy to find links at the moment).</p>\n\n<p>Instead, consider:</p>\n\n<pre><code>function count_directory_files($path)\n{\n ...\n}\n\nfunction is_directory_empty($path)\n{\n ...\n}\n</code></pre>\n\n<p>The names clearly express the functionality. There's no need for a magical flag.</p>\n\n<p><code>directory_with_contents</code> is a bit badly named to begin with, but if I had to guess what it does, I would guess that it returns true if a directory is empty, and false otherwise. The counting-functionality is hidden.</p>\n\n<p>(On the bad naming note: what does <code>directory_with_contents</code> mean? Consider if you hadn't named it. Could you look at that and know, with certainty, what it does? I would imagine not. In my opinion, functions that return booleans should typically be named as a binary predicate: <code>is_&lt;object&gt;_&lt;property&gt;</code>, <code>can_&lt;object&gt;_&lt;property&gt;</code>, etc. [I'm actually a fan of camelCase, like, isDirectoryEmpty, but that's a superfluous opinion to this post :p.])</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:17:38.903", "Id": "25415", "Score": "0", "body": "Thank you for the extensive analysis on the function. I'm also a fan of camelCase, but this function is to be supported by a underscore fan :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:17:56.577", "Id": "25416", "Score": "0", "body": "Yes, the name is poor and so the methodology implemented I see, that's why I like coming here and read your reviews! ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:13:59.013", "Id": "15628", "ParentId": "15623", "Score": "3" } } ]
{ "AcceptedAnswerId": "15628", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T16:12:27.987", "Id": "15623", "Score": "2", "Tags": [ "performance", "file-system", "php5" ], "Title": "Checking if a directory is empty when having over a million files inside" }
15623
<p>I've done some tinkering about with Knockout in search for a better solution on how to bind select lists (dropdowns). I came up with a extender in combination with a binding.</p> <p>Extender:</p> <pre><code>ko.extenders.selectList = function (target, params) { var result = ko.computed({ read: target, write: function (newValue) { if (newValue) { target(newValue); } else { target(undefined); } } }); //add some sub-observables result.options = $.map(params.options, function (v, k) { return { val: k, txt: v }; }); result.caption = params.caption; function getInitialEnableValue(){ if(params.hasOwnProperty('enable')){ if($.isFunction(params.enable)){ return params.enable(); } return params.enable; } return true; } var isEnabled = ko.observable(getInitialEnableValue()); result.enable = ko.computed({ read: function(){ return isEnabled(); }, write: function(newValue){ if(!newValue) result(undefined); isEnabled(newValue); } }); if(isEnabled() &amp;&amp; result.options.length === 1){ result(result.options[0].val); } //return the new observable return result; }; </code></pre> <p>Binding:</p> <pre><code>var selectListHTML = "&lt;select data-bind=\"value: {0}, options: {0}.options, optionsCaption: {0}.caption, optionsText: 'txt', optionsValue: 'val', enable: {0}.enable\"&gt;&lt;/select&gt;"; ko.bindingHandlers.selectList = { init: function(element, vA, aBA,vm,bc){ $(element).html(selectListHTML.replace(/\{0\}/g,vA())); } }; </code></pre> <p>Example <a href="http://jsfiddle.net/NV4gN/" rel="nofollow">fiddle</a></p> <p>Are there any pitfalls I'm missing? Does this look like good code? Any comments welcome, thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T16:16:18.187", "Id": "70623", "Score": "0", "body": "This is an old question, but still, it would be great it you could update your fiddle, right now it stopped working because it relies on http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>Your indentation in <code>ko.extenders.selectList = function (target, params) {</code> should be 4 spaces to make it far more readable</li>\n<li><p><code>write</code> could use a ternary approach:<br></p>\n\n<pre><code>write: function (newValue) {\n target( newValue || undefined );\n}\n</code></pre></li>\n<li>This code could use some more/better comment</li>\n<li>JSHint could find nothing wrong with it</li>\n<li>I am not too excited by seeing all those options as part of the HTML, it just feels wrong. None of the tools work for you in this case ( linting, beautifying, even colored syntax ). I guess that's more a reflection on knockout than on your code.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T16:20:46.120", "Id": "41161", "ParentId": "15625", "Score": "2" } } ]
{ "AcceptedAnswerId": "41161", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T16:48:34.300", "Id": "15625", "Score": "3", "Tags": [ "javascript" ], "Title": "Knockout selectlist binding" }
15625
<p><strong>Router</strong> is a <strong>generic class</strong> that manage multiple contracts that. It is able to find out wheter it's an online or offline situation, on the very moment when an <strong>operation</strong> is being made. </p> <p>There's a really easy way of doing it: a class for each Online-Offline pair that implement the contract and check on every each method wheter if it's online or not, and makes the right call. And that's exactly what I want to avoid.</p> <p>Just FYI, behind the scenes it would be an <em>Online</em> scenario connected to <strong>WCF services</strong> and an <em>Offline</em> scenario connected to a <strong>client local database</strong>.</p> <p>FYI 2: I've tried to accomplish this avoiding Interception and AOP stuff, but I found a dead end. You can see <strong><a href="https://stackoverflow.com/questions/12395778/how-to-code-a-good-offline-online-dispatcher">this post</a></strong> where I implement what seems to be a good solution, but stablishes if it's connected or not on the contructor, but real-world scenario needs this check at <strong>Operation level</strong>, not <strong>constructor level</strong>.</p> <p>It's ready to run &amp; test: just copy/paste on a new console application.</p> <pre><code>using System; using System.Reflection; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.InterceptionExtension; namespace ConsoleApplication1 { public class Unity { public static IUnityContainer Container; public static void Initialize() { Container = new UnityContainer(); Container.AddNewExtension&lt;Interception&gt;(); Container.RegisterType&lt;ILogger, OnlineLogger&gt;(); Container.Configure&lt;Interception&gt;().SetInterceptorFor&lt;ILogger&gt;(new InterfaceInterceptor()); } } class Program { static void Main(string[] args) { Unity.Initialize(); var r = new Router&lt;ILogger, OnlineLogger, OfflineLogger&gt;(); try { r.Logger.Write("Method executed."); } catch (CantLogException ex) { r.ManageCantLogException(ex); } Console.ReadKey(); } } public class Router&lt;TContract, TOnline, TOffline&gt; where TOnline : TContract, new() where TOffline : TContract, new() { public TContract Logger; public Router() { Logger = Unity.Container.Resolve&lt;TContract&gt;(); } public void ManageCantLogException(CantLogException ex) { // Is this an ugly trick? I mean, the type was already registered with online. Unity.Container.RegisterType&lt;TContract, TOffline&gt;(); Logger = Unity.Container.Resolve&lt;TContract&gt;(); var method = ((MethodBase)ex.MethodBase); method.Invoke(Logger, ex.ParameterCollection); } } public interface ILogger { [Test] void Write(string message); } public class OnlineLogger : ILogger { public static bool IsOnline() { // A routine that check connectivity return false; } public void Write(string message) { Console.WriteLine("Logger: " + message); } } public class OfflineLogger : ILogger { public void Write(string message) { Console.WriteLine("Logger: " + message); } } [System.Diagnostics.DebuggerStepThroughAttribute()] public class TestAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new TestHandler(); } } public class TestHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.WriteLine("It's been intercepted."); if (!OnlineLogger.IsOnline() &amp;&amp; input.Target is OnlineLogger) { Console.WriteLine("It's been canceled."); throw new CantLogException(input.MethodBase, input.Inputs); } return getNext()(input, getNext); } } public class CantLogException : Exception { public MethodBase MethodBase { get; set; } public object[] ParameterCollection { get; set; } public CantLogException(string message) : base(message) { } public CantLogException(MethodBase methodBase, IParameterCollection parameterCollection) { this.MethodBase = methodBase; var parameters = new object[parameterCollection.Count]; int i = 0; foreach (var parameter in parameterCollection) { parameters[i] = parameter; i++; } this.ParameterCollection = parameters; } } } </code></pre> <h2>Questions</h2> <ol> <li><p>Performance? Handling online-offline status through exceptions smells really bad.</p></li> <li><p>Multi-threading operations would expose this design as thread-unsafe?</p></li> <li><p>Isn't there any other way of preventing method execution?</p></li> <li><p>Any other constructive comments are apreciated too.</p></li> </ol> <hr> <p>I'm not interested on paid third-party stuff, so sadly things like <strong><a href="http://www.sharpcrafters.com/" rel="nofollow noreferrer">PostSharp</a></strong> aren't options for me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T17:37:56.973", "Id": "25388", "Score": "1", "body": "I'm not familiar with Unity, but this seems like something you should be able to do in your `ICallHandler`. I'm quite sure you could do this with Castle, which has something very similar. I think the solution here is to somehow let the handler know about the types in question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:51:25.450", "Id": "25401", "Score": "0", "body": "Sounds good... an example even with Castle might be helful. I don't know how can that make a difference. Supouse the handler knows Online, Offline and Contract types, what would happen? I still need to stop method execution using an exception." } ]
[ { "body": "<p>Ok, finally, I have the solution for this. I'll share it because I find this really helpful in such Online-Offline scenarios. There's a little improvement that would be nice to do: this way, Online will always be hitted first, it would be nice to set whom has to be used first. But that's for the release, this will be just fine for a beta.</p>\n\n<pre><code>using System;\nusing Microsoft.Practices.Unity;\nusing Microsoft.Practices.Unity.InterceptionExtension;\n\nnamespace ConsoleApplication1\n{\n public enum ConnectionStatus\n {\n Online,\n Offline,\n System // System checks connectivity\n }\n\n public static class Connectivity\n {\n private static ConnectionStatus ConnectionStatus = ConnectionStatus.Offline;\n\n public static void ForceConnectionStatus(ConnectionStatus connectionStatus)\n {\n ConnectionStatus = connectionStatus;\n }\n\n public static bool IsConnected()\n {\n switch (ConnectionStatus)\n {\n case ConnectionStatus.Online:\n return true;\n case ConnectionStatus.Offline:\n return false;\n case ConnectionStatus.System:\n return CheckConnection();\n }\n return false;\n }\n\n private static bool CheckConnection()\n {\n return true;\n }\n }\n\n public class Unity\n {\n public static IUnityContainer Container;\n\n public static void Initialize()\n {\n Container = new UnityContainer();\n\n Container.AddNewExtension&lt;Interception&gt;();\n Container.RegisterType&lt;ILogger, OnlineLogger&gt;();\n Container.Configure&lt;Interception&gt;().SetInterceptorFor&lt;ILogger&gt;(new InterfaceInterceptor());\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Unity.Initialize();\n\n var r = new Router&lt;ILogger, OnlineLogger, OnlineLogger&gt;();\n\n Connectivity.ForceConnectionStatus(ConnectionStatus.Offline);\n\n Console.WriteLine(\"Calling Online, will attend offline: \");\n\n r.Logger.Write(\"Used offline.\");\n\n Connectivity.ForceConnectionStatus(ConnectionStatus.Online);\n\n Console.WriteLine(\"Calling Online, will attend online: \");\n\n r.Logger.Write(\"Used Online. Clap Clap Clap.\");\n\n Console.ReadKey();\n }\n }\n\n public class Router&lt;TContract, TOnline, TOffline&gt;\n where TOnline : TContract\n where TOffline : TContract\n {\n public TContract Logger;\n\n public Router()\n {\n Logger = Unity.Container.Resolve&lt;TContract&gt;();\n }\n }\n\n public interface IOnline\n {\n IOffline Offline { get; set; }\n }\n\n public interface IOffline\n {\n }\n\n public interface ILogger\n {\n [Test()]\n void Write(string message);\n }\n\n public class OnlineLogger : ILogger, IOnline\n {\n public IOffline Offline { get; set; }\n\n public OnlineLogger()\n {\n this.Offline = new OfflineLogger();\n }\n\n public void Write(string message)\n {\n Console.WriteLine(\"Online Logger: \" + message);\n }\n }\n\n public class OfflineLogger : ILogger, IOffline\n {\n public IOnline Online { get; set; }\n\n public void Write(string message)\n {\n Console.WriteLine(\"Offline Logger: \" + message);\n }\n }\n\n [System.Diagnostics.DebuggerStepThroughAttribute()]\n public class TestAttribute : HandlerAttribute\n {\n public override ICallHandler CreateHandler(IUnityContainer container)\n {\n return new TestHandler();\n }\n }\n\n public class TestHandler : ICallHandler\n {\n public int Order { get; set; }\n\n public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)\n {\n Console.WriteLine(\"It's been intercepted.\");\n\n if (!Connectivity.IsConnected() &amp;&amp; input.Target is IOnline)\n {\n Console.WriteLine(\"It's been canceled.\");\n\n var offline = ((input.Target as IOnline).Offline);\n\n if (offline == null)\n throw new Exception(\"Online class did not initialized Offline Dispatcher.\");\n\n var offlineResult = input.MethodBase.Invoke(offline, this.GetObjects(input.Inputs));\n\n return input.CreateMethodReturn(offlineResult, this.GetObjects(input.Inputs));\n }\n\n return getNext()(input, getNext);\n }\n\n private object[] GetObjects(IParameterCollection parameterCollection)\n {\n var parameters = new object[parameterCollection.Count];\n\n int i = 0;\n foreach (var parameter in parameterCollection)\n {\n parameters[i] = parameter;\n i++;\n }\n return parameters;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T08:01:37.680", "Id": "25493", "Score": "0", "body": "So, each online type has to know its corresponding offline type? That doesn't sound very flexible to me. For example, you can't switch to a different implementation of the offline service without changing the code of the online service." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T14:44:18.973", "Id": "25511", "Score": "0", "body": "It's simplified for the sake of the code example. I'm using IoC, so implementation won't depend on Online service, but from IoC framework. Online type only knows there's an Offline contract. Is this what you mean? Thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:51:43.200", "Id": "15633", "ParentId": "15626", "Score": "4" } }, { "body": "<p>With Castle DynamicProxy, I would create an interface proxy without a target and an interceptor that would choose which implementation to use. Something like:</p>\n\n<pre><code>class OnlineOfflineInterceptor&lt;TInterface&gt; : IInterceptor\n{\n private readonly TInterface m_online;\n private readonly TInterface m_offline;\n\n public OnlineOfflineInterceptor(TInterface online, TInterface offline)\n {\n m_online = online;\n m_offline = offline;\n }\n\n public void Intercept(IInvocation invocation)\n {\n invocation.ReturnValue = invocation.Method.Invoke(\n Connectivity.IsConnected() ? m_online : m_offline, invocation.Arguments);\n }\n}\n\n…\n\nvar proxyGenerator = new ProxyGenerator();\nILogger logger = proxyGenerator.CreateInterfaceProxyWithoutTarget&lt;ILogger&gt;(\n new OnlineOfflineInterceptor&lt;ILogger&gt;(new OnlineLogger(), new OfflineLogger()));\n</code></pre>\n\n<p>I think this is more elegant than binding offline implementation to the online implementation by having a property on the online version that returns the offline version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T14:04:35.890", "Id": "25877", "Score": "0", "body": "I like this, didn't know Castle had this feature, much cleaner and readable than Unity attributes approach. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T13:14:13.553", "Id": "15872", "ParentId": "15626", "Score": "3" } } ]
{ "AcceptedAnswerId": "15872", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T17:02:50.387", "Id": "15626", "Score": "6", "Tags": [ "c#", "generics" ], "Title": "Online-Offline Class Manager" }
15626
<p>This is a simple script to make ls output first folders, then files, then other stuff (symlink). I think this is really neat and would like to share the script in exchange for comments.</p> <p>It should be noted that I'm working with <em>GNU findutils</em> and <em>coreutils</em>.</p> <p><strong>Some basic criteria that I'm aiming for include:</strong> </p> <ul> <li>lssort must accept the same arguments as ls </li> <li>lssort should depend on <code>bash</code>, <code>find</code>, <code>ls</code> and <code>xargs</code></li> <li><p>the output must not be prefixed with "./" </p> <p><strong>Problems:</strong></p> <ul> <li>arguments can not be augmented (-CFXtrs does not work)</li> </ul> <p><strong>Script</strong></p></li> </ul> <pre><code> #! /bin/bash #source $HOME/.scripts/string_manipulation.mergeme function trim { local var="$@" #$ var=" hello space " #$ echo ">" #$ > var="${var#"${var%%[![:space:]]*}"}" # rm leading whitespace characters var="${var%"${var##*[![:space:]]}"}" # rm trailing whitespace characters echo -n "$var" } function arrayContains { # remove the shortest needle from array and compare lengths # needs more testing... declare -a array declare -a arrayLess declare needle array=( "${!1}" ); shift # expand the passed array name needle="$@" # try to match the rest as a string arrayLess=( `trim "${array[@]#${needle}}"` ) # remove value $needle if [ ${#array[@]} -eq 0 ];then return 1 ;fi if [ ${#array[@]} -eq ${#arrayLess[@]} ];then return 1 ;fi if [ ${#array[@]} -lt ${#arrayLess[@]} ];then return 1 ;fi return 0 } # d dir f file p named pipe (FIFO) l sylink s socket D door (Solaris) # c character (unbuffered) special b block (buffered) special function finddirs { find "$@" \ -maxdepth 1 -depth -type d \ -regextype gnu-awk -regex "$REGEX" \ -printf '%f\0' } function findfiles { find "$@" \ -maxdepth 1 -depth -type f \ -regextype gnu-awk -regex "$REGEX" \ -printf "%f\0" } function findspecials { find "$@" \ -maxdepth 1 -depth \( -type l -o -type p -o -type s \) \ -regextype gnu-awk -regex "$REGEX" \ -printf "%f\0" } ## ## vars and such ## validswitches=(-X -l -r -t -C -F -1 -a -A -d -s) PATHS=() FPATHS="" LSSWITCHES="" ORIGIN_DIR="`pwd`" LSHIDDEN="^\./.+" # gnu-awk regex for find, single dot does not match LSNORMAL="^\./[^\.]+.+" # exclude files starting with . LS=ls\ --color=auto ARG=$1 ARGC=0 while [ "$ARG" != "" ]; do if [ `arrayContains validswitches[@] $ARG ;echo $?` -eq 0 ];then LSSWITCHES="${LSSWITCHES} $ARG" unset ARG fi if [ -d "$ARG" ];then #PATHS="${PATHS} $ARG" PATHS[${ARGC}]=$ARG let ARGC=ARGC+1 else FPATHS="${FPATHS} $ARG" fi shift ARG=$1 done # FIX only -A excludes . and .. if [[ "$LSSWITCHES" =~ '-a' || "$LSSWITCHES" =~ '-A' ]]; then REGEX=$LSHIDDEN else REGEX=$LSNORMAL fi #PATHS=`trim $PATHS` FPATHS=`trim $FPATHS` if [ ${#FPATHS} -eq 0 ]; then if [ ${#PATHS[@]} -eq 0 ]; then PATHS=(".") fi fi for arg in "${PATHS[@]}"; do if [[ ${#arg} -eq 1 && "$arg" == "/" ]];then p=/ else #p=${arg%%/} p=$arg fi cd "$p" if [[ "$p" != "." && "$p" != "./" ]];then echo "$p": ;fi finddirs | xargs -r0 $LS $LSSWITCHES -d findfiles | xargs -r0 $LS $LSSWITCHES findspecials | xargs -r0 $LS $LSSWITCHES -d [ ${#PATHS[@]} -gt 1 ] && echo cd $ORIGIN_DIR done echo $FPATHS |xargs -r $LS $LSSWITCHES #echo paths.:\ size: ${#PATHS[@]} #echo fpaths:\ </code></pre> <ul> <li><a href="http://www.pvv.ntnu.no/~rakhmato/bash/lssort" rel="nofollow noreferrer">lssort</a></li> </ul> <p><img src="https://i.stack.imgur.com/9yNKh.png" alt="lssort.png"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T18:45:30.370", "Id": "25399", "Score": "0", "body": "Alright, done. Good points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:09:50.920", "Id": "67492", "Score": "0", "body": "The coreutils people have made this easier: `ls --group-directories-first`." } ]
[ { "body": "<ol>\n<li>If you use <code>getopt</code> or <code>getopts</code> to parse the options, you can use multiple options together, and it would simplify your code quite a bit. <a href=\"https://github.com/l0b0/tilde/blob/e48ba0c2c892ac2426a1e6b6e5f9930253398b70/scripts/make-links.sh#L67\" rel=\"nofollow\">Example</a>.</li>\n<li>When you create arrays explicitly (<code>name=(values)</code>) you don't need to <code>declare</code> it first.</li>\n<li><code>arrayContains</code> should take one <code>needle</code> and then the contents of the array in question. This is how it works in other languages, and is easier to program and more explicit than using an array reference and concatenated needles. Also, when expanding <code>needle</code> the values will be concatenated with a space between them, which is rather arbitrary.</li>\n<li>If <code>needle</code> is empty, <code>arrayContains</code> should <code>return 0</code> regardless of the array contents.</li>\n<li><p>You can merge the <code>if</code> statements in <code>arrayContains</code> by separating them with <code>-o</code>:</p>\n\n<pre><code>if [ $a -eq 0 -o $b -eq 0 -o $c -eq $a ]\n</code></pre></li>\n<li><p><strike><code>ls</code> works with <a href=\"http://mywiki.wooledge.org/BashGuide/Patterns\" rel=\"nofollow\">globs rather than regular expressions</a> by default.</strike> The <code>find*</code> functions will not return the same filenames as <code>ls</code> with the same input. For example, run <code>touch example &amp;&amp; mkdir eclectic</code> and compare</p>\n\n<pre><code>ls [e]*\n</code></pre>\n\n<p>with</p>\n\n<pre><code>find . -maxdepth 1 -depth -type f -regextype gnu-awk -regex \"[e]*\"\n</code></pre></li>\n<li>You should be able to get the current working directory with <code>$PWD</code> rather than <code>pwd</code> to save a fork. This makes the code a tiny bit faster, without losing clarity, and fixes a very common but little known bug: The <code>`command`</code> construct (identical to the preferred <a href=\"http://mywiki.wooledge.org/CommandSubstitution\" rel=\"nofollow\"><code>$(command)</code> when using Bash</a>) <em>removes newlines from the end of the command output</em>. That means if you <code>mkdir $'foo\\n' &amp;&amp; cd $'foo\\n'</code> , <code>ORIGIN_DIR=\"`pwd`\"</code> will give the wrong result, but <code>ORIGIN_DIR=\"$PWD\"</code> will give the right one.</li>\n<li><a href=\"http://mywiki.wooledge.org/BashGuide/Practices/#Quoting\" rel=\"nofollow\">Use More Quotes</a>, for example do <code>ARG=\"$1\"</code> to enable working with whitespace in filenames. This is a <a href=\"http://www.dwheeler.com/essays/filenames-in-shell.html\" rel=\"nofollow\">very tricky subject</a>.</li>\n<li>If you want to get this working with <a href=\"https://github.com/l0b0/tilde/blob/master/examples/safe-find.sh\" rel=\"nofollow\">all filenames</a>, you'll need to use an array to store the <code>find</code> results before sending them to <code>ls</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T21:35:40.060", "Id": "25988", "Score": "0", "body": "Wow, tanks a lot! I've been avoiding getopts for far too long. I'll read up on it. Would you care to elaborate on why point 7 is relevant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T10:52:53.340", "Id": "26011", "Score": "0", "body": "I meant point 6 about ls working on shell globs rather than regex. What would I gain by running ls with regex?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T15:56:29.733", "Id": "26030", "Score": "0", "body": "I'm not sure why you think I have those confused, but thank you anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-04T16:52:40.963", "Id": "91917", "Score": "0", "body": "As far as I know, point 7 is not correct - command substitution strips _a newline_ from the end of the commands output, not _all newlines_. And pwd prints a newline after its output. So, pwd would emit \"foo\\n\\n\", command substitution would strip the last newline, and you'd be left with \"foo\\n\" - which is the correct directory name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-04T16:55:02.593", "Id": "91918", "Score": "0", "body": "@godlygeek Wrong: `printf '%q' \"$(printf '%s\\n\\n' 'foo')\"` prints `foo` and no newlines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-04T17:16:59.633", "Id": "91920", "Score": "0", "body": "You're right, I stand corrected - I clearly screwed something up when I tested that a minute ago. Nevermind me." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T15:11:16.003", "Id": "15983", "ParentId": "15627", "Score": "2" } } ]
{ "AcceptedAnswerId": "15983", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T17:11:08.057", "Id": "15627", "Score": "5", "Tags": [ "bash" ], "Title": "An attempt at making a neat ls" }
15627
<p>I there a better way to write this query? I feel sure it can be done in one statement with joins, but I couldn't get it, and I'm afraid I've made it too slow. What suggestions do you have? I'm running it in SQL Server 2000 (yeah, I know, upgrade is coming).</p> <p>Basically, I want to match estimated and actual costs, but sometimes the estimate is done on 1 cost center, and the actual costs are set to another cost center (hence the possibility of having null in est or act. I want to get all possible combinations for that job.</p> <pre><code>ALTER view [dbo].[JobCost_EstVsAct] --SELECT * FROM JobCost_EstVsAct Where jobnumber = '122773' as SELECT JobNumber, CostCenter, sum(Amount) as Est, sum(cost) as Act FROM ( SELECT JobNumber, CostCenter, Amount, 0 as cost FROM Avanti_ActiveJobBudgets AJB UNION SELECT jobnumber, costcentre as CostCenter, 0 as Est, cost as Act FROM Avanti_ActiveCostDetails ) temp --where cost + Amount &gt; 0 This line is a bug GROUP by JobNumber, CostCenter HAVING sum(Amount) + sum(cost) &gt; 0 --bug correction </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:10:54.050", "Id": "25418", "Score": "1", "body": "Small remark: why are you doing something like `'' as Est` rather than `null as Est`? I think you are forcing an unnecessary cast. I do not think a join will help. Algorithmically your query is pretty fast; the only potential concern is the elimination of duplicates performed by `UNION`. If not for that, then your query would be potentially linear. 'Join' is not a magic keyword that makes everything fast; neither is 'index'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:12:23.603", "Id": "25419", "Score": "0", "body": "@Leonid -The elimination of duplicates makes sense in this dataset, so I'm not worried there. You think `null as Est` is better? I just thought I could do this same thing with a join that would not bring in the duplicates in the first place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:17:59.503", "Id": "25420", "Score": "0", "body": "Try `select '' union select 1;` - you get `0` and `1`. It converts `''` to `0` which is surprising - might as well write `0` instead of `''`. If you did want an empty string, then `null` is better (unless 0 makes even better sense). This way you can reuse this view for further computation or you can plug it into a report. Most reporting tools allow you to replace a null with whatever string or value you wish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:23:59.583", "Id": "25421", "Score": "0", "body": "Well these are cost, so 0 makes sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:43:44.773", "Id": "25422", "Score": "0", "body": "Ok, then do `0 as cost`. I do not like having an implicit cast where one is not necessary. For example: this creates problems (but only at run time): `create procedure foo as begin select 1 union select 'a' end`. There is no compiler that will catch problems for you. It is a general principle of programming - keep things simple and readable. If you want `0` then type `0`. Just because you have memorized the implicit cast table http://i.msdn.microsoft.com/dynimg/IC170617.gif does not mean that the next programmer will or should. Other than that it looks ok to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:48:52.667", "Id": "25423", "Score": "0", "body": "No arguements here, I just didn't think about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:26:33.273", "Id": "28197", "Score": "0", "body": "*‘The elimination of duplicates makes sense in this dataset’* – I can see only one way when removing duplicates makes sense in your case. It's when either `Avanti_ActiveJobBudgets` or `Avanti_ActiveCostDetails` have duplicate rows that need to be eliminated before applying the `SUM`s. But is it really possible for those tables to have \"real\" duplicates (i.e. ones that shouldn't be there in the first place)? If not, you should probably not worry about duplicates and try `UNION ALL` instead of `UNION`." } ]
[ { "body": "<p>First off, it's not a stored procedure, it's a view.</p>\n\n<p>That said, the main change I would make is to use a CTE, once you have upgraded.</p>\n\n<pre><code>ALTER view [dbo].[JobCost_EstVsAct]\n --SELECT * FROM JobCost_EstVsAct Where jobnumber = '122773'\nAS\nWITH cte1 as (\n SELECT JobNumber, CostCenter, Amount, 0 as cost\n FROM Avanti_ActiveJobBudgets AJB\n),\ncte2 as (\n SELECT jobnumber, costcentre as CostCenter, 0 as Amount, cost as Act\n FROM Avanti_ActiveCostDetails\n),\ncte3 as (\n Select * From cte1\n Union\n Select * From cte2\n)\nSELECT JobNumber, CostCenter, sum(Amount) as Est, sum(cost) as Act\nFROM cte3\n--where cost + Amount &gt; 0     /* This line is a bug */\nGROUP by JobNumber, CostCenter\nHAVING sum(Amount) + sum(cost) &gt; 0   --bug correction\n</code></pre>\n\n<p>Replacing the cteX with more appropriate names. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T14:48:30.547", "Id": "25512", "Score": "0", "body": "Quite right, not a proc at all. I meant to say \"query\". Whats the main advantage of using a CTE here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T15:48:32.240", "Id": "25514", "Score": "2", "body": "The advantage in this case is readability, but IMO that is a significant advantage. It's also easier to work with as you are developing your query, switching between different parts of the final query as needed. You could even add a cte4 that does your group, and the looking at the different resultsets is dead easy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T19:33:04.680", "Id": "15650", "ParentId": "15630", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:44:35.797", "Id": "15630", "Score": "3", "Tags": [ "optimization", "sql", "sql-server" ], "Title": "SQL view, better way?" }
15630
<p>I've just got a Raspberry Pi, so I thought I'd try my hand at some Python. This is my first ever Python program (hurrah!).</p> <p>It's a very simple command-line implementation of noughts and crosses. The computer opponent's strategy is simply to pick at random, the code is very verbose in places and there's no way to restart the game without closing and restarting the program, but my aim wasn't to make a working game; I just wanted to practice using the language.</p> <p>Really, I'm just looking for help making this more Python-y, and any features of the language I've missed that would have been more effective. I've come from several years of C# and Java, so the language feels a little jarring to me right now.</p> <p>P.S. this is Python 3.2</p> <pre><code>import random import sys #### Initialising #### boxes = [[0, 0, 0], # 0 - empty [0, 0, 0], # 1 - nought [0, 0, 0]] # 2 - cross #### Functions #### #Converts the box's magic number into a character def intToText(num): if (num == 0): return ' ' if (num == 1): return 'O' if (num == 2): return 'X' #This outputs the grid, with the correct symbols in the boxes def printGrid(): print('┌─┬─┬─┐' '\n' '│' + intToText(boxes[0][0]) + '│' + intToText(boxes[1][0]) + '│' + intToText(boxes[2][0]) + '│' '\n' '├─┼─┼─┤' '\n' '│' + intToText(boxes[0][1]) + '│' + intToText(boxes[1][1]) + '│' + intToText(boxes[2][1]) + '│' '\n' '├─┼─┼─┤' '\n' '│' + intToText(boxes[0][2]) + '│' + intToText(boxes[1][2]) + '│' + intToText(boxes[2][2]) + '│' '\n' '└─┴─┴─┘') def checkVictory(): #This method looks at each box in the grid and checks the two boxes #in each of the four directions defined as vectors below for i in range(0, 3): for j in range(0, 3): if (boxes[i][j] == 0): continue for vector in [[1, 0], [1, 1], [0, 1], [-1, 1]]: #The four directions to check for a complete line in try: boxToCheck = [i, j] charToCheckFor = boxes[i][j] for x in range(1, 3): boxToCheck[0] += vector[0] boxToCheck[1] += vector[1] #Check if the box contains the same symbol as the previous ones in the line if (boxes[boxToCheck[0]][boxToCheck[1]] != charToCheckFor): break #If we're on the last box in the loop and haven't broken out yet, #we've found 3 in a row. Return the character in the box. if (x == 2): return intToText(boxes[i][j]) except: continue return ' ' def chooseComputerMove(): #This just fills a list with all the empty boxes and chooses one at random emptyBoxes = [] for i in range(0, 3): for j in range(0, 3): if (boxes[i][j] == 0): emptyBoxes += [[i, j]] return emptyBoxes[random.randint(1, len(emptyBoxes) - 1)] #### Program #### input('Welcome to noughts and crosses! Press enter to start.') print('\n' 'You are playing as crosses') printGrid() while(1): while(1): #Loop until valid input is entered move = input('\n' 'Your turn. Make your move:' '\n') if (move == 'help'): print('Type the coordinates (originating from the top left) of the box you want to put a cross into in the format \'x y\' (e.g. 3 2)') print('') continue if (len(move) == 3): if (1 &lt;= int(move[0]) &lt;= 3 and 1 &lt;= int(move[2]) &lt;= 3): #Check the user has entered valid coordinates if (boxes[int(move[0]) - 1][int(move[2]) - 1] == 0): #Check that the chosen box is empty boxes[int(move[0]) - 1][int(move[2]) - 1] = 2 #Put an X in the box printGrid() break print('Invalid input. Type \'help\' if you\'re stuck') # Check if the player's move won the game victoryResult = checkVictory() if (victoryResult == 'X'): print ('You win!') break # Make the computer's move computerMove = chooseComputerMove() boxes[computerMove[0]][computerMove[1]] = 1 print('\n' 'Computer\'s turn:') printGrid() # Check if the computer's move won the game victoryResult = checkVictory() if (victoryResult == 'O'): print ('Computer wins!') break sys.exit </code></pre>
[]
[ { "body": "<h3>1. Introduction</h3>\n\n<p>If this is your first Python program, then it's not too bad at all. There are a whole host of things that can be improved, but there are also a good few things you got right. For example, your code is pretty well-commented. Also, I liked the response \"Invalid input. Type 'help' if you're stuck\" which came at just the right time.</p>\n\n<p>On to the review!</p>\n\n<h3>2. Bugs</h3>\n\n<ol>\n<li><p>The computer doesn't play very well:</p>\n\n<pre><code>┌─┬─┬─┐\n│ │ │X│\n├─┼─┼─┤\n│X│O│X│\n├─┼─┼─┤\n│O│X│O│\n└─┴─┴─┘\n\nComputer's turn:\n┌─┬─┬─┐\n│ │O│X│\n├─┼─┼─┤\n│X│O│X│\n├─┼─┼─┤\n│O│X│O│\n└─┴─┴─┘\n</code></pre>\n\n<p>It's one thing not to have any strategic look-ahead, but quite another to miss an easy win like this!</p></li>\n<li><p>There's a bug in the win determination:</p>\n\n<pre><code>Your turn. Make your move:\n1 1\n┌─┬─┬─┐\n│X│O│X│\n├─┼─┼─┤\n│X│O│X│\n├─┼─┼─┤\n│O│X│O│\n└─┴─┴─┘\nYou win!\n</code></pre>\n\n<p>This happens because your win determination code starts from each of the nine squares and walks for two squares in each of four directions checking to see if the three cells form a line. You rely on getting an <code>IndexError</code> if this walks off the side of the array of boxes. But that's not always going to happen, because Python is perfectly happy for you to supply <em>negative array indices</em>: these count backwards from the end of the array, so that <code>a[-1]</code> is the last element, <code>a[-2]</code> is the second-to-last, and so on.</p>\n\n<p>One of these searches starts at box (0, 0), and then walks in the direction (−1, 1), getting to (−1, 1) which is the same as (2, 1), and then to (−2, 2) which is the same as (1, 2). All three cells contain an X, so it thinks that you have won!</p>\n\n<p>So you really do need to check that the indices are in range here.</p></li>\n<li><p>Here's another bug. The program raises an exception if the game is drawn.</p>\n\n<pre><code>Your turn. Make your move:\n2 1\n┌─┬─┬─┐\n│X│O│X│\n├─┼─┼─┤\n│X│X│O│\n├─┼─┼─┤\n│O│X│O│\n└─┴─┴─┘\n\nTraceback (most recent call last):\n ...\n File \"./cr15631.py\", line 78, in chooseComputerMove\n return emptyBoxes[random.randint(1, len(emptyBoxes) - 1)]\n ...\nValueError: empty range for randrange() (1,0, -1)\n</code></pre>\n\n<p>You need to check for draws as well as wins.</p></li>\n</ol>\n\n<h3>3. Coding style and technique</h3>\n\n<ol>\n<li><p>Python has a common set of coding conventions, which are written down in <a href=\"http://www.python.org/dev/peps/pep-0008/\">\"PEP8\"</a>. The majority of Python developers follow these conventions, so if you learn them too then you will find it easier to collaborate with other Python programmers. Some of these you follow already, but you might take a look at \"<a href=\"http://www.python.org/dev/peps/pep-0008/#function-names\">Function names should be lowercase, with words separated by underscores as necessary to improve readability.</a>\"</p></li>\n<li><p>Your code has good descriptions of each function in the form of comments. In Python it's usual to put the description of a function into a <a href=\"http://www.python.org/dev/peps/pep-0257/\"><em>docstring</em></a> which can users can retrive using the built-in <a href=\"http://docs.python.org/library/functions.html#help\"><code>help</code></a> function.</p>\n\n<p>Often you'll find that the discipline of writing documentation for a user helps you choose a better name for your function. For example, instead of </p>\n\n<pre><code>#Converts the box's magic number into a character\ndef intToText(num):\n if (num == 0): return ' '\n if (num == 1): return 'O'\n if (num == 2): return 'X'\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>def box_display(num):\n \"\"\"\n Return the character to display for a box containing `num`.\n \"\"\"\n return ' OX'[num]\n</code></pre></li>\n<li><p>Instead of using <code>+</code> to join lots of strings together, you can use Python's powerful <a href=\"http://docs.python.org/library/string.html#formatstrings\">string formatting mechanism</a>. Your printing code could be written:</p>\n\n<pre><code>def print_grid():\n \"\"\"\n Print the grid of boxes.\n \"\"\"\n print('┌─┬─┬─┐\\n'\n '│{}│{}│{}│\\n'\n '├─┼─┼─┤\\n'\n '│{}│{}│{}│\\n'\n '├─┼─┼─┤\\n'\n '│{}│{}│{}│\\n'\n '└─┴─┴─┘\\n'\n .format(*[box_display(boxes[i][j])\n for i in range(3)\n for j in range(3)]))\n</code></pre>\n\n<p>(I've used a couple of advanced features in the last three lines to avoid the repetition of <code>box_display(boxes[0][0]), box_display(boxes[0][1]), ...</code> and so on: first, a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\">list comprehension</a> to build the list of characters to pass to the <code>format</code> method, and secondly the <a href=\"http://docs.python.org/reference/expressions.html#calls\"><code>*args</code> syntax</a> to pass arguments to the function as a list instead of individual parameters.)</p></li>\n<li><p><code>range(0, 3)</code> can be abbreviated to <code>range(3)</code>.</p></li>\n<li><p>Python doesn't need parentheses around the test in an <code>if</code> statement.</p></li>\n<li><p>In the win determination code, you test for the last time around a loop with your test <code>if x == 2:</code>. Python has syntax for handling the last time around a loop with <a href=\"http://docs.python.org/reference/compound_stmts.html#the-for-statement\">the <code>else:</code> clause to the <code>for</code> statement</a>.</p></li>\n<li><p>You statement <code>sys.exit</code> doesn't actually call the function: you'd need to write <code>sys.exit()</code> for that. But there's no point in doing so: when a Python program comes to an end it exits automatically without you having to tell it to do so.</p></li>\n</ol>\n\n<h3>4. Design improvements</h3>\n\n<ol>\n<li><p>There's no particular need to store the box contents as numbers (and then to convert them to letters for display). Why not just store <code>O</code> and <code>X</code>?</p></li>\n<li><p>You'll find that a lot of things become easier if you don't try to keep the board in a 3-by-3 array, but in a 9-element list. That way, you only need one loop over the elements instead of two nested loops. It will be easier for the player to type in a number from 1 to 9 than to try to remember which co-ordinate axis is which.</p>\n\n<p>And for the win determination, you can just keep a list of all the winning lines, as there are only eight of them:</p>\n\n<pre><code>winning_lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),\n (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]\n</code></pre></li>\n</ol>\n\n<p>That's probably enough for you to be going on with. Good luck, and enjoy your Python programming.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T23:33:29.547", "Id": "25435", "Score": "0", "body": "Thanks! That's a lot to digest... I'm sort of ashamed that I didn't think of some of those things myself too. Anyway, again, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T05:55:37.453", "Id": "25492", "Score": "0", "body": "+1 On keeping a list of winning lines, often relatively less 'smarter' functions perform superior to the smarter counter parts, especially with small data sets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T03:37:09.130", "Id": "33260", "Score": "0", "body": "That finally explained the *args syntax to me! Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-14T11:18:51.490", "Id": "288232", "Score": "0", "body": "An amazing number of tips and tricks that really helped me! Also, it is common to put `while True` instead of `while 1`, although they function the same." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T22:46:41.307", "Id": "15634", "ParentId": "15631", "Score": "17" } } ]
{ "AcceptedAnswerId": "15634", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:08:37.983", "Id": "15631", "Score": "13", "Tags": [ "python", "beginner", "game", "console" ], "Title": "Command-line noughts and crosses" }
15631
<p>After reading Herb Sutter's <a href="http://www.drdobbs.com/windows/associate-mutexes-with-data-to-prevent-r/224701827" rel="nofollow noreferrer">Associate Mutexes with Data to Prevent Races</a>, I found that my solution was superior in several aspects, least important first:</p> <ul> <li>The code is cleaner, without macros </li> <li>No code added to every struct/class</li> <li>Does not prevent the use of non-protected versions of the classes/structs</li> <li>Does not rely on code coverage, which is subject to omission (relies on the compiler instead)</li> </ul> <p>The idea is to never give access to an object which associated mutex has not been locked. The locking is still explicit, but without it, one simply can't do anything with the objects. One passes around Lockable. Lockable has a mutex and a T. To be able to access T, one has to call Lockable::GetLockedProxy() that returns a LockedProxy object. A LockedProxy has a scoped_lock and a T*, and allows operations on the T.</p> <p>To access the T, one uses LockedProxy::operator->() or operator*().</p> <p>While a LockedProxy is alive, that is, while one has access to the T, the associated scoped_lock is alive, meaning that the mutex is locked, and subsequent calls to GetLockedProxy, which will try to create a scoped_lock, will hang.</p> <p>The drawback is, one still can be nasty and Lock the object and get a pointer to it (via LockedProxy's operator*) and store it, then release the lock and use the pointer. That's the abstraction's leak. But that's pointing the gun to one's foot and pulling the trigger.</p> <p><strong>The classes: Lockable.h</strong></p> <pre><code>#include &lt;boost/thread/mutex.hpp&gt; #include &lt;boost/interprocess/sync/scoped_lock.hpp&gt; template&lt;typename T&gt; class LockedProxy : boost::noncopyable { public: inline LockedProxy(boost::mutex &amp; m, T * obj) :lock(m), t(obj) {} inline LockedProxy(LockedProxy &amp;&amp; other) :lock(std::move(other.lock)), t(std::move(other.t)) {} inline T * operator-&gt;() { return t; } inline const T * operator-&gt;() const { return t; } inline const T &amp; operator*() const { return *t; } inline T &amp; operator*() { return *t; } private: boost::interprocess::scoped_lock&lt;boost::mutex&gt; lock; T * t; }; template&lt;typename T&gt; class Lockable { public: // Convenience typefed for subclasses to use typedef T LockableObjectType; inline Lockable(const T &amp; t) :lockableObject(t) {} inline LockedProxy&lt;LockableObjectType&gt; GetLockedProxy() { return LockedProxy&lt;LockableObjectType&gt;(mutex, &amp;lockableObject); } protected: LockableObjectType lockableObject; boost::mutex mutex; }; </code></pre> <p><strong>How to use them:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string.h&gt; #include "Lockable.h" void f(Lockable&lt;std::string&gt; &amp; str) { auto proxy = str.GetLockedProxy(); *proxy = "aa"; proxy-&gt;append("bb"); std::cout &lt;&lt; "str = " &lt;&lt; *proxy &lt;&lt; std::endl; } void g(Lockable&lt;int&gt; &amp; i) { { // reduce lock's lifespan auto proxy = i.GetLockedProxy(); *proxy = 321; } // relock, lock lives for the statement std::cout &lt;&lt; "i = " &lt;&lt; *i.GetLockedProxy() &lt;&lt; std::endl; } int main() { Lockable&lt;std::string&gt; str("abc"); //Can't use str here, it is not locked f(str); Lockable&lt;int&gt; i(123); g(i); return 0; } </code></pre> <p><strong>The usual question goes here</strong>: What do you think ?</p> <p>Are there drawbacks or pitfalls I did not see ?</p> <p>Do other libs like boost have something similar that I should use instead ?</p> <hr> <p><strong>EDIT:</strong></p> <p>The following code implements @useless', @Loki Astari's and my own suggestions and should compile with both VS and g++.</p> <p>I renamed <code>Lockable</code> and <code>LockedProxy</code> into <code>Synchronized</code> and <code>SynchronizedProxy</code>, for I found the former could lead to misunderstanding.</p> <p>The classes have gronw some hair, but their use have not, which is what matters. Using <code>proxy</code> after <code>TryGetSynchronizedProxy</code> failed is equivalent to using a <code>nullptr</code> which throws, which is good.</p> <p>Getting rid of the dependency on boost was a bit tricky. TryLock has some caveats in C++ 11 as described <a href="https://stackoverflow.com/questions/14920997/should-unique-lock-with-try-to-lock-owns-the-mutex-even-if-lock-fails">here</a>, which motivates the use of <code>recursive_mutex</code> as default.</p> <p>boost' safe bool is no longer required thanks to <a href="https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11">this</a>, but it does not compile with VS2012, even with the november 2012 compiler update.</p> <p><strong>Synchronized.hpp:</strong></p> <pre><code>#include &lt;mutex&gt; template&lt;typename T, class Mutex&gt; class SynchronizedProxy { template&lt;typename X, class Y&gt; friend class Synchronized; private: SynchronizedProxy(); SynchronizedProxy(const SynchronizedProxy &amp;); SynchronizedProxy &amp; operator=(const SynchronizedProxy &amp;); SynchronizedProxy &amp; operator=(SynchronizedProxy &amp;&amp;); SynchronizedProxy(Mutex &amp; m, T &amp; obj) :lock(m) ,t(&amp;obj) {} SynchronizedProxy(Mutex &amp; m, T &amp; obj, int) :lock(m, std::try_to_lock) ,t((lock)?&amp;obj:nullptr) {} public: SynchronizedProxy(SynchronizedProxy &amp;&amp; other) :lock(*other.lock.mutex(), std::adopt_lock) ,t(std::move(other.t)) { other.t = nullptr; } explicit operator bool() const { return (bool)lock; } const T * operator-&gt;() const { return t; } T * operator-&gt;() { return t; } const T &amp; operator*() const { return *t; } T &amp; operator*() { return *t; } private: std::unique_lock&lt;Mutex&gt; lock; T * t; }; template&lt;typename T, class Mutex=std::recursive_mutex&gt; class Synchronized { public: // Convenience typefed for subclasses to use typedef T SynchronizedObject; Synchronized(const T &amp; t) :t(t) {} SynchronizedProxy&lt;T,Mutex&gt; GetSynchronizedProxy() { return SynchronizedProxy&lt;T,Mutex&gt;(mutex, t); } SynchronizedProxy&lt;T,Mutex&gt; TryGetSynchronizedProxy() { return SynchronizedProxy&lt;T,Mutex&gt;(mutex, t, 0); } protected: T t; Mutex mutex; }; </code></pre> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;string&gt; #include "Synchronized.hpp" void f(Synchronized&lt;std::string&gt; &amp; str) { auto proxy = str.GetSynchronizedProxy(); *proxy = "aa"; proxy-&gt;append("bb"); std::cout &lt;&lt; "str = " &lt;&lt; *proxy &lt;&lt; std::endl; } void g(Synchronized&lt;int&gt; &amp; i) { { // reduce lock's lifespan auto proxy = i.GetSynchronizedProxy(); *proxy = 321; } // relock, lock lives for the statement std::cout &lt;&lt; "i = " &lt;&lt; *i.GetSynchronizedProxy() &lt;&lt; std::endl; } int main() { Synchronized&lt;std::string&gt; str("abc"); //Can't use str here, it is not locked f(str); Synchronized&lt;int&gt; i(123); g(i); { auto proxy = i.TryGetSynchronizedProxy(); if (proxy) { *proxy = 222; } } { auto p = i.GetSynchronizedProxy(); std::thread([&amp;i] { auto proxy = i.TryGetSynchronizedProxy(); if (proxy) { *proxy = 333; } } ).join(); } std::cout &lt;&lt; "i = " &lt;&lt; *i.GetSynchronizedProxy() &lt;&lt; std::endl; return 0; } </code></pre> <p>Output:</p> <pre><code>str = aabb i = 321 i = 222 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T23:14:18.330", "Id": "25431", "Score": "7", "body": "<quote>I found that my solution was superior in several aspects</quote> Brave words." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T20:57:48.010", "Id": "25451", "Score": "0", "body": "@LokiAstari One could use a T instead of a T* inside LockedProxy. When locking, move the T from Lockable to LockedProxy, and move it back when unlocking. I think that would not be very efficient, though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T21:07:35.220", "Id": "25453", "Score": "0", "body": "You could change T* into T but that brings another whole set of problems (just off the top of my head slicing)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T13:44:21.987", "Id": "25968", "Score": "0", "body": "Turns out that Mr. Edd had a similar solution a year earlier (this was posted in 2012 but developped in 2011), as he posted in 2010 in Sutter's Mill's comments: http://herbsutter.com/2010/05/24/effective-concurrency-associate-mutexes-with-data-to-prevent-races/ , and on his own site: http://www.mr-edd.co.uk/blog/associate_mutexes_to_prevent_races" } ]
[ { "body": "<p>Since the only place you should be creating a <code>LockedProxy</code> from is within the call <code>Lockable::GetLockedProxy()</code> you should therefore make the constructor private and friend this function. You don't actually want to give people the ability to make objects of this type themselves.</p>\n\n<pre><code>inline LockedProxy(boost::mutex &amp; m, T * obj)\n :lock(m),\n t((lock)?obj:nullptr)\n{\n}\n</code></pre>\n\n<p>Also since the access to this constructor is so controlled you never really want to pass a NULL object so you should pass <code>obj</code> by reference. If you must store it internally as a pointer fine take the address of the reference parameter for local storage but personally I would maintain everything as references.</p>\n\n<p>You should not be using the keyword <code>inline</code> unless you are required to do so. Declaring and defining it inside the class makes it automatically tagged inline. And apart from linking it has no affect on the compiler. So avoid this keyword unless you actually need in and you don't (it just clutters the code and makes people think you are trying to inline code (which only happens if the compiler thinks it is required)).</p>\n\n<p>Does it make sense to be able to move the Locked Proxy?</p>\n\n<pre><code>inline LockedProxy(LockedProxy &amp;&amp; other)\n</code></pre>\n\n<p>Not sure. I don't understand the use case where you would want or need to do that.</p>\n\n<p>Auto conversion to bool?</p>\n\n<pre><code>inline operator bool() const\n{\n return lock;\n}\n</code></pre>\n\n<p>Why? Again I don't see the use case. Also you should probably look up the <strong>safe bool idiom</strong>. The problem with bool is that is auto converted to integer so the compiler will now be able to compile your code what it see this:</p>\n\n<pre><code>LockedProxy&amp; x = /* Get a lock proxy */;\n\nint y = 10 + x; // Will now compile fine (you probably want a compile error here).\n</code></pre>\n\n<p>Rather than pass the object in. You should look up variadic templates.<br>\nThis will allow your constructor here to take the same arguments as the T and forward them directly to the T object being constructed. So now the only T is the one inside the object.</p>\n\n<pre><code>inline Lockable(const T &amp; t)\n :lockableObject(t)\n{}\n</code></pre>\n\n<p>Same comments about inline as above.</p>\n\n<pre><code>inline LockedProxy&lt;LockableObject,Mutex&gt; GetLockedProxy() {\n return LockedProxy&lt;LockableObject,Mutex&gt;(mutex, &amp;lockableObject);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T17:48:38.843", "Id": "25517", "Score": "0", "body": "As suggested on SO, I removed the const from `inline LockedProxy(const LockedProxy && other)`. Hopefully it works now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T21:47:42.780", "Id": "25838", "Score": "0", "body": "Private + friend: OK. Pass-by-reference: OK. `inline`: OK. The move constructor in LockedProxy enables returning in `GetLockedProxy()`. Safe bool idiom: OK (nice one, i'll sleep less dumb tonight). I'll have to pass on the variadic templates, VS won't compile them. Many thanks, \"that was very educational\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T21:54:17.887", "Id": "25840", "Score": "0", "body": "Ah, and the conversion to `bool` allows for testing after `TryGetLockedProxy()`, which may fail." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T21:04:55.057", "Id": "15654", "ParentId": "15632", "Score": "8" } }, { "body": "<p>The only weaknesses I can see immediately are that:</p>\n\n<ol>\n<li><p>you're limited to the mutex type you've hard-coded, although I'm sure you could template it out (read-write locks would probably require another, read-only, proxy class to be useful)</p></li>\n<li><p>no support for try-lock operations: again this probably requires another proxy type</p>\n\n<ul>\n<li>I was thinking it could simply call <code>try_lock</code> and record the boolean success/failure status,\n<ul>\n<li>expose the success or failure by conversion to bool</li>\n<li>and be convertible to a regular locked proxy (only in case if success) using the adopt tag</li>\n</ul></li>\n</ul>\n\n<p>eg.</p>\n\n<pre><code> auto maybe = lockable.trylock();\n if (maybe) { auto proxy = maybe.proxy(); // normal locked proxy use ...\n } else ; // failed to lock ...\n</code></pre>\n\n<ul>\n<li>alternatively of course, it could just throw if it fails</li>\n</ul></li>\n<li><p>your LockedProxy move constructor should probably reset <code>other.t = NULL</code> explicitly</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T14:26:28.400", "Id": "25599", "Score": "0", "body": "1. Indeed that should be easy. Maybe with nice default values? 2. Interesting! What would GetTryLockProxy do on failure? Return a TryLockProxy that compares true with nullptr? 3. True!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:56:00.193", "Id": "25607", "Score": "1", "body": "I like the bool. Throwing exceptions should be, by definition, reserved to exceptional cases." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T15:15:44.213", "Id": "15709", "ParentId": "15632", "Score": "4" } }, { "body": "<p>Remove the dependency on boost. Not everybody uses it. Although the way you are using the <code>mutex</code>, its subtype <code>scoped_try_lock</code> and <code>scoped_lock</code> are very boost-like, any kind of mutex and lock should be allowed, as not everybody can or want to use boost.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T17:26:24.607", "Id": "25658", "Score": "0", "body": "What is this a comment on something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T21:38:58.770", "Id": "25751", "Score": "1", "body": "A possible improvement. I'm waiting for up/downvotes to consider implementing it or not. Is talking to oneself using the second person unusual ? (;" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T18:11:59.927", "Id": "15742", "ParentId": "15632", "Score": "1" } }, { "body": "<p>Herb suggested another way for associating mutexes with data in c++11 more recently than the linked article in this <a href=\"http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism\" rel=\"noreferrer\">video</a>. The whole video is worth watching in my opinion, but he explains a wrapper pattern around minute 38 and shows how it applies to associating a mutex in minute 40. His implementation looks like this:</p>\n\n<pre><code>template&lt; class T &gt; class monitor {\nprivate:\n mutable T t;\n mutable std::mutex m;\n\npublic:\n monitor( T t_ = T{} ) : t(t_) {}\n\n template&lt; typename F &gt;\n auto operator()( F f ) const -&gt; decltype(f(t))\n { std::lock_guard&lt;std::mutex&gt; _{m}; return f(t); }\n};\n</code></pre>\n\n<p>You then use the wrapped object it by passing a <a href=\"http://en.cppreference.com/w/cpp/concept/Callable\" rel=\"noreferrer\">callable</a> object that takes by reference the object being synchronized. Here is a brief example:</p>\n\n<pre><code>monitor&lt;string&gt; s;\ns([]( string &amp;s ) {\n s.append( \"syncrhonized append\" );\n});\n</code></pre>\n\n<p>I think it is a pretty slick way of forcing synchronization which makes the synchronization a little more visually explicit than returning a proxy. He gave a minimal implementation for his slide. My take on it, hopefully, made it a bit more useful. It...</p>\n\n<ol>\n<li>Abstracts the mutex type to anything that models the <a href=\"http://en.cppreference.com/w/cpp/concept/BasicLockable\" rel=\"noreferrer\">BasicLockable</a> concept.</li>\n<li>Uses empty base class optimization to combine the BasicLockableT with the protected value. This preserves space in the case that you have an empty BasicLockableT.</li>\n<li>Forwards all constructor arguments to the protected value. This allows you to construct T with any of T's constructors.</li>\n<li>Overloads the sync function to preserve constness of the protected value.</li>\n</ol>\n\n<p>Here it is:</p>\n\n<pre><code>template&lt; typename T, typename BasicLockableT = std::mutex &gt;\nclass Synchronized\n{\n struct ProtectedValue : BasicLockableT {\n template&lt; typename ...Args &gt;\n ProtectedValue ( Args&amp;&amp;... params )\n : value( std::forward&lt;Args&gt;(params)... )\n {}\n\n BasicLockableT&amp; lockable()\n { return *this; }\n\n T value;\n };\n mutable ProtectedValue m_protected_value;\n\npublic:\n template&lt; typename ...Args &gt;\n Synchronized( Args&amp;&amp;... params )\n : m_protected_value( std::forward&lt;Args&gt;(params)... )\n {}\n\n template&lt; typename F &gt;\n auto sync( F f ) -&gt; decltype( f( m_protected_value.value ) )\n {\n std::lock_guard&lt; BasicLockableT &gt; lock( m_protected_value.lockable() );\n return f( m_protected_value.value );\n }\n\n template&lt; typename F &gt;\n auto sync( F f ) const\n -&gt; decltype( f( const_cast&lt;T const &amp;&gt;(m_protected_value.value) ) )\n {\n std::lock_guard&lt; BasicLockableT &gt; lock( m_protected_value.lockable() );\n return f( const_cast&lt;T const &amp;&gt;(m_protected_value.value) );\n }\n};\n</code></pre>\n\n<p>Anyway I just wanted to throw a c++11 way of doing this out there. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-01T04:55:40.677", "Id": "52181", "ParentId": "15632", "Score": "5" } } ]
{ "AcceptedAnswerId": "15654", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T21:16:49.013", "Id": "15632", "Score": "15", "Tags": [ "c++", "c++11", "locking", "boost" ], "Title": "Force locking for thread-safety" }
15632
<p>I am looking for pointers / comments / critiques regarding the below code. One major flaw I know is that I need to define Nodes first and then manually join them to create a List.</p> <p>Are there any flaws apart from that? C++ programming style errors? RAII?</p> <pre><code>#include&lt;iostream&gt; template&lt;typename T&gt; class Node { private: T data_; public: Node&lt;T&gt;* prev; Node&lt;T&gt;* next; const T&amp; getData() const { return data_; } T&amp; setData() { return data_; } const T&amp; setData(const T&amp; data) { data_ = data; return data_; } Node() { prev = NULL; next = NULL; } }; template&lt;typename T&gt; class List { private: Node&lt;T&gt;* head_; Node&lt;T&gt;* tail_; public: List() { head_ = NULL; tail_ = NULL; } Node&lt;T&gt;* getHead() const { return head_; } Node&lt;T&gt;* getTail() const { return tail_; } Node&lt;T&gt;* addNode(Node&lt;T&gt; &amp; rhs) { if (tail_) { tail_-&gt;next = &amp;rhs; tail_ = tail_-&gt;next; } else { tail_ = &amp;rhs; head_ = tail_; } return tail_; } }; int main() { List&lt;int&gt; li; Node&lt;int&gt; temp1; temp1.setData(5); li.addNode(temp1); Node&lt;int&gt; temp2; temp2.setData(10); li.addNode(temp2); Node&lt;int&gt;* h = li.getHead(); while(h) { std::cout &lt;&lt; h-&gt;getData() &lt;&lt; std::endl; h = h-&gt;next; } } </code></pre>
[]
[ { "body": "<p>First of all, <code>Node</code> should definitely be a nested type of <code>List</code> -- there's no need to ever expose nodes to the users of the list. You should also be the one to manage the lifetime of the node. You definitely don't want users of the list to be able to assign the <code>next</code> and <code>prev</code> pointers of a node; it makes absolutely no sense to make data (which you care little about hiding) private but to expose implementation details.</p>\n\n<p>While this code is fairly long, it mostly consists of trivial functions that are hard to say anything about, while the key features of a list (abstracted iteration via iterators, abstracted away insertion in the middle) is left for the user to do. There's not much to say.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T09:39:51.320", "Id": "15645", "ParentId": "15636", "Score": "3" } }, { "body": "<h2>Design</h2>\n\n<p>Getters and setters are horrible.</p>\n\n<p>The expose your code to the possibility tight coupling as they expose the internal representation. So remove them. You should be thinking in terms of what actions can be performed on the list and secondly (since this is a container) how do I expose the contained elements.</p>\n\n<p>So I agree with Anton Node should not even be exposed outside the list. Why does the user of the list need to know about Node(s)?</p>\n\n<p>Why does the user need to know about the head and tail of the list. That's an implementation detail. Exposing those will tightly couple your code to require to implement them even if a future version does not have the concept of head and tail internally. Now I can see getting the first and last element of a list (but they don't need to know that internally you have head and tail pointers) and also iterators (but iterators have a much simpler cleaner interface than node*).</p>\n\n<p>Actions that can be done on a list.</p>\n\n<ul>\n<li>Check for empty (other functions may have a precondition that it is not empty)</li>\n<li>Add an element</li>\n<li>Remove an element (pre-condition not empty)</li>\n<li>ability to traverse the list (usually this mean iterators of some form but there are other ways).</li>\n<li>Access to specific elements\n<ul>\n<li>Maybe.</li>\n</ul></li>\n</ul>\n\n<h2>Implementation</h2>\n\n<p>I would say your list leaks; but it does not actually own the nodes (it should) otherwise how do you gurantee that all the members of the list are valid.</p>\n\n<p>Secondly the addNode()</p>\n\n<pre><code>Node&lt;T&gt;* addNode(Node&lt;T&gt; &amp; rhs) {\n</code></pre>\n\n<p>This assumes that the passed node is virgin and has not been re-used. Since somebody else created it you can not assume this. You must set the next pointer of rhs to NULL to guarantee that it is correct.</p>\n\n<p>You never set the prev member. So I see no point in having it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T20:57:54.943", "Id": "15653", "ParentId": "15636", "Score": "4" } } ]
{ "AcceptedAnswerId": "15653", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T01:52:42.317", "Id": "15636", "Score": "3", "Tags": [ "c++" ], "Title": "LinkedList in C++" }
15636
<p>I have the following function to insert a new row into a table:</p> <pre><code>/** * Insert row into the designated table * * Function to add a new row into the designated table * * @param str $table Table name to insert the row * @param arr $data Array with values * * @return int row Last inserted ID */ public function database_add_row($table, $data) { try { $fields = ''; foreach ($data as $field) { $fields.= '?,'; } $fields = substr($fields,0,-1); $sql = "INSERT INTO ".$table." VALUES(".$fields.")"; $sth = $this-&gt;database-&gt;prepare($sql); $sth-&gt;execute($data); return $this-&gt;database-&gt;lastInsertId(); } catch(PDOException $e) { throw new userman_Exception("&lt;h1&gt;ups!&lt;/h1&gt;&lt;br/&gt;". $e-&gt;getMessage()); } } </code></pre> <p>I'm counting the values in the array to prepare the query, and adding placeholders for each position, then subtracting the last comma from the generated string. This avoids using the field names, which leads to a table agnostic function, </p> <p><strong>Considerations:</strong></p> <ul> <li>All columns values are passed with the <code>$data</code> array.</li> <li>The function is designed to insert on any table with any number of columns.</li> </ul> <p><strong>My question is:</strong></p> <p>Is my method adequate, leading to a secure row insertion?</p>
[]
[ { "body": "<p>As long as the <code>$table</code> variable is properly scrubbed / initialized you are fine as far as secure goes.</p>\n\n<p>However, I don't care for the insert statement format where you do not specify the column names. For this to work for any insert statement for any table you would have to make sure that the array has been setup to include EVERY column in the table in the correct order. </p>\n\n<p>For basic scenarios this may work but you are probably going to end up with bugs. You will get values inserted into the wrong columns and you will have a headache trying to figure out where it is occurring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T23:33:03.240", "Id": "25458", "Score": "0", "body": "Thank you for your answer! I ended up accepting the answer from @Corbin. He provided a practical way to deal with the most pertinent issues." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T04:27:02.827", "Id": "15638", "ParentId": "15637", "Score": "0" } }, { "body": "<p>As noted in your other question, that exception handling completely masks the true exception. It adds no value yet detracts. There's no reason to do that. Just allow the exception to throw out of the function.</p>\n\n<hr>\n\n<p>As for 'security', assuming you properly control the table name, it is safe. (A better way to phrase that may be that SQL injection is not possible as long as you control <code>$table</code>.)</p>\n\n<hr>\n\n<p>I might consider writing it a bit differently though:</p>\n\n<pre><code>public function database_add_row($table, $data) {\n $placeholders = implode(', ', array_fill(0, count($data), '?'));\n $sql = \"INSERT INTO {$table} VALUES ({$placeholders})\";\n $stmt = $this-&gt;database-&gt;prepare($sql);\n if ($stmt-&gt;execute($data)) {\n return $this-&gt;database-&gt;lastInsertId();\n } else {\n return false;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I also might consider using associative arrays. That would allow you to specify columns (which could be useful if you had default-valued columns or auto incrementing columns).</p>\n\n<pre><code>public function database_add_row($table, $data) {\n $cols = array_keys($data);\n $columns = implode(', ', $cols);\n $placeholders = implode(', ', array_map(function($c) { return \":{$c}\"; }, $cols));\n $sql = \"INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})\";\n $stmt = $this-&gt;database-&gt;prepare($sql);\n if ($stmt-&gt;execute($data)) {\n return $this-&gt;database-&gt;lastInsertId();\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>Then you would use it like:</p>\n\n<pre><code>$obj-&gt;database_add_row(\"table1\", array('column1' =&gt; 'val1', 'column2' =&gt; 'val2'));\n</code></pre>\n\n<hr>\n\n<p>Depending on how far you plan to go with your DB abstractions, you might want to consider a DBAL or ORM library. The <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow\">Doctrine Project</a> has quite widely used versions of both of those.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T04:27:23.103", "Id": "15639", "ParentId": "15637", "Score": "3" } } ]
{ "AcceptedAnswerId": "15639", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T03:12:56.103", "Id": "15637", "Score": "3", "Tags": [ "optimization", "security", "php5", "pdo" ], "Title": "Secure row insertion using a position-based prepared statement" }
15637
<p>Please comment on the same. How can it be improved?</p> <p>Specific improvements I am looking for:</p> <ol> <li>Memory leaks</li> <li>C++ style</li> <li>Making code run faster</li> <li>RAII</li> </ol> <p></p> <pre><code>#include&lt;iostream&gt; #include&lt;algorithm&gt; template &lt;typename T&gt; class Stack { private: T* array_; int length_; T* last_; void expandArray(); public: Stack(int length = 8) : array_(new T[length]), length_(length), last_(array_) {} Stack&lt;T&gt;&amp; push(const T&amp;); Stack&lt;T&gt;&amp; pop(); }; template&lt;typename T&gt; void Stack&lt;T&gt;::expandArray() { T* array_temp = new T[length_ &lt;&lt; 1]; std::copy(array_, array_ + length_, array_temp); std::swap(array_, array_temp); delete[] array_temp; last_ = array_ + length_ - 1; length_ &lt;&lt;= 1; } template&lt;typename T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::push(const T&amp; data) { if (last_ == (array_ + length_ - 1)) { expandArray(); } last_[0] = data; last_++; std::cout &lt;&lt; "[" &lt;&lt; data &lt;&lt; "] pushed." &lt;&lt; std::endl; return *this; } template&lt;typename T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::pop() { if(array_ != last_) { last_--; std::cout &lt;&lt; "[" &lt;&lt; last_[0] &lt;&lt; "] popped." &lt;&lt; std::endl; } else { std::cout &lt;&lt; "Nothing to pop." &lt;&lt; std::endl; } return *this; } int main() { Stack&lt;std::string&gt; s; s.push(std::string("a")) .push(std::string("b")) .push(std::string("c")) .push(std::string("d")); s.pop().pop().pop().pop().pop(); } </code></pre>
[]
[ { "body": "<p>First of all, I would specify that your stack is using a \"dynamically allocated array\", as opposed to just an array, as I at first expected a C array when looking at the title. That varies from person to person, though.</p>\n\n<p>On to more important things:</p>\n\n<ul>\n<li>I would not print anything in the stack functions. If someone wants information on what they're pushing and popping, let them do it themselves.</li>\n<li>You seem to be missing a peek function.</li>\n<li>Either throw an exception or add an assert to pop for the <code>array_ == last_</code> case.</li>\n<li><code>length_</code> should actually be called <code>capacity_</code>.</li>\n<li><code>expandArray</code> may leak memory if the copy throws. I would use an <code>std::vector&lt;T*&gt;</code> internally for this stuff.</li>\n<li>You don't check that <code>length &gt; 0</code> in the constructor.</li>\n<li>I would not allocate so anything by default.</li>\n<li>You lack all three of a copy constructor, assignment operator, and destructor, so you'll definitely leak memory. You should also have a move constructor and a move assignment operator, but those aren't as critical.</li>\n<li>You provide no way to check whether the stack is empty.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T09:34:55.360", "Id": "15644", "ParentId": "15640", "Score": "11" } }, { "body": "<blockquote>\n<p>Memory leaks</p>\n</blockquote>\n<p>Yes. No destructor</p>\n<blockquote>\n<p>C++ style</p>\n</blockquote>\n<p>Where? This is C code. Just uses a few things from C++. But basically this is C in style and usage.</p>\n<blockquote>\n<p>Making code run faster</p>\n</blockquote>\n<p>It will run infinitely faster when correct. Currently it is broken.</p>\n<pre><code>{\n Stack&lt;int&gt; x;\n Stack&lt;int&gt; y(x);\n} // breaks here with a double delete.\n</code></pre>\n<blockquote>\n<p>RAII</p>\n</blockquote>\n<p>Would be nice. But no destructor. Also you are not implementing the rule of three(five). To help you should probably look up the copy/swap idiom (assuming it is assignable in the first place).</p>\n<h3>Code Review:</h3>\n<p>When you create this array:</p>\n<pre><code>T* array_temp = new T[length_ &lt;&lt; 1];\n</code></pre>\n<p>You are creating (length * 2) members (that will be fully constructed). I suppose this is OK. But if T is expensive to construct then this may not be something you want to pay for. As an example std::vector&lt;&gt; does not initialize the elements between size() and capacity().</p>\n<p>The rest is good you create it in a temporary and then swap with the current. But you start deleting the old stuff before finishing the update on this object. If the destructor of T throws an exception your object is now in an intermediate state.</p>\n<p>The order is:</p>\n<ol>\n<li>Create an new stuff that can throw (int temps)</li>\n<li>Change the state of the current object (using no-throw actions).</li>\n<li>Destroy the old stuff.</li>\n</ol>\n<p>This way if destroying the old stuff causes problems you don't leave your object in an intermediate state. You should probably look up copy and swap idiom. It will help with this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T18:55:37.197", "Id": "25479", "Score": "0", "body": "Thanks, can you please comment on 'how to make it more C++'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T19:50:51.773", "Id": "25480", "Score": "0", "body": "Constructor/Destructor. Rule of three(five). Copy/Swap idom. Automatic Resource management. Exception safety. All mentioned above. The user of your class should not need to understand anything about your class (apart from the public API to use it (I suppose this is C as well)) and they should not be able to break it (or anything else) by using it incorrectly (ie you should not be able to use it incorrectly (this is very C++)). Currently I can break it (and other stuff) just by using it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T21:16:48.370", "Id": "15655", "ParentId": "15640", "Score": "6" } }, { "body": "<p>I would use std::aligned_storage for the backing store and then use placement new and placement delete to manage elements. Currently you are default constructing elements above the capacity and are also not destroying objects when they are popped. You may also want to consider changing the interface to use move semantics to push and pop items (if using my first suggestion this just means offering an emplace_push(T&amp;&amp;) inteface and using placement new with move constructor, conversely offer a T pop() function that move constructs the head to the result (using NRVO) and then placement deletes the head). Also when you reallocate the backing store you should use move semantics. The advantage of doing it this way (apart from performance) is that T does not need to be default constructible, copy constructible or assignable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T00:56:34.913", "Id": "15659", "ParentId": "15640", "Score": "1" } } ]
{ "AcceptedAnswerId": "15644", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T04:41:46.070", "Id": "15640", "Score": "4", "Tags": [ "c++", "array", "stack" ], "Title": "Stack implementation using arrays" }
15640
<p><img src="https://i.stack.imgur.com/uXeQb.png" alt="enter image description here"></p> <p>I'm designing a client (UI made with WPF) and server (WCF) that communicates with a device known as DDC (Direct Digital Control). A user on the client side can make requests to adjust the state of the DDC, then the server receives the information from the client and invokes appropriate operation on the DDC. DDC uses SOAP protocol for communication so I have a WSDL file that is being imported as service reference in Server, so invoking operations from the Server to DDC is very straight forward.</p> <p>I'm having some trouble designing a solid data structure and interfaces for communication between UI and Engine, largely because there are a lot of operations defined in the WSDL file that I need to handle (like over 300 operations). Most of them return a string or a list of string, but some of them are defined as structures with a lot of fields.</p> <p>For my interface, I initially thought about defining operationcontracts based on what parameters/return types some trivial function Require:</p> <pre><code>[ServiceContract] public interface IDDCEngine { [OperationContract(Name = "GetPointValueSpecific")] string GetPointValueSpecific(string host, string operation, out List&lt;PointSpecificInformation&gt; pointSpecificInfoList); [OperationContract(Name = "GetPointValueCommon")] string GetPointValueCommon(string host, string operation, out List&lt;PointCommonInformation&gt; pointCommonInfoList); [OperationContract(Name = "SetPointValueCommon")] string SetPointValueCommon(string host, string operation, List&lt;PointCommonInformation&gt; pointCommonInfo); [OperationContract(Name = "SetPointValueSpecific")] string SetPointValueSpecific(string host, string operation, List&lt;PointSpecificInformation&gt; pointSpecificInfo); [OperationContract(Name = "SendRequestListMultipleInMultipleOut")] string SendRequest(string host, string operation, List&lt;string&gt; parameters, out List&lt;string&gt; ddcResponse); [OperationContract(Name = "SendRequestSingleInMultipleOut")] string SendRequest(string host, string operation, string parameters, out List&lt;string&gt; ddcResponse); [OperationContract(Name = "SendRequestMultipleInSingleOut")] string SendRequest(string host, string operation, List&lt;string&gt; parameters, out string ddcResponse); [OperationContract(Name = "SendRequestSingleInSingleOut")] string SendRequest(string host, string operation, string parameter, out string ddcResponse); [OperationContract(Name = "SendRequestSingleOut")] string SendRequest(string host, string operation, out string ddcResponse); } </code></pre> <p>The return type is string to indicate the status connection between UI/Engine (Validate/Error). Out parameter is the relevant response (data) received from DDC.</p> <p>Here is an example of my engine implementation:</p> <pre><code>//Parameters: Single //Response: Multiple public string SendRequest(string host, string operation, string parameter, out List&lt;string&gt; value) { value = new List&lt;string&gt;(); string result = OPERATION_VALIDATE; try { DDCService.LGeDDCClient ddc = new DDCService.LGeDDCClient(DDC_NAMESPACE, host); switch (operation) { case "GetCPUMemoryStatus": int count; if (!int.TryParse(parameter, out count)) result = INVALID_PARAMETER; //Returns in the order of Process/Memory: string memory; string process = ddc.GetCPUMemoryStatus(count, out memory); value.Add(process); value.Add(memory); return OPERATION_VALIDATE; case "GetVersion": string kernel; string ramdisk = ddc.GetVersion(out kernel); value.Add(kernel); value.Add(ramdisk); return OPERATION_VALIDATE; default: result = UNDEFINED_OPERATION; return result; } } catch (Exception ex) { result = ex.Message; return result; } finally { DisplayTransmissionOnTextbox(operation, host, result); } } //Parameters: Multiple //Response: Single public string SendRequest(string host, string operation, List&lt;string&gt; parameter, out string value) { value = String.Empty; string result = OPERATION_VALIDATE; try { DDCService.LGeDDCClient ddc = new DDCService.LGeDDCClient(DDC_NAMESPACE, host); switch (operation) { case "RequestUpgrade": if (parameter.Count != 2) return INVALID_PARAMETER; int upgradeTarget; if (!int.TryParse(parameter[1], out upgradeTarget)) return INVALID_PARAMETER; value = ddc.RequestUpgrade(parameter[0], upgradeTarget); return OPERATION_VALIDATE; default: value = null; return UNDEFINED_OPERATION; } } catch (Exception ex) { result = ex.Message; return result; } finally { DisplayTransmissionOnTextbox(operation, host, result); } } //Parameters: Single //Response: Single public string SendRequest(string host, string operation, string parameter, out string value) { value = String.Empty; string result = OPERATION_VALIDATE; try { DDCService.LGeDDCClient ddc = new DDCService.LGeDDCClient(DDC_NAMESPACE,host); switch (operation) { case "EndRestore": value = ddc.EndRestore(parameter); return OPERATION_VALIDATE; case "EndBackup": value = ddc.EndRestore(parameter); return OPERATION_VALIDATE; case "GetLogicSource": value = ddc.GetLogicSource(parameter); return OPERATION_VALIDATE; default: result = UNDEFINED_OPERATION; return result; } } catch (Exception ex) { result = ex.Message; return result; } finally { DisplayTransmissionOnTextbox(operation, host, result); } } //Parameters: None //Response: Single public string SendRequest(string host, string operation, out string value) { value = String.Empty; string result = OPERATION_VALIDATE; try { DDCService.LGeDDCClient ddc = new DDCService.LGeDDCClient(DDC_NAMESPACE, host); switch (operation) { case "StartRestore": value = ddc.StartRestore(); return result; case "StartBackup": value = ddc.StartBackup(); return result; case "RequestReboot": value = ddc.RequestReboot(); return result; case "StartUpgrade": value = ddc.StartUpgrade(); return result; case "GetDatabaselist": value = ddc.GetDatabaselist(); return result; case "GetProcesslist": value = ddc.GetProcesslist(); return result; case "GetCurrenttime": value = ddc.GetCurrenttime(); return result; case "GetUptime": value = ddc.GetUptime(); return result; default: result = UNDEFINED_OPERATION; return result; } } catch (Exception ex) { result = ex.Message; return result; } finally { DisplayTransmissionOnTextbox(operation, host, result); } } </code></pre> <p>Is this really a good approach of designing my interface for Client/Engine? My goal was to minimize the number of interfaces by stuffing many DDC operations, but I feel like what I'm writing is pretty dirty and can lead to problems. I would really appreciate any recommendations that can be made here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-25T08:22:46.480", "Id": "116688", "Score": "0", "body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_" } ]
[ { "body": "<p>Rather than based on return types or parameters I think it would be best to base it on the functional grouping of the operations so that those more closely related are all grouped into one contract. Much like you might consider when naming namespaces and putting classes in there. </p>\n\n<p>It's hard to know exactly from your example of what these groupings or whether even this is a good approach, however based on your existing contract I might start thinking can I seperate the point related functionality into a seperate <code>IDDCPointService</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T07:49:58.077", "Id": "25468", "Score": "0", "body": "Thank you for your response. I thought about grouping them by functional relevance myself but i was afraid of running into a problem where I have way too many operation contracts, like over 20 perhaps. Would you still recommend this approach despite the number of interfaces I may have to design?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T09:55:58.573", "Id": "25473", "Score": "0", "body": "I guess only you can really answer that. My basic thought is still to look at the functional grouping. However there's a few good discussions on SO that might help you decide further e.g. http://stackoverflow.com/questions/1929728/one-big-webservice-or-lots-of-little-ones. A good start would be to create the groupings onto paper/design and then go from there before you even code anything." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T20:10:11.207", "Id": "15652", "ParentId": "15646", "Score": "1" } } ]
{ "AcceptedAnswerId": "15652", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T12:08:53.940", "Id": "15646", "Score": "5", "Tags": [ "c#", ".net", "wcf" ], "Title": "Allowing a client and server to communicate with a DDC" }
15646
<p>I have a custom class for Smarty that was partially borrowed. This is how the only example reflects the basic idea of using it across my current project:</p> <pre><code>class Template { function Template() { global $Smarty; if (!isset($Smarty)) { $Smarty = new Smarty; } } public static function display($filename) { global $Smarty; if (!isset($Smarty)) { Template::create(); } $Smarty-&gt;display($filename); } </code></pre> <p>Then in the PHP, I use the following to display templates based on the above example:</p> <pre><code>Template::display('head.tpl'); Template::display('category.tpl'); Template::display('footer.tpl'); </code></pre> <p>I made the following example of code (see below) work across universally, so I wouldn't repeat the above lines (see 3 previous lines) all the time in each PHP file.</p> <p>I would just like to set, e.g.:</p> <pre><code>Template::defauls(); </code></pre> <p>that would load:</p> <pre><code>Template::display('head.tpl'); Template::display('template_name_that_would_correspond_with_php_file_name.tpl'); Template::display('footer.tpl'); </code></pre> <p>As you can see <code>Template::display('category.tpl');</code> will always be changing based on the PHP file, which name is corresponded with the template name, meaning, if for example, PHP file is named stackoverflow.php then the template for it would be stackoverflow.tpl.</p> <p>I've tried my solution that have worked fine but I don't like it the way it looks (the way it's structured).</p> <p>What I did was:</p> <ol> <li>Assigned in config a var and called it <code>$current_page_name</code> (that derives the current PHP page name, like this: <code>basename($_SERVER['PHP_SELF'], ".php");</code> ), which returned, for e.g.: <code>category</code>.</li> <li>In my PHP file I used <code>Template::defaults($current_page_name);</code>.</li> <li><p>In my custom Smarty class I added the following:</p> <pre><code>public static function defaults($template) { global $Smarty; global $msg; global $note; global $attention; global $err; if (!isset($Smarty)) { Templates::create(); } Templates::assign('msg', $msg); Templates::assign('note', $note); Templates::assign('attention', $attention); Templates::assign('err', $err); Templates::display('head.tpl'); Templates::display($template . '.tpl'); Templates::display('footer.tpl'); } </code></pre></li> </ol> <p>Is there a way to make it more concise and well structured?</p>
[]
[ { "body": "<p>Well, there's a few things wrong here, but let's go over it together and I'll try to steer you in the right direction. Let's start with globals. Globals are extremely bad and should be avoided at all costs. If you have a variable that needs to be available in multiple parts of your script, then you should pass that variable as a parameter to whichever function needs it, and return the modified version if applicable. Why? Well globals are an old feature that have been proven to be full of all kinds of security issues. Not to mention they are just plain impossible to track. Sure, I know where <code>$Smarty</code> came from because I saw you define it in your constructor, but lets say I'm pages into your code and see that for the first time. How am I to know where this came from? Hopefully PHP will deprecate this soon, but until then, just take my word, and that of the entire community's, and don't use globals.</p>\n\n<p>Lets take a look at your constructor. First you should know that the access parameter (public, private, or protected) should be used on every function, more accurately known as a method. This includes the constructor. By default it uses the public status, but I've heard rumors of this getting deprecated soon and it is better to go ahead and assume the default won't always be there for you. Besides, its always a good idea to explicitly define what you expect a method or property's access type to be. Second, the proper way to make a constructor is no longer to create a method with the same name as the class. This used to be the case in PHP 4 I think, but it is now deprecated. It still exists for backwards compatibility, but there's no saying how long that will last. Use the magic method <code>__construct()</code> instead. Magic meaning reserved.</p>\n\n<p>So, let's review. Globals are bad, constructors are built with <code>__construct()</code>. How then do we create a class where we have a \"global\" variable created in the class contructor? Well like this:</p>\n\n<pre><code>private $smarty;\n\npublic function __construct() {\n $this-&gt;smarty = new Smarty();\n}\n</code></pre>\n\n<p>You'll notice there's a couple of new things going on here. Hopefully you'll also notice how much cleaner this is. So, what's <code>private $smarty</code>? Its pretty much the same as <code>global $smarty</code>, except the variable isn't available globally, only within the class scope (<code>$this-&gt;smarty</code>). If we set the access parameter to public, it would be a little more like a global in that we could access it outside of the class, but in order to do so we would have to use an instance of the class like so: <code>$template-&gt;smarty</code>. That's because the variable, or, more accurately property, is associated with that class. The reason we are using a private access type her is because <code>$smarty</code> defines an interior \"property\" that should only be accessed from within the scope of the class. Sorry I can't explain that any better. Look at it like this. If I created a user class, I wouldn't want the password database to be \"public\" and available outside of the class. It is sort of the same here, except without sensitive data in the mix.</p>\n\n<p>Let's continue. Next is a static <code>display()</code> method. Static methods exist for no other purpose than to defy OOP. Some might argue that I'm wrong here, but let's break down that acronym. Object Oriented Programming. About the only thing static still has in common with OOP is that it is <em>vaguely</em> related to an object. The inner principles of OOP (encapsulation, inheritance, and polymorphism) are simply ignored by static methods. In a lot of cases you'd be better off with just a normal helper function. Assume you won't ever need static methods for the time being. It is an advanced feature of classes and isn't likely to be necessary until you have a better grasp on the whole concept. Instead, what you should do is drop the static keyword and use the class property like it was meant to be.</p>\n\n<pre><code>public function display( $filename ) {\n $this-&gt;smarty-&gt;display( $filename );\n}\n</code></pre>\n\n<p>Now, you may have started noticing a pattern here. Each of these new methods I have showed you are simply wrappers for the Smarty class. And that is because you are not doing anything yet that requires \"extending\" the Smarty class. From what I can see, you would be better of just using the smarty class directly and dropping classes altogether. But hopefully the above helped explain some of the basic concepts for you so that when you do decide to start using OOP, you have a better grasp of it.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Oh, and about your problem. The above should help you with the structure, but until you start getting into the more advanced stuff (frameworks and autoloading), this is the best solution. At least as far as I know. The only improvement I would make is to use an absolute path name instead of relative, and you can do that using the magic constant <code>__FILE__</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T09:01:25.503", "Id": "25470", "Score": "0", "body": "Thanks you, mseancole! ;) Here is the full example of my current code. http://codepad.org/nTVDHMVP. So far I have no luck applying to what you have said. If I remove `static` metod *PHP 5.4.7* throws a warning: `Strict Standards: Non-static method Template::create() should not be called statically`. If I try to do what you have mentioned (I'm not sure that I'm doing everything correctly), I get fatal errors. I will keep trying but if you have chance please take a look at my small but complete custom Smarty class and tweak few lines for me so it would be your great explanation + working example" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T09:25:04.717", "Id": "25472", "Score": "0", "body": "This is what I just tried: http://codepad.org/u98EBoSF" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T11:19:12.140", "Id": "25474", "Score": "0", "body": "Please also take a look at my today's question about `global`'s: http://stackoverflow.com/questions/12445972/stop-using-global-in-php/12446305#12446305" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T15:25:38.810", "Id": "25475", "Score": "0", "body": "@IliaRostovtsev: Well, as the error states, you are still trying to call those methods statically with the class name and scope resolution operator `::`. You should create an instance of your template class and assign it to a variable like so: `$template = new Template();`. Then you can call methods using that instance, just like you would with `$this`, for example `$template->create();`. And, as codepad as said, the required inclusion failed, and that's because `$config` is undefined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T15:35:07.813", "Id": "25476", "Score": "0", "body": "That second attempt should be asked as a second question, its completely different and could use some attention itself. Such as those properties being undefined and the continued use of globals, but I wont go into that here. As to your final question, I think that was adequately addressed in both the answers you got personally and those provided via links. You are lucky they didn't downvote that question into oblivion. As pointed out, it has been asked many times, but I believe your show of effort and knowledge helped there :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T16:07:00.307", "Id": "25477", "Score": "0", "body": "I just left `globals` on my try just because I wanted first properly construct my custom Smarty class. I will work on that! Thank you very much! I will keep updating on this in the near future! Regards, Ilia" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T00:01:54.653", "Id": "15658", "ParentId": "15648", "Score": "1" } } ]
{ "AcceptedAnswerId": "15658", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:44:54.510", "Id": "15648", "Score": "3", "Tags": [ "php", "beginner", "smarty" ], "Title": "Assigning defaults for Smarty using object-oriented style" }
15648
<p>I created a script to allow a user to drag a <code>div</code> around the page and save it's position and style to <code>localStorage</code>, and I'm wondering if there's anything I can do to make the script more efficient. I have posted the code below, but I left out the drag functionality because I'd like to work on that myself, but the rest I'd like feedback on.</p> <pre><code>$(document).ready(function () { // Load function (10 steps) function loadDiv() { $(".base").each(function () { // (1) Find each div with the class of base var id = $(this).attr("id"); // (2) Get the id from the element and set it to a variable var counter = localStorage.getItem("counter-" + id) || 0; // (3) See if counter is at 0 and get each LS key with the syntax (counter-(2)) var active = localStorage.getItem(id + "-active") || ""; // (4) Get each LS key with the syntax ((2)-active) and see if it's undefined $.each(active.split(" "), function (k, v) { var s = v.split(","); // (5) Split each variable from (4) with K = Key and V = Value if (s.length != 2) { // (6) Check if length is not equal to 2 return; // (7) Do nothing } var newElement = $("#" + s[0]).clone(); // (8) Set the element that's getting cloned to a variable newElement.attr("id", s[1]).attr("class", "drag " + id).data("id", id).appendTo("body"); // (9) Clone element }); }); dragWidget(); // (10) Initialize dragging for these elements } // Set CSS function (5 steps) function setCSS() { $(".drag").each(function () { // (1) Find all divs on the page with the class drag var id = $(this).not(".base").attr("id"); // (2) Set then id of each div that's not .base to a variable $(this).css({ "left": localStorage.getItem(id + "-x"), // (3) Retrieve localStorage item with the variable from (2) and append -x to the end to get and set left offset "top": localStorage.getItem(id + "-y"), // (4) Retrieve localStorage item with the variable from (2) and append -y to the end to get and set top offset "z-index": localStorage.getItem(id + "-z"), // (5) Retrieve localStorage item with the variable from (2) and append -z to the end to get and set the z-index }); }); } // Close function (7 steps) function closeDiv() { var id = $(this).parent().attr("id").match(/[a-zA-Z]+/g); // (1) Get only the first word from the parent element and assign it to a variable $(this).parent().remove(); // (2) Remove the parent element var active = []; // (3) Set the active variable to a blank array $($("." + id).not(".base")).each(function () { // (4) Go through every element that's not .base active.push(id + "," + $(this).attr("id")); // (5) Add each element to an array with the syntax ((1),(1)+id from element) }); active = active.join(" "); // (6) Join the array together by a space localStorage.setItem(id + "-active", active); // (7) Set the LS item with the syntax ((1)-active, (5)) } // Clone function (13 steps) function cloneDiv() { var id = $(this).attr("href").match(/[a-zA-Z]+/g); // (1) Get only the first word from the parent element and assign it to a variable var key = "counter-" + id; // (2) Set a variable with the syntax "counter-(1)" var counter = localStorage.getItem(key) || 0; // (3) Get the LS item with the name (2) and see if it's equal to 0 counter++; // (4) Add one to the counter var newElement = $("#" + id).clone(); // (5) Set clone parameters to a variable newElement.attr("id", id + counter).attr("class", "drag " + id).appendTo("body"); // (6) Duplicate the div to the body var active = []; // (7) Set the active variable to an array $($("." + id).not(".base")).each(function () { // (8) Get all elements that match ".(1)" that aren't ".base" and loop through them active.push(id + ',' + $(this).attr("id")); // (9) Add each element to an array with the syntax ((1),(1)+id from element) }); active = active.join(" "); // (10) Join the array together by a space localStorage.setItem(id + "-active", active); // (11) Set the LS item with the syntax ((1)-active, (7)) localStorage.setItem(key, counter); // (12) Set the LS item with the syntax ((2), (4)) dragWidget(); // (13) Enable dragging } // Clear localStorage (2 steps) function clearLocalstorage() { localStorage.clear(); // (1) Clear all localStorage items location.reload(); // (2) Reload the page } loadDiv(); setCSS(); $(".close").click(closeDiv); $(".nav a").click(cloneDiv); $(".clear a").click(clearLocalstorage); }); </code></pre>
[]
[ { "body": "<p>Looks ok so far. Here are some tips.</p>\n\n<h1>1)</h1>\n\n<p>Only provide comments for sections arounds complex code. Also, it's best to place comment directly above the statements and not side by side.</p>\n\n<p>Bad:</p>\n\n<pre><code>$(\".base\").each(function () { // (1) Find each div with the class of base\n var id = $(this).attr(\"id\"); // (2) Get the id from the element and set it to a variable\n</code></pre>\n\n<p>Better: </p>\n\n<pre><code>// (1) Find each div with the class of base\n$(\".base\").each(function () { \n // (2) Get the id from the element and set it to a variable\n var id = $(this).attr(\"id\"); \n</code></pre>\n\n<p>Best:</p>\n\n<pre><code>$(\".base\").each(function () { \n var id = $(this).attr(\"id\"); \n</code></pre>\n\n<h1>2)</h1>\n\n<p>Not really needed but I think you should create a function for creating the <code>active</code> string.</p>\n\n<p>Old Code:</p>\n\n<pre><code>//...\nvar active = [];\n$($(\".\" + id).not(\".base\")).each(function () {\n active.push(id + \",\" + $(this).attr(\"id\"));\n});\nactive = active.join(\" \");\n\n//...\nvar active = [];\n$($(\".\" + id).not(\".base\")).each(function () {\n active.push(id + \",\" + $(this).attr(\"id\"));\n});\nactive = active.join(\" \");\n//...\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var getActiveIdStr = function( id ){\n var active = [];\n $($(\".\" + id).not(\".base\")).each(function () {\n active.push(id + ',' + $(this).attr(\"id\"));\n });\n return active.join(\" \");\n}\n//...\ngetActiveIdStr( id );\n//...\ngetActiveIdStr( id );\n</code></pre>\n\n<h1>3)</h1>\n\n<p>Here's a tip on how to store objects to <code>localStorage</code>. The trick is to use <code>JSON.stringify</code> to set values and <code>JSON.parse</code> to retrieve values. <a href=\"https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage\">More here:</a></p>\n\n<p>Code:</p>\n\n<pre><code>var lsHelper = {};\nlsHelper.set = function (key, value) {\n if (typeof value === \"object\") {\n value = JSON.stringify(value);\n }\n localStorage.setItem(key, value);\n};\nlsHelper.get = function (key) {\n var value = localStorage.getItem(key);\n if (value &amp;&amp; value[0] === \"{\") {\n value = JSON.parse(value);\n }\n return value;\n};\n</code></pre>\n\n<h1>4)</h1>\n\n<p>The easiest way to save the positions of draggable elements is to use <code>localStorage</code> and the module <a href=\"http://docs.jquery.com/UI/Draggable\" rel=\"nofollow noreferrer\">\"Draggable\"</a> from the jQuery UI project.\nUse <code>lsHelper</code> to save the position once an element is dropped. Then when the page is refreshed, use the <code>create</code> option in <code>Draggable</code> to re-position all the draggable elements by the positions saved in <code>localStorage</code>.</p>\n\n<p>HTML Code:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/&gt;\n\n Load using Script Tag: \"http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js\"\n Load using Script Tag: \"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js\"\n\n &lt;style type=\"text/css\"&gt;\n .dragMe { width: 100px; height: 70px; background: silver; }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body style=\"font-size:62.5%;\"&gt;\n\n&lt;div id=\"draggable1\" class=\"dragMe\"&gt;1: Drag me&lt;/div&gt;\n&lt;div id=\"draggable2\" class=\"dragMe\"&gt;2: Drag me&lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>JS Code:</p>\n\n<pre><code>var ls = ls || {};\nls.set = function (key, value) {\n if (typeof value === \"object\") {\n value = JSON.stringify(value);\n }\n localStorage.setItem(key, value);\n};\nls.get = function (key) {\n var value = localStorage.getItem(key);\n if (value &amp;&amp; value[0] === \"{\") {\n value = JSON.parse(value);\n }\n return value;\n};\n\n$(function () {\n $(\".dragMe\").draggable({\n create : function (event, ui) {\n var position = ls.get(\"position:\" + $(this).attr(\"id\"));\n if(position){\n $(this).offset( position );\n }\n },\n stop : function (event, ui) { \n var currentPos = ui.helper.position();\n ls.set(\"position:\" + $(this).attr(\"id\"), currentPos);\n }\n });\n});\n</code></pre>\n\n<p>Demo here: <a href=\"http://jsfiddle.net/DLM3n/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/DLM3n/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T16:11:28.810", "Id": "25478", "Score": "0", "body": "Do you think using `regex` is fine though?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T03:44:00.443", "Id": "25487", "Score": "0", "body": "Yeah it's ok, but in `cloneDiv()` you should use `$(this).parent().attr(\"href\")` instead of `$(this).attr(\"href\")` to get the parent element." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T09:47:31.877", "Id": "15670", "ParentId": "15656", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T21:44:06.103", "Id": "15656", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Feedback on JS that drags elements around page and saves styles to localStorage?" }
15656
<p>I am trying to teach myself haskell by means of project Euler</p> <p>i sovled <a href="http://projecteuler.net/problem=9" rel="nofollow">problem #9</a> by means of this code which is on the brute force side I was wondering if there is a more elegant/haskell/efficient solution</p> <pre><code>let project_euler_9 = [(a,b,c) | c &lt;- [1..500], b &lt;- [1..c], a &lt;- [1..b], a^2 + b^2 == c^2, a+b+c==1000 ] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T07:56:17.163", "Id": "25469", "Score": "0", "body": "Your solution main not be the fastest one but it's easy to read. Here's another [solution](http://scrollingtext.org/project-euler-problem-9). Also, shouldn't you return the product of `(a*b*c)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T03:21:50.210", "Id": "25527", "Score": "0", "body": "One thing that you could do is filter the list, a, b, c, to contain only values that have a integer as the square root." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T21:25:01.770", "Id": "26321", "Score": "1", "body": "Consider the order of the conditions `a+b+c==1000` and `a^2+b^2 == c^2` and how that order might affect run time. Also, from `a+b+c == 1000` you can replace `a <- [1..b]` with `a = 1000-b-c`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T09:24:26.170", "Id": "198436", "Score": "0", "body": "There are [formulas](http://mathworld.wolfram.com/PythagoreanTriple.html) to enumerate all pythagorean triples. You can use them to reduce the search space." } ]
[ { "body": "<p>As already mentioned there are formulas for enumerating the pythagorean triples, but your solution can be made quite fast by bounding the search space more. You have already taken care of the symmetry in the solutions by letting <code>a</code> be less then <code>b</code> (<code>a &lt;- [1..b]</code>), but note that since <code>a + b + c == 1000</code>, once you know the value of <code>a</code> and <code>b</code> you know that <code>c = 1000 - a - b</code> so you only need to check that one case:</p>\n\n<pre><code>[(a,b,c) | a &lt;- [1..500], b &lt;- [1..a], let c = 1000 - a - b, a^2 + b^2 == c^2]\n</code></pre>\n\n<p>The above code runs in less then a second on my machine with GHCi.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T11:05:13.140", "Id": "16295", "ParentId": "15657", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T22:21:35.003", "Id": "15657", "Score": "5", "Tags": [ "haskell", "project-euler", "programming-challenge" ], "Title": "Project Euler #9 in haskell" }
15657
<p>Just for fun, I want to try to write this Ruby function more succinctly. I imagine it can be done, I'm just not knowledgeable enough with Ruby yet to know how. Any suggestions?</p> <pre><code> def tags return ['Cancelled'] if cancelled? tags = [] tags &lt;&lt; 'Filled' if filled? tags &lt;&lt; 'In Progress' if in_progress? tags end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T12:31:45.963", "Id": "25460", "Score": "3", "body": "@Mark: The question is indeed in the frontier with codereview. But this thing is, a code review is usually broader, on longer code that may have many things to address. Here is just \"what's the best way to build an array with conditional elements?\". Imo that's ok for SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T12:48:02.460", "Id": "25461", "Score": "0", "body": "@MarkThomas, I knew but I forgot. Thanks for the reminder." } ]
[ { "body": "<p>Functional approach:</p>\n\n<pre><code>def tags\n if cancelled?\n [\"Cancelled\"]\n else\n [(\"Filled\" if filled?), (\"In Progress\" if in_progress?)].compact\n end\nend\n</code></pre>\n\n<p>Ideas behind the snippet:</p>\n\n<ul>\n<li>Don't perform imperative side-effects on arrays (unless performance is a problem, not the case here).</li>\n<li>Use the pattern: array of \"nilable\" expressions + compact to build arrays with conditional elements.</li>\n<li>Minimize the use of inline conditional statements, they make a function harder to understand. They are ok as guards (early exit of functions), but not here. Note that I do use inline <code>if</code>s, but they are expressions, not statements; more orthodox -but also more verbose- would be <code>(filled? ? \"Filled\" : nil)</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T11:50:33.970", "Id": "15661", "ParentId": "15660", "Score": "19" } }, { "body": "<p>Not exactly the same, but here's another idea:</p>\n\n<pre><code>def tags\n [ :cancelled?, :filled?, :in_progress? ].map do |m|\n m.to_s if send( m )\n end.compact\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:56:05.123", "Id": "25462", "Score": "0", "body": "LOL, I thought of the same thing. It can get closer in Rails (or by requiring `active_support`) if you add `.titleize` to the `m.to_s`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T12:33:25.480", "Id": "15662", "ParentId": "15660", "Score": "2" } }, { "body": "<pre><code>def tags\n if cancelled? then [\"Cancelled\"]\n else [*(\"Filled\" if filled?), *(\"In Progress\" if in_progress?)]\n end\nend\n</code></pre>\n\n<p>If you design your code so that <code>filled?</code> and <code>in_progress?</code> be <code>false</code> whenever <code>cancelled?</code> is <code>true</code>, then the logic will be much prettier:</p>\n\n<pre><code>def tags\n [\n *(\"Cancelled\" if cancelled?),\n *(\"Filled\" if filled?),\n *(\"In Progress\" if in_progress?),\n ]\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:22:22.937", "Id": "25463", "Score": "1", "body": "I think this is the best answer, although what I actually ended up doing was a slight variation on your first suggestion. First line: `return ['Cancelled'] if cancelled?`, second line: `[*(\"Filled\" if filled?), *(\"In Progress\" if in_progress?)]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:25:43.233", "Id": "25464", "Score": "1", "body": "The splats (`*`) here are superfluous and can be removed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:28:47.827", "Id": "25465", "Score": "1", "body": "@AndrewMarshall You would be left with `nil` if you didn't have the splats. That's the whole point of this answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T13:31:13.173", "Id": "25466", "Score": "2", "body": "@sawa Whoops I thought there was a `compact` in there (which I would prefer anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T22:59:45.567", "Id": "57189", "Score": "1", "body": "@sawa - I have only seen the splat operator in method definitions like `def foo(*args)`, for example. I never knew it can do this. Can you give more info about it (a link?)? Can we say - if you have conditional values in an array, put a splat before them to eliminate nil values?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T12:36:08.807", "Id": "15663", "ParentId": "15660", "Score": "11" } } ]
{ "AcceptedAnswerId": "15663", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T11:10:51.337", "Id": "15660", "Score": "14", "Tags": [ "ruby" ], "Title": "Is there a more succinct way to write this Ruby function?" }
15660
<p>I'm about a week into learning pdo. I've created, with help from an example online, a database connection function. I have a config file with all my info (username, pass, database, host) and a function inside a file called <code>db.php</code>. Everything works great with the function below. </p> <p>Though, I have to put <code>dataConnect()</code> on the top of every page that uses <code>$dbo</code>. Since the function is included in my db.php file, I was hoping that the file was the only thing I needed to include on the page: not both the <code>db.php</code> and <code>dataConnect()</code>.</p> <p>I've been searching online for a better way to do this function but most of the db examples are single use examples.</p> <p>Also, having the variables from the config file as global in the function... I'm assuming is a bad thing. I'm hoping someone can help or let me know that this is a good function.</p> <pre><code>require('config.php'); function dataConnect() { try { global $dbo; global $dbname; global $dbuser; global $dbpass; $info['dbhost_name'] = $dbserver; $info['database'] = $dbname; $info['username'] = $dbuser; $info['password'] = $dbpass; $dbConnString = "mysql:host=" . $info['dbhost_name'] . "; dbname=" . $info['database']; $dbo = new PDO($dbConnString, $info['username'], $info['password'], array(PDO::ATTR_PERSISTENT =&gt; true)); $dbo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); $dbo-&gt;exec("SET CHARACTER SET utf8"); } catch(PDOException $e) { header("Location:$basehttp/error"); exit(); } } </code></pre> <p>Thanks for your help!</p>
[]
[ { "body": "<p>Globals are indeed a bad thing. They are old and full of security issues as well as being nearly impossible to debug. Stay away from them at all costs. Instead, pass those variables as a parameter into any function that needs them and have the function return any modifications if necessary. Once you start learning OOP then you can use class properties in place of globals, but parameter injection is the only solution for procedural programming. Well, you could also use constants, but you don't want to go flashing your password into the global scope that way. At least, I'm pretty sure that is a bad idea. It sounds bad... My experience with security and SQL databases is a bit limited, so you might want clarification here. Database names and non-sensitive information should make fine constants though.</p>\n\n<p>Speaking of constants, typically that is what config files are for. For storing site constants so that they can be reused. You <code>define()</code> a constant by giving it a name, conventionally in caps separated by underscores, and a value and use it almost the same way as a variable, except without the <code>$</code>. For example:</p>\n\n<pre><code>define( 'DB_NAME', 'name' );\n//implementation\n$info[ 'database' ] = DB_NAME;\n</code></pre>\n\n<p>Another problem here is that you are not using those globals even though you went to all the trouble of making them. Instead, you immediately wrap them into an associative array. This seems kind of redundant. What's wrong with using the variables as they are? You don't appear to be using that <code>$info</code> array anywhere else and besides adding clutter, you are just making your code harder to read by using longer instances of the same data.</p>\n\n<p>Finally, in regards to your problem, you could use your .htaccess file to advantage, but this really depends on the situation. I would not use this for database connections as it would enforce that connnection on EVERY page, which does not seem necessary. It would be helpful in including the config file in every page though, which is why I mention it.</p>\n\n<pre><code>php_value auto_prepend_file \"config.php\"\n</code></pre>\n\n<p>As I said, I would not recommend the above for database connections. If you have a number of pages that require a database connection, I would use a \"template\" to create this connection, then use specific \"views\" to do certain tasks. This way you only have to write the code once and you can dynamically change which action is performed. For instance, here is an extremely basic, barebone example. Please don't just copy-paste this, its for demonstration purposes only. Extrapolate from it.</p>\n\n<p><strong>Template</strong></p>\n\n<pre><code>&lt;?php\n//create db connection\n$db;//db should be available in local scope\ninclude $_GET[ 'view' ] . '.php';\n?&gt;\n</code></pre>\n\n<p><strong>Sample View</strong></p>\n\n<pre><code>&lt;?php\n$db-&gt;stuff();//do some stuff with db\n//print results\n?&gt;\n</code></pre>\n\n<p>The template is the page you would call, but a GET parameter would define what action to perform by loading another page with the database specific actions to take. Whatever variables are in the local scope in the template will also be available in the local scope on the view. Which is why we are able to use the <code>$db</code> as if it were a global. Though this is typically frowned upon because, just like globals, it is hard to figure out where those variables are coming from without the proper context. Again, this is just to give you an idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T04:45:04.860", "Id": "25528", "Score": "0", "body": "Thanks for the feedback! I've made some changes you've listed in your post. Now the only global is global $dbo; I've used your define( 'DB_NAME', 'name' ); in my config matching them in the db.php file to the $info[]. Everything seem to work great. I'm hoping that this will do the trick. Being that I'm using $dbo throughout the script to connect to the database, being global (I hope) isn't a bad thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:01:29.103", "Id": "25549", "Score": "0", "body": "@JimK: Globals are always bad. You could go the rest of your career without ever needing them. You can try converting it to a SESSION variable instead, `$_SESSION[ 'dbo' ] = $dbo;`. This will make it available on every page, all you have to do is make sure you have a session started first (should be the very first thing you do to avoid accidental whitespace). Just remember, you don't need to start the session if one already exists from a page that is already loaded, this will throw errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T17:58:57.847", "Id": "25568", "Score": "0", "body": "mseancole thanks for the feedback. I've found a great example using classes, so I'm going to take a stab at that and hopefully I can get this global thing nipped in the bud!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T04:51:30.450", "Id": "15667", "ParentId": "15666", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T01:02:02.763", "Id": "15666", "Score": "2", "Tags": [ "php" ], "Title": "Better Database Connection Function" }
15666
<p>I have a set of Service, and I want to partition them into ServiceClass, and have a reference from a Service to the Service class its belong. I am storing the reference in <code>Dictionary&lt;Service, ServiceClass&gt;</code>.</p> <p>In the code below, I want to split into five service classes. I feel the code below is not well written, such as the naming of variable, but I am not sure how to improve it, can anyone help?</p> <pre><code>int group = 5; List&lt;Service&gt; service = FileIO.ReadFeatureFile(@"D:\C Drive\Desktop\input.txt"); int numPerClass = service.Count / group; Dictionary&lt;Service, ServiceClass&gt; ServiceToServiceClass = new Dictionary&lt;Service, ServiceClass&gt;(); for (int i = 0; i &lt; group - 1;i++ ) { List&lt;Service&gt; serviceGrp = service.GetRange(0, numPerClass); ServiceClass sc=new ServiceClass(serviceGrp); foreach(Service service1 in serviceGrp) { ServiceToServiceClass.Add(service1, sc); } service.RemoveRange(0, numPerClass); } ServiceClass sc1 = new ServiceClass(service); foreach (Service service1 in service) { ServiceToServiceClass.Add(service1, sc1); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T20:40:31.303", "Id": "25482", "Score": "0", "body": "For naming guidelines check out microsofts link at http://msdn.microsoft.com/en-nz/library/ms229002%28v=vs.100%29.aspx. That should help you tidy up your code a bit." } ]
[ { "body": "<p>First off, as dreza said, work on your variable names. Secondly, you should really think about using more than one method for solving these types of problems.</p>\n\n<p>All of my suggestions are assuming this is inside a class meant to hold this information.</p>\n\n<p>Now to your code.</p>\n\n<p>The line int group = 5; should be a constant. I would also rename it to something like numberOfServiceGroups. So the code line looks like:</p>\n\n<pre><code>const int numberOfServiceGroups = 5;\n</code></pre>\n\n<p>I would move the dictionary to a class variable and instantiate it in the constructor. I would also rename it to something like _<em>serviceLookup. The _</em> signifying it is a class variable</p>\n\n<p>Instead of using GetRange and RemoveRange, I would change it to use the linq statements Skip([int items]).Take([int items]) and because you are using a for loop, the Skip count can be calculated:</p>\n\n<pre><code>for (var i = 0; i &lt; numberOfServiceGroups; i++)\n{\n var servicesToProcess = service.Skip(i * servicesPerGroup).Take(servicesPerGroup);\n // More on this in a minute\n}\n</code></pre>\n\n<p>The nice thing about Take() is that it will not blow-up if you go over bounds, it will just return what is left. Doing this will eliminate the need to have the catch loop at the end of your method.</p>\n\n<p>I would move the processing of the services into the group to another method. This reduces nesting.</p>\n\n<pre><code>private void ProcessGroup(IList&lt;Service&gt; services)\n{\n var serviceClass = new ServiceClass(services);\n foreach (var currentService in services)\n {\n _serviceLookup.Add(currentService, serviceClass);\n }\n}\n</code></pre>\n\n<p>So your method now looks like:</p>\n\n<pre><code>private void Group()\n{\n const int numberOfServiceGroups = 5;\n\n List&lt;Service&gt; services = FileIO.ReadFeatureFile(@\"D:\\C Drive\\Desktop\\input.txt\");\n var servicesPerGroup = service.Count/numberOfServiceGroups;\n var serviceToServiceClass = new Dictionary&lt;Service, ServiceClass&gt;();\n\n for (var i = 0; i &lt; numberOfServiceGroups; i++)\n {\n var servicesToProcess = services.Skip(i * servicesPerGroup).Take(servicesPerGroup);\n ProcessGroup(servicesToProcess.ToList());\n }\n}\n</code></pre>\n\n<p>And your class:</p>\n\n<pre><code>public class ClassName\n{\n public IDictionary&lt;Service, ServiceClass&gt; _serviceLookup;\n\n public ClassName()\n {\n _serviceLookup = new Dictionary&lt;Service, ServiceClass&gt;();\n } \n\n private void Group()\n {\n const int numberOfServiceGroups = 5;\n\n List&lt;Service&gt; services = FileIO.ReadFeatureFile(@\"D:\\C Drive\\Desktop\\input.txt\");\n var servicesPerGroup = service.Count/numberOfServiceGroups;\n\n for (var i = 0; i &lt; numberOfServiceGroups; i++)\n {\n var servicesToProcess = services.Skip(i * servicesPerGroup).Take(servicesPerGroup);\n ProcessGroup(servicesToProcess.ToList());\n }\n }\n\n private void ProcessGroup(IList&lt;Service&gt; services)\n {\n var serviceClass = new ServiceClass(services);\n foreach (var currentService in services)\n {\n _serviceLookup.Add(currentService, serviceClass);\n }\n }\n}\n</code></pre>\n\n<p>This should be a good start. I see a few more things I'd like to do, but they are beyond this scope.</p>\n\n<p>Also note, I have not tested this due to missing classes / information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T05:48:43.803", "Id": "25491", "Score": "0", "body": "I have one question, what is the advantage of using IList<Service> compare to List<Service>? IDictionary<Service, ServiceClass> compare to Dictionary? And var compare to respective class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T16:03:13.913", "Id": "25515", "Score": "0", "body": "I make it a habit of using interfaces because it removes alot of the fluff from the List<T> class: Interface http://msdn.microsoft.com/en-us/library/5y536ey6.aspx Class http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx. Here's a decent article on why you should code to interfaces: http://www.fatagnus.com/program-to-an-interface-not-an-implementation/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T03:57:59.740", "Id": "15676", "ParentId": "15672", "Score": "5" } } ]
{ "AcceptedAnswerId": "15676", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T15:03:53.323", "Id": "15672", "Score": "4", "Tags": [ "c#", "object-oriented" ], "Title": "Divide List into groups" }
15672
<p>I've prepared a function using cURL to get a remote file to the local storage:</p> <pre><code>/** * cURL - Get Remove File * * Function using CURL the get a remote file to the local storage. * * @param str $url Full remote URL * @param str $xml_path Internal path to the storage the file * @param str $xml_file Filename of the xml file to save * @param arr $access Access credentials (usr;pwd) * * @return bollean */ function get_remote_file($url, $xml_path, $xml_file, $access = null) { $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_HEADER, 0); curl_setopt($curl_handle, CURLOPT_URL, $url); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,true); if ($access) { curl_setopt($curl_handle, CURLOPT_USERPWD, $access["usr"].":".$access["pwd"]); } curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); $buffer = curl_exec($curl_handle); curl_close($curl_handle); if ($buffer != false) { file_put_contents($xml_path.$xml_file, $buffer); return true; } return false; } </code></pre> <p>While is working fine, even with password protected files, I'm not too comfortable with <a href="http://php.net/manual/en/book.curl.php" rel="nofollow">CURL</a>, so I wonder if this can be optimized or improved.</p>
[]
[ { "body": "<p>I'm not very familiar with cURL either, but looking at the documentation I noticed a <a href=\"http://www.php.net/manual/en/function.curl-setopt-array.php\" rel=\"nofollow\"><code>curl_setopt_array()</code></a> function that may be worth looking into.</p>\n\n<pre><code>$options = array(\n CURLOPT_HEADER =&gt; FALSE,\n CURLOPT_URL =&gt; $url,\n //etc...\n);\n\ncurl_setopt_array( $curl_handle, $options );\n</code></pre>\n\n<p>Looking at the documentation for <code>curl_exec()</code> shows that the only time its output will be FALSE is on failure. The only time it is really necessary to compare a value explicitly with a boolean is if that value will at some point be a boolean and at all other times won't, but may be mistaken for it (0, '', 'false', etc...). However, at this point you would then use absolute equality comparison instead of a loose one. For instance, the below example will output \"asdf\", \"false\", '', and 0 from the first if statement, but the second and third if statements will only ever output \"asdf\". This is because the first if statement uses an absolute, or strict, comparison to the boolean. The third if statement shows a cleaner way of doing the second. Any variable you can loosely compare with a boolean, can loosely be used as a boolean, so there's no need to type out the actual comparison. I would use that last if statement because its not likely you want to create an empty file, and unless you have a file with only a \"false\" value in it, then you are not likely to notice the difference.</p>\n\n<pre><code>$buffer = array( FALSE, 'asdf', 'false', '', 0 );\n\nforeach( $buffer AS $test ) {\n if( $test !== FALSE ) {//absolute\n var_dump( $test );\n }\n if( $test != FALSE ) {//loose\n var_dump( $test );\n }\n if( $test ) {//another way of writing loose\n var_dump( $test )\n }\n}\n</code></pre>\n\n<p>The only other thing I would suggest here is that you verify that your <code>$xml_file</code> exists before trying to write to it.</p>\n\n<pre><code>if( $buffer &amp;&amp; is_file( $xml_path . $xml_file ) ) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T09:47:00.657", "Id": "25537", "Score": "0", "body": "Thank you for the analisys, I'll be looking into this as to ascertain the improvement :) About the `file_put_contents`, the goal is actually to create or overwrite the existent file, hence the reason as to why I'm not confirming if it exists, leaving the [default action of this function](http://php.net/manual/en/function.file-put-contents.php) taking place. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T13:44:05.273", "Id": "15682", "ParentId": "15673", "Score": "2" } } ]
{ "AcceptedAnswerId": "15682", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T19:21:44.297", "Id": "15673", "Score": "2", "Tags": [ "php", "curl" ], "Title": "Getting a remote file to local storage" }
15673
<p>Does this looks ok to everyone?</p> <pre><code>NSFetchRequest *oldFetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *oldEntryEntity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:oldContext]; [oldFetchRequest setEntity:oldEntryEntity]; int numberOfEntries = [oldContext countForFetchRequest:oldFetchRequest error:nil]; int batchSize = 10; [oldFetchRequest setFetchBatchSize:10]; int offset = 0; while (numberOfEntries - offset &gt; 0) { [oldFetchRequest setFetchOffset:offset]; NSError *error; NSArray *entries = [oldContext executeFetchRequest:oldFetchRequest error:&amp;error]; for (NSManagedObject *entry in entries) { Entry *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry" inManagedObjectContext:newContext]; [newEntry setupCreationDate:[entry valueForKey:@"creationDate"] withSave:NO]; newEntry.entryID = [entry valueForKey:@"entryID"]; NSMutableOrderedSet *newMediaSet = [[NSMutableOrderedSet alloc] init]; NSOrderedSet *mediaSet = [entry valueForKey:@"media"]; int i = 0; for (NSManagedObject *media in mediaSet) { Media *newMedia = [NSEntityDescription insertNewObjectForEntityForName:@"Media" inManagedObjectContext:newContext]; newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1]; //Potentially needs changing newMedia.mediaID = [Entry generateString]; MediaImageData *imageData = [NSEntityDescription insertNewObjectForEntityForName:@"MediaImageData" inManagedObjectContext:newContext]; if ([newMedia.type isEqualToString:@"Image"]) { imageData.data = [media valueForKey:@"originalImage"];; } else if ([newMedia.type isEqualToString:@"Movie"]) { NSURL *movieURL = [NSURL URLWithString:newMedia.movie]; MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL]; [moviePlayer stop]; UIImage *screenshot = [moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame]; [moviePlayer stop]; imageData.data = UIImageJPEGRepresentation(screenshot, 1.0); } newMedia.imageData = imageData; newMedia.entry = newEntry; [newMediaSet addObject:newMedia]; i++; } newEntry.media = newMediaSet; } [newContext save:&amp;error]; offset = offset + batchSize; } </code></pre>
[]
[ { "body": "<p>The first big problem I see with this code is here:</p>\n\n<pre><code>int i = 0;\n\nfor (NSManagedObject *media in mediaSet) {\n // stuff\n newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1];\n // more stuff\n i++;\n}\n</code></pre>\n\n<p>First of all, if <code>positionInEntry</code> is a property intended to hold some sort of index or something for your <code>Media</code> class, then it should be of the same type that collections tend to use for their indexing: <code>NSUInteger</code>. Although... the object itself probably doesn't need to know what position it is in the array, and as this could change, it's probably best to just not have this property at all.</p>\n\n<p>Next, <code>i</code> is defined as an <code>int</code>, and <code>1</code> is an <code>int</code> literal, so we're creating the <code>NSNumber</code> in the wrong way. We should be doing this (if we're going to continue to keep this <code>positionInEntry</code> property):</p>\n\n<pre><code>newMedia.positionInEntry = [NSNumber numberWithInt:i + 1];\n</code></pre>\n\n<p>Finally, we really shouldn't be doing this in this manner at all. If we want to know what index we're working with, we should use a traditional <code>for</code> loop.</p>\n\n<pre><code>for (int i = 0; i &lt; [mediaSet count]; ++i) {\n NSManagedObject *media = mediaSet[i];\n // stuff\n newMedia.positionInEntry = @(i+1);\n // more stuff\n}\n</code></pre>\n\n<p>However, there's a slightly better option.</p>\n\n<p>It is good to use a <code>forin</code> loop where we can, because this actually is faster than a traditional <code>for</code> loop in Objective-C. We still don't want to rely on <code>i</code> however, for a couple of reasons, right now, I'll say, the most important of which is readability. But there is this option:</p>\n\n<pre><code>for (NSManagedObject *media in mediaSet) {\n // stuff\n\n NSUInteger index = [mediaSet indexOfObject:media];\n\n newMedia.positionInEntry = @(index + 1);\n\n // more stuff\n}\n</code></pre>\n\n<p>We can call <code>indexOfObject:</code> on an <code>NSArray</code> and it will return the first index it finds that object at. As a note, this method returns <code>NSNotFound</code> if the object isn't found in the array, but in a <code>forin</code> loop, this should hopefully never be the case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-16T03:12:04.030", "Id": "54340", "ParentId": "15674", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T21:46:13.720", "Id": "15674", "Score": "2", "Tags": [ "objective-c", "ios" ], "Title": "Core Data code for manually creating a lot of entries from old ones" }
15674
<p>I'm architecting a basic SSO solution to pass a user between two sites.</p> <p>Site A handles authentication against a user database and then generates links to Site B which pass a HMAC token comprising a nonce and the user's ID. The HMAC is hashed with a shared secret between the two sites.</p> <p>The following shows the token generation in PHP.</p> <pre><code>$sso['nonce'] = hash('sha1', rand() ); $sso['sharedKey'] = 'someVerySecureString'; $sso['hmacKey'] = hash_hmac ( 'sha256', $test['sharedKey'] , $test['nonce'] ); $sso['userId'] = '123456'; $sso['hmac'] = hash_hmac ( 'sha256', $test['userId'] , $test['hmacKey'] ); $sso['url'] = '/?id=' . urlencode($test['userId']) . '&amp;nonce=' . urlencode($test['nonce']) . '&amp;hmac=' . urlencode($test['hmac']); </code></pre> <p>I'm using the nonce to HMAC the key before transmission.</p> <p>This is the PHP function on Site B to validate the token:</p> <pre><code>function validateSSOToken($sharedKey='someVerySecureString') { $isValid = false; if ( isset( $_GET['id'] ) &amp;&amp; isset( $_GET['nonce'] ) &amp;&amp; isset( $_GET['hmac'] ) &amp;&amp; strlen( $_GET['nonce'] ) == 40 &amp;&amp; strlen( $_GET['hmac'] ) == 64) { $userId = $_GET['id']; $nonce = $_GET['nonce']; $hmac = $_GET['hmac']; // Sign the key with the nonce to get the tmp key $hmacKey = hash_hmac ( 'sha256', $sharedKey, $nonce ); // rebuild the string to sign $localHmac = hash_hmac ( 'sha256', $userId , $hmacKey ); // Compare against the incoming key $isValid = $localHmac == $hmac ? true : false; } return $isValid; } </code></pre> <p>I'm aware of the replay attack vector and will be addressing it in due course.</p> <p>Could you advise if this is secure? Is there anything else I might look at considering to achieve the same goal?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T14:00:52.267", "Id": "25505", "Score": "1", "body": "You are not likely to get too many answers to this as a number of these security questions seem to go unanswered. If after a few days you have not received any helpful advice, I would suggest posting this again on SO with an explanation that no answers were forthcoming here. They may move it here again, but it should still be visible from SO and you might get better answers that way. That being said, you can combine that `isset()` check. `isset( $_GET[ 'id' ], $_GET[ 'nonce' ], $_GET[ 'hmac' ] )`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T19:26:44.623", "Id": "25522", "Score": "0", "body": "Thanks for the honest apprisal. First time using CR so I hope I get some feedback. And thanks for the tip on isset(). I've been developing in PHP for almost 10 years now and never realised you could validate multiple vars that way. Guess that just goes to show that it's always worth reading the manual even for functions you *think* you know!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-06T15:29:07.070", "Id": "46568", "Score": "0", "body": "So does the user exist on both sites? or do those sites share the 'user database'?" } ]
[ { "body": "<p>This looks good. </p>\n\n<p>I do almost exactly the same thing as a password reset mechanism. I am including it here in case it will help you with adding a timer to help prevent replay attacks. </p>\n\n<p>The user receives an email with a link to click to reset their password (the <code>$oldpassword</code> is the nonce because once the password is changed once, it is not valid anymore and the HMAC key is the old password salt (used by the php <code>crypt</code> function)).</p>\n\n<pre><code>$time = time();\n$userid = $user-&gt;id;\n$oldpassword = hash('sha256', $password_info['Password']);\n$token = \"t={$time}&amp;i={$userid}&amp;o={$oldpassword}\";\n$verification = hash_hmac('sha256', $token, $password_info['Salt']);\n\n$newpasswordurl = Router::url('user_r')-&gt;uri(array(\n 't' =&gt; $time,\n 'i' =&gt; $userid,\n 'o' =&gt; $oldpassword,\n 'v' =&gt; $verification,\n));\n</code></pre>\n\n<p>The validation is similar.</p>\n\n<pre><code>$userid = $input['i'];\n$time = $input['t'];\n$expire_time = date_create_from_format('U', $input['t'])-&gt;add(date_interval_create_from_date_string(self::$settings['ResetPassword']['LinkValidityTime']));\n$oldpassword = $input['o'];\n$hash = $input['v'];\n\n$p_info = self::getPasswordParts($OldPassword);\n\n$token = \"t=$time&amp;i=$UserID&amp;o=$oldpassword\";\n$correct_hash = hash_hmac('sha256', $token, $p_info['Salt']);\n\nif ( ($hash != $correct_hash) || ($oldpassword != hash('sha256', $p_info['Password'])) ) {\n throw new ChangePasswordException(\"That password link is invalid, has expired or has been used.\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-03T22:23:54.283", "Id": "32205", "ParentId": "15677", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T09:44:25.490", "Id": "15677", "Score": "8", "Tags": [ "php", "security" ], "Title": "Is this the correct way to implement a HMAC token system?" }
15677
<p>Recently I've tried to teach myself basic things about MySQL databases, however I received some help on <a href="https://stackoverflow.com/questions/12415548/i-need-a-good-mysql-database-structure">Stack Overflow</a> with creating a good database structure trying to avoid redundancy as much as possible.</p> <p>I finally came up with the database structure below and would like to know if that's the way to go and if not, what you would improve/change to it.</p> <pre><code>CREATE TABLE artists ( artist_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, artist_name varchar(100) UNIQUE, artist_aka varchar(255) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE labels ( label_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, label_name varchar(100) UNIQUE, label_aka varchar(255) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE producers ( producer_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, producer_forename varchar(100), producer_nickname varchar(100) UNIQUE, producer_lastname varchar(100) ) ENGINE = 'InnoDB'; CREATE TABLE years ( year_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, year_value varchar(4) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE genres ( genre_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, genre_name varchar(10) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE flags ( flag_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, flag_name varchar(12) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE tags ( tag_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, tag_name varchar(16) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE sources ( source_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY, source_name varchar(30) UNIQUE ) ENGINE = 'InnoDB'; CREATE TABLE riddims ( riddim_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, riddim_name varchar(40) UNIQUE, riddim_aka varchar(255) UNIQUE, genre_fk TINYINT, youtube varchar(11) UNIQUE, image varchar(11) UNIQUE, FOREIGN KEY (genre_fk) REFERENCES genres(genre_id) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = 'InnoDB'; CREATE TABLE tunes ( tune_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, riddim_fk INT DEFAULT NULL, artist_fk INT DEFAULT NULL, tune_name varchar(60) DEFAULT NULL, tune_aka varchar(255) DEFAULT NULL, label_fk SMALLINT DEFAULT NULL, producer_fk SMALLINT DEFAULT NULL, year_fk TINYINT DEFAULT NULL, lyrics TEXT DEFAULT NULL, flag_fk TINYINT, tag_fk SMALLINT, source_fk TINYINT, last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (riddim_fk) REFERENCES riddims(riddim_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (artist_fk) REFERENCES artists(artist_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (producer_fk) REFERENCES producers(producer_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (year_fk) REFERENCES years(year_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (flag_fk) REFERENCES flags(flag_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (tag_fk) REFERENCES tags(tag_id) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (source_fk) REFERENCES sources(source_id) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = 'InnoDB'; </code></pre> <p>Later the website will contain information about "riddims" (rythms), artists that have a song on that riddim, songnames, release years etcetera. I guess the best way to show what its supposed to do is showing you a first, unfinished version of the <a href="http://riddimbase.net/" rel="nofollow noreferrer">website</a>.</p>
[]
[ { "body": "<p>Just a couple of suggestions.</p>\n\n<p>First, <code>artists</code> and <code>producers</code> are both <code>persons</code> and a person can be both an artist and a producer (even on their own songs).</p>\n\n<p>Second, more than one <code>persons</code> can work together on a song, but in lots of different <code>roles</code> (backup musician, backup singer, \"featuring\", \"uncredited\", or as a member of a <code>groups</code>). So <code>performers</code> and <code>roles</code> would probably look something like:</p>\n\n<pre><code>CREATE TABLE roles (\n role_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n description varchar(100) not null\n) ENGINE = 'INNODB';\n\nCREATE TABLE performers (\n performer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n tune_fk INT NOT NULL,\n person_fk INT NOT NULL,\n role_fk INT NOT NULL,\n FOREIGN KEY (tune_fk) REFERENCES tunes(tune_id) ON DELETE SET NULL ON UPDATE CASCADE,\n FOREIGN KEY (person_fk) REFERENCES persons(person_id) ON DELETE SET NULL ON UPDATE CASCADE,\n FOREIGN KEY (role_fk) REFERENCES roles(role_id) ON DELETE SET NULL ON UPDATE CASCADE,\n) ENGINE = 'InnoDB';\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T12:42:10.873", "Id": "25503", "Score": "0", "body": "I was going to add a few more details like \"birthdate\", \"day of death\" and \"birthdates\" to artists later on, might aswell take ur suggestion into consideration, thanks. Though my question is more about the efficiency of my database layout (maybe I didn't state that clear enough, apologies); is it a good structure to work with when each (major) table will have between 50.000 and 100.000 entries at the beginning, growing consistently per week? Is it a good structure when there's a lot of searches (for \"tune\", \"artist\" and \"riddim\") performed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T14:09:35.600", "Id": "25506", "Score": "0", "body": "There isn't anything terribly complicated about your design and all of the links from one table to another are done through integer keys so it seems very unlikely that you will have any major performance issues." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T14:22:44.087", "Id": "25507", "Score": "0", "body": "Tahnks, I was just very unsure about this as I'm pretty new to databases. I just added your earlier suggestion and stick with that database layout now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T12:21:26.137", "Id": "15680", "ParentId": "15678", "Score": "4" } } ]
{ "AcceptedAnswerId": "15680", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T10:44:47.770", "Id": "15678", "Score": "6", "Tags": [ "sql", "mysql" ], "Title": "Music categorization database" }
15678
<p>I implemented a fixed sized priority queue. How can I improve my code?</p> <pre><code>public class FixedSizedPriorityQueue { private final int capacity; private boolean sorted = false; private double smallest = Double.POSITIVE_INFINITY; private ArrayList&lt;Double&gt; list; protected static final Comparator&lt;Double&gt; comparator = new Comparator&lt;Double&gt;() { @Override public int compare(Double o1, Double o2) { return o2.compareTo(o1); } }; public FixedSizedPriorityQueue(int capacity) { this.capacity = capacity; list = new ArrayList&lt;Double&gt;(capacity); } public void add(double value) { if (list.size() &lt; capacity) { list.add(value); sorted = false; if (value &lt; smallest) { smallest = value; } } else { if (value &gt; smallest) { if (!sorted) { Collections.sort(list, comparator); sorted = true; } list.set(capacity - 1, value); if (list.get(capacity - 2) &gt; value) { smallest = value; } else { smallest = list.get(capacity - 2); sorted = false; } } } } public int getSize() { return list.size(); } public Double poll() { if (list.size() == 0) return null; if (!sorted) { Collections.sort(list, comparator); sorted = true; } Double value = list.get(0); list.remove(0); if (list.size() == 0) smallest = Double.POSITIVE_INFINITY; return value; } public void print() { for (int i = 0; i &lt; list.size(); i++) { System.out.println(i + ": " + list.get(i)); } System.out.println("Smallest: " + smallest); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T06:29:56.600", "Id": "25532", "Score": "2", "body": "You may want to implement the [Queue](http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html) interface as well" } ]
[ { "body": "<ol>\n<li><p>The following is used multiple times and it could be extracted out:</p>\n\n<pre><code>if (!sorted) {\n Collections.sort(list, comparator);\n sorted = true;\n}\n</code></pre>\n\n<p>to a helper method:</p>\n\n<pre><code>private void sortIfNeccessary() {\n if (sorted) {\n return;\n }\n Collections.sort(list, comparator);\n sorted = true;\n}\n</code></pre>\n\n<p>Note the <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a>.</p></li>\n<li><p><code>List.remove</code> returns the removed elements.</p>\n\n<pre><code>Double value = list.get(0);\nlist.remove(0);\n</code></pre>\n\n<p>The code above could be simplified to this:</p>\n\n<pre><code>final Double value = list.remove(0);\n</code></pre></li>\n<li><p>The comparator could be substituted with the <code>reverseOrder</code> method/comparator:</p>\n\n<pre><code>Collections.sort(list, Collections.reverseOrder());\n</code></pre></li>\n<li><p>The <code>list</code> could be <code>final</code>. <code>final</code> helps readers, because they know that the reference always points to the same instance and it doesn't change later. <a href=\"https://softwareengineering.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods\">https://softwareengineering.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods</a> but you can find other questions on Programmers.SE in the topic.</p></li>\n<li><p>Furthermore, its type could be only <code>List&lt;Double&gt;</code> instead of <code>ArrayList&lt;Double&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p>The <code>print</code> method violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Other clients may want to write the elements to a log file or a network socket so you shouldn't mix the queue logic with the printing. I'd consider creating a <code>List&lt;Double&gt; getElements</code> method (which would return a copy or unmodifiable version of <code>list</code> to make sure that malicious clients does not modify the inner state of the queue) or providing an iterator to clients and move the <code>print</code> method to another class. </p></li>\n<li><p>Does it make sense to create a queue with negative capacity? If not, check it and throw an <code>IllegalArgumentException</code>. \nActually, it does not work with capacities less than 2. It throws a <code>java.lang.ArrayIndexOutOfBoundsException: -1</code> when the capacity is 1 because of the <code>list.get(capacity - 2)</code> call. (<em>Effective Java, Second Edition</em>, <em>Item 38: Check parameters for validity</em>)</p>\n\n<pre><code>public FixedSizedPriorityQueue(final int capacity) {\n if (capacity &lt; 2) {\n throw new IllegalArgumentException(\"Illegal capacity: \" + capacity);\n }\n ...\n}\n</code></pre></li>\n<li><p>Instead of </p>\n\n<pre><code>if (list.size() == 0) ...\n</code></pre>\n\n<p>you could use </p>\n\n<pre><code>if (list.isEmpty()) ...\n</code></pre>\n\n<p>It's the same but easier to read.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T21:00:21.133", "Id": "15692", "ParentId": "15683", "Score": "7" } }, { "body": "<p>I think your code would be a lot simpler if you kept your list sorted at all times. It would also probably be faster. Constantly resorting the list is going to more expensive then inserting new items in the proper location. You might be saving a little by not sorting in certain cases, but probably less then you lose by having to resort the list rather then just insert in the correct location.</p>\n\n<p>You could also consider using a data structure such as a heap. Heaps are often used for priority queues. It lets you fetch the smallest element, but is cheaper then the expense of maintaing a sorted list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T06:14:49.947", "Id": "25531", "Score": "0", "body": "I think you didn't look at my code very carefully. I DON'T insert a new element in a correct location. I rather use a lazy ordered list, so sorting only occurs when it is really needed. As I understand, to implement such a lazy style priority queue, heaps cannot be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T06:57:48.897", "Id": "25533", "Score": "0", "body": "@heejin there seems to be a misunderstanding here. Winston was suggesting that you **don't** lazy-sort. He *does* recommend that you insert items in the correct location instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T07:05:06.160", "Id": "25534", "Score": "1", "body": "Arghhhh sorry for my poor English. I was confused. Sorry, Winston!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T00:45:50.627", "Id": "15694", "ParentId": "15683", "Score": "3" } } ]
{ "AcceptedAnswerId": "15692", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T16:15:34.210", "Id": "15683", "Score": "6", "Tags": [ "java", "priority-queue" ], "Title": "My implementation of FixedSizedPriorityQueue" }
15683
<p>I found <a href="http://nvie.com/posts/a-successful-git-branching-model/" rel="nofollow noreferrer">nvie's git branching model</a> simple enough to grasp and suitable for my projects - but the frontend supplied at GitHub was far too complex for me to understand. Hence, I wrote this script to start and finish tasks, automatically running the related commands to speed it all up a bit (without it becoming <em>too</em> abstract/complex).</p> <p>I've read a handful of tutorials on writing shell scripts but found it difficult to find one that emphasized on portability/POSIX compliancy. I'd like the script to run just fine in sh, dash, bash and zsh. Any feedback is appreciated - for one thing, I'm a bit unsure about where to use <code>$variable</code> and <code>${variable}</code>...</p> <h2>Intended usage</h2> <p>When I want to create a new branch for a task I run this:</p> <pre><code>gittask.sh new feature name_of_feature </code></pre> <p>When I'm done:</p> <pre><code>gittask.sh done </code></pre> <p>Finishing a task has it automatically deduce by the branch name prefix (feature/release/hotfix) what to do next.</p> <ul> <li>Features are merged back into the development branch.</li> <li>Releases are continuously merged back into the development branch (bugfixes) and, once the release branch is considered stable enough (decided upon by the user), merged into master (with a tag), ending the release branch.</li> <li>Hotfixes are merged back into both the master (with a tag) and the development branch.</li> </ul> <p><strong>Branch model</strong></p> <p>I use two persistent/remote branches, master and development, as well as three temporary/local branches, feature, release and hotfix.</p> <p><strong>Master branch</strong></p> <ul> <li>Persistent</li> <li>Remote branch</li> <li>Each merge into master equals a new tag</li> </ul> <p><strong>Development branch</strong></p> <ul> <li>Persistent</li> <li>Remote branch</li> </ul> <p><strong>Feature branches</strong></p> <ul> <li>Temporary</li> <li>Branch off from development</li> <li>Merge back into development</li> <li>Naming: &quot;subject&quot; or &quot;issue#&quot; if on issue tracker (&quot;feature/&quot; is prepended)</li> </ul> <p><strong>Release branches</strong></p> <ul> <li>Temporary</li> <li>Branch off from development</li> <li>Merge back into development (continuously) and master (when done)</li> <li>Naming: &quot;major.minor.z&quot;, e.g. &quot;1.2.0&quot; (z is defined by hotfix, &quot;release/&quot; is prepended)</li> <li>Signed tag needed when merging with master</li> </ul> <p><strong>Hotfix branches</strong></p> <ul> <li>Temporary</li> <li>Branch off from master</li> <li>Merge back into development and master</li> <li>Naming: &quot;x.y.fix&quot;, e.g. &quot;1.2.1&quot; (x, y is defined by release, &quot;hotfix/&quot; is prepended)</li> <li>Signed tag needed when merging with master</li> </ul> <h2>Script</h2> <pre><code>#!/bin/sh # gittask.sh: taskbased git branching utility # This script requires that git has been installed and properly configured, # that the remote &quot;master&quot; and &quot;development&quot; branches exist (locally too) # and that a network connection to the &quot;origin&quot; repository is established. set -o errexit usage() { echo echo &quot;Usage:&quot; echo &quot; gittask.sh new feature name_of_feature&quot; echo &quot; - Creates a new branch off from 'development' named&quot; echo &quot; 'feature/name_of_feature'.&quot; echo &quot; gittask.sh new release name_of_release&quot; echo &quot; - Creates a new branch off from 'development' named&quot; echo &quot; 'release/name_of_release'.&quot; echo &quot; gittask.sh new hotfix name_of_hotfix&quot; echo &quot; - Creates a new branch off from 'master' named&quot; echo &quot; 'hotfix/name_of_hotfix'.&quot; echo &quot; gittask.sh done&quot; echo &quot; - Merges current branch into master and/or development&quot; echo &quot; depending on if it's a feature, release or hotfix.&quot; } delete_branch() { # Infinite loop, only way out (except for Ctrl+C) is to answer yes or no. while true; do echo &quot;Delete $current branch? &quot; read yn case $yn in [Yy]* ) git branch -d ${current} break ;; [Nn]* ) echo &quot;Leaving $current branch as it is.&quot; break ;; * ) echo &quot;Error: Please answer (y)es or (n)o.&quot; ;; esac done } define_tag() { # Don't proceed until both variables have been set. while [ -z ${version_number} ] &amp;&amp; [ -z ${version_note} ]; do echo &quot;Enter version number (major.minor.fix): &quot; read version_number echo &quot;Enter version number note: &quot; read version_note done } # Confirm that user is in a git repository, abort otherwise. git status &gt;/dev/null 2&gt;&amp;1 || { echo &quot;Error: You're not in a git repository.&quot;; exit 1; } # If &quot;new&quot;, confirm that the required arguments were provided. if [ &quot;$1&quot; == &quot;new&quot; ] &amp;&amp; [ -n &quot;$2&quot; ] &amp;&amp; [ -n &quot;$3&quot; ]; then # Validate $3, only allow a-z (lower case), 0-9 and _ (underscore) in branch names. [ &quot;${3//[0-9a-z_]/}&quot; = &quot;&quot; ] || { echo &quot;Error: Branch names may only consist of a-z, 0-9 and underscore.&quot;; exit 1; } case $2 in feature ) git checkout development git checkout -b &quot;feature/$3&quot; exit 0 ;; release ) git checkout development git checkout -b &quot;release/$3&quot; exit 0 ;; hotfix ) git checkout master git checkout -b &quot;hotfix/$3&quot; exit 0 ;; * ) echo &quot;Error: You didn't specify feature, release or hotfix.&quot; exit 1 ;; esac # If &quot;done&quot;, proceed to determine current branch and by that what to do next. elif [ &quot;$1&quot; == &quot;done&quot; ]; then current=`git branch | awk '/\*/{print $2}'` case ${current} in feature* ) echo &quot;Merging into development branch...&quot; git checkout development git merge ${current} git push origin development delete_branch exit 0 ;; release* ) echo &quot;Merging into development branch...&quot; git checkout development git merge ${current} git push origin development # Infinite loop, only way out (except for Ctrl+C) is to answer yes or no. while true; do echo &quot;Merge into master (make a release)? &quot; read yn case $yn in [Yy]* ) echo &quot;Merging into master branch...&quot; git checkout master git merge ${current} define_tag git tag -s ${version_number} -m ${version_note} git push --tags origin master delete_branch break ;; [Nn]* ) echo &quot;Leaving branch master as it is.&quot; break ;; * ) echo &quot;Error: Please answer (y)es or (n)o.&quot; ;; esac done exit 0 ;; hotfix* ) git checkout master git merge ${current} define_tag git tag -s ${version_number} -m ${version_note} git push --tags origin master git checkout development git merge ${current} git push origin development delete_branch exit 0 ;; * ) echo &quot;Error: You're not on a feature, release or hotfix branch.&quot; exit 1 ;; esac else echo &quot;Error: You didn't provide the needed arguments.&quot; usage exit 1 fi </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T09:54:10.853", "Id": "25538", "Score": "3", "body": "I've revised this post and script several times, only to discover a new shortcoming each time it has been submitted. I don't expect myself to write a perfect piece of text or code at the first attempt - but it's odd how some things only become apparent once spoken out aloud." } ]
[ { "body": "<p>The following is one of my favorite \"rosetta stone\" like references:</p>\n\n<p><a href=\"http://hyperpolyglot.org/unix-shells\" rel=\"nofollow\">Unix Shells</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T17:46:34.720", "Id": "15772", "ParentId": "15684", "Score": "1" } }, { "body": "<p>It seems fine for me. Just three minor things:</p>\n\n<ol>\n<li><p>I'd consider calling the <code>define_tag</code> before the <code>git merge</code> or any other command which changes the current state of the repository. If a user press <kbd>Ctrl</kbd>+<kbd>C</kbd> they will find the repository in a different state than the beginning of the script.</p></li>\n<li><p>In the <code>define_tag</code> I'd print the existing tags (or the last five or ten tags). It could help users to choose the next one.</p></li>\n<li><p>There are same requirements in the comments:</p>\n\n<pre><code># This script requires that git has been installed and properly configured,\n# that the remote \"master\" and \"development\" branches exist (locally too) \n# and that a network connection to the \"origin\" repository is established.\n</code></pre>\n\n<p>You could check that <a href=\"https://stackoverflow.com/q/592620/843804\">git is installed properly</a> and the required branches are exist at the beginning of the script.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:36:47.980", "Id": "23933", "ParentId": "15684", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T16:16:47.337", "Id": "15684", "Score": "8", "Tags": [ "shell", "git", "sh" ], "Title": "Shell script to assist with branch management for tasks in git" }
15684
<p>I connected to the db, pull the data using <code>fetch_assoc()</code> (<code>fetch_all(NUMB)</code> is not available on the machine we are working with else this would be less of an issue). I get the returned data and load it into an array. However, it ends up in as an numeric array embedded inside another assoc array. What is the best way to have get the returned data in one, single, simple ASSOC array?</p> <pre><code>/** * @Param $conn object [required], $tableName string [required] * @Return $clmNames array */ public function getColumnName($conn = NULL, $tableName = NULL ) { if ( !is_object( $conn ) || !is_string( $tableName ) ) { //params are not of correct type. This will eventually throw an error instead of printing to screen echo("Error: getColumnName returning false"); return false; } //create SQL query $stmt = "SELECT column_name FROM information_schema.columns WHERE table_name = '". $tableName ."' ORDER BY ordinal_position"; //create query $query = $conn-&gt;query($stmt); //execute query $tmp = array(); while ($row = $query-&gt;fetch_assoc()) { //load all returned rows into an array $tmp[] = $row; } //clear memory $query-&gt;free();unset($query); //reCreate Array as a single assoc array instead of a double enbedded one. $clmNames = array(); foreach( $tmp as $tmpKey=&gt;$tmpValue ) { foreach( $tmpValue as $tmpValueKey=&gt;$tmpValueValue ) { $clmNames[] = $tmpValueValue; } } return $clmNames; } </code></pre> <p>The above returns the data correctly. However, I would like to be able to remove the entire foreach dealing with <code>$tmp</code> and <code>$clmNames</code> if possible.</p>
[]
[ { "body": "<p>First off, there is no need to check if <code>$conn</code> is an object, simply use the proper procedure for checking if the connection was successful.</p>\n\n<pre><code>if( ! $conn ) {//MySQL\nif( $conn-&gt;connect_error ) {//MySQLi\ntry {\n $conn = new PDO( $dsn, $user, $pass );\n} catch( PDOException $e ) {\n die( $e-&gt;getMessage() );\n}\n</code></pre>\n\n<p>And what is <code>$tableName</code> if not a string? The only other value I see is NULL, in which case you can use an <code>is_null()</code> check instead.</p>\n\n<p>Anyways, now that we are done with that, lets look at the actual problem. The reason you are getting a numerical array of associative arrays is because that is the way you have it coded. You are appending a new array element on to the end of the <code>$tmp</code> array foreach <code>$row</code> in the <code>fetch_assoc()</code> table. Because you used an empty assignment <code>[]</code>, this element uses the internal iterator to determine its position in the array, which is always the next available numeric index.</p>\n\n<p>If you want to combine all of these arrays together into one associative array, then you will have to merge them somehow. The easiest way would be to use <code>array_merge()</code>, but then you risk overwriting keys from a previous row. This means if you have identical keys in each row array, then only the last row will be available. This, as you can imagine, would be rather pointless. That leaves us with merging it ourselves. Or does it? Since it appears that you only want the insides of the <code>$row</code> array, then you can just do it all at once, for example:</p>\n\n<pre><code>while( $row = $query-&gt;fetch_assoc() ) {\n foreach( $row AS $value ) {\n $clmNames[] = $value;\n }\n}\n</code></pre>\n\n<p>The above should, if I understand your code correctly, result in the same thing. I'm not sure if its the \"best\" solution, but it removes two loops, an unnecessary array, and makes your code a little more obvious in what it is trying to do.</p>\n\n<p>A couple more things before I go, try only looping over information once. As shown above, if you find yourself looping over information just to create a new array to loop over it again, then chances are you can do whatever you needed to the first time and avoid having that second loop altogether. Finally, lets look at your foreach loops. If you compare yours to mine, you will notice I am not assigning the key pointer in mine. This is because it is unnecessary unless I am planning on using that value. Avoid assigning variables you are not going to use.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T19:38:16.093", "Id": "25571", "Score": "0", "body": "Helps a lot actually. Thank you very much.\n\nAs for the $conn check, I should have thougt of this: I could just add a check for the error in the createDBOject method. if it fails: stop there; otherwise I know $conn is good.\n\nI'll be re-factoring the rest later on and will defiantly be using your input. Thank you for the help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T18:42:57.193", "Id": "15688", "ParentId": "15685", "Score": "5" } }, { "body": "<p>using </p>\n\n<pre><code>while( $row = $query-&gt;fetch_assoc() ) {\n\n statement relating $row \n\n}\n</code></pre>\n\n<p>The loop Will Escape the first OR the Zeroth Index in the Query \nas While loop loops till the End of the Array is reached the \n$row is assigned automatically the first value and is per-incremented \nso you wont help \nArray(first_query);</p>\n\n<p>if you want it to retrieve values from your db \nuse a array such that</p>\n\n<pre><code>$a2=array();\n $a2[0]=mysqli_fetch_assoc($my_sql_query); //fetches the first missing value\n while( $row = $query-&gt;fetch_assoc() ) {\n statement relating $row \n $a2[]=$row;\n}\necho json_decode($a2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-11T18:08:13.647", "Id": "80291", "ParentId": "15685", "Score": "-1" } } ]
{ "AcceptedAnswerId": "15688", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T16:20:15.873", "Id": "15685", "Score": "5", "Tags": [ "php", "array", "mysqli" ], "Title": "Handling data returned from fetch_assoc()" }
15685
<p>I have a feeling I might be doing it wrong, what major things would you improve in this code?</p> <p>The code is basically handling a tour on first login, showing it only for first login users (activated externally via calling <code>activate</code>) and preventing the step to apear again if the user has already seen it.</p> <p>I intentionally used only the basic building blocks of backbone.js to a bare minimum, e.g. I didn't use templates as the DOM at this moment is given as is, and the HTML elements are not "backbone" friendly</p> <pre><code>var tourModel, tourView; (function($){ var VISITED = "visited"; function cookieName(step){ return "tour_step" + step; } function isStepVisited(step){ return $.cookie(cookieName(step)) === VISITED; } function setStepVisited(step){ $.cookie(cookieName(step.number),VISITED); } var TourModel = Backbone.Model.extend({ active: false, //private flag defaults: { step: { number:1, display:false } }, activate:function(){ this.active = true; }, close:function(){ this.toggleStep(this.get("step").number, false); }, toggleStep: function(step, show){ //if this is active (e.g. first time login) and the user haven't seen this step yet (e.g. cookie isn't set) or if this is closing the step (!show) then continue, else ignore if(!show || this.active &amp;&amp; !isStepVisited(step)){ this.set("step",{number:step, display:show}); } }, initialize: function(){ this.on("change:step",function(model,step){ if(step.display){ setStepVisited(step); } }); } }); tourModel = new TourModel(); })(jQuery); (function($){ var closeStepOne = function(){ $("#step1").hide(); $("#rss, #gorss, #mySitesTab").glowToggle(false); }; var closeStepTwo = function(){ $("#step2").hide(); $(".help-text-drag, #gallery").glowToggle(false); }; var stepFunctions = { 1:function (show){ if(show) { $("#step1").show(); $("#rss, #gorss, #mySitesTab").glowToggle(true); $("#rssInputs, #mySitesTab").expose({ closeOnEscape : true, closeOnClick : false, close:function(){ closeStepOne(); } }); } else { closeStepOne(); $("#mySitesTab").expose("remove"); } }, 2:function (show){ if(show) { $("#step2").show(); $(".help-text-drag, #gallery").glowToggle(true); $(".help-text-drag, #step2, #gallery").expose({ closeOnEscape : true, closeOnClick : false, close:function(){ closeStepTwo(); //$("#rss, #gorss, #mySitesTab").glowToggle(false); } }); $("#step2").css("z-index","1003"); } else { closeStepTwo(); $("#gallery").expose("remove"); } } }; var TourView = Backbone.View.extend({ model: tourModel, initialize: function() { this.model.on( 'change:step', this.render, this ); }, render: function(model,step) { //alert(JSON.stringify(step,4)); stepFunctions[step.number](step.display); } }); tourView = new TourView(); //view private functions })(jQuery); $(function(){ $(".tourCloseButton").click(function(){ tourModel.close(); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T17:04:14.827", "Id": "25737", "Score": "1", "body": "I don't see anything wrong with your code." } ]
[ { "body": "<p>Alternative Approach:</p>\n\n<p>In your case, I believe that the use of a model is not really necessary for this task. I would construct this using a master view with child views for each step:</p>\n\n<p>A TourView that contains a variable tracking which step is currently active and listenting for an event from it's child views for navigation.</p>\n\n<p>A TourStep1View .. TourStepNView for each step of the tutorial whose render function contains corresponding show and close function contains the hide.</p>\n\n<p>Launch the TourView and have it render a child view for the first step. The child view should throw an event to signal the parent view to swap it out for the next child view.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T01:54:17.537", "Id": "20454", "ParentId": "15686", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T16:24:05.657", "Id": "15686", "Score": "3", "Tags": [ "javascript", "jquery", "backbone.js" ], "Title": "First attempt incorporating backbone.js in my code" }
15686
<p>I have this JavaScript to make a sidebar widget stick to a fixed position once the page is scrolled down, once you scroll to the bottom of the page where the footer div is I then un-sticky it so that the stickied div does not overlap the footer.</p> <p>It works great but I am not very good with JavaScript, so I am hoping to clean it up because it looks sloppy.</p> <p>JavaScript</p> <pre><code>$(window).load(function () { /*-----------------------*/ * Fixed Widget on Scroll *-----------------------*/ // set some Div vars var stickyID = $("#sticky-scroll-wrapper"), footerID = $('#footer'), stickyDivHeight = stickyID.outerHeight(), stickyIDMargin = 70; $(window).scroll(function () { var currentPosition = $(document).scrollTop() + stickyIDMargin; var stickyIDPosition = stickyID.offset().top; // cut off point/un sticky when we reach this far down the page var limit = footerID.offset().top - stickyDivHeight; //determines whether sidebar should stick and applies appropriate settings to make it stick if (currentPosition &gt;= stickyIDPosition &amp;&amp; currentPosition &lt; limit) { $('#sticky-elements').css({ 'position': 'fixed', 'top': '70px' }); } else { $('#sticky-elements').css({ 'position': 'static', }); } // Un-stick once we reach the #fotter section of the page to prevent overlapping if (limit &lt; currentPosition) { var diff = limit - currentPosition; $('#sticky-elements').css({ 'top': diff + stickyIDMargin, 'position': 'fixed', }); } }); }); </code></pre> <p>HTML</p> <pre><code>&lt;div id="sticky-scroll-wrapper"&gt; &lt;div id="sticky-elements" style="position: static; "&gt;sidebar content&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T18:07:24.840", "Id": "25520", "Score": "0", "body": "@ANeves You are right I fixed that but you should of also noticed that I only had 4 questions and some only with 1 answer which wasn't good at all. I'm not new I have nearly 8k score on SO. I agree with you though I had overlooked it" } ]
[ { "body": "<p>I can make a small improvement in your logic structure that may make a very small improvement in performance. If <code>limit &lt; currentPosition</code>, all you need to do is that code block, and you can use else if and remove testing its opposite. See code:</p>\n\n<pre><code>$(window).load(function () {\n/*-----------------------*/\n * Fixed Widget on Scroll\n *-----------------------*/\n\n // set some Div vars\n var stickyID = $(\"#sticky-scroll-wrapper\"),\n footerID = $('#footer'),\n stickyDivHeight = stickyID.outerHeight(),\n stickyIDMargin = 70;\n\n $(window).scroll(function () {\n var currentPosition = $(document).scrollTop() + stickyIDMargin;\n var stickyIDPosition = stickyID.offset().top;\n\n // cut off point/un sticky when we reach this far down the page\n var limit = footerID.offset().top - stickyDivHeight;\n\n // Un-stick once we reach the #fotter section of the page to prevent overlapping\n if (limit &lt;= currentPosition) {\n var diff = limit - currentPosition;\n $('#sticky-elements').css({\n 'top': diff + stickyIDMargin,\n 'position': 'fixed',\n });\n }\n //determines whether sidebar should stick and applies appropriate settings to make it stick\n else if (currentPosition &gt;= stickyIDPosition) {\n $('#sticky-elements').css({\n 'position': 'fixed',\n 'top': '70px'\n });\n }\n else {\n $('#sticky-elements').css({\n 'position': 'static',\n });\n }\n });\n\n});\n</code></pre>\n\n<p>Also, you might consider consolidating <code>var diff = limit - currentPosition;</code> with <code>'top': diff + stickyIDMargin</code> if you are comfortable with that.\nOtherwise, it looks great to me. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T05:22:29.463", "Id": "15700", "ParentId": "15687", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T17:12:46.947", "Id": "15687", "Score": "3", "Tags": [ "javascript" ], "Title": "Sticky element for a sidebar widget" }
15687
<p>I've just finished coding a Shunting-Yard algorithm implementation, following Wikipedia's C code example and I've got it to finally work.</p> <p>However, looking at my code now, the two "worker" methods seem bloated. I was wondering what your opinion was regarding the current code stubs and whether or not they need to be split up and to what extent.</p> <p>Worker: overriden methods</p> <pre><code>package math; import java.math.BigDecimal; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /** * Implementation of the Shunting-yard algorithm invented by Edsger Dijkstra. * Parse 'infix' mathematical expressions, and output to Reverse Polish * Notation. Used to then evaluate RPN expression and work out the initial * 'infix' expression. * * @author Llifon Osian Jones * @version 1.0 */ public class ShuntingYardImpl implements ShuntingYard { private final Stack&lt;Operator&gt; operatorStack; private final Queue&lt;String&gt; outputQueue; /** * operatorStack - Store Operator Values. outputQueue - Output queue * containing values and operators - RPN. */ public ShuntingYardImpl() { operatorStack = new Stack&lt;&gt;(); outputQueue = new LinkedList&lt;&gt;(); } /** * {@inheritDoc} */ @Override public String[] infixToReversePolishNotation(String input) { final String[] expression = input.trim().split(" "); for (String token : expression) { final char op = token.charAt(0); // Validated beforehand. if (isOperator(op)) { // if token is an operator final Operator op1 = Operator.getOperatorByValue(op); while (!operatorStack.isEmpty()) { final Operator op2 = operatorStack.peek(); final boolean condition1 = (isLeftAssociative(op1) &amp;&amp; compareOperators( op1, op2) &lt;= 0); final boolean condition2 = (!isLeftAssociative(op1) &amp;&amp; compareOperators( op1, op2) &lt; 0); if (condition1 || condition2) { outputQueue.add(String.valueOf(operatorStack.pop() .getSymbol())); continue; } else { break; } } operatorStack.push(op1); } else if (token.equals("(")) { // if token is an open parenthesis operatorStack.push(Operator.OPEN_PARENTHESIS); } else if (token.equals(")")) { // if token is a closed parenthesis while (!operatorStack.isEmpty() &amp;&amp; (operatorStack.peek() != Operator.OPEN_PARENTHESIS)) { outputQueue.add("" + operatorStack.pop().getSymbol()); } operatorStack.pop(); // pop and discard left parenthesis. } else if (isNumerical(token)) { outputQueue.add(token); } } while (!operatorStack.empty()) { // Empty out remainder. outputQueue.add("" + operatorStack.pop().getSymbol()); } return outputQueue.toArray(new String[] {}); } /** * {@inheritDoc} */ @Override public String reversePolishNotationToResult(String[] input) { final Stack&lt;String&gt; execution = new Stack&lt;String&gt;(); for (final String token : input) { final char symbol = token.charAt(0); if (isOperator(symbol)) { final Operator operator = Operator.getOperatorByValue(symbol); if (!isParenthesis(operator) &amp;&amp; !execution.isEmpty()) { // Stack - FILO (LIFO), 1st pop = "RIGHT" hand expression final String right = String.valueOf(execution.pop()); if (right.equals("0") &amp;&amp; symbol == Operator.DIVIDE.getSymbol()) { return "Division By Zero"; } if (!execution.isEmpty()) { // Stack - FILO (LIFO), 2nd pop = "LEFT" hand expression final String left = String.valueOf(execution.pop()); final BigDecimal result = MathUtils.evaluateExpression( left, right, symbol); // Push latest result back into the stack. execution.push(result.toPlainString()); } } } else { execution.push(token); // push numbers into stack. } } return execution.isEmpty() ? "Error" : execution.pop(); } /** * Tests whether or not an Operator represents parenthesis. * * @param operator * Object to evaluate. * @return True if the operator is either "(" or ")". */ private boolean isParenthesis(Operator operator) { return operator == Operator.OPEN_PARENTHESIS || operator == Operator.CLOSED_PARENTHESIS; } /** * Test if an Operator object is assigned Left or Right Associativity. * * @param op * Operator object to evaluate. * @return True if assigned LEFT, false otherwise. */ private boolean isLeftAssociative(Operator op) { return op.getAssociativity() == Associativity.LEFT; } /** * Test if input matches a numerical format: E.g - 23, 23.1, 2, 1000. * * @param input * String to evaluate * @return True if a valid number. */ private boolean isNumerical(String input) { final char[] tokens = input.toCharArray(); for (char c : tokens) { if (!Character.isDigit(c) &amp;&amp; c != '.') { return false; } } return true; } /** * Test if current CHAR matches a valid Operator specification. Operator * defined in OPERATOR ENUM, but excluding parenthesis. * * @param op * Character value of a supposed operator. * @return True if 'op' matches an Operator value, excluding parenthesis. */ private boolean isOperator(char op) { final Operator operator = Operator.getOperatorByValue(op); if (operator != null) { final boolean isParenthesis = operator.getAssociativity() == Associativity.NONE; if (!isParenthesis) { return true; } } return false; } /** * Compares the 'priority' level of two Operator enums. Priority determined * by precedence values of Operator enums. * * @param op1 * Operator 1 to compare * @param op2 * Operator 2 to compare * @return ( -1 if op1 &lt; op2 ), ( 0 if op1 == op2 ), ( 1 if op1 &gt; op2 ). */ private int compareOperators(Operator op1, Operator op2) { final int op1V = op1.getPrecedence(); final int op2V = op2.getPrecedence(); if (op1V &lt; op2V) { return -1; } else if (op1V == op2V) { return 0; } // op1v &gt; op2v return 1; } public static void main(String... args) { ShuntingYardImpl syi = new ShuntingYardImpl(); String input = "( 10.2 + ( 2 ^ 4 ) ) + ( 2 - 2 )"; String[] array = syi.infixToReversePolishNotation(input); System.out.println("Answer = " + syi.reversePolishNotationToResult(array)); } } </code></pre> <p>Related to the question: Is it a bad sign when conditional statements span so widely?</p> <p>I tried to clean them up by assigning values to <code>boolean</code> variables, but it still looks a tad ugly.</p>
[]
[ { "body": "<p>I would recommend creating a <code>Token</code> class with specialized sub-classes for things like operators, parenthesis and values/identifiers. Your pre-defined tokens can all be saved in a Map so that you can access them quickly. The big loops that go through the token stream and \"if it's an do the thing\" logic can all be moved to the specialized <code>Token</code> instances. The body of the loop then becomes: 1) convert text to <code>Token</code>, 2) have the <code>Token</code> do it's thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T23:26:48.133", "Id": "25577", "Score": "0", "body": "Thanks Donald, I've taken on what you've suggested and I've also replaced the Stack with a Deque implementation of a Stack, of which I'm led to believe is far superior to the old Vector implementation of the concrete Stack class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T20:15:29.490", "Id": "15691", "ParentId": "15690", "Score": "3" } }, { "body": "<p>Ad \"wide conditional statements\":</p>\n\n<pre><code>if (isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 1\n || !isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 0) {\n // ...\n}\n</code></pre>\n\n<p>is not equal to your refactoring:</p>\n\n<pre><code>final boolean condition1 = isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 1;\nfinal boolean condition2 = !isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 0;\n\nif (condition1 || condition2) {\n // ...\n}\n</code></pre>\n\n<p>because you loose <a href=\"http://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"nofollow\">evaluation short-circuit</a>. You can get it back by chaining:</p>\n\n<pre><code>boolean condition = isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 1;\ncondition = condition || !isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 0;\n\nif (condition) {\n // ...\n}\n</code></pre>\n\n<p>or by deferring the evaluation:</p>\n\n<pre><code>interface Condition { boolean eval(); }\n\nfinal Condition condition1 = new Condition() {\n @Override\n public boolean eval() {\n return isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 1;\n }\n};\nfinal Condition condition2 = new Condition() {\n @Override\n public boolean eval() {\n return !isLeftAssociative(op1) &amp;&amp; compareOperators(op1, op2) &lt; 0;\n }\n};\n\nif (condition1.eval() || condition2.eval()) {\n // ...\n}\n</code></pre>\n\n<p>In general, instead of conditions themselves, you should precompute those expensive calls that have to be performed <strong>in any case</strong>:</p>\n\n<pre><code>final int compareOperators = compareOperators(op1, op2);\n\nif (compareOperators &lt; 0 || isLeftAssociative(op1) &amp;&amp; compareOperators &lt; 1) {\n // ...\n}\n</code></pre>\n\n<p>while in your code, a more concise option is:</p>\n\n<pre><code>if (compareOperators(op1, op2) &lt; (isLeftAssociative(op1) ? 1 : 0)) {\n // ...\n}\n</code></pre>\n\n<p>But in fact, instead of returning <code>int</code> from <code>compareOperators()</code>, you should introduce and return an <code>enum</code> like:</p>\n\n<pre><code>enum Precedence { LOWER, EQUAL, HIGHER; }\n</code></pre>\n\n<p>which would break some of the approaches outlined above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:14:35.763", "Id": "25605", "Score": "0", "body": "Awesome answer Charlie, real intense ;p. I never knew short circuit evaluations existed, I always believed all conditions were tested regardless (in this scenario), so thanks. Could I get your opinion on nesting an interface like that inside a class? Is it still good practice? I always try to split any interface or classes to their own source file as I've always felt it is what is expected, it just often gets ugly with many parameters and added coupling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:55:47.357", "Id": "25619", "Score": "0", "body": "From *Effective Java* -- **Minimize the accessibility of classes and members**: You should always reduce accessibility as much as possible. You should prevent any class, interface or member from becoming a part of the API. This concept, known as encapsulation, is one of the fundamental tenets of software design.\n• If a top-level class or interface can be made package-private, it should be. If a package-private\ntop-level class or interface is used only from within a single class, you should consider making it a **private nested class (or interface)** of the class in which it is used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:03:43.060", "Id": "25620", "Score": "0", "body": "Well now that totally flips what I've been taught on its head! Ever considered being a lecturer? I've learnt at least 2 things from you today :D. Thanks Charlie." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T08:40:24.613", "Id": "25639", "Score": "0", "body": "You may think it goes against the [code reuse](http://en.wikipedia.org/wiki/Code_reuse), but it doesn't. It's just a way to limit & control entry points, to hide internal specifics to be able to change them in the future without breaking API clients, and to ensure [loose coupling](http://en.wikipedia.org/wiki/Loose_coupling). For **package-private** classes (or interfaces) it doesn't make any difference if you keep them in a separate file, or not. Anybody can declare a new class in \"your\" package to get access to its internals. You can prevent it only by using **`private`**, i.e. nesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T08:53:41.330", "Id": "25640", "Score": "0", "body": "But please, don't get an impression that you should start nesting everything from now on. You can't totally prevent a misuse of your code (e.g. by reflection). If somebody invades \"your\" package, it's his design flaw, not yours. Still, nesting is good for _loose coupling_ **inside** your package." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:55:58.373", "Id": "15733", "ParentId": "15690", "Score": "3" } } ]
{ "AcceptedAnswerId": "15733", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T19:32:29.950", "Id": "15690", "Score": "6", "Tags": [ "java", "algorithm" ], "Title": "Shunting-Yard algorithm implementation" }
15690
<p>I'm working on a fairly mundane ASP.NET MVC app that allows users to do basic CRUD operations on a number of different domain objects. I'm trying to minimize duplicate code and boring, monkey code as much as possible, so I'm using <code>AutoMapper</code> to map types and MVC's scaffolding feature to spit out forms. I have a standard template for <code>Index</code>, <code>Details</code>, <code>Create</code>, <code>Edit</code>, <code>Delete</code>, and <code>DeleteConfirmed</code> views. Finally, I use specific view models to support these views (<code>IndexModel</code>, <code>RowModel</code>, <code>DisplayModel</code>, and <code>EditModel</code>).</p> <p>I've written an abstract base class called <code>StandardService</code>, which works with AutoMapper to provide support for mapping from entities to view models and back again. It has generic type parameters for the entity and each type of view model.</p> <p>I began a refactoring of this class based on concern that it violated SRP (and had "too many" generic parameters), but I quickly realized this just meant a lot more classes and a lot more code. Yes, the classes would be more tightly focused, and there would no doubt be greater flexibility, but it didn't seem to be flexibility I needed at this point.</p> <p>So, I reverted to the single base class. I'd like feedback on whether this is a sensible/practical use of inheritance or an anti-pattern/code smell. Is there a better solution that doesn't result in an explosion of classes?</p> <p><strong>StandardService`5</strong></p> <pre><code>public class StandardService&lt;TEntity, TIndexModel, TRowModel, TDisplayModel, TEditorModel&gt; : ServiceBase where TEntity : class, IEntity where TIndexModel : IIndexModel&lt;TRowModel&gt; where TDisplayModel : IDisplayModel where TEditorModel : IEditorModel, new() { public StandardService(MainDbContext dbContext) : base(dbContext) { } public virtual TIndexModel GetIndexModel(GridSortOptions sortOptions) { var processedEntities = GetProcessedEntities(); var rowModels = MapProcessedEntitiesToRowModels(processedEntities); var processedRowModels = ProcessRowModels(rowModels); processedRowModels = SortRowModels(processedRowModels, sortOptions); var model = MapProcessedRowModelsToIndexModel(processedRowModels); model.SortOptions = sortOptions; return model; } protected virtual IEnumerable&lt;TEntity&gt; GetProcessedEntities() { return GetDbSet(); } protected virtual IEnumerable&lt;TRowModel&gt; MapProcessedEntitiesToRowModels(IEnumerable&lt;TEntity&gt; processedEntities) { return Mapper.Map&lt;IEnumerable&lt;TRowModel&gt;&gt;(processedEntities); } protected virtual IEnumerable&lt;TRowModel&gt; ProcessRowModels(IEnumerable&lt;TRowModel&gt; rowModels) { return rowModels; } protected virtual IEnumerable&lt;TRowModel&gt; SortRowModels(IEnumerable&lt;TRowModel&gt; rowModels, GridSortOptions sortOptions) { if (sortOptions == null || string.IsNullOrWhiteSpace(sortOptions.Column)) return rowModels; return rowModels.OrderBy(sortOptions.Column, sortOptions.Direction); } protected virtual TIndexModel MapProcessedRowModelsToIndexModel(IEnumerable&lt;TRowModel&gt; processedRowModels) { return Mapper.Map&lt;TIndexModel&gt;(processedRowModels); } public virtual TDisplayModel GetDisplayModel(int id) { var entity = FindOrThrow(id); return MapEntityToDisplayModel(entity); } protected virtual TDisplayModel MapEntityToDisplayModel(TEntity entity) { return Mapper.Map&lt;TDisplayModel&gt;(entity); } public virtual TEditorModel GetEditorModel() { return new TEditorModel(); } public virtual TEditorModel GetEditorModel(int id) { var entity = FindOrThrow(id); return MapEntityToEditorModel(entity); } public virtual void UpdateModel(TEditorModel model) { } public virtual TEntity AddAndSave(TEditorModel model) { var entity = MapEditorModelToEntity(model); GetDbSet().Add(entity); SaveChanges(); return entity; } protected virtual TEntity MapEditorModelToEntity(TEditorModel model) { return Mapper.Map&lt;TEntity&gt;(model); } public virtual TEntity EditAndSave(TEditorModel model) { var entity = FindOrThrow(model.Id); MapEditorModelToEntity(model, entity); SaveChanges(); return entity; } protected virtual TEditorModel MapEntityToEditorModel(TEntity entity) { return Mapper.Map&lt;TEditorModel&gt;(entity); } protected virtual void MapEditorModelToEntity(TEditorModel model, TEntity entity) { Mapper.Map(model, entity); } public virtual bool CanDelete(int id) { var entity = FindOrThrow(id); return CanDelete(entity); } public virtual bool CanDelete(IEnumerable&lt;TEntity&gt; entities) { foreach (var entity in entities) if (CanDelete(entity)) return false; return true; } protected virtual bool CanDelete(TEntity entity) { return true; } public virtual void DeleteAndSave(int id) { var entity = FindOrThrow(id); DeleteAndSave(entity); } public virtual void DeleteAndSave(TEntity entity) { Delete(entity); SaveChanges(); } public virtual void Delete(TEntity entity) { GetDbSet().Remove(entity); } public virtual TEntity Find(int id) { return GetDbSet().Find(id); } protected virtual TEntity FindOrThrow(int id) { return GetDbSet().FindOrThrow(id); } protected DbSet&lt;TEntity&gt; GetDbSet() { return DbContext.Set&lt;TEntity&gt;(); } } </code></pre> <p><strong>ServiceBase</strong></p> <pre><code>public abstract class ServiceBase { private readonly MainDbContext _dbContext; protected MainDbContext DbContext { get { return _dbContext; } } public ServiceBase(MainDbContext dbContext) { _dbContext = dbContext; } protected void SaveChanges() { _dbContext.SaveChanges(); } } </code></pre> <p><strong>LadderMatchService</strong> (example base class)</p> <pre><code>public class LadderMatchService : StandardService&lt;LadderMatch, IndexModel, RowModel, DisplayModel, EditorModel&gt; { private readonly NameFinderService _nameFinderService; public LadderMatchService(MainDbContext dbContext, NameFinderService nameFinderService) : base(dbContext) { _nameFinderService = nameFinderService; } protected override IEnumerable&lt;RowModel&gt; ProcessRowModels(IEnumerable&lt;RowModel&gt; rowModels) { return rowModels.OrderBy(model =&gt; model.ReportedOn); } public override void UpdateModel(EditorModel model) { model.ChallengerNames = _nameFinderService.GetExactNameOrSimilarNames(model.ChallengerNames.Single(), false); model.ChallengeeNames = _nameFinderService.GetExactNameOrSimilarNames(model.ChallengeeNames.Single(), true); } } </code></pre>
[]
[ { "body": "<p>I think your first instinct was right. When I see</p>\n\n<pre><code>public class StandardService&lt;TEntity, TIndexModel, TRowModel, TDisplayModel, TEditorModel&gt; : ServiceBase\n where TEntity : class, IEntity\n where TIndexModel : IIndexModel&lt;TRowModel&gt;\n where TDisplayModel : IDisplayModel\n where TEditorModel : IEditorModel, new()\n</code></pre>\n\n<p>my nose curls at the code smell. There are far too many generics in the declaration, and a good chance it will clutter up your code later on.</p>\n\n<p>If you have to have to use <em>where</em> with an interface, why don't you just use the interface in the class? I don't see anywhere where the classes are instantiated in your base class, and if I'm missing something, make an abstract method that returns the required class from the child class. That goes for any of the methods, use the interfaces where you can, let the sub classes take care of the rest.</p>\n\n<p>Of course, I might be missing something because I haven't worked with AutoMapper before.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T05:53:46.087", "Id": "25530", "Score": "0", "body": "Thanks, Jeff. I new up a `TEditorModel` in `GetEditorModel()`. `DbContext.Set<TEntity>()` requires a class, not an interface. `TRowModel` is required in `IIndexModel<TRowModel>`. Finally, AutoMapper requires generic parameters as inputs (example: `Mapper.Map<TDisplayModel>(entity)`). True, I could make `GetEditorModel()` abstract, but I need the `TEditorModel` generic parameter anyway (to enable auto-mapping). I agree that the generic parameters are ugly, but I don't see a way around it without breaking up the class into multiple classes (which will result in many more classes and more code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T17:56:25.433", "Id": "25778", "Score": "0", "body": "What I was trying to say in my previous comment is that, if I use interfaces instead of generics, I would need to make a significant number of methods abstract, which would increase the amount of repetitive code I have to write. That said, I agree what I have now is ugly and feels wrong, and I'm still seeking ways to improve upon what I have. Please let me know if you have any other suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T03:49:51.900", "Id": "15697", "ParentId": "15695", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T01:24:10.197", "Id": "15695", "Score": "5", "Tags": [ "c#", "object-oriented", "design-patterns" ], "Title": "A base class to handle mapping between entities and view models" }
15695
<p>Pseudocode:</p> <blockquote> <pre><code>// B = nxn binary matrix // Bm = resulting matrix for (i=1; i&lt;=n; i++) { for (j=1; j&lt;=n; j++) { if (B[i,j] == 1) { for (k=1; k&lt;=n; k++) { Bm[i,j] = B[i,j] | B[k,j]; } } } } </code></pre> </blockquote> <p>This is the Warshall algorithm written (in my way):</p> <pre><code>B = [1 1 0 0 0; 0 0 0 1 0; 0 0 0 0 1; 0 1 0 0 0; 0 0 0 0 0]; n = 5; Bm = zeros(n); for i = 1:n for j = 1:n if B(i,j) == 1 for k = 1:n Bm(i,k) = B(i,k) | B(k,j); end end end end </code></pre> <p>It works but, how can I improve the matrix loops?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-07T13:48:37.517", "Id": "40082", "Score": "0", "body": "Did you mean `Bm(i,j) = B(i,k) | B(k,j)`?" } ]
[ { "body": "<p>This post may help you in removing a loop:\n<a href=\"http://mathforum.org/kb/message.jspa?messageID=845980\" rel=\"nofollow\">http://mathforum.org/kb/message.jspa?messageID=845980</a></p>\n\n<p>Furthermore, one way to speed up your code is to use a short circuit logical operator:</p>\n\n<pre><code>B(i,k) || B(k,j); \n</code></pre>\n\n<p>Also it seems to have a small effect if you use a logical matrix as input rather than a double:</p>\n\n<pre><code>B = logical(b);\n</code></pre>\n\n<p>Last and least, it would be nicer to initialize Bm with the datatype that it will have:</p>\n\n<pre><code>Bm = false(n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T15:36:44.967", "Id": "19971", "ParentId": "15696", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T01:47:12.257", "Id": "15696", "Score": "3", "Tags": [ "algorithm", "matrix", "matlab" ], "Title": "Getting B+ matrix (Warshall algorithm) in Matlab" }
15696
<p>I found out the hardway that access to DbContext in .NET is not threadsafe. I have a singleton for logging things using a dbcontext. The original version uses something like</p> <pre><code>public Logger{ private MyContext context; private static Logger instance = new Logger(); private Logger(){ //init stuff, including context } public static Logger Instance { return this.instance; } public void someMethod(){ //do something with this.context } } </code></pre> <p>I'm thinking of a few solutions: </p> <p>one would be is not making this a singleton at all, but instantiate a logger each time I need one.</p> <p>I can think of added overhead as a disadvantage for this way, and simplicity as an advantage.</p> <p>another one is locking (on the context or type) for each public method: </p> <pre><code>public void someMethod(){ lock(this.context){ //do something with this.context } } </code></pre> <p>This adds extra maintenance complexity.</p> <p>a third one could be one context per thread in a form of</p> <pre><code>private ConditionalWeakTable&lt;Thread, MyContext&gt; contexts = new ConditionalWeakTable&lt;Thread, MyContext&gt;(); private MyContext Context{ get { return contexts.GetValue(Thread.CurrentThread, createContext()); } } private MyContext createContext(){ //instantiate a context } </code></pre> <ul> <li>Pro: fairly consice, complexity is isolated</li> <li>Con: batshit insane? Using <code>System.Runtime.CompilerServices</code> for something fairly mondaine, which also isn't what it's meant for.</li> </ul> <p>Am I overlooking any arguments? What would you do?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T15:05:55.110", "Id": "25563", "Score": "1", "body": "+1 for the con, although if you are looking at logging as 'mondaine' then why do you need a dbcontext with it? If you are actually logging to a database then in all honesty use a pre-made solution, will save you lots of time and effort." } ]
[ { "body": "<p>I believe that the dbcontext shouldn't be shared between multiple threads - I remember reading about that somewhere, but I can't find the link.\nSharing a context between threads can lead to all sorts of problems, though in your case (a logger) that should be limited, cause as I understand it would be used as a 'push only' class.</p>\n<p>My suggestion would be to either create the dbcontext each time you use it and wrapp it in a using statement or provide it as a dependency to the logger class and perhaps use an IoC container to control the lifetime of the context.\nInstantiating a context is not expensive - at least that's what the docs say.</p>\n<p>Here are some links that may help:</p>\n<p><a href=\"https://docs.microsoft.com/en-us/archive/blogs/alexj/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext\" rel=\"nofollow noreferrer\">how to decide on a lifetime for your objectcontext</a></p>\n<p><a href=\"https://stackoverflow.com/questions/7647912/why-re-initiate-the-dbcontext-when-using-the-entity-framework\">Why re-initiate the DbContext when using the Entity Framework?</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T20:12:11.010", "Id": "25572", "Score": "0", "body": "well, all these ideas were to avoid sharing the context between the threads; that is shouldn't be shared is just the problem I'm trying to fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T20:16:08.620", "Id": "25573", "Score": "0", "body": "the reason I have it static is to avoid problems with attaching objects from one context to another, which leads to headaches on add vs attach. Having multiple instances of the logging class would fix that though, that is solution #1 I propose above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T09:50:37.860", "Id": "25581", "Score": "1", "body": "I can see the problems that you mention - that's why I'd suggest the IoC. If it's a web app then you can set the lifetime of the context to be per request which is (usually) handled by one thread - unless you're doing some async operations. If it's a win app then depending on the container you choose, you may want to experiment - maybe you'll find a container with a instance per thread lifetime and that should solve the problem. \n\nOf course having the context as an external dependency for the logger adds verbosity, but I'd choose that over struggling with the problems you mentioned any time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-09-18T17:12:28.533", "Id": "15714", "ParentId": "15703", "Score": "3" } }, { "body": "<p>General rules of thumb:</p>\n\n<ol>\n<li><p>In order to take advantage of connection pooling (and you should), database connections should be as short lived as possible. Create, use, then immediately destroy.</p></li>\n<li><p>Single instance objects should always be agile (defined as not holding system resources e.g. db connections, file handles, etc.).</p></li>\n<li><p>If you need a single instance object to handle a system resource, it should be done in a protected manner using a named mutex (naming makes a mutex available to all threads across the computer) or Monitor. Within the protected block of code, if the resource is a db connection, apply rule 1.</p></li>\n<li><p>When using object locking, you should create your locks around an arbitrary object, not the current object's instance e.g.:</p>\n\n<pre><code>private static readonly object _lockObject = new object();\n</code></pre>\n\n<p>...</p>\n\n<pre><code>try {\n Monitor.Enter(_lockObject);\n // Do protected stuff...\n}\nfinally {\n Monitor.Exit(_lockObject);\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:56:54.893", "Id": "59947", "Score": "3", "body": "I disagree with point 4. nothing wrong with locking the object you are using if it is private." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T20:06:07.020", "Id": "15818", "ParentId": "15703", "Score": "12" } }, { "body": "<p>DBContext also has a cache that I would like to leverage for queries behind a WebAPI. Would any of these allow the threads of the WebAPI to use the same DBContext and provide the response via the DBContext cache? I would likely use a timed refresh to ensure the cache is refreshed, as most of the queries are for reference data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-14T16:22:25.210", "Id": "189593", "ParentId": "15703", "Score": "0" } }, { "body": "<blockquote>\n <p>I'm thinking of a few solutions:</p>\n \n <p>one would be is not making this a singleton at all, but instantiate a\n logger each time I need one.</p>\n \n <p>I can think of added overhead as a disadvantage for this way, and\n simplicity as an advantage.</p>\n</blockquote>\n\n<p>This is probably the right move. The overhead of instantiating a DbContext object is pretty minimal.</p>\n\n<p>What would be ideal is if you created a <code>DbContextFactory</code> class to build you instances of your DbContext. Add a private readonly field for the factory and build a new context object for each database interaction. </p>\n\n<p>Something like this</p>\n\n<pre><code>public class DbContextFactory\n{\n private readonly string _connectionString;\n\n private static DbContextFactory _instance;\n public static DbContextFactory Instance\n {\n get \n {\n if (_instance == null)\n {\n _instance = new DbContextFactory(\"MyConnectionStringOrWhatever\");\n }\n\n return _instance;\n }\n }\n\n private DbContextFactory(string connectionString)\n {\n _connectionString = connectionString;\n }\n\n public DbContext BuildDbContext()\n {\n //or whatever you need to do to build your dbcontext\n return new DbContext(Instance._connectionString);\n }\n}\n</code></pre>\n\n<p>And the</p>\n\n<pre><code>public class Logger\n{\n private readonly DbContextFactory _dbContextFactory;\n\n private static Logger _instance;\n public static Logger Instance\n {\n get \n {\n if (_instance == null)\n {\n _instance = new Logger();\n }\n\n return _instance;\n }\n }\n\n private Logger()\n {\n this._dbContextFactory = DbContextFactory.Instance;\n }\n\n public void SomeMethod()\n {\n using (var context = _dbContextFactory.BuildDbContext())\n {\n //do something with context\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-03-15T00:05:00.007", "Id": "189629", "ParentId": "15703", "Score": "2" } } ]
{ "AcceptedAnswerId": "15818", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T12:38:12.080", "Id": "15703", "Score": "9", "Tags": [ "c#", "multithreading", "entity-framework", "singleton" ], "Title": "Threadsafe DBContext in singleton" }
15703
<p>Below is my method in checking if entity already exist.</p> <pre><code>public boolean isExist(String genreName) throws PersistenceException{ EntityManager em = EMF.get().createEntityManager(); boolean flag = false; try{ Genre genre = em.find(Genre.class, genreName); if (genre != null) flag = true; }finally{ em.close(); } return flag; } </code></pre> <p>Is the code above ok? Please suggest.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T23:47:03.210", "Id": "25578", "Score": "0", "body": "see http://meta.codereview.stackexchange.com/questions/598/google-application-engine-tag-synonym-request for tag synonym request." } ]
[ { "body": "<p>It looks fine. You could omit the boolean flag if you return immediately when you know the answer:</p>\n\n<pre><code>public boolean isExist(final String genreName) throws PersistenceException {\n final EntityManager em = EMF.get().createEntityManager();\n try {\n final Genre genre = em.find(Genre.class, genreName);\n if (genre != null) {\n return true;\n }\n return false;\n } finally {\n em.close();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:22:37.597", "Id": "25550", "Score": "0", "body": "if return immediately, `em.close` will not be executed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:24:12.603", "Id": "25551", "Score": "3", "body": "@JRGalia the *finally* block is *always* executed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:21:05.370", "Id": "15705", "ParentId": "15704", "Score": "5" } }, { "body": "<ul>\n<li><code>isExist</code> is not English. Call it something like <code>genreExists</code>.</li>\n<li>In addition to omitting the flag, as palacsint suggested, you can get rid of the if branch:</li>\n</ul>\n\n<hr>\n\n<pre><code>public boolean genreExists(String genreName) throws PersistenceException {\n EntityManager em = EMF.get().createEntityManager();\n try {\n return em.find(Genre.class, genreName) != null;\n } finally {\n em.close();\n }\n}\n</code></pre>\n\n<hr>\n\n<p><em>Probably irrelevant side note:</em></p>\n\n<p>If you were using Java 7, and EntityManager implemented <code>AutoCloseable</code> or one of its various subinterfaces (such as <code>Closeable</code>), your code could be even cleaner using the new <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\"><em>try-with-resources statement:</em></a></p>\n\n<pre><code>try (EntityManager em = EMF.get().createEntityManager()) {\n return em.find(Genre.class, genreName) != null;\n}\n</code></pre>\n\n<p>But it doesn't, so you can't. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T16:40:34.977", "Id": "25565", "Score": "0", "body": "I'm not familiar with GAE, don't know if `EMF.get().createEntityManager()` is mockable. If not there could be difficulties if we want to cover this function with unit tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T16:41:06.617", "Id": "25566", "Score": "0", "body": "But looks like it is :) so just ignore my comments :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:23:57.423", "Id": "15706", "ParentId": "15704", "Score": "5" } } ]
{ "AcceptedAnswerId": "15706", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:02:01.207", "Id": "15704", "Score": "5", "Tags": [ "java", "google-app-engine", "jpa" ], "Title": "Checking if entity exist in Google App Engine Datastore using JPA 1" }
15704
<p>This is a code automatically converted from VB 6.0 to C#.net What is a safe and correct way to get rid of that <code>GOTO</code> statement?</p> <pre><code>public bool IsDirty(bool checkChildrenInd) { bool result = false; //Determine if this object is 'dirty', or has been updated since it was created. if (Parent.NewInd) { return true; } if (backup == null) { goto CheckChildren; //Check any child lists } if (!String.Equals(MissingDataValue, backup.MissingDataValue)) { return true; } if (!String.Equals(PreviewDataValue, backup.PreviewDataValue)) { return true; } if (FieldOption != backup.FieldOption) { return true; } CheckChildren: if (!checkChildrenInd) { return result; } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:05:55.220", "Id": "25553", "Score": "7", "body": "are you sure this is all? checkChildren will always return false. The whole thing could be rewritten as `public bool IsDirty(bool checkChildrenInd){ return Parent.NewId || backup != null)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:09:06.387", "Id": "25554", "Score": "1", "body": "I agree with Martijn: it seems like \"Check any child lists\" is not actually checking any child lists whatsoever." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:13:55.927", "Id": "25555", "Score": "0", "body": "yes that's all. The PATTERN is always like the method above. Now for some other classes in the code I may have so much more things to check after the (if backup == null) and before GOTO ... and also so much more stuff to check inside the GOTO section as well...but the pattern is like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:18:52.927", "Id": "25556", "Score": "1", "body": "@Martijn : well how about those IFs for MissingDataValue in String.Equals? aren't we missing them with your code? how?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:23:32.560", "Id": "25558", "Score": "0", "body": "They all return true. There isn't much choise there. By the way, I might refactor this to its negation, `IsClean`. returning `true` on something that seems \"good\" feels more natural than returning `true` on something that seems \"bad\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T16:12:28.103", "Id": "25564", "Score": "2", "body": "@BDotA If you wish to work on the pattern and not on this particular instance, I recommend leaving comments like `// do something` in the places where your code might (or not) do something. (Just make sure that the \"do something\" has no side-effects to the existing instructions... otherwise it's required, for the refactor.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:02:58.537", "Id": "25583", "Score": "0", "body": "@Martijn: the original code can return `false` even if `backup != null`, depending on the backup fields checks, your rewritten version will always return `true` in such case" } ]
[ { "body": "<p>EDIT: FIXED</p>\n\n<p>This <em>specific</em> instance can be rewritten as</p>\n\n<pre><code>public bool IsDirty(bool checkChildrenInd) {\n return ! ( Parent.NewId ||\n backup == null ||\n String.Equals(MissingDataValue, backup.MissingDataValue) ||\n String.Equals(PreviewDataValue, backup.PreviewDataValue) ||\n FieldOption == backup.FieldOption );\n}\n</code></pre>\n\n<p>if this pattern is always the same, but there may be other conditions as you note in the comments, I note that CheckChildren </p>\n\n<ul>\n<li>Takes a parameter which is also the function parameter</li>\n<li>returns on all code paths</li>\n<li>result is never assigned to before the <code>goto</code> statement</li>\n</ul>\n\n<p>If this is always true, you can factor it out. replace the CheckChildren label with a function:</p>\n\n<pre><code>private bool CheckChildren(bool checkChildrenInd){\n bool result = false;\n if (!checkChildrenInd)\n {\n return result;\n }\n return result;\n}\n</code></pre>\n\n<p>and the <code>goto CheckChildren;</code> with <code>return CheckChildren(checkChildrenInd);</code></p>\n\n<p>if <code>result</code> <em>is</em> possibly set to true before the goto statement, you will need to pass result as a variable to the funcion too (and include it in the signature).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:22:26.773", "Id": "25557", "Score": "0", "body": "Thanks. Just one last question: How about those IFs for MissingDataValue in String.Equals? aren't we missing them with your code? how?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:25:06.287", "Id": "25559", "Score": "1", "body": "The only path that returns false is if Parent.FirstId is false (otherwise it would have returned true) and backup == null. All other paths return true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:31:31.100", "Id": "25561", "Score": "1", "body": "No, you're right. It falls through to the goto label, and if all checks return false, it returns result, which is initialised as false and never changed. Will update the answer accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:21:33.250", "Id": "25585", "Score": "1", "body": "@Martijn: sorry, but this is completely flawed -- first, you inverted the result for `Parent.NewInd`, you return `false` where the original returned `true` -- then if `MissingDataValue` is clean, but `PreviewDataValue` is dirty, you still return `false` instead of `true`, because the code then never checks `PreviewDataValue` -- last, you should call `CheckChildren()` in place of `goto` AND at the end..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T13:20:29.370", "Id": "25596", "Score": "0", "body": "@Martijn: You tried to negate the condition to `return ! IsClean();`. But in that case the **correct** expression would look like: `return ! ( ! Parent.NewId && ( backup == null || String.Equals(MissingDataValue, backup.MissingDataValue) && String.Equals(PreviewDataValue, backup.PreviewDataValue) && FieldOption == backup.FieldOption ) );`. Be careful with the logic inversions." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T14:20:57.057", "Id": "15708", "ParentId": "15707", "Score": "5" } }, { "body": "<p>The minimal amount of changes to get rid of the <code>goto</code> is:</p>\n\n<pre><code>public bool IsDirty(bool checkChildrenInd) {\n bool result = false;\n //Determine if this object is 'dirty', or has been updated since it was created.\n if (Parent.NewInd) {\n return true;\n }\n if (backup != null) {\n if (!String.Equals(MissingDataValue, backup.MissingDataValue)) {\n return true;\n }\n if (!String.Equals(PreviewDataValue, backup.PreviewDataValue)) {\n return true;\n }\n if (FieldOption != backup.FieldOption) {\n return true;\n }\n }\n if (!checkChildrenInd) {\n return result;\n }\n return result;\n}\n</code></pre>\n\n<p>Or if you want some refactoring:</p>\n\n<pre><code>public bool IsDirty(bool checkChildrenInd) {\n //Determine if this object is 'dirty', or has been updated since it was created.\n return Parent.NewInd\n || backup != null &amp;&amp; CheckBackup()\n || checkChildrenInd &amp;&amp; CheckChildren();\n}\n\nprotected bool CheckBackup() {\n return !String.Equals(MissingDataValue, backup.MissingDataValue)\n || !String.Equals(PreviewDataValue, backup.PreviewDataValue)\n || FieldOption != backup.FieldOption;\n}\n\nprotected bool CheckChildren() {\n return false; // or delegate, when there are any children\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:46:12.117", "Id": "15725", "ParentId": "15707", "Score": "5" } } ]
{ "AcceptedAnswerId": "15725", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T13:57:07.320", "Id": "15707", "Score": "3", "Tags": [ "c#" ], "Title": "Rewriting the code without use of GOTO" }
15707
<p>I am pretty new to TDD and is following problems on spoj.pl for practice. I need help with following code; it was my first attempt.</p> <p>Problem: Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. Mentioned <a href="http://www.spoj.pl/problems/TEST/">here</a>.</p> <p>Tests:</p> <pre><code>describe "life universe and everything" do before(:each) do @life = Life.new end it "should accept input" do @life.stub(:gets) { "5, 4, 23, 42, 4" } @life.input.should == [5,4,23,42,4] end it "check number validity" do @life.valid?(23).should be_true @life.valid?(42).should be_false end it "process input" do array1 = [5,4,23,42,4] @life.process_input(array1).should == [5,4,23] array2 = [1,4,76,34,90] @life.process_input(array2).should == [1,4,76,34,90] end end </code></pre> <p>Code:</p> <pre><code>class Life def input puts "List comma(',') seperated numbers. Press enter when done." numbers_string = gets numbers = numbers_string.split(',') numbers.map {|n| n.strip.to_i} end def valid?(number) (number==42) ? false : true end def process_input(numbers) processed_numbers = [] numbers.each do |number| break unless valid?(number) processed_numbers &lt;&lt; number end processed_numbers end end </code></pre> <p>I would like it to be reviewed and would be glad to know my mistakes and what can I do to improve quality of code. Thanks!</p>
[]
[ { "body": "<p>This wouldn't be the way I'd develop it, your class is used more as a module (a library of functions) and not in OOP, ie: you're not using instance variables. I'd rather go for something like the following:</p>\n\n<pre><code>class Life\n\n def input\n puts \"List comma (',') seperated numbers. Press enter when done.\"\n @data = user_string\n @numbers = input_to_numbers!\n end\n\n # NOTE: I don't know how to stub instance variables in rspec\n # so I stub these two methods\n def numbers\n @numbers\n end\n\n def user_string\n gets\n end\n\n # NOTE: this works similarly to\n # numbers.first numbers.index(42) || numbers.size\n def process_input\n processed_numbers = []\n numbers.each do |number|\n break unless valid?(number)\n processed_numbers &lt;&lt; number\n end\n processed_numbers\n end\n\n\nprivate\n\n def input_to_numbers!\n @data.split(',').map(&amp;:to_i)\n end\n\n def valid?(number)\n number != 42\n end\n\nend\n</code></pre>\n\n<p>and I'd test something like this:</p>\n\n<pre><code>require './code1.rb'\n\ndescribe \"life universe and everything\" do\n before(:each) do \n @life = Life.new\n end\n\n it \"should accept input\" do \n @life.stub(:user_string) { \"5, 4, 23, 42, 4\" }\n @life.input.should == [5,4,23,42,4]\n end\n\n # NOTE: many people wouldn't test private methods\n # saying you should only test the functionality you expose\n # I personally see nothing wrong\n it \"check number validity\" do\n @life.send(:valid? , 23).should be_true\n @life.send(:valid? , 42).should be_false\n end\n\n it \"process input without 42\" do\n @life.stub(:numbers) {[5,4,23,42,4]} \n @life.process_input.should == [5,4,23]\n end\n\n it \"process input with 42\" do\n @life.stub(:numbers) {[1,4,76,34,90]}\n @life.process_input.should == [1,4,76,34,90]\n end\nend\n</code></pre>\n\n<p>I'm not sure I got what you mean, but I hope it's useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:26:28.240", "Id": "15730", "ParentId": "15711", "Score": "2" } }, { "body": "<p>Congratulations. That's a pretty nice first attempt.</p>\n\n<p>I see only a few issues:</p>\n\n<ul>\n<li><p>The problem statement shows that you will receive one number per line; your code expects one line with multiple numbers, separated by commas.</p></li>\n<li><p>The problem statement asks you to print the numbers; your program doesn't.</p></li>\n<li><p>When run, the test writes its prompt to $stdout. Tests should be quiet when passing.</p></li>\n</ul>\n\n<p>The issue with the prompt can be fixed with an expectation:</p>\n\n<pre><code>@life.should_receive(:puts)\\\n.with(\"List comma(',') separated numbers. Press enter when done\"\n</code></pre>\n\n<p>If your intent is to solve a slightly different problem, then we won't worry about the differences between what your program does and what they're asking for. But read below the fold for a simple test and implementation, TDD Style, for the stated problem.</p>\n\n<hr>\n\n<p>This problem can be solved pretty simply. For example,</p>\n\n<pre><code> loop do\n n = gets.chomp.to_i\n puts n\n break if n == 42\n end\n</code></pre>\n\n<p>What test or tests could you write that would allow you to have code this simple? Let's see if we can get there from nothing:</p>\n\n<pre><code>class Life\n def process_input\n end\nend\n\ndescribe Life do\n\n it \"should copy numbers from $stdin to $stdout\" do\n life = Life.new\n life.should_receive(:gets).with(no_args).and_return('41')\n life.should_receive(:puts).with(41)\n life.process_input\n end\n\nend\n</code></pre>\n\n<p>Running that, we find that the spec fails because the code never called <code>gets</code>. We add the call to <code>gets</code>, then find that the spec fails because the code never called <code>puts</code>. Adding them, we get a passing test:</p>\n\n<pre><code>class Life\n def process_input\n puts gets.to_i\n end\nend\n</code></pre>\n\n<p>Of course, we've got no loop, so let's tell the test there should be multiple calls to gets and puts. We'll use <code>.ordered</code> to tell rspec that the calls should occur in a certain order.</p>\n\n<pre><code>it \"should copy numbers from $stdin to $stdout\" do\n life = Life.new\n life.should_receive(:gets).ordered.with(no_args).and_return('41')\n life.should_receive(:puts).ordered.with(41)\n life.should_receive(:gets).ordered.with(no_args).and_return('42')\n life.should_receive(:puts).ordered.with(42)\n life.process_input\nend\n</code></pre>\n\n<p>Now there needs to be a loop. Let's add it:</p>\n\n<pre><code>def process_input\n loop do\n puts gets.to_i\n end\nend\n</code></pre>\n\n<p>Our test neither passes nor fails. Instead, it hangs. That's because we didn't give it any way to get out of the loop. Let's add the termination condition:</p>\n\n<pre><code>def process_input\n loop do\n n = gets.to_i\n puts n\n break if n == 42\n end\nend\n</code></pre>\n\n<p>So, we can write a test that lets us have pretty simple code. But in a few ways, this test is bothersome. One reason is that it is <em>too picky</em> about the way that the I/O is done. What if we changed the program to use print instead of puts? It would have produce exactly the same output, but the test would fail. Also, having the test hang when the program fails to terminate isn't very good. We want tests that pass or fail quickly and cleanly, with no guessing. So let's rewrite our test (and the program) using dependency injection for I/O.</p>\n\n<hr>\n\n<p>Starting over, we're going to change the the Life program so that it takes and input object and an output object:</p>\n\n<pre><code>class Life\n\n def initialize(input = $stdin, output = $stdout)\n @input = input\n @output = output\n end\n\n def process_input\n end\n\nend\n</code></pre>\n\n<p>And our test:</p>\n\n<pre><code>require 'stringio'\n\ndescribe Life do\n\n it \"should copy numbers from input to output\" do\n input = StringIO.new(\"41\\n\")\n output = StringIO.new\n life = Life.new(input, output)\n life.process_input\n output.string.should == \"41\\n\"\n end\n\nend\n</code></pre>\n\n<p>Using StringIO instances as mock I/O objects is very handy, and lets us test the result of the I/O rather than the actions that produce the I/O. That's nice.</p>\n\n<p>Since our program doesn't process anything yet, the test fails:</p>\n\n<pre><code> 1) Life should copy numbers from $stdin to $stdout\n Failure/Error: output.string.should == \"41\\n\"\n expected: \"41\\n\"\n got: \"\" (using ==)\n</code></pre>\n\n<p>Let's fix that:</p>\n\n<pre><code> def process_input\n @output.print @input.gets\n end\n</code></pre>\n\n<p>The test now passes. Let's modify the test to show that it should loop:</p>\n\n<pre><code> it \"should copy numbers from $stdin to $stdout\" do\n input = StringIO.new(\"41\\n42\\n\")\n output = StringIO.new\n life = Life.new(input, output)\n life.process_input\n output.string.should == \"41\\n42\\n\"\n end\n</code></pre>\n\n<p>The test fails:</p>\n\n<pre><code> 1) Life should copy numbers from $stdin to $stdout\n Failure/Error: output.string.should == \"41\\n42\\n\"\n expected: \"41\\n42\\n\"\n got: \"41\\n\" (using ==)\n</code></pre>\n\n<p>Let's add the loop:</p>\n\n<pre><code> def process_input\n loop do\n @output.print @input.gets\n end\n end\n</code></pre>\n\n<p>Now it hangs again! That's because I/O objects like StringIO and $stdin just return a nil when they run out of input. Our program is happily printing nil over and over. Let's make the test die nicely when the loop fails to terminate:</p>\n\n<pre><code> it \"should copy numbers from $stdin to $stdout\" do\n input = StringIO.new(\"41\\n42\\n43\\n\")\n def input.gets\n super.tap { |s| raise \"no more input\" unless s }\n end\n output = StringIO.new\n life = Life.new(input, output)\n life.process_input\n output.string.should == \"41\\n42\\n\"\n end\n</code></pre>\n\n<p>Here we monkey patch our input objects so that when it runs out of input, it raises an error rather than just returning nil. The result:</p>\n\n<pre><code> 1) Life should copy numbers from $stdin to $stdout\n Failure/Error: super.tap { |s| raise \"no more input\" unless s }\n RuntimeError:\n no more input\n</code></pre>\n\n<p>Great! let's get the loop to terminate when it encounters that \"42\":</p>\n\n<pre><code> def process_input\n loop do\n s = @input.gets\n @output.print s\n break if s == \"42\\n\"\n end\n end\n</code></pre>\n\n<p>Now we've got a robust test that doesn't care about the details of how I/O is done, and code that is pretty simple.</p>\n\n<hr>\n\n<p>There's just one more enhancement I'd make to this program, and that is to have it exit when it runs out of input. While not strictly required by the problem statement, a program that prints blank lines endlessly upon EOF is obnoxious! Now we need another \"it\" in our test:</p>\n\n<pre><code> it \"should exit on EOF\" do\n input = StringIO.new(\"41\\n&lt;EOF&gt;\")\n def input.gets\n s = super\n case s\n when \"&lt;EOF&gt;\"\n nil\n when nil\n raise \"no more input\"\n else\n s\n end\n end\n output = StringIO.new\n life = Life.new(input, output)\n life.process_input\n output.string.should == \"41\\n\"\n end\n</code></pre>\n\n<p>Our monkey-patched input object just got a little more interesting. We want it to return \"nil\" on end of input, because that's how the loop will detect end of input in real life, but we want it to raise an exception if the code under test tries to get more input after the nil. This test fails:</p>\n\n<pre><code> 1) Life should exit on EOF\n Failure/Error: raise \"no more input\"\n RuntimeError:\n no more input\n</code></pre>\n\n<p>So let's make the loop exit on end of input:</p>\n\n<pre><code> def process_input\n loop do\n s = @input.gets\n @output.print s\n break if s.nil?\n break if s == \"42\\n\"\n end\n end\n</code></pre>\n\n<p>Now the program meets the stated requirements, and our own requirement of not filling the output with blank lines on end-of-input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T15:13:39.220", "Id": "25601", "Score": "0", "body": "that was great input thanks! I look forward to post more exercises and compile all of them at one place and make it public for beginners like me to get started with TDD. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T21:28:57.150", "Id": "39370", "Score": "2", "body": "This was a fantastic answer. it helped me understand how to use StringIO to test my own cli app." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:43:42.260", "Id": "15731", "ParentId": "15711", "Score": "6" } } ]
{ "AcceptedAnswerId": "15731", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T15:51:58.707", "Id": "15711", "Score": "5", "Tags": [ "ruby", "rspec" ], "Title": "Spoj's 1st problem in tdd using Ruby" }
15711
<p>I wrote this MySQL stored procedure to emulate <code>DROP USER IF EXISTS</code> (not available in MySQL). Any comments or identified bugs?</p> <pre><code>DROP PROCEDURE IF EXISTS DropUserIfExists; DELIMITER $$ CREATE PROCEDURE DropUserIfExists(MyUserName VARCHAR(100)) BEGIN DECLARE foo BIGINT DEFAULT 0 ; SELECT COUNT(*) INTO foo FROM mysql.user WHERE User = MyUserName ; IF foo &gt; 0 THEN SET @A = (SELECT Result FROM (SELECT GROUP_CONCAT("DROP USER"," ",MyUserName,"@'%'") AS Result) AS Q LIMIT 1); PREPARE STMT FROM @A; EXECUTE STMT; FLUSH PRIVILEGES; END IF; END ;$$ DELIMITER ; </code></pre>
[]
[ { "body": "<p>I would say you are wrong!!!</p>\n\n<p>Let me explain...</p>\n\n<p>If there is a user named <code>'tempuser'@'localhost'</code> and you are trying to call <code>DropUserIfExists('tempuser')</code>, the above procedure may produce error something like:</p>\n\n<p><code>Error Code: 1396 Operation DROP USER failed for 'tempuser'@'%'</code>, since there is no user <code>'tempuser'@'%'</code></p>\n\n<p>A workaround for this problem is to pass both username and host name to the SP (pass a null host name if you want to delete all users named <code>tempuser</code>)</p>\n\n<p>The following SP will help you to remove user <code>'tempuser'@'%'</code> by executing <code>CALL DropUserIfExistsAdvanced('tempuser', '%');</code></p>\n\n<p>If you want to remove all users (say <code>'tempuser'@'%'</code>, <code>'tempuser'@'localhost'</code> and <code>'tempuser'@'192.168.1.101'</code>) execute SP like <code>CALL DropUserIfExistsAdvanced('tempuser', NULL);</code> This will delete all users named <code>tempuser</code>!!! seriously...</p>\n\n<p>Now please have a look on mentioned SP <code>DropUserIfExistsAdvanced</code>:</p>\n\n<pre><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `DropUserIfExistsAdvanced`$$\n\nCREATE DEFINER=`root`@`localhost` PROCEDURE `DropUserIfExistsAdvanced`(\n MyUserName VARCHAR(100)\n , MyHostName VARCHAR(100)\n)\nBEGIN\nDECLARE pDone INT DEFAULT 0;\nDECLARE mUser VARCHAR(100);\nDECLARE mHost VARCHAR(100);\nDECLARE recUserCursor CURSOR FOR\n SELECT `User`, `Host` FROM `mysql`.`user` WHERE `User` = MyUserName;\nDECLARE CONTINUE HANDLER FOR NOT FOUND SET pDone = 1;\n\nIF (MyHostName IS NOT NULL) THEN\n -- 'username'@'hostname' exists\n IF (EXISTS(SELECT NULL FROM `mysql`.`user` WHERE `User` = MyUserName AND `Host` = MyHostName)) THEN\n SET @SQL = (SELECT mResult FROM (SELECT GROUP_CONCAT(\"DROP USER \", \"'\", MyUserName, \"'@'\", MyHostName, \"'\") AS mResult) AS Q LIMIT 1);\n PREPARE STMT FROM @SQL;\n EXECUTE STMT;\n DEALLOCATE PREPARE STMT;\n END IF;\nELSE\n -- check whether MyUserName exists (MyUserName@'%' , MyUserName@'localhost' etc)\n OPEN recUserCursor;\n REPEAT\n FETCH recUserCursor INTO mUser, mHost;\n IF NOT pDone THEN\n SET @SQL = (SELECT mResult FROM (SELECT GROUP_CONCAT(\"DROP USER \", \"'\", mUser, \"'@'\", mHost, \"'\") AS mResult) AS Q LIMIT 1);\n PREPARE STMT FROM @SQL;\n EXECUTE STMT;\n DEALLOCATE PREPARE STMT;\n END IF;\n UNTIL pDone END REPEAT;\nEND IF;\nFLUSH PRIVILEGES;\nEND$$\n\nDELIMITER ;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:58:45.583", "Id": "15745", "ParentId": "15716", "Score": "3" } } ]
{ "AcceptedAnswerId": "15745", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T20:51:58.293", "Id": "15716", "Score": "7", "Tags": [ "sql", "mysql" ], "Title": "Emulating \"DROP USER IF EXISTS\"" }
15716
<p>Is this a good method to Read\Write packets</p> <pre><code>using System.Text; namespace namespace { public unsafe class DataPacket { public DataPacket(byte[] buffer) { _buffer = new byte[buffer.Length]; System.Buffer.BlockCopy(buffer, 0, _buffer, 0, buffer.Length); } public DataPacket(ushort size, ushort type) { _buffer = new byte[size]; WriteUInt16(size, 0); WriteUInt16(type, 2); } private readonly byte[] _buffer; protected byte[] Buffer { get { return _buffer; } } public byte* Ptr { get { fixed (byte* ptr = Buffer) return ptr; } } public ushort Size { get { return ReadUInt16(0); } set { WriteUInt16(value, 0); } } public ushort Type { get { return ReadUInt16(2); } set { WriteUInt16(value, 2); } } public void WriteSByte(sbyte value, int offset) { (*(sbyte*)(Ptr + offset)) = value; } public void WriteInt16(short value, int offset) { (*(short*)(Ptr + offset)) = value; } public void WriteInt32(int value, int offset) { (*(int*)(Ptr + offset)) = value; } public void WriteInt64(long value, int offset) { (*(long*)(Ptr + offset)) = value; } public void WriteByte(byte value, int offset) { (*(Ptr + offset)) = value; } public void WriteUInt16(ushort value, int offset) { (*(ushort*)(Ptr + offset)) = value; } public void WriteUInt32(uint value, int offset) { (*(uint*)(Ptr + offset)) = value; } public void WriteUInt64(ulong value, int offset) { (*(ulong*)(Ptr + offset)) = value; } public void WriteStringWithLength(string value, int offset, out int nextoffset) { WriteByte((byte)(value.Length &gt; 255 ? 255 : value.Length), offset); offset++; foreach (var c in value) { WriteByte((byte)c, offset); offset++; } nextoffset = offset; } public void WriteString(string value, int offset) { foreach (var c in value) { WriteByte((byte)c, offset); offset++; } } public sbyte ReadSByte(int offset) { return (*(sbyte*)(Ptr + offset)); } public short ReadInt16(int offset) { return (*(short*)(Ptr + offset)); } public int ReadInt32(int offset) { return (*(int*)(Ptr + offset)); } public long ReadInt64(int offset) { return (*(long*)(Ptr + offset)); } public byte ReadByte(int offset) { return (*(Ptr + offset)); } public byte[] ReadBytes(int offset, int length) { var bytes = new byte[length]; for (var i = offset; i &lt; length; i++) bytes[i] = (*(Ptr + i)); return bytes; } public ushort ReadUInt16(int offset) { return (*(ushort*)(Ptr + offset)); } public uint ReadUInt32(int offset) { return (*(uint*)(Ptr + offset)); } public ulong ReadUInt64(int offset) { return (*(ulong*)(Ptr + offset)); } public string ReadString(int offset, int length) { var sb = new StringBuilder(); for (var i = 0; i &lt; length; i++) sb.Append((char)ReadByte(offset + i)); return sb.ToString().Replace("\0", "").Replace("\r", ""); } public string ReadString(int offset) { var size = ReadByte(offset); offset++; return ReadString(offset, size); } public byte[] ToArray() { var newbuffer = new byte[Buffer.Length]; System.Buffer.BlockCopy(Buffer, 0, newbuffer, 0, Buffer.Length); return newbuffer; } public static implicit operator byte[](DataPacket dPacket) { return dPacket.ToArray(); } public static implicit operator DataPacket(byte[] packet) { return new DataPacket(packet); } } } </code></pre>
[]
[ { "body": "<p>At first glance, I can see several problem with this code (why are you even using pointers? what happens with non-ASCII characters in <code>WriteString()</code>?). But my main issue is that <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx\" rel=\"nofollow\"><code>BinaryReader</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx\" rel=\"nofollow\"><code>BinaryWriter</code></a> do something very similar, so you're kind of reinventing the wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T14:29:26.237", "Id": "25600", "Score": "0", "body": "I always prefer using pointers its just a prefer :D even i use memory copy instead of Buffer.BlockCopy.\nAlso could you provide me with an edited code with what you expect it to be ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:11:51.507", "Id": "25621", "Score": "0", "body": "Well, I would expect you to use the two classes instead of `DataPacket`, so there is no code to show." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T21:31:50.203", "Id": "25628", "Score": "0", "body": "BinaryWriter is working with stream, not with buffer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T01:18:29.030", "Id": "25630", "Score": "1", "body": "Yeah, but you can use `MemoryStream`, which is just a `Stream` wrapper around a `byte[]`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T11:08:05.107", "Id": "15727", "ParentId": "15720", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T01:46:06.143", "Id": "15720", "Score": "4", "Tags": [ "c#" ], "Title": "Packet Read\\Write" }
15720
<p>The following code is from a university assignment of mine to write a classification algorithm (using nearest neighbour) to classify whether or not a given feature set (each feature is the frequency of words in an email) is spam or not. </p> <p>We are given a CSV file (the training data) with the frequencies, and an integer (1 or 0) at the end of the row indicating whether or not it is spam. So in this form:</p> <pre><code>X1,X2,...,Xn,SPAM </code></pre> <p>The test data is also in this form (including the SPAM column, so we can verify the accuracy).</p> <p>My question is, how can I make this code more idiomatic, and what speedups can I make to this code? For example, is there a way to write <code>getMostCommon</code>, without having to <code>groupBy</code> and then run a <code>maximumBy</code> again?</p> <pre><code>import Text.CSV import Data.List data SpamType = Spam | NotSpam deriving (Show, Eq) type FeatureSet = [Float] toSpam :: Int -&gt; SpamType toSpam 0 = NotSpam toSpam 1 = Spam toSpam a = NotSpam parseClassifiedRecord :: Record -&gt; (FeatureSet, SpamType) parseClassifiedRecord x = (init converted, toSpam (truncate (last converted))) where converted = map (\val -&gt; read val :: Float) x -- returns the euclidean distance between two feature sets difference :: FeatureSet -&gt; FeatureSet -&gt; Float difference first second = sqrt (sum (zipWith (\x y -&gt; (x - y)^2) first second)) -- finds the SpamType of the k nearest 'nodes' in the training set findKNearest :: [(FeatureSet, SpamType)] -&gt; FeatureSet -&gt; Int -&gt; [SpamType] findKNearest trainingSet toMatch k = take k (map snd (sortBy (\x y -&gt; (compare (fst x) (fst y))) [(difference (fst x) toMatch, snd x) | x &lt;- trainingSet])) -- returns item which occurs most often in the list getMostCommon :: (Eq a) =&gt; [a] -&gt; a getMostCommon list = head (maximumBy (\x y -&gt; (compare (length x) (length y))) (groupBy (\x y -&gt; (x == y)) list)) -- given a feature set, returns an ordered (i.e. same order as input) -- list of whether or not feature is spam or not spam -- looks at the closest k neighbours classify :: [(FeatureSet, SpamType)] -&gt; FeatureSet -&gt; Int -&gt; SpamType classify trainingSet toClassify k = getMostCommon (findKNearest trainingSet toClassify k) -- gives a value for the accuracy of expected vs actual for spam classification -- i.e. num classified correctly / num total accuracy :: [(SpamType, SpamType)] -&gt; Float accuracy classifications = (fromIntegral $ length (filter (\x -&gt; (fst x) == (snd x)) classifications)) / (fromIntegral $ length classifications) main = do packed &lt;- parseCSVFromFile "spam-train.csv" packedtest &lt;- parseCSVFromFile "spam-test.csv" let (Right trainingSet) = packed let (Right testSet) = packedtest let classifiedTrainingSet = map parseClassifiedRecord (tail (init trainingSet)) let unclassified = map parseClassifiedRecord (tail (init testSet)) let classified = map (\x -&gt; (classify classifiedTrainingSet (fst x) 1, snd x)) unclassified putStrLn (show (accuracy classified)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T00:27:46.290", "Id": "26500", "Score": "0", "body": "small suggestion: don't use sqrt. Comparing squared distances won't change the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T17:34:38.247", "Id": "26706", "Score": "0", "body": "Using unboxed vectors should be even faster. I will look into adding a `FromRecord` instance for unboxed vectors to cassava." } ]
[ { "body": "<p>One helpful function is <a href=\"http://hackage.haskell.org/packages/archive/base/4.6.0.0/doc/html/Data-Ord.html\" rel=\"nofollow\"><code>Data.Ord.comparing</code></a>:</p>\n\n<pre><code>comparing :: (Ord a) =&gt; (b -&gt; a) -&gt; b -&gt; b -&gt; Ordering\ncomparing p x y = compare (p x) (p y)\n</code></pre>\n\n<p>With this and using function composition you can write:</p>\n\n<pre><code>getMostCommon :: (Eq a) =&gt; [a] -&gt; a\ngetMostCommon = head . maximumBy (comparing length) . groupBy (==)\n</code></pre>\n\n<p>Similar changes apply to several places. Another small simplification could be changing <code>(\\x -&gt; (fst x) == (snd x))</code> to <code>uncurry (==)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T17:45:28.800", "Id": "15741", "ParentId": "15721", "Score": "4" } }, { "body": "<ul>\n<li>As previously noted, the <code>comparing</code> function is very useful for making compare functions. Especially if you are simply comparing by some field since you just have to give the accessor to <code>comparing</code>.</li>\n<li><p>Its a good idea to display the error message if there is one and for the <code>Either</code> type use <code>either</code> to handle both <code>Left</code> and <code>Right</code> cases.</p></li>\n<li><p>There is no need to make long variable names if they have a small scope and the variables don't have a nice succinct name, eg. with the <code>difference</code> function, using <code>first</code> and <code>second</code> as parameter names just clutters the definition.</p></li>\n<li><p>It is common practice in Haskell to use function composition <code>.</code> and application <code>$</code> rather than parentheses wherever applicable. It is simply more readable.</p></li>\n<li><p><code>putStrLn . show == print</code></p></li>\n<li><p><code>groupBy (==) == group</code></p></li>\n<li><p>There are quite a lot of combinators for working with functions over tupels,\nunfortunately (or fortunately depending on how you look at it) most of them are abstracted over <code>Control.Arrow</code>, I haven't included any of that in the code below, but <code>(\\x -&gt; difference toMatch (fst x),snd x)</code> could be written as <code>first (difference toMatch)</code> using <code>Control.Arrow.first</code>.</p></li>\n<li><p>Rather than limiting the use of <code>findKNearest</code> to the <code>k</code> first elements of the list, make the function give all the elements and just consume as many as you need, saves you a parameter and makes the function more reusable.</p></li>\n</ul>\n\n<p><em>Note: I left out comments only to make the changes more visible.</em>\n</p>\n\n<pre><code>parseClassifiedRecord :: Record -&gt; (FeatureSet, SpamType)\nparseClassifiedRecord x = (init converted, toSpam . truncate . last $ converted)\n where converted = map read x\n\ndifference a b = sqrt . sum . zipWith (\\x y -&gt; (x - y)^2) a $ b\n\nfindNearest :: [(FeatureSet, SpamType)] -&gt; FeatureSet -&gt; [SpamType]\nfindNearest trainingSet toMatch =\n map snd\n . sortBy (comparing fst)\n . map (\\(a,b) -&gt; (difference a toMatch, b))\n $ trainingSet\n\ngetMostCommon = head . maximumBy (comparing length) . group\n\nclassify :: Int -&gt; [(FeatureSet, SpamType)] -&gt; FeatureSet -&gt; SpamType\nclassify k trainingSet = getMostCommon . take k . findNearest trainingSet\n\naccuracy :: [(SpamType, SpamType)] -&gt; Float\naccuracy cs = \n (fromIntegral \n . length \n . filter (uncurry (==)) \n $ cs) / (fromIntegral . length $ cs)\n\nparseFile = liftM (either (error . show) (tail . init)) . parseCSVFromFile\n\nmain = do \n trainingSet &lt;- parseFile \"spam-train.csv\"\n testSet &lt;- parseFile \"spam-test.csv\"\n let classifiedTrainingSet = map parseClassifiedRecord trainingSet\n let unclassified = map parseClassifiedRecord testSet\n let classified = map\n (\\(x,y) -&gt; (classify 1 classifiedTrainingSet x, y))\n unclassified\n print (accuracy classified)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-10-07T23:12:14.110", "Id": "16315", "ParentId": "15721", "Score": "4" } }, { "body": "<p>I liked HaskellElephant's answer, but since you mentioned performance, I put together a version using the killer cassava library + vector. It's a little less elegant, but runs 30x faster in my tests.</p>\n\n<pre><code>module CSVTest.New where\nimport Data.Csv\nimport Data.Vector\nimport Data.ByteString.Lazy (ByteString, readFile)\nimport Prelude hiding (tail, readFile, filter, take, init, \n last, sum, zipWith, map, head, length,\n foldl)\nimport Data.Vector.Algorithms.Heap\nimport Data.Ord\nimport Control.Monad\nimport Control.Monad.ST\n\ndata SpamType = Spam | NotSpam\n deriving (Show, Eq, Enum, Bounded)\n\ntype FeatureSet = Vector Float \n\ntoSpam :: Int -&gt; SpamType\ntoSpam 0 = NotSpam\ntoSpam 1 = Spam \ntoSpam a = NotSpam\n\nparseClassifiedRecord :: Vector Float -&gt; (FeatureSet, SpamType)\nparseClassifiedRecord x = (init x, toSpam . truncate . last $ x)\n\ndifference :: FeatureSet -&gt; FeatureSet -&gt; Float\ndifference a b = sum . zipWith (\\x y -&gt; (x - y)^2) a $ b\n\nfindNearest :: Vector (FeatureSet, SpamType) -&gt; FeatureSet -&gt; Vector SpamType\nfindNearest trainingSet toMatch = result where\n v = map (\\x -&gt; (difference (fst x) toMatch, snd x)) trainingSet\n v' = runST $ do\n mv &lt;- thaw v\n sortBy (comparing fst) mv\n freeze mv\n result = map snd v \n\ngetMostCommon :: Vector SpamType -&gt; SpamType\ngetMostCommon v = result where\n (spamCount, notSpamCount) = foldl (\\(sc, nsc) x -&gt; if x == Spam \n then (sc + 1, nsc) \n else (sc, nsc + 1)) (0,0) v\n result = if spamCount &gt;= notSpamCount \n then Spam\n else NotSpam\n\nclassify :: Int -&gt; Vector (FeatureSet, SpamType) -&gt; FeatureSet -&gt; SpamType\nclassify k trainingSet = getMostCommon . take k . findNearest trainingSet\n\n\naccuracy :: Vector (SpamType, SpamType) -&gt; Float\naccuracy cs = \n (fromIntegral . length . filter (uncurry (==)) $ cs)\n / (fromIntegral . length $ cs)\n\nparseCSVFromFile :: FilePath -&gt; IO (Either String (Vector FeatureSet))\nparseCSVFromFile = fmap decode . readFile \n\nparseFile = liftM (either (error . show) (tail . init)) . parseCSVFromFile\n\nrun trainingFile testFile = do \n trainingSet &lt;- parseFile trainingFile\n testSet &lt;- parseFile testFile\n let classifiedTrainingSet = map parseClassifiedRecord trainingSet\n let unclassified = map parseClassifiedRecord testSet\n let classified = map (\\x -&gt; (classify 1 classifiedTrainingSet (fst x), snd x)) \n unclassified\n print (accuracy classified) \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T03:43:52.920", "Id": "16385", "ParentId": "15721", "Score": "3" } } ]
{ "AcceptedAnswerId": "16315", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T04:05:17.380", "Id": "15721", "Score": "5", "Tags": [ "algorithm", "performance", "haskell", "homework", "clustering" ], "Title": "Nearest Neighbour classification algorithm" }
15721
<p>I am trying to read a line ending in <code>\r\n</code> from a <code>Handle</code>. This is an HTTP header.</p> <p>I’m fairly new to functional programming, so I tend to use a lot of case expressions and stuff. This makes the code very long and ugly.</p> <pre><code>handleRequest :: HostName -&gt; Handle -&gt; IO () handleRequest host handle = do requestLine &lt;- readHeaderLine putStrLn $ requestLine ++ "\n-------------------" -- FIXME: This code is bad, and its author should feel bad. where readHeaderLine = do readHeaderLine' "" where readHeaderLine' s = do chr &lt;- hGetChar handle case chr of '\r' -&gt; do nextChr &lt;- hGetChar handle case nextChr of '\n' -&gt; return s _ -&gt; readHeaderLine' $ s ++ [chr, nextChr] _ -&gt; readHeaderLine' $ s ++ [chr] </code></pre> <p>How can I reduce the amount of case expressions in this code? I thought of using Parsec, but that seemed overkill to me for something this trivial, and I don’t know how well it works with <code>Handle</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T09:20:06.793", "Id": "25580", "Score": "0", "body": "The answer depends on your goal. If you want high performance or an elegant HTTP parser, you should choose different algorithm and libraries.\n\nIf you just want to see how your current code can be cleaned up with only structural changes without changing the algoritm, it's a different story. Please specify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:17:54.627", "Id": "25584", "Score": "0", "body": "@nponeccop performance isn’t really an issue. The point is making the code more concise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:54:50.300", "Id": "25587", "Score": "0", "body": "Can't you just use `hGetLine`? There are many alternatives to your code. For example, you can just use `hGetContent` and parse the resulting list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T11:40:44.417", "Id": "25588", "Score": "0", "body": "@nponeccop `hGetContent` won’t work, since the length of the data isn’t known before the headers are parsed. `hGetLine` won’t work if the headers contain a newline." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:38:27.013", "Id": "25589", "Score": "0", "body": "`hGetContent` doesn't require length to be known in advance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:09:59.113", "Id": "25602", "Score": "0", "body": "@nponeccop but I do need to have the length of the HTTP request, otherwise I won’t be able to know the request has already ended. The length of the request body is in the `Content-Length` header." } ]
[ { "body": "<p>Here I assume you just want to see how your current code can be improved without changing the algoritm.</p>\n\n<p>First of all, give HLint tool a chance to suggest you obvious improvements. In your case the only improvement was that <code>do</code> in <code>do readHeaderLine' \"\"</code> was redundant, so not much.</p>\n\n<p>Second, in my opinion many small top-level definitions are better than few large ones. You can still control namespace pollution by not exporting definitions local to the module:</p>\n\n<pre><code>import System.IO\n\ntype HostName = String\n\nhandleRequest :: HostName -&gt; Handle -&gt; IO ()\nhandleRequest host handle = do\n requestLine &lt;- readHeaderLine handle\n putStrLn $ requestLine ++ \"\\n-------------------\"\n\n-- FIXME: This code is bad, and its author should feel bad.\nreadHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = do\n chr &lt;- hGetChar handle\n case chr of\n '\\r' -&gt; do\n nextChr &lt;- hGetChar handle\n case nextChr of\n '\\n' -&gt; return s\n _ -&gt; readHeaderLine' $ s ++ [chr, nextChr]\n _ -&gt; readHeaderLine' $ s ++ [chr]\n</code></pre>\n\n<p>Next, your <code>nextChr &lt;- hGetChar handle ; case nextChr of</code> limes appear twice, so you can extract a function and reduce code duplication.</p>\n\n<p>Thanks to purity, you can do pretty mechanically:</p>\n\n<pre><code>foo handle quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz\n</code></pre>\n\n<p>Now replace the two fragments with calls to <code>foo</code>. Let's start with inner one:</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = do\n chr &lt;- hGetChar handle\n case chr of\n '\\r' -&gt; do\n foo handle '\\n' (return s) (readHeaderLine' $ s ++ [chr, nextChr])\n _ -&gt; readHeaderLine' $ s ++ [chr]\n</code></pre>\n\n<p>Heh, it didn't work because <code>nextChr</code> is only known inside <code>foo</code>. No problem, pass it as parameter to <code>baz</code> branch and use lambda to catch it:</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = do\n chr &lt;- hGetChar handle\n case chr of\n '\\r' -&gt; do\n foo handle '\\n' (return s) (\\nextChr -&gt; readHeaderLine' $ s ++ [chr, nextChr])\n _ -&gt; readHeaderLine' $ s ++ [chr] \n\nfoo handle quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>So now you can do the outer one.</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = do\n foo handle '\\r' (foo handle '\\n' (return s) (\\nextChr -&gt; readHeaderLine' $ s ++ [chr, nextChr])) (\\chr -&gt; readHeaderLine' $ s ++ [chr])\n</code></pre>\n\n<p>No luck again as first <code>chr</code> is nowhere to get from. Fortunately we know it's always '\\r', so </p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = do\n foo handle '\\r' (foo handle '\\n' (return s) (\\nextChr -&gt; readHeaderLine' $ s ++ ['\\r', nextChr])) (\\chr -&gt; readHeaderLine' $ s ++ [chr])\n</code></pre>\n\n<p>As line got too long, we can split it, removing another redundant <code>do</code>:</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = foo handle '\\r' haveCR noCR where\n haveCR = foo handle '\\n' (return s) haveCRnoLF\n noCR chr = readHeaderLine' $ s ++ [chr]\n haveCRnoLF nextChr = readHeaderLine' $ s ++ ['\\r', nextChr]\n</code></pre>\n\n<p>Now there are more repeated patterns to eliminate: <code>foo handle</code> and <code>readHeaderLine' $ s ++</code>. To remove <code>foo handle</code> we move <code>foo</code> back in and remove its <code>handle</code> parameter both from applications and definition as it's now accessible from closure:</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = readHeaderLine' $ s ++ [chr]\n haveCRnoLF nextChr = readHeaderLine' $ s ++ ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>To eliminate <code>readHeaderline'</code> repeated patterns we extract them into <code>recurse</code> local function:</p>\n\n<pre><code>readHeaderLine handle = readHeaderLine' \"\" where\n readHeaderLine' s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = recurse [chr]\n haveCRnoLF nextChr = recurse ['\\r', nextChr]\n recurse x = readHeaderLine' $ s ++ x\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>This is how far you can get with mechanical code deduplication. Now it's time for heavier weapons. You can still:</p>\n\n<ul>\n<li>separate recursive code from non-recursive code</li>\n<li>separate monadic code from non-monadic code</li>\n</ul>\n\n<p>The initial <code>redHeaderLine'</code> call can be implemented using <code>recurse</code> with an extra parameter:</p>\n\n<pre><code>readHeaderLine handle = recurse [] [] where\n recurse s x = readHeaderLine' $ s ++ x \n readHeaderLine' s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = recurse s [chr]\n haveCRnoLF nextChr = recurse s ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>Now we can inline <code>readHeaderLine'</code> as it is only applied once:</p>\n\n<pre><code>readHeaderLine handle = recurse [] [] where\n recurse s1 x = foo '\\r' haveCR noCR where\n s = s1 ++ x\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = recurse s [chr]\n haveCRnoLF nextChr = recurse s ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>And we can remove duplication of <code>recurse s</code>:</p>\n\n<pre><code>readHeaderLine handle = recurse [] [] where\n recurse s1 x = foo '\\r' haveCR noCR where\n s = s1 ++ x\n rf = recurse s\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = rf [chr]\n haveCRnoLF nextChr = rf ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>Now let's put return value of <code>recurse</code> into a local declaration <code>g</code>:</p>\n\n<pre><code>readHeaderLine handle = recurse [] [] where\n recurse s1 x = g where\n s = s1 ++ x\n rf = recurse s\n\n g = foo '\\r' haveCR noCR\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = rf [chr]\n haveCRnoLF nextChr = rf ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>Our goal is to divorse <code>g</code> from <code>recurse</code>. You can do it by adding parameters to both <code>recurse</code> and <code>g</code> and localizing identifiers used only in <code>recurse</code> and used only in <code>g</code>:</p>\n\n<p>readHeaderLine handle = recurse g [] [] where\n recurse g s1 x = g rf s where\n s = s1 ++ x\n rf = recurse g s</p>\n\n<pre><code>g rf s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = rf [chr]\n haveCRnoLF nextChr = rf ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n</code></pre>\n\n<p>Now <code>recurse</code> is completely self-contained:</p>\n\n<p>readHeaderLine handle = recurse g [] [] where\n g rf s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return s) haveCRnoLF\n noCR chr = rf [chr]\n haveCRnoLF nextChr = rf ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr</p>\n\n<p>recurse g s1 x = g rf s where\n s = s1 ++ x\n rf = recurse g s</p>\n\n<p>But <code>g</code> is still recursive: it has a nasty <code>rf</code> parameter which is an indirect recursive application. We need to move <code>rf</code> into <code>recurse</code> too. So here comes a trick: convert a function call into a constructor.</p>\n\n<p><code>g</code> can have only 3 return values: <code>return s</code>, rf [chr] and <code>rf ['\\r', nextChr]</code>. We can represent them with a data type and return it instead of calling <code>return</code> or <code>rf</code>:</p>\n\n<pre><code>data Outcomes a b c = RF1 a | RF2 b | Return c\n\nreadHeaderLine handle = recurse g [] [] where\n g rf s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return $ Return s) haveCRnoLF\n noCR chr = return $ RF1 [chr]\n haveCRnoLF nextChr = return $ RF2 ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n\nrecurse g s1 x = analyzeOutcomes $ g rf s where\n s = s1 ++ x\n rf = recurse g s\n analyzeOutcomes outcomeM = do\n outcome &lt;- outcomeM\n case outcome of\n RF1 a -&gt; rf a\n RF2 a -&gt; rf a\n Return a -&gt; return a\n</code></pre>\n\n<p>Now <code>rf</code> parameter is unused, so we can clean the definitions of <code>g</code> and <code>recurse</code>:</p>\n\n<p>data Outcomes a b c = RF1 a | RF2 b | Return c</p>\n\n<pre><code>readHeaderLine handle = recurse g [] [] where\n g s = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return $ Return s) haveCRnoLF\n noCR chr = return $ RF1 [chr]\n haveCRnoLF nextChr = return $ RF2 ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n\nrecurse g s1 x = analyzeOutcomes $ g s where\n s = s1 ++ x\n rf = recurse g s\n analyzeOutcomes outcomeM = do\n outcome &lt;- outcomeM\n case outcome of\n RF1 a -&gt; rf a\n RF2 a -&gt; rf a\n Return a -&gt; return a\n</code></pre>\n\n<p>Now two more improvements: a) <code>RF1</code> and <code>RF2</code> outcomes can be joined into one outcome as they are handled uniformly and have the same types; b) the only reason we pass <code>s</code> is to return it in <code>Return</code> outcome, so we can eliminate <code>s</code> argument of <code>g</code> too.</p>\n\n<pre><code>data Outcomes a = RF a | Return\n\nreadHeaderLine handle = recurse g [] [] where\n g = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return Return) haveCRnoLF\n noCR chr = return $ RF [chr]\n haveCRnoLF nextChr = return $ RF ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n\nrecurse g s1 x = analyzeOutcomes g where\n s = s1 ++ x\n rf = recurse g s\n analyzeOutcomes outcomeM = do\n outcome &lt;- outcomeM\n case outcome of\n RF a -&gt; rf a\n Return -&gt; return s\n</code></pre>\n\n<p>Now <code>rf</code> and <code>analyzeOutcomes</code> are used only once and <code>Outcomes</code> type became the same as <code>Maybe</code>. So:</p>\n\n<pre><code>readHeaderLine handle = recurse g [] [] where\n g = foo '\\r' haveCR noCR where\n haveCR = foo '\\n' (return Nothing) haveCRnoLF\n noCR chr = return $ Just [chr]\n haveCRnoLF nextChr = return $ Just ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n\nrecurse outcomeM s1 x = do\n outcome &lt;- outcomeM\n let s = s1 ++ x in case outcome of\n Just a -&gt; recurse outcomeM s a\n Nothing -&gt; return s\n</code></pre>\n\n<p>Now <code>s1</code> and <code>x</code> are only used in <code>recurse</code> to construct <code>s</code>. We can then construct <code>s</code> outside of <code>recurse</code> and pass it. Also, <code>g</code> now can be inlined.</p>\n\n<pre><code>readHeaderLine handle = recurse (foo '\\r' haveCR noCR) [] where\n haveCR = foo '\\n' (return Nothing) haveCRnoLF\n noCR chr = return $ Just [chr]\n haveCRnoLF nextChr = return $ Just ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else baz chr\n\nrecurse outcomeM s = do\n outcome &lt;- outcomeM\n case outcome of\n Just a -&gt; recurse outcomeM (s ++ a)\n Nothing -&gt; return s\n</code></pre>\n\n<p>Now note that <code>outcomeM</code> is just a constant and it is not changed across recursive calls. So we can proceed further with our splitting of recursive and non-recursive code:</p>\n\n<pre><code>recurse outcomeM s = f s where\n f s = do\n outcome &lt;- outcomeM\n case outcome of\n Just a -&gt; f (s ++ a)\n Nothing -&gt; return s\n</code></pre>\n\n<p>And duplicate <code>return $ Just</code> can be moved inside <code>foo</code>:</p>\n\n<pre><code>readHeaderLine handle = recurse (foo '\\r' haveCR noCR) [] where\n haveCR = foo '\\n' (return Nothing) haveCRnoLF\n noCR chr = [chr]\n haveCRnoLF nextChr = ['\\r', nextChr]\n foo quux bar baz = do\n chr &lt;- hGetChar handle\n if chr == quux then bar else return (Just $ baz chr)\n</code></pre>\n\n<p>After renaming of nonsense identifiers in definition of <code>foo</code> we get:</p>\n\n<pre><code>readHeaderLine handle = recurse (match '\\r' haveCR noCR) [] where\n haveCR = match '\\n' (return Nothing) haveCRnoLF\n noCR chr = [chr]\n haveCRnoLF nextChr = ['\\r', nextChr]\n match expectedChar onSuccess onFailure = do\n actualChar &lt;- hGetChar handle\n if actualChar == expectedChar\n then onSuccess \n else return (Just $ onFailure actualChar)\n\nrecurse outcomeM s = f s where\n f s = do\n outcome &lt;- outcomeM\n case outcome of\n Just a -&gt; f (s ++ a)\n Nothing -&gt; return s\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T17:28:13.880", "Id": "25611", "Score": "1", "body": "Perhaps replace the expression `recurse (match '\\r' haveCR noCR) []` with `unfoldM (match '\\r' haveCR noCR)`, where [`unfoldM`](http://hackage.haskell.org/packages/archive/monad-loops/latest/doc/html/Control-Monad-Loops.html#v:unfoldM) is in the [monad-loops](http://hackage.haskell.org/package/monad-loops) package." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T09:35:24.173", "Id": "15723", "ParentId": "15722", "Score": "15" } }, { "body": "<p>You're trying to read from <code>stdin</code> until \"\\r\\n\" is encountered? You could just recursively call <code>hGetChar</code> until you find the right sequence (the buffer is maintained in reverse order and reversed at the end for efficiency reasons and to allow nice pattern-matching):</p>\n\n<pre><code>readHeaderLine :: Handle -&gt; IO String\nreadHeaderLine h = reverse &lt;$&gt; go \"\"\n where go :: String -&gt; IO String\n go ('\\n':'\\r':s) = return s\n go xs = do\n ch &lt;- hGetChar h\n go (ch:xs)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:11:19.317", "Id": "25603", "Score": "0", "body": "I changed `go s@('\\n':'\\r':_) = return s` into `go s@('\\n':'\\r':s') = return s'` so that it wouldn’t include the `\\r\\n` in the result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:12:57.057", "Id": "25604", "Score": "0", "body": "@RadekSlupik: Ah, good point - I overlooked that the EOL marker is not included in the output. I'll adjust my answer accordingly (you don't need the `s@` part anymore in that case)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:00:29.543", "Id": "15739", "ParentId": "15722", "Score": "10" } }, { "body": "<p>Note as Frerich mentioned that one serious antipattern in that code is the use of ++ to build up a list element by element. That's bad because each time you add an element, ++ traverses the whole list so far, which means building an n-element list takes O(n**2) operations. It's better to use the ByteString snoc function, or use a difference list, or build up the return string in reverse order and then reverse it. </p>\n\n<p>As for recognizing the \\r\\n, it's pretty easy to code a straightforward state machine, using a datatype to remember what's been seen so far. In the code below I build up the reversed output and then reverse it, and introduce a newtype for reversed lists to keep track of when a list hasn't been reversed yet. \"snoc\" inserts a new element at the front of a reversed list, which means it will be at the end of the unreversed list. \"snoc\" is \"cons\" spelled backwards and \"cons\" is the traditional name (from Lisp) for putting a new element at the front of a linked list.</p>\n\n<pre><code>import System.IO\n-- Seen is the datatype for the current state\n-- we don't call it State because that's a commonly used\n-- library module\ndata Seen = SeenNothing | SeenCR\ntype HostName = String\n\nhandleRequest :: HostName -&gt; Handle -&gt; IO ()\nhandleRequest host handle = do\n requestLine &lt;- readHeaderLine handle\n putStrLn $ requestLine ++ \"\\n-------------------\"\n\n-- below is a datatype we'll use for reversed lists\nnewtype Reversed a = Reversed a\nsnoc :: Reversed [a] -&gt; a -&gt; Reversed [a]\nsnoc (Reversed xs) x = Reversed (x:xs)\n\n-- turn a reversed list back to a normal one\nunreverse :: Reversed [a] -&gt; [a]\nunreverse (Reversed xs) = reverse xs\n\nreadHeaderLine h = do\n r &lt;- f h SeenNothing (Reversed \"\")\n return $ unreverse r\n\n-- this helper function does the work of building the reversed string\nf :: Handle -&gt; Seen -&gt; Reversed String -&gt; IO (Reversed String)\nf h state result = do\n c &lt;- hGetChar h\n let r = snoc result c\n go :: Seen -&gt; IO (Reversed String)\n go state = f h state r\n case (state,c) of\n (SeenCR,'\\n') -&gt; return r\n (_, '\\r') -&gt; go SeenCR\n otherwise -&gt; go SeenNothing\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:54:02.643", "Id": "15748", "ParentId": "15722", "Score": "1" } }, { "body": "<p>You can use <code>hGetContents</code> to read lazily from a handle, and the <a href=\"http://hackage.haskell.org/package/split\">split</a> package (which will hopefully be bundled into the next Haskell Platform release) provides some nice ways of dealing with lists.</p>\n\n<pre><code>import Data.List.Split (splitOn)\nimport System.IO (hGetContents)\n\n... do\n ...\n contentLines &lt;- splitOn \"\\r\\n\" &lt;$&gt; hGetContents handle\n</code></pre>\n\n<p><code>contentLines</code> will contain a lazy list of the \"entire contents\" of that handle, split into chunks that were originally separated by <code>\\r\\n</code>.</p>\n\n<p>Another approach is to use something like the <a href=\"http://hackage.haskell.org/package/conduit\">conduit</a> package. See, for example, <code>Data.Conduit.Binary.lines</code>. Keep an eye on conduit &amp; friends; I get the feeling that within the next year or so the Haskell community will start to agree on the \"best\" implementation of this sort of abstraction, and then some good tutorials will inevitably follow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T01:27:02.137", "Id": "15753", "ParentId": "15722", "Score": "7" } } ]
{ "AcceptedAnswerId": "15753", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T08:16:39.473", "Id": "15722", "Score": "15", "Tags": [ "haskell", "parsing", "functional-programming", "http" ], "Title": "How to shorten this terrible HTTP header parser?" }
15722
<p>I am a single developer on a numerics project. As it is growing, I would like to improve </p> <ul> <li>the Makefile</li> <li>the general organisation of the project</li> <li>structuring of the files</li> <li>workflow</li> </ul> <p>As it stands now I have a few classes (where a few depend on each other) and a <code>main.cc</code>. In total maybe 20 files. From that the executable is build via <code>make</code> and <code>./projectName</code> creates data files, which are later processed with gnuplot script files. This whole process can also be compressed in a shell script <code>run.sh</code>.</p> <p>I am working under Linux using gnu make and g++ compiler.</p> <p>What bothers me is:</p> <ol> <li>As I add new classes <code>make</code> takes more and more time.</li> <li>Everything is build from scratch each time <code>make</code> runs, even if only one class file is changed.</li> <li>Related to that I have seen others using a build/ directory where object files files are stored. I haven't used .obj files so far. Does that solve the problem of (2.) and if yes how do I create them using make? </li> <li>A debug and release build would be nice too, but I have seen questions on that on Stack Overflow, so I'll get to that.</li> </ol> <p>What I have is the following:</p> <p><strong>Dir Tree</strong></p> <pre><code>ProjectName |+data/ &lt;-- data files generated by program |+scripts/ &lt;-- scripts that handle data processing |~includes/ | |-headerClass1.h | |-headerClass2.h | |-... | |-main.h | |-parameters.h |~src/ | |-main.cc | |-class1.cc | |-class2.cc | |... |-Makefile |-tags |-projectname &lt;--executable </code></pre> <p><strong>Makefile</strong></p> <pre><code>workdir:=$(shell pwd) SRCS = $(workdir)/src/main.cc \ $(workdir)/src/class1.cc \ $(workdir)/src/class2.cc \ ... INCLUDE = -I$(workdir)/include/\ -I$(workdir)/src/ CTALL = $(workdir)/include/*\ $(workdir)/src/* CTAGS = ctags DEL = /bin/rm -f RESULT = projectname CC = g++ LIBS= -lm -lboost_timer -lboost_filesystem -lboost_system OPT = -O3 -Wall -ggdb -D__STDC_FORMAT_MACROS -std=c++0x -fipa-matrix-reorg all: clean $(RESULT) ctags $(RESULT): $(SRCS) $(CC) $(LIBS) $(OPT) $(INCLUDE) $(SRCS) -o $@ # Rules for generating the tags. # #------------------------------------- ctags: $(CTALL) $(CTAGS) $(CTALL) clean: @echo "cleaning ..." $(DEL) $(RESULT) </code></pre>
[]
[ { "body": "<p>Note that some of the commands below may be specific to GNU Make - you haven't said what tools you're using (although I guess you're on Windows since you mention .obj files).</p>\n\n<h2>Rules and object files</h2>\n\n<p>Currently, you have <code>$(RESULT): $(SRCS)</code>, so it has to re-run your whole (single) compile line every time anything in <code>$(SRCS)</code> changes. Cacheing the compiler output for each individual file can indeed save time here:</p>\n\n<pre><code>$(OBJS) = $(patsubst %.cc, %.obj, $(SRCS))\n\n$(RESULT): $(OBJS)\n $(CC) $(LIBS) $(OPT) $(INCLUDE) -o $@ $^\n</code></pre>\n\n<p>would do this (it just links all the .obj files to form your executable).</p>\n\n<p>Now you need to tell make how to build those .obj files, which you can either leave up to the implicit rule (setting CXXFLAGS appropriately) or explicitly with:</p>\n\n<pre><code>%.obj : %.cc\n $(CC) $(OPT) $(INCLUDE) -c -o $@ $^\n</code></pre>\n\n<hr>\n\n<h2>Directory structure</h2>\n\n<p>Note that leaving your build objects and output data inside your project tree isn't ideal - specifically it can add noise to whatever SCM tool you use, risks adding .obj files to source code control, which you almost certainly don't want, and makes it generally harder than necessary to clean your source tree.</p>\n\n<p>You can use the <code>patsubst</code> command to change the path as well as the suffix of your object files, eg.</p>\n\n<pre><code>$(OBJS) = $(patsubst src/%.cc, build/%.obj, $(SRCS))\n</code></pre>\n\n<hr>\n\n<h2>Dependencies</h2>\n\n<p>One major thing you're missing is header file dependencies: if you change a <code>.h</code> file, your makefile should be able to figure out which .o files need re-building. I don't know your toolchain, but for example <a href=\"https://stackoverflow.com/q/2394609/212858\">gcc can automate this</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:56:06.077", "Id": "15726", "ParentId": "15724", "Score": "0" } }, { "body": "<h3>Common Conventions</h3>\n\n<ol>\n<li>The C++ compiler is named CXX</li>\n<li>What you call RESULT is usually named TARGET</li>\n<li>In addition to SRC you probably need OBJ</li>\n<li>Commands are usually replaced by uppercase version varaiable names that name themselves.\n<ul>\n<li>ie. RM not DEL</li>\n</ul></li>\n</ol>\n\n<h3>Building issues</h3>\n\n<p>It rebuilds everything every time for two reasons.</p>\n\n<p>The <code>all:</code> rule performs a <code>clean:</code> before it starts. So obviously it has to rebuild everything:</p>\n\n<pre><code>all: clean $(RESULT) ctags\n # ^^^^^^ Get rid of this\n</code></pre>\n\n<p>RESULT is dependent on SRC and rebuilds the executable from scratch each time. What you need to do is depend on OBJ and then you only need to link the objects together to build the executable. Each object will have its own dependency and only be re-built if the source file changes.</p>\n\n<p>Note: Any common commands should follow the conventions set by the implicit rules:</p>\n\n<p>The implicit rule for linking is:</p>\n\n<pre><code>$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)\n</code></pre>\n\n<p>You have a slightly more complex case but I would thus make my link command:</p>\n\n<pre><code>$(RESULT): $(OBJ)\n $(CXX) $(LDFLAGS) -o $@ $(OBJ) $(LOADLIBES) $(LDLIBS) \n</code></pre>\n\n<p>In your case you have a set of extra libs I would then add them as follows</p>\n\n<pre><code>LDLIBS += -lm -lboost_timer -lboost_filesystem -lboost_system\n # ^^^^ Notice the +=\n # This makes it easy to add future enhancements to the makefile\n</code></pre>\n\n<p>The default rule for building <code>*.o</code> files from C++ files is:</p>\n\n<pre><code>$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c\n</code></pre>\n\n<p>Your header files inclusion is part of the pre-processor stage so should be added to the <code>CPPFLAGS</code> macro.</p>\n\n<pre><code>CPPFLAGS += $(INCLUDE)\n</code></pre>\n\n<p>Now your object files will build as you expect.</p>\n\n<p>But normally you don't want to build your object files into the same directory as your source files. This is because you can have different <code>build</code> versions. eg you can have a debug build and a release build. You should never mix and match object from different builds. In fact no compiler manufacturer makes any guarantees about object files built with different compiler flags. So any differences in compiler flags can potentially make the object files incompatible. As a result build your object files into different sub directories based on the type of build.</p>\n\n<p>Personally I build release into a directory called <code>release</code> and debug into a directory called <code>debug</code>. I know very boring. I also suffix any targets with their type.</p>\n\n<p>Say I am building the lib <code>plop</code>.</p>\n\n<pre><code>libplop.&lt;version&gt;.so // release version of plop\nlibplopD.&lt;version&gt;.so // debug version of plop\nlibplopS.&lt;version&gt;.so // Single threaded version (only build this if there is a specific difference for a single threaded version of the library that can be exploited (rare))\nlibplopSD.&lt;version&gt;.so // Single threaded debug version\n</code></pre>\n\n<p>This way I can install both normal and debug version of a library and explicitly link other code against them.</p>\n\n<p>Anyway back to your make file. To achieve this I normally do</p>\n\n<pre><code>OBJ = $(patsubst %.cc,$(BUILD)/%.o, $(SRC))\nBUILD ?= .\nTARGET = projectname$(BUILD_EXT)\n # BUIlD_EXT is the suffix I place on executable to tell if it is debug/relese and version information\n # BUILD defines the build type. If this is not specified an unadulterated\n # build is done into the current directory (rather than debug/release)\n # You can do this by directory building target `make target`\n\n## You can add build specific flags like this\n## Set BUILD_EXT using the same technique.\nCXX_BUILD_FLAGS_debug = -g\nCXX_BUILD_FLAGS_release = -O3\nCXXFLAGS += $(CXX_BUILD_FLAGS_$(BUILD))\n\nall: debug ctags\n # by default build debug version\n # if you want release you must explicitly ask for it\n\ndebug:\n $(MAKE) BUILD=debug target\nrelease:\n $(MAKE) BUILD=release target\n\ntarget: $(TARGET)\n\n$(TARGET): $(OBJ)\n $(CXX) $(LDFLAGS) -o $@ $(OBJ) $(LOADLIBES) $(LDLIBS) \n\n$(BUILD)/%.o: %.cc\n $(CXX) $^ -c -o $@ $(CPPFLAGS) $(CXXFLAGS)\n</code></pre>\n\n<h3>Organization of files.</h3>\n\n<p>I normally put header and source files into the same directory. And I normally break these into directories based on libraries or executable. </p>\n\n<p>But I add an install target into to my makefile that uploads the <code>binary and required header files</code> to a build directory for other projects so they can use it. </p>\n\n<pre><code># Note this is not real makefile (pseudo make)\n# It is designed to show intention not real make instructions.\ninstall:\n $(generate_source_control_tag)\n $(CP) $(TARGET) $(BUILD)/bin # used for executables\n $(CP) $(TARGET) $(BUILD)/lib # used for libs\n $(CP) $(TARGET_INCLUDES) $(BUILD)/include/$(TARGET_BASE)/\n</code></pre>\n\n<p>This way if I am working on a project I can leave it (potentially in mid modification) and work on another library without the two being affected. The two will only ever interact after they have been installed into the build directory.</p>\n\n<p>This means I also add the following too my makefile</p>\n\n<pre><code> CPPFLAGS += -I$(BUILD)/include\n LDFLAGS += -L$(BUILD)/lib\n</code></pre>\n\n<p>Now if project <code>B</code> wants to use the library from project <code>A</code>. Then the convention becomes.</p>\n\n<pre><code> #include \"A/A_HeaderFile_1.h\"\n\n LDLIBS += -lA\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T18:09:33.187", "Id": "25613", "Score": "0", "body": "Hi Loki, thanks for the in-depth answer. I tried to implement you suggestions as good as I could, however i am not able to build my project. Could you have a look at my **EDIT2** above? That would be great." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T18:25:50.363", "Id": "25615", "Score": "0", "body": "@DaFrenk: That is because your makefile is not in the directory with the source files (which is where I would normally place the make file). Thus the following `OBJ = $(patsubst %.cc,$(BUILD)/%.o, $(SRC))` is not matching correctly. Here `%` will be matching `$(workdir)/src/main` and thus your output file will be named: `$(BUILD)/$(workdir)/src/main.o`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T15:53:37.417", "Id": "15738", "ParentId": "15724", "Score": "11" } } ]
{ "AcceptedAnswerId": "15738", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T10:24:57.907", "Id": "15724", "Score": "7", "Tags": [ "c++", "makefile" ], "Title": "Improving Makefile and general C++ project structure" }
15724
<p>I am developing a meta-data framework for monitoring systems such that I can easily create data adapters that can pull in data from different systems. One key component is the unit of measurement. To compare datasets which have different units I need to convert them to a common unit. To build adapters I need to have a system capable of describing complicated situations.</p> <p>Units are just strings that define what the numbers mean e.g. 102 kWh is 102 kiloWatt hours, this can be converted to the SI unit for energy (Joules) by multiplying by a conversion factor (3600000 in this case).</p> <p>Some data sources have built in conversion systems and provide me with data to a base unit that they specify, e.g. one database will give me energy data measured in various units (one may be called 'kWh*0.01', another 'Btu*1000'). These data will be provided along with a conversion factor to calculate the 'base unit' for that system which is e.g. GJ.</p> <p>Here is my code to define units</p> <pre><code>class Unit(object): def __init__(self, base_unit, coefficient, name, suffix): self.name = name self.suffix = suffix self.base_unit = base_unit self.coefficient = float(coefficient) def to_base(self, value): return value * self.coefficient def from_base(self, value): return value / self.coefficient def to_unit(self, value, unit): if unit.base_unit != self.base_unit: raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit, unit.base_unit) return unit.from_base(self.to_base(value)) def __repr__(self): return "%s (%s)" % (self.name, self.suffix) class BaseUnit(Unit): def __init__(self, name, suffix): super(BaseUnit, self).__init__(self, 1.0, name, suffix) </code></pre> <p>I use these classes to represent the unit information pulled from the source database. In this case, I pass in a record from the 'units' table and use the appropriate fields to construct a unit with the given description and abbreviation that can then be converted into the base unit provided by the system (GJ for energy, M3 for water).</p> <pre><code>def convert_unit(unit): """Convert a provided unit record into my unit""" desc = unit.description.strip() suffix = unit.abbreviation.strip() if unit.type == 'energy': base = BaseUnit("GigaJoules", "GJ") return Unit(base, float(unit.units_per_gj), desc, suffix) elif unit.type == 'water': base = BaseUnit("Cubic metres", "m3") return Unit(base, float(unit.units_per_m3), desc, suffix) else: return BaseUnit(desc, suffix) </code></pre> <p>When designing my classes I had in the back of my mind an idea to enforce a common base unit (e.g. Joules) for energy across multiple data sources, I think I can do this by adding another tier and simply making the current base unit a unit with a given base (may require hard coding the conversion factor between my base unit and GJ).</p> <pre><code>def convert_unit(unit): """Convert a provided unit record into my unit""" desc = unit.description.strip() suffix = unit.abbreviation.strip() if unit.type == 'energy': base = BaseUnit("Joules", "J") source_base = Unit(base, 1000000000, "GigaJoules", "GJ") return Unit(source_base, float(unit.units_per_gj), desc, suffix) elif unit.type == 'water': base = BaseUnit("Cubic metres", "m3") return Unit(base, float(unit.units_per_m3), desc, suffix) else: return BaseUnit(desc, suffix) </code></pre> <p>The to_base, from_base and to_unit methods are intended for use with numpy arrays of measurements. I typically use the unit classes inside a dataset class that holds data as a numpy array and a unit instance.</p> <p>How does this look? It feels neat to me. Are there any style issues? </p>
[]
[ { "body": "<pre><code>raise TypeError, \"Units derived from %s and %s are incompatible.\" % (self.base_unit)\n</code></pre>\n\n<p>The python style guide recommends raising exceptions in the <code>raise TypeError(message)</code> form. TypeError is also questionable as the correct exception to throw here. The error here doesn't seem to be quite the same as making inappropriate use of python types. I'd have a UnitError class.</p>\n\n<pre><code>def __repr__(self): \n return \"%s (%s)\" % (self.name, self.suffix)\n</code></pre>\n\n<p><code>__repr__</code> is supposed to return either a valid python expression or something of the form <code>&lt;text&gt;</code></p>\n\n<pre><code>base = BaseUnit(\"Cubic metres\", \"m3\") \n</code></pre>\n\n<p>I'd make a global cubic meter object</p>\n\n<p>My overall thought is: do you really need this? My inclination would be to convert all data to the correct units as I read it. That way all data in my program would be using consistent units and I wouldn't have to worry about whether data is in some other exotic unit. Of course, depending on your exact scenario, that may not be a reasonable approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:14:25.433", "Id": "25652", "Score": "0", "body": "Thanks Winston, I think I need it primarily because I don't know what units the raw data will be in. This code is part of" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:23:04.427", "Id": "25653", "Score": "0", "body": "A system for converting the data into the required units. The required units are not always known in advance. I may want to define a custom unit (e.g. The 'cup of tea') for a particular task." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:29:07.963", "Id": "25654", "Score": "0", "body": "Re global units. Would these be best as separate constants in the module namespace or a single dict or set of units?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T18:43:26.513", "Id": "25746", "Score": "0", "body": "@GraemeStuart, I'd make them constants in a module namespace. I might make a module just for my standard units." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T14:26:34.163", "Id": "15734", "ParentId": "15728", "Score": "2" } } ]
{ "AcceptedAnswerId": "15734", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T11:24:08.107", "Id": "15728", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "OOP design of code representing units of measurement" }
15728
<p>I'm looking at some code that goes a bit like this:</p> <pre><code>class Foo { public int Frob; public int Frib; } class Bar { public Foo Left; public Foo Right; } public void ProcessBars(Bar[] bars) { this.LeftFrobs = new int[bars.Count]; this.RightFrobs = new int[bars.Count]; this.LeftFribs = new int[bars.Count]; this.RightFribs = new int[bars.Count]; //... you get the idea int counter = 0; foreach(Bar bar in bars) { LeftFrobs[counter] = bar.Left.Frob; LeftFribs[counter] = bar.Left.Frib; //...27 more lines of similar if(bar.Left.Frob == MAGICNUM_A) LeftFribs[counter] = MAGICNUM_B; RightFrobs[counter] = bar.Right.Frob; RightFribs[counter] = bar.Right.Frib; //...27 more lines of similar if(bar.Right.Frob == MAGICNUM_C) LeftFribs[counter] = MAGICNUM_D; counter++; } } </code></pre> <p>Aesthetically, this bothers me, but so far, I haven't managed to come up with anything better. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:40:34.223", "Id": "25590", "Score": "2", "body": "I don't understand, why do you have *27* more lines like that? Do you mean `Foo` and `Bar` have more properties? How exactly do you use the arrays after you create them? I mean, why do you need an array for each combination?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:49:59.740", "Id": "25591", "Score": "0", "body": "@svick, yes, more properties. You're right about usage. I *think* it's to dump them as columns into Excel (via a wrapper which likes columns), but I haven't got that far yet. I'm just trying to refactor this bit into something manageable. Currently looking at reducing to two properties `Left` and `Right` of `Data { Frobs, Fribs }`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T13:01:44.060", "Id": "25592", "Score": "1", "body": "I don't think doing it that way would work well. If you have 60 fields, then the best way to set them is probably to have a line of code for each fields. On the other hand, having 60 fields is probably not the way to do this. But to know how to fix that, you will need to know how are they used." } ]
[ { "body": "<p>That method is immense, and is surely impossible to easily read and maintain. Once you break it into smaller methods you will be able to work with it (\"just like those acorns, one at a time\").<br>\nThis will also help avoid repetitions of code.</p>\n\n<p>I propose creating a class to hold all that data, and merely instantiate a <code>Left</code> and a <code>Right</code> objects of that class. Then move the loading of data into the class as well.</p>\n\n<p>Then the <code>foreach</code> is limited to 3 lines plus all the ifs:</p>\n\n<pre><code>public class WildGooseChaser\n{\n class Foo { public int Frob; public int Frib; }\n class Bar { public Foo Left; public Foo Right; }\n\n private InternalData Left;\n private InternalData Right;\n\n class InternalData\n {\n public int[] Frobs;\n public int[] Fribs;\n // ... 27 more lines of similar.\n\n public InternalData(int dataLength) {\n Frobs = new int[dataLength];\n Fribs = new int[dataLength];\n //... you get the idea\n }\n\n public void LoadBar(int index, Bar bar) {\n Frobs[index] = bar.Left.Frob;\n Fribs[index] = bar.Left.Frib;\n //...27 more lines of similar\n }\n }\n\n public void ProcessBars(Bar[] bars) {\n Left = new InternalData(bars.Length);\n Right = new InternalData(bars.Length);\n\n int counter = 0;\n foreach (Bar bar in bars) {\n Left.LoadBar(counter, bar);\n Right.LoadBar(counter, bar);\n\n if (bar.Left.Frob == MAGICNUM_A) {\n Left.Fribs[counter] = MAGICNUM_B;\n }\n\n if (bar.Right.Frob == MAGICNUM_C) {\n Left.Fribs[counter] = MAGICNUM_D;\n }\n\n counter++;\n }\n }\n}\n</code></pre>\n\n<p>If you receive an array, you can use for instead of foreach.<br>\nSo you can either get rid of the <code>counter</code> variable, or receive an <code>IEnumerable&lt;Bar&gt;</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T13:10:33.473", "Id": "25593", "Score": "0", "body": "Very nice. I was already part of the way there, but hadn't got as far as pulling the common logic into the data class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T13:15:11.473", "Id": "25594", "Score": "0", "body": "It's actually a list, but I'm always in two minds about for when I also need to access the objects: `for i` with added `bar = bars[i]`, or `foreach` with `index++`, or even `Select((bar, index) =>`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T13:23:36.947", "Id": "25597", "Score": "0", "body": "Sorry, that's three minds :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:47:29.547", "Id": "15732", "ParentId": "15729", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T12:13:06.390", "Id": "15729", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Converting 'list of Foo' into 'lists of Foo properties'" }
15729
<p>I've created this very small header that allows direct creation of threads from lambdas. I can't find anything else similar on the net so I want to know whether there are any problems with this that I have not thought of. It is based on <a href="http://tinythreadpp.bitsnbites.eu/">tinythread++</a>, but can easily be altered to work with pthread or other threading libraries that can take a <code>void (void*)</code> (or <code>void* (void*)</code>) function and a <code>void*</code> argument for the function to start a thread. Note that this implementation is assuming limited C++0x/11 support, i.e. just lambdas.</p> <pre><code>#include "tinythread.h" namespace lthread { /// implementation details - do not use directly namespace impl { template&lt;typename Func&gt; void use_function_once(void* _f) { const Func* f = (const Func*)_f; (*f)(); delete f; // delete - no longer needed } template&lt;typename Func&gt; void use_function(void* _f) { const Func* f = (const Func*)_f; (*f)(); } } /// Creates a thread based on a temporary function. /// Copies the function onto the heap for use outside of the local scope, removes from the heap when finished. template&lt;typename Func&gt; tthread::thread* new_thread(const Func&amp; f) { Func* _f = new Func(f); // copy to heap return new tthread::thread(&amp;impl::use_function_once&lt;Func&gt;,(void*)_f); } /// Creates a thread based on a guaranteed persistent function. /// Does not copy or delete the function. template&lt;typename Func&gt; tthread::thread* new_thread(const Func* f) { return new tthread::thread(&amp;impl::use_function&lt;Func&gt;, (void*)f); } } </code></pre> <p>Example usage:</p> <pre><code>size_t a = 1; size_t b = 0; tthread::thread* t = lthread::new_thread([&amp;] () { std::cout &lt;&lt; "I'm in a thread!\n"; std::cout &lt;&lt; "'a' is " &lt;&lt; a &lt;&lt; std::endl; b = 1; }); t-&gt;join(); std::cout &lt;&lt; "'b' is " &lt;&lt; b &lt;&lt; std::endl; delete t; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T23:17:04.880", "Id": "46357", "Score": "1", "body": "What if `(*f)();` should throw? You get a leak." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-05T10:39:20.420", "Id": "46461", "Score": "0", "body": "@user1095108 Good point." } ]
[ { "body": "<ol>\n<li><p>surely you can just use <code>std::function&lt;void()&gt;</code> instead of templating on the function type?</p></li>\n<li><p>capturing by reference can go horribly wrong. It's not a bug in your library, just an observation ...</p>\n\n<pre><code>tthread::thread* startthread(size_t a, size_t b)\n{\n return lthread::new_thread([&amp;] ()\n {\n std::cout &lt;&lt; \"I'm in a thread!\\n\";\n std::cout &lt;&lt; \"'a' is \" &lt;&lt; a &lt;&lt; std::endl;\n b = 1;\n }\n );\n}\n\nint main()\n{\n tthread::thread *t = startthread(1,2);\n t-&gt;join();\n delete t;\n}\n</code></pre></li>\n<li><p><code>use_function_once</code> is vulnerable to the function call throwing an exception: you should probably assign it to a smart pointer before calling, and lose the explicit delete.</p></li>\n<li><p>that overload of <code>new_thread</code> also has a problem if either <code>new</code> or <code>tthread::thread</code> can throw: it will leak the heap-allocated Func. You can fix this with a smart pointer too.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:59:56.020", "Id": "25608", "Score": "0", "body": "I have already made a change to the code - the two `new_thread` functions now have different names - the by reference version was capturing the pointer argument instead of the pointer version and thus didn't compile as intended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T17:01:32.853", "Id": "25609", "Score": "0", "body": "Also, I am fully aware of the point you are making with that snippet, but that also applies to any other deferred running of a lambda function. Users should be aware of this as when using by-reference lambdas in other situations." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T16:30:18.853", "Id": "15740", "ParentId": "15736", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T15:13:35.570", "Id": "15736", "Score": "11", "Tags": [ "c++", "multithreading", "c++11", "pthreads" ], "Title": "Threading lambda functions" }
15736
<p>These two methods do the exact same thing (or at least they are supposed to!). They both pass a simple test based on a mock context. Neither has been exposed to any integrated testing yet. </p> <ul> <li>Would one of the methods be preferred over the other (and why)?</li> <li>Does anyone see any glaring mistakes in the LINQ version (this is my first real attempt at a LINQ query)?</li> </ul> <p>As you can see the first method is using a repository to hit a database. In order to get the data needed, it makes two db calls to two different tables. The second method is an attempt to simplify the code, make it cleaner and more readable. Performance is not a primary concern at this point. It's really more of a learning exercise.</p> <pre><code>public string GetDealerEmail( string dealerId ) { var dealerAddressRepo = StagRepositoryFactory&lt;DealerAddress&gt;.GetRepository( _spcomContext ); List&lt;DealerAddress&gt; dealerAddress = dealerAddressRepo.GetWhere( x =&gt; x.DealerId.Equals( dealerId ) ).ToList( ); string addressId = dealerAddress.FirstOrDefault( item =&gt; item.AddressTypeCode.Equals( "dealer", StringComparison.CurrentCultureIgnoreCase ) ).AddressId; var addressRepo = StagRepositoryFactory&lt;Address&gt;.GetRepository( _spcomContext ); Address address = addressRepo.GetSingle( x =&gt; x.AddressId.Equals( addressId ) ); return address.Email; } public string GetDealerEmailWithLinq( string dealerId) { ISpcomContext context = _spcomContext as ISpcomContext; var query = from dealerAddress in context.DealerAddresses where dealerAddress.DealerId.Equals( dealerId ) where dealerAddress.AddressTypeCode.Equals( "dealer", StringComparison.CurrentCultureIgnoreCase ) join address in context.Addresses on dealerAddress.AddressId equals address.AddressId select address.Email; var emailAddress = query.FirstOrDefault( ); return emailAddress; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:19:27.873", "Id": "25622", "Score": "1", "body": "What library are you using in the first version of the method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T21:02:16.177", "Id": "25626", "Score": "0", "body": "@svick It's using a generic repository for database access via DbContext and EF 4.1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T21:12:25.743", "Id": "25627", "Score": "0", "body": "I would go with option 2 encapsulated within a repository method. I personally find it easier to read whilst putting inside the repository you can reuse elsewhere if required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T05:35:19.183", "Id": "25762", "Score": "3", "body": "You may also use Include() as Third option. Check out this http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx context.DealerAddresses.Where(d => d.DealerId.Equals( dealerId ) && d.AddressTypeCode.Equals( \"dealer\", StringComparison.CurrentCultureIgnoreCase )).\nInclude(d => d.Addresses).Select(d => d.Email).FirstOrDefault();" } ]
[ { "body": "<p>I personally like the Second option, like you said it is cleaner, easier to read, and looks fairly simple and straight to the point. </p>\n\n<p>I don't see any obvious mistakes in your code.</p>\n\n<p>I can only suggest that you test it vigorously and perhaps check out the option given by @Jignesh Thakker in the comments.</p>\n\n<hr>\n\n<p>you could reduce the amount of code by merging a variable to your return statement in the second block of code like this.</p>\n\n<pre><code>return query.FirstOrDefault( );\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>var emailAddress = query.FirstOrDefault( );\nreturn emailAddress;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T18:00:30.793", "Id": "33474", "ParentId": "15737", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T15:28:07.350", "Id": "15737", "Score": "10", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "Multiple repository calls or LINQ query" }
15737
<p>I couldn't find an example on how to have a custom function inherit jQuery's functions while leaving the original jQuery function I'm inheriting from unchanged (I wanted my function to have a <code>read</code> but didn't want it to get added to <code>$.Deferred</code>)</p> <p>This works, but I really suspect it isn't the right way to do it.</p> <pre><code>var DeferredFileEntry = function(){ var def = $.Deferred(); var promise = def.promise; def.read = function(textFnCallback){ // &lt;--this is the method I'm adding return $.Deferred(function(newDefer){ var newDefer = $.Deferred(); def.done(function(fileEntry){ fileEntry.getText() .done(function(text){ textFnCallback(text); newDefer.resolve(fileEntry); }); }); }).promise(); }; def.promise = function(){ //expose the custom method to the returned promise promise.read = def.read; return promise(); }; return def; }; </code></pre> <p>An example usage: </p> <pre><code>var getFileEntry = function(){ var def = DeferredFileEntry(); libraryCall() // that promises to resolve with a FileEntry object .done(function(fileEntry){ def.resolve(fileEntry); }); return def.promise(); } getFileEntry() .read(function(text){ console.log("reading content:" + text); }) .read(function(text){ //chained, //doesn't run until the previous one has resolved console.log("reading content again: "+text); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:51:28.853", "Id": "25618", "Score": "0", "body": "Did you try using [jQuery.sub](http://api.jquery.com/jQuery.sub/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:27:26.063", "Id": "25623", "Score": "1", "body": "*facepalm* didn't know about that X(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:37:04.490", "Id": "25624", "Score": "0", "body": "Where's the code for `getFileEntry`? Does it just return `DeferredFileEntry`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T00:13:37.443", "Id": "25629", "Score": "0", "body": "ah right, it returns a DeferredFileEntry promise. I should edit that in" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T10:55:56.360", "Id": "25706", "Score": "0", "body": "Why are you receiving a parameter that you never use? `function (newDefer) { var newDefer = $.Deferred();`" } ]
[ { "body": "<h2>Tips:</h2>\n\n<h1>1)</h1>\n\n<p>Returning <code>this</code> from a function of an object instance allows for the method to become chainable.</p>\n\n<p>Example:</p>\n\n<pre><code>var File = function(){\n this.readCallCount = 0;\n return this;\n};\nFile.prototype.readLine = function(){\n this.readCallCount++;\n console.log( \"read line: \" + this.readCallCount );\n return this;\n};\nvar fileA = new File();\nfileA.readLine().readLine().readLine();\n/*\noutput:\nread line: 1\nread line: 2\nread line: 3\n*/\n</code></pre>\n\n<h1>2)</h1>\n\n<p>The passed arguments from <code>deferred.resolve()</code> are saved until <code>deferred.resolve()</code> is invoked again. \nTherefore the callbacks stored from <code>deferred.done()</code> will be passed the same values from the last call from <code>deferred.resolve()</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>var arr = [];\nfunction log(str){\n return arr.push( str );\n}\nfunction fn1(time) {\n return log( \"fn1 called at \" + time );\n}\nfunction fn2(time) {\n return log( \"fn2 called at \" + time );\n}\nvar dfd = $.Deferred();\ndfd.done(fn1);\ndfd.resolve( +(new Date()) );\n\nsetTimeout(function(){\n dfd.done(fn2);\n console.log( arr.join( \", \" ) );\n}, 2000);\n/*\n outputs after 2 seconds\n fn1 called at 1348177948625, fn2 called at 1348177948625\n*/\n</code></pre>\n\n<p>Different results can be produced if a function or object is passed to <code>deferred.resolve()</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>var arr = [];\nfunction log(str){\n return arr.push( str );\n}\nfunction fn1(getTimeFunc) {\n return log( \"fn1 called at \" + getTimeFunc() );\n}\nfunction fn2( getTimeFunc ) {\n return log( \"fn2 called at \" + getTimeFunc() );\n}\nvar dfd = $.Deferred();\ndfd.done(fn1);\ndfd.resolve(function(){\n return +(new Date()) \n});\n\nsetTimeout(function(){\n dfd.done(fn2);\n console.log( arr.join( \", \" ) );\n}, 2000);\n/*\noutput after 2 seconds\nfn1 called at 1348178107859, fn2 called at 1348178109860\n*/\n</code></pre>\n\n<h1>3)</h1>\n\n<p>The callbacks passed to <code>deferred.done()</code> are saved in a callback queue called <code>$.Callbacks()</code>. \nThe queue is set like so, <code>jQuery.Callbacks(\"once memory\")</code>. This means that all the callbacks stored in the queue will only fired once and that every callback receieves the same arguments.\nAlso notes that the callbacks are fired in order of First in First out.</p>\n\n<h2>Final Code:</h2>\n\n<p>This might work. Instead of extending the deferred object to include a read method, I opted to return an plain object.</p>\n\n<p><strong>Note</strong>: My code is assuming that <code>libraryCall()</code> and <code>fileEntry.getText()</code> return a <code>deferred.promise()</code> or <code>deferred</code> object.</p>\n\n<p>Code:</p>\n\n<pre><code>var FileEntryObj = function(){\n this.libraryCallObj = libraryCall();\n};\nFileEntryObj.prototype.read = function(fn){\n this.libraryCallObj.done( function( fileEntry ){\n return fileEntry.getText().done( fn );\n });\n return this;\n};\nvar getFileEntry = function(){\n return new FileEntryObj();\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>getFileEntry().read(function (text) {\n console.log(\"reading content:\" + text);\n}).read(function (text) {\n console.log(\"reading content again: \" + text);\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:00:05.280", "Id": "15776", "ParentId": "15743", "Score": "5" } } ]
{ "AcceptedAnswerId": "15776", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:00:07.700", "Id": "15743", "Score": "4", "Tags": [ "javascript", "jquery", "asynchronous" ], "Title": "Custom function extending jQuery.Deferred" }
15743
<p>I'm upgrading/rewriting our online client portal and wondering if my log in page code looks okay so far. during this rewriting/learning process I am upgrading a number of things: PHP 5.2 to 5.3.5, MYSQL 4.1 to 5.5, md5() to SHA512 using pbkdf2, salt and multiple iterations, MySQL functions to PDO, HTML4 to 5. I'm learning about and trying to implement prepared statements, exceptions and OOP, thanks in large part to reading StackOverflow. Its a lot to wrap my head around and its not done yet (just starting) but I just want to make sure I am on the right track. I connect to MySQL on the webserver for log in/user management and I connect to Sybase on a fileserver for client account database. I have looked into classes but not sure I am ready to go there yet. So please tell me how the code looks, what I can do different/better, logic, flow.... thanks</p> <pre><code>&lt;?php set_include_path( 'c:/server/web/new/includes' ); require 'functions.php'; debug_errors(); secure_session_start(); require 'pbkdf2.php'; require 'connect_mysql.php'; require 'connect_sybase.php'; if( isset( $_SESSION[ 'user_id' ] ) ) { header( "Location: index.php" ); exit(); } if( isset( $_POST[ 'process' ] ) ) { try { $pdo_mysql = pdo_mysql(); $pdo_sybase = pdo_sybase(); $user_id = $_POST[ 'user_id' ]; $password = $_POST[ 'password' ]; if( !( preg_match( '/^[a-zA-Z0-9]{1,60}$/', $user_id ) ) || strlen( $password ) &lt; 1 || strlen( $password ) &gt; 1024 ) { $error = 'Please enter a valid User ID and Password'; } else { try { $mysql_select = $pdo_mysql-&gt;prepare( "SELECT userid, password, email, login_attempts FROM users WHERE userid = :userid LIMIT 1" ); $mysql_select-&gt;bindParam( ':userid', $user_id ); $mysql_select-&gt;execute(); if( $mysql_select-&gt;rowCount() == 1 ) { $row = $mysql_select-&gt;fetch( PDO::FETCH_ASSOC ); if( $row[ 'login_attempts' ] == 5 ) { $error = 'Your login account has been locked.'; } else { if( validate_password( $password, $row[ 'password' ] ) ) //password is correct { //session stuff here //header to index } else //password is wrong { $error = 'Incorrect User ID and/or Password'; $login_attempts =++ $row[ 'login_attempts' ]; $mysql_update = $pdo_mysql-&gt;prepare( "UPDATE users SET login_attempts = :login_attempts WHERE userid = :userid" ); $mysql_update-&gt;bindParam( ':login_attempts', $login_attempts ); $mysql_update-&gt;bindParam( ':userid', $row[ 'userid' ] ); $mysql_update-&gt;execute(); } } } else { $error = 'Incorrect User ID and/or Password'; } } catch( PDOException $ex ) { $error = "A database query error occured."; log_action( "pdo_mysql", "(" . $ex-&gt;getCode() . ")" . $ex-&gt;getMessage() ); } } } catch( PDOException $ex ) { $error = "Unable to connect to database."; log_action( "pdo_mysql", "(" . $ex-&gt;getCode() . ")" . $ex-&gt;getMessage() ); } } ?&gt; &lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;login&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;login page&lt;/div&gt; &lt;?php if( !( empty( $error ) ) ) { echo $error; } ?&gt; &lt;form action="login.php" method="post"&gt; &lt;label for="user_id"&gt;User ID&lt;/label&gt; &lt;input type="text" name="user_id" /&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="text" name="password" /&gt; &lt;input type="hidden" name="process" value="true"/&gt; &lt;input type="submit" name="submit" value="Submit" /&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p>
[]
[ { "body": "<p>Since you are updating anyways, you should just update to the most recent version of PHP if you can. I believe its supposed to be faster in addition to offering a bunch of new toys to play with, but I haven't gotten IT to update me yet and I haven't gotten around to playing with it in my spare time :(</p>\n\n<p>I'm not sure about any other devs, but I tend to avoid messing with the include path. Instead, I just provide the full path whenever necessary. But I'd be interested in hearing what the others think about this.</p>\n\n<pre><code>require $_SERVER[ 'DOCUMENT_ROOT' ] . 'relative/path/to/file.php';\n</code></pre>\n\n<p>If you are trying to learn OOP, then you are going to have to learn how to use functions first. The main problem with this script is the flow and legibility. Both would benefit quite a bit from the use of functions. Once you have everything set up in a function, then you will want to take a look at the Single Responsibility Principle to help you separate the logic into separate functions, and those functions into separate files. Then you are going to want to apply the \"Don't Repeat Yourself\" (DRY) Principle to them to make them more efficient. Once you have these concepts mastered, adapting that knowledge to OOP should be relatively simple. Trying to do it backwards is just going to confuse you. I'll try and explain some of the basics of the above concepts below.</p>\n\n<p>Another way to check if a form has been submitted is to use the super global, <code>$_SERVER[ 'REQUEST_METHOD' ]</code>. Both methods are fine, but I think having a form element just to verify that POST was done with YOUR form is a security measure that is easily bypassed. The only exception might be a unique key generated for each session id with a limited shelf life, but this is getting into some more advanced stuff that I don't have much experience in.</p>\n\n<pre><code>if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {\n</code></pre>\n\n<p>While the concept of indenting your code is good, having to indent your code over large blocks and nesting is not. This is called the Arrow Anti-Pattern. Google it to learn more, but essentially it states that heavy indentation is bad. Break early if necessary by using returns, or by reversing if/else statements so that the larger block is outside of the if/else logic and only the smaller remains then use a return in the remaining if block to prevent further parsing. For example</p>\n\n<pre><code>if( ! isset( $_POST[ 'process' ] ) ) {\n return FALSE;\n}\n\n//rest of code\n</code></pre>\n\n<p>Of course this concept will only get you so far without functions, so you'll have to implement some first. The same also holds true for try/catch blocks.</p>\n\n<p>Something from 5.2 that is still available in the newer versions is a neat, but little-known, function called <code>filter_input()</code>. This function makes REGEX unnecessary by using built in filtering/sanitizing/validating. Eliminating REGEX is always a plus in my book. Take a look at the documentation for it for a full list of what it can do, but here's an example:</p>\n\n<pre><code>$user_id = filter_input( INPUT_POST, 'user_id', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>Those <code>$error</code> strings are perfect examples of \"early return\" candidates. Returning in the case of an error ensures that no additional overhead is accrued when not necessary. Of course the drawback of this is that you can't register more than one error at a time, but sometimes this is more effort than it is worth. Besides, the way you have your current structure set up, that's all you would have gotten anyways.</p>\n\n<p>I'm not too certain what you are doing when you say \"session stuff here\" and \"header to index\", but it looks like it might be violating DRY by repeating the first redirect. Again, this is where functions would come in handy. I feel there is going to need to be more rework here, but I can't grasp what that will be at this point. The main thing that is throwing me right now is the need for an else statement. I feel incrementing the attempt before attempting authentication might be a better tactic. I'm assuming you reset this once validated, so the increment wont make a difference then. Although, an even better tactic might be to use a session variable for this, and once that variable has been incremented to the max, then log that the account has been locked. No need to access the database so frequently for something so trivial.</p>\n\n<p>Let's see... I went over the Arrow Anti-Pattern and DRY. That leaves the Single Responsibility Principle. You don't really have a good example for me to demonstrate with, but let's look at the following bit of code. This is one of the more obvious candidates for a function. Lets say the function is called <code>reloadIndex()</code>. That's a horrible name, but bare with me. Going by that name we can assume that the function is going to reload the index. Looking at the code we can confirm this, but it is also checking if the session variable \"user_id\" is set first. This is not following that principle. This function should only be concerned with reloading the index, not what is required before the index can be reloaded. That's the responsibility of whatever is calling this function. That's not to say that a function can't do more than one thing, but everything it does should be related to what it is saying its going to do. So for instance, the function that would call this one might be called <code>authenticate()</code>, and this is what it does on success.</p>\n\n<pre><code>function reloadIndex() {\n if( isset( $_SESSION[ 'user_id' ] ) )\n {\n header( \"Location: index.php\" );\n exit();\n }\n}\n</code></pre>\n\n<p>The last thing I would like to point out is that your catch statements are redundant. I'm not too familiar with try/catch, but if I'm remembering correctly, you throw an interior try error, and catch it on the outside. But, as I pointed out above, this also violates the Arrow Anti-Pattern. The easiest way to fix this is to only encapsulate the creation of the database object in the try block, as that is the only thing being tried. And then do the same with the query.</p>\n\n<pre><code>try {\n $pdo_mysql = pdo_mysql();\n} catch( PDOException $ex ) {//this will break execution\n $error = \"Unable to connect to database.\";\n log_action( \"pdo_mysql\", \"(\" . $ex-&gt;getCode() . \")\" . $ex-&gt;getMessage() );\n}\n\n//rest of code assuming success\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T11:39:38.747", "Id": "25708", "Score": "0", "body": "Yes, PHP 5.4 is better than PHP 5.3. It's faster and it is easier to code with. We expect the next PHP 5.5 version not that late, too. So if you do not want to jump over one version and still eager, try PHP 5.4 today. It's mainly backwards compatible, so you can normally just replace your current PHP binary with the new one. You can keep the old one if you want to run both next to each other (I sometimes do that for tests for community projects, so next to PHP 5.4 I can run them against 5.3, too, but normally this is not needed)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-26T17:05:40.307", "Id": "25943", "Score": "0", "body": "Thanks. Ive researched what you've said and have already begun improving. I am moving stuff into functions (where I can figure out how) and I am seeing the value of early returns. my arrow anti patterns are also disappearing. The reason for only PHP 5.3.5 is that its the last VC6 version and I didn't wan t to upgrade my Apache also." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T19:22:39.747", "Id": "15774", "ParentId": "15750", "Score": "5" } }, { "body": "<p>First of all, if you are aware of a security issue, fix it first and deploy the fixes. That is before doing something new.</p>\n\n<p>Related to this would be to switch to prepared SQL statements, which on it's own might already take you some time. You should write yourself some <strong><em>procedural</em></strong> helper functions for an easier transition.</p>\n\n<p>Doing so will also help you to identify all the places where your current code-base needs maintenance and love.</p>\n\n<p>You can then better decide with all you want to do, if that is possible.</p>\n\n<p>And btw., why didn't you list SVN -> GIT or similar? Probably you're totally missing the uttermost important tooling here? What is your version control? Do you have got any?</p>\n\n<blockquote>\n <p>procedural->oop</p>\n</blockquote>\n\n<p>Apart from switching to PDO - which has got an object oriented interface - I would not suggest you to switch to OO too much. From the code example you give, you should first learn more procedural and improve your style with it, you will then pick OO when you actually <em>need</em> it.</p>\n\n<p>Concepts like DRY work very well in many paradigms.</p>\n\n<p>You might be also interested in a sort of checklist:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/8646283/367456\">How to implement MVC style on my PHP/SQL/HTML/CSS code?</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T11:48:28.043", "Id": "15803", "ParentId": "15750", "Score": "1" } } ]
{ "AcceptedAnswerId": "15774", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T21:52:36.337", "Id": "15750", "Score": "5", "Tags": [ "php", "mysql", "pdo" ], "Title": "moving from->to: mysql->pdo, md5->pbkdf2, procedural->oop" }
15750
<p>This is my first Wordpress plugin. I would love some input from the WP/PHP/JavaScript gurus out there. It's a simple plugin that saves a post using <kbd>ctrl</kbd>-<kbd>Q</kbd> and opens a preview in a new or current window.</p> <pre><code>&lt;?php add_action('admin_menu', 'plugin_admin_add_page'); add_action('admin_init', 'plugin_admin_init'); add_action('admin_init', 'pass_option_value'); wp_register_script('quick_preview',plugins_url('/quick-preview/quick-preview.js'),array('jquery')); wp_enqueue_script('quick_preview'); function pass_option_value(){ //Gets the preview option and passes it to the quick_preview script $options = get_option('quick_preview_options'); wp_localize_script( 'quick_preview', 'quickPreviewOption', $options['window_preference'] ); } function plugin_admin_add_page() { add_options_page('Quick Preview', 'Quick Preview', 'manage_options', 'quick_preview', 'qp_options_page'); } function plugin_admin_init(){ register_setting( 'quick_preview_options', 'quick_preview_options', 'qp_options_validate'); add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'quick_preview'); add_settings_field('plugin_window_preference', 'Window Preference', 'plugin_setting_string', 'quick_preview', 'plugin_main'); } function plugin_section_text() { echo '&lt;p&gt;Choose whether you would like the post preview to open in a new window or the current window.&lt;/p&gt;'; } function plugin_setting_string() { $options = get_option('quick_preview_options');?&gt; &lt;p&gt;&lt;input id='plugin_window_preference' name='quick_preview_options[window_preference]' size='40' type='radio' value='current' &lt;? php if($options['window_preference'] === "current"){echo ("checked='checked'");}?&gt; /&gt; Current Window &lt;/p&gt; &lt;input id='plugin_window_preference' name='quick_preview_options[window_preference]' size='40' type='radio' value='new' &lt;?php if($options['window_preference'] === "new"){echo ("checked='checked'");}?&gt; /&gt; New Window&lt;p class="description"&gt;If popups are disabled you will need to add your site to the exception list in your broswer. &lt;/p&gt; &lt;?php } function qp_options_validate($input) { $newinput = array('window_preference' =&gt; trim($input['window_preference'])); if( $newinput['window_preference'] != "new" &amp;&amp; $newinput['window_preference'] != "current" ) { $newinput[ 'window_preference' ] = ""; } return $newinput; } function qp_options_page() { ?&gt; &lt;div class="wrap"&gt; &lt;div id="icon-options-general" class="icon32"&gt; &lt;br /&gt; &lt;/div&gt; &lt;h2&gt;Quick Preview Options&lt;/h2&gt; &lt;form action="options.php" method="post"&gt; &lt;?php settings_fields('quick_preview_options'); ?&gt; &lt;?php do_settings_sections('quick_preview'); ?&gt; &lt;p class="submit"&gt; &lt;input name="Submit" type="submit" class="button-primary" value="&lt;?php esc_attr_e('Save Changes'); ?&gt;" /&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p><strong>JavaScript:</strong></p> <pre><code>jQuery(document).ready(function(){ if (document.cookie.indexOf("previewCookie") &gt;= 0){ //expires added for IE document.cookie="previewCookie=true; max-age=0;expires=0;path=/wp-admin/"; //quickPreviewOption is set in quick-preview.php var previewURL = document.getElementById('post-preview'); if(quickPreviewOption === 'current'){ window.location = previewURL; } if(quickPreviewOption === 'new'){ window.open(previewURL,"wp_PostPreview","","true"); } } jQuery(document).keydown(function(e){ if((e.ctrlKey || e.metaKey) &amp;&amp; e.which == 81){ //Find #save post if it's a draft. If post is published, #save-post doesn't exist. if(jQuery('#save-post').length){ jQuery('#save-post').click(); } else if(jQuery('publish').length){ jQuery('#publish').click(); } //Sets a cookie to open the preview on page refresh. Saving a post auotmatically refreshes the page. document.cookie = "previewCookie = true;max-age = 60;path=/wp-admin/"; } }); }); </code></pre>
[]
[ { "body": "<p>Well, I can't help you with the WordPress specifics, or the jquery, which means not much at all really. But here are a few things that might help you with your PHP.</p>\n\n<p>Foremost, I would definitely consider separating your HTML from your logic. Or at the very least separate your escapes from PHP so that your PHP does not run into your HTML. It makes for much cleaner code that is also much easier to adapt and reuse. You can also take a look at heredocs and includes as another possible solution.</p>\n\n<pre><code>//proper escaping\n?&gt;\nHTML\n&lt;?php//notice not on the same line as the HTML\n\n//heredoc\necho &lt;&lt;&lt;HTML\n Long\n bit\n of\n HTML\n maybe even with some $php_variables though no statements\nHTML;//must not be indented, even if current line is 5 tabs in, this must be all the way to the left\n</code></pre>\n\n<p>You should also make sure you declare a variable before using it. <code>$newinput</code> came out of nowhere. Is it a global? Assuming for now that its not, you should declare <code>$newinput</code> as an array before manipulating it. This insures that <code>$newinput</code> definitely doesn't have any previous values, whether from a global state or some other fluke. This means no accidental appending onto another array, and no out of bounds warnings from accidentally treating a string as an array. So:</p>\n\n<pre><code>$newinput = array(\n 'window_preference' =&gt; trim( $input[ 'window_preference' ] )\n);\n</code></pre>\n\n<p>Since we are looking at this anyways, here's a couple of minor things. First, the absolute equality comparison <code>===</code> is usually only used when type is a factor. For example, <code>TRUE === TRUE</code> but <code>\"TRUE\" !== TRUE</code>. If we use the loose comparison <code>==</code>, it accomplishes the same thing and allows for the type conversion, meaning that second comparison is TRUE as well. With strings this usually isn't a factor unless comparing a false string (empty, 0, \"null\", \"false\"). Second, I believe you have comparisons confused with assignments. The body of your if and else statements don't accomplish anything. If we were to read them, it would read like so, \"<code>if( TRUE ) { TRUE; } else { TRUE; }\". Which makes no sense. If instead you meant to assign the value of</code>$newinput[ 'window_preference' ]` to itself, you needn't bother, that's redundant. If all you want to do is remove the value from the array element given the opposite of that if statement, then you can alter the if statement slightly and use an actual assignment operator like so.</p>\n\n<pre><code>if( $newinput[ 'window_preference' ] != 'new' &amp;&amp; $newinput[ 'window_preference' ] != 'current' ) {\n $newinput[ 'window_preference' ] = '';\n}\n</code></pre>\n\n<p>But then, a better way to write this would be to make this the default value and only assign the new one if necessary. This makes the code lighter and much easier to read.</p>\n\n<pre><code>$newinput = array(\n 'window_preference' =&gt; ''\n);\n\n$preference = trim( $input[ 'window_preference' ] );\nif( $preference == 'new' || $preference == 'current' ) {\n $newinput[ 'window_preference' ] = $preference;\n}\n</code></pre>\n\n<p>Hopefully this helps, sorry I couldn't answer any more specific concerns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:38:25.450", "Id": "25668", "Score": "0", "body": "Thanks for the PHP suggestions. I didn't realize how backward my validation function was! I'll also look into separating out the html and php. I've updated the code and up voted your answer. If no one else can provide a little more help with the WordPress specifics and js then I'll happily accept your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T16:42:58.307", "Id": "15770", "ParentId": "15752", "Score": "5" } }, { "body": "<p>Here are some tips for the JavaScript side:</p>\n\n<p><strong>1) Use <code>$</code> instead of <code>jQuery</code>.</strong></p>\n\n<p><strong>2) Use constant variables in place of numeric literals.</strong></p>\n\n<p>Old Code:</p>\n\n<pre><code>if ((e.ctrlKey || e.metaKey) &amp;&amp; e.which == 81) {\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var CHAR_CODE_q = 81;\nif ((e.ctrlKey || e.metaKey) &amp;&amp; e.which == CHAR_CODE_q ) {\n</code></pre>\n\n<p><strong>3) The id attribute value must be unique for all elements on a page. The opposite is true for the class attribute.</strong></p>\n\n<p>Be direct with a selection involving an id.</p>\n\n<p>Old Code:</p>\n\n<pre><code>jQuery('input[type=\"submit\"]#save-post').click();\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>jQuery('#save-post').click();\n</code></pre>\n\n<p><strong>4) <code>window.location</code> and the first argument of <code>windown.open()</code> should be set to an string that is a URL.</strong> </p>\n\n<p><code>document.getElementById()</code> returns a node element. The string value of a node element is the type of node element and not the HTML contained within the node.</p>\n\n<p>Old Code:</p>\n\n<pre><code>window.location = document.getElementById('post-preview');\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>// assuming there is a url within the html of element #post-preview.\nvar previewURL = document.getElementById('post-preview').innerHTML;\nwindow.location = previewURL;\n</code></pre>\n\n<p><strong>Final Code:</strong></p>\n\n<pre><code>if (document.cookie.indexOf(\"previewCookie\") &gt;= 0) {\n document.cookie = \"previewCookie=true; max-age=0;expires=0;path=/wp-admin/\";\n\n var previewURL = $('#post-preview').text();\n if (quickPreviewOption === 'current') {\n window.location = previewURL;\n }\n if (quickPreviewOption === 'new') {\n window.open(previewURL, \"wp_PostPreview\", \"\", \"true\");\n }\n}\n$(document.body).keydown(function (e) {\n var CHAR_CODE_q = 81;\n if ((e.ctrlKey || e.metaKey) &amp;&amp; e.which == CHAR_CODE_q) {\n if ($('#save-post').length) {\n $('#save-post').click();\n } else if ($('#publish').length) {\n $('#publish').click();\n }\n document.cookie = \"previewCookie=true;max-age=60;path=/wp-admin/\";\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T01:46:38.350", "Id": "25675", "Score": "0", "body": "Thanks for the javascript tips. I changed most of them and up voted your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T03:55:29.807", "Id": "25676", "Score": "0", "body": "@FajitaNachos What does `var previewURL = document.getElementById('post-preview');` mean? You should check the value of `previewURL`. Great job on your site by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T04:38:03.023", "Id": "25680", "Score": "0", "body": "When I print it to the console it shows the URL of the post preview. Something like www.yourblog.com/?p=266&preview=true . I tried using innerHTML like you suggested but it gave me the html of the button which was \"preview\". Thanks for the help. I'm just getting started on the site but it's fun :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T17:36:24.897", "Id": "38854", "Score": "2", "body": "One note: [Don’t use `$` instead of `jQuery` in WordPress](http://wordpress.stackexchange.com/questions/2895/not-defined-using-jquery-in-wordpress)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T01:27:03.053", "Id": "15781", "ParentId": "15752", "Score": "5" } }, { "body": "<p>I'll fill up with the missing part. <a href=\"https://codereview.stackexchange.com/a/15770\">mseancole</a> covered the PHP and <a href=\"https://codereview.stackexchange.com/a/15781\">Larry Battle</a> the JavaScript, now let's see WP Plugins perspective.</p>\n\n<p>First of all, it's recommended to dispatch all our plugin action in a safe point, i.e., the hook <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded\" rel=\"nofollow noreferrer\"><code>plugins_loaded</code></a>. And also encapsulate the functionality inside a class, so we don't have to worry with function prefixes and collisions. As boilerplate, I use <a href=\"https://gist.github.com/toscho/3804204/\" rel=\"nofollow noreferrer\">Plugin Class Demo</a>, from one of <a href=\"https://wordpress.stackexchange.com/\">WordPress Developers</a> moderators. And <a href=\"https://github.com/tommcfarlin/WordPress-Plugin-Boilerplate\" rel=\"nofollow noreferrer\">here's another one</a>, collaborative maintained, at GitHub.</p>\n\n<p>The register and enqueue functions have to be inside a proper hook, <code>admin_print_scripts</code> for the backend and <code>wp_enqueue_scripts</code> for the frontend. And, <em>most important</em>, they should only be enqueued <strong>in your plugin page</strong>, not everywhere. Note that register->enqueue->localize must be together and <code>admin_init</code> is not the place for them.</p>\n\n<p>We target the specific plugin page just after <code>add_menu_page</code>:</p>\n\n<pre><code># PHP 5.3+ anonymous function\n# we could chain all this sequence of actions like this, albeit may be a bit confusing\nadd_action( 'plugins_loaded', function() \n{\n add_action( 'admin_menu', 'my_plugin_admin_add_page' );\n});\n\nfunction my_plugin_admin_add_page() \n{\n $page_hook = add_options_page(\n 'Quick Preview', \n 'Quick Preview', \n 'manage_options', \n 'quick_preview', \n 'qp_options_page'\n );\n add_action( \"admin_print_scripts-$page_hook\", 'my_plugin_enqueue' );\n}\n\nfunction my_plugin_enqueue()\n{\n $options = get_option('quick_preview_options');\n wp_register_script( \n 'quick_preview', \n plugins_url('/quick-preview/quick-preview.js'), \n array('jquery') \n );\n wp_enqueue_script( 'quick_preview' );\n wp_localize_script( \n 'quick_preview', \n 'quickPreviewOption', \n array(\n 'window_pref' = &gt; $options['window_preference']\n )\n );\n}\n</code></pre>\n\n<p>Finally, a <a href=\"https://wordpress.stackexchange.com/a/55232\">small observation</a> regarding <code>$</code> and jQuery with WordPress:</p>\n\n<pre>\njQuery(document).ready(function( <b>$</b> ) // &lt;------- <b>$</b>\n{\n $('#now-its-safe-to-use-dollar-sign').show()\n});\n</pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:58:24.523", "Id": "32299", "ParentId": "15752", "Score": "1" } } ]
{ "AcceptedAnswerId": "15770", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T01:24:26.600", "Id": "15752", "Score": "6", "Tags": [ "javascript", "php", "wordpress" ], "Title": "First Wordpress plugin for saving a post" }
15752
<p>my connection code:</p> <pre><code> &lt;?php try { $pdo = new PDO("mysql:host=localhost;dbname=game; charset=utf8", "root"); } catch(PDOException $e){ echo $e-&gt;getMessage(); } ?&gt; </code></pre> <p>my class code:</p> <pre><code> &lt;?php include './database/config.php'; class DB { public function dataWarrior($battle,$name,$type){ global $pdo; try { $stmt = $pdo-&gt;prepare("SELECT battle_id,warrior_name,warrior_type,health,attack,defense,speed,evade FROM battle WHERE battle_id = :battle AND warrior_name = :name AND warrior_type = :type LIMIT 1"); $stmt-&gt;execute(array(":battle"=&gt;$battle, ":name"=&gt;$name, ":type"=&gt;$type)); return $stmt; } catch(PDOException $e){ echo $e-&gt;getMessage(); } } public function checkBattleID($battle){ global $pdo; try { $stmt = $pdo-&gt;prepare("SELECT battle_id FROM battle WHERE battle_id=:battle LIMIT 1"); $stmt-&gt;execute(array(":battle"=&gt;$battle)); if($stmt-&gt;rowCount()&gt;0){ return false; } else { return true; } } catch(PDOException $e){ echo $e-&gt;getMessage(); } } public function createBattle($warrior){ global $pdo; try { $stmt = $pdo-&gt;prepare('INSERT INTO battle(battle_id,warrior_name,warrior_type, health,attack,defense,speed,evade) VALUES(:battle,:name,:type,:health,:attack,:defense,:speed,:evade)'); $stmt-&gt;execute(array(':battle'=&gt;$warrior['battle'], ':name'=&gt;$warrior['name'], ':type'=&gt;$warrior['type'], ':health'=&gt;$warrior['health'], ':attack'=&gt;$warrior['attack'], ':defense'=&gt;$warrior['defense'], ':speed'=&gt;$warrior['speed'], ':evade'=&gt;$warrior['evade'])); } catch(PDOException $e){ echo $e-&gt;getMessage(); } } public function deleteBattle($battle){ global $pdo; try { $stmt = $pdo-&gt;prepare('DELETE FROM battle WHERE battle_id = :battle'); $stmt-&gt;execute(array(':battle'=&gt;$battle)); } catch(PDOException $e){ echo $e-&gt;getMessage(); } } } ?&gt; </code></pre>
[]
[ { "body": "<p>No, you can't bocouse you relying on a global object which is bad try dependency injection at you class constructor.</p>\n\n<pre><code>&lt;?php \ninclude './database/config.php'; \n\nclass DB { \n\n private $_pdo;\n\n public function __construct(\\PDO $pdo) {\n $this-&gt;_pdo = $pdo;\n }\n\n public function dataWarrior($battle,$name,$type){ \n $stmt = $this-&gt;_pdo-&gt;prepare(\"SELECT battle_id,warrior_name,warrior_type,health,attack,defense,speed,evade \n FROM battle WHERE battle_id = :battle AND warrior_name = :name AND warrior_type = :type LIMIT 1\"); \n\n $stmt-&gt;execute(array(\":battle\"=&gt;$battle, \":name\"=&gt;$name, \":type\"=&gt;$type)); \n\n return $stmt;\n } \n public function checkBattleID($battle){ \n $stmt = $this-&gt;_pdo-&gt;prepare(\"SELECT battle_id FROM battle WHERE battle_id=:battle LIMIT 1\"); \n\n $stmt-&gt;execute(array(\":battle\"=&gt;$battle)); \n\n return $stmt-&gt;rowCount() &gt; 0; \n } \n public function createBattle($warrior){ \n $stmt = $this-&gt;_pdo-&gt;prepare('INSERT INTO battle(battle_id,warrior_name,warrior_type, \n health,attack,defense,speed,evade) VALUES(:battle,:name,:type,:health,:attack,:defense,:speed,:evade)'); \n\n $stmt-&gt;execute(array(':battle'=&gt;$warrior['battle'], ':name'=&gt;$warrior['name'], \n ':type'=&gt;$warrior['type'], ':health'=&gt;$warrior['health'], ':attack'=&gt;$warrior['attack'], \n ':defense'=&gt;$warrior['defense'], ':speed'=&gt;$warrior['speed'], ':evade'=&gt;$warrior['evade']));\n\n //return battle?\n } \n public function deleteBattle($battle){ \n $stmt = $this-&gt;_pdo-&gt;prepare('DELETE FROM battle WHERE battle_id = :battle'); \n $stmt-&gt;execute(array(':battle'=&gt;$battle));\n\n //return true/false?\n } \n}\n</code></pre>\n\n<p>The try-catch block also unnecessary in your class if you only echos the error messages.</p>\n\n<p>And you should create a new connection logic (do not put the new PDO stuff in a code file which is included every time when you need somewhere) becouse this type of connecting to database is not a solution in 2012.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:09:21.653", "Id": "25633", "Score": "0", "body": "thankS! hm how can I able to know if there is error in my query?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:10:21.873", "Id": "25634", "Score": "0", "body": "how can I improve my connection logic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:18:48.820", "Id": "25635", "Score": "0", "body": "The will throw an exception and the PHP script will stop executing when this happens and will produce error messages by it's self. The connection logic is a harder question all depends on you application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:24:36.067", "Id": "25636", "Score": "0", "body": "for example an application with login, user registration update user like that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:51:05.347", "Id": "25637", "Score": "0", "body": "It not depends on that your application dong much more on how your application built up. I recommend you to look after the SOLID principles, dependency injection (and also search for a dependency injection container) and maybe the MVC (and any other recommended pattern on your way) pattern." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:07:02.563", "Id": "15757", "ParentId": "15755", "Score": "3" } }, { "body": "<p>Stay away from globals. You will never need them. Never. Especially don't use globals in a class where they are completely unnecessary. They are an older technology that is full of security holes. Because <code>$pdo</code> is in the global scope, if I were of malicious intent I could hack into your database simply by using the already authenticated variable you gave me. This also makes it difficult to figure out where your variables are coming from. Without any kind of context it could become very easy to lose track of it. Instead of separating your connection logic from your class, just put it in the class constructor and use class properties to simulate a \"global\" state. Unlike Peter's example, this keeps the connection logic associated with the class instead of injecting it. The problem with dependency injection, in this case, is that it makes no sense unless you are reusing that same connection in another class at the same time. With the limited knowledge of this system I cannot know one way or the other and so DI seems a bit abstract.</p>\n\n<pre><code>private $pdo;//declare class property first\n\npublic function __construct() {\n try {\n $this-&gt;pdo = new PDO(//define class property\n 'mysql:host=localhost;\n dbname=game;\n charset=utf8',\n\n 'root'\n );\n } catch( PDOException $e ) {\n echo $e-&gt;getMessage();\n }\n}\n\n//to use class property\n$this-&gt;pdo-&gt;prepare(/*etc...*/);\n</code></pre>\n\n<p>The reason we are using private in the above scenario is the same reason we aren't using globals. If the property were public it could be accessed outside of the class, which is not something we want to provide access to.</p>\n\n<p>You have three more variables that could be made into properties. Properties are an essential part of OOP, they encapsulate the data needed to make the class work. They do this by allowing different methods to communicate with each other by storing and accessing properties within their class instead of returning and parsing parameters. Not to say methods can't have parameters, only that most become unnecessary. Without properties, you might as well be using regular functions. So, how do we apply this? The parameters you pass to your <code>dataWarrior()</code> method seem to be reused at different points in the class. The <code>$battle</code> parameter is used to determine the <code>battle_id</code> in every method, the <code>$name</code> parameter is used to get the <code>warrior_name</code> in two of the methods, and the <code>$type</code> parameter is used to get the <code>type</code> in two methods. So, instead of passing these values again and again, just assign them to a property and use that property whenever you would have used the passed parameter. This is most effective if done in the first method in which these parameters are all used. I would assume this is in <code>createBattle()</code>?</p>\n\n<pre><code>public function createBattle( $warrior ) {\n $this-&gt;battle = $warrior[ 'battle' ];\n $this-&gt;name = $warrior[ 'name' ];\n $this-&gt;type = $warrior[ 'type' ];\n\n //etc...\n}\n</code></pre>\n\n<p>Don't forget to declare those properties at the top of your class. Declaring a property is equally as important as declaring your methods. If you don't declare a property or method it defaults to the public scope, but this wont always be the case. I have heard rumors of this being deprecated soon, which means no more default values and whole lot more warnings. So be prepared and code accordingly.</p>\n\n<p>So, to answer your question: Not really, but a decent enough start. Just keep in mind the following principles: \"Don't Repeat Yourself\" (DRY), Single Responsibility, and, as Peter pointed out, SOLID, which is kind of the first two plus a few others all rolled into one. If your code follows these principles and utilizes the fundamental aspects of the OOP (Encapsulation, Inheritance, and Polymorphism), then you should be fine.</p>\n\n<p>BTW: What tutorials are you using that is teaching you to use globals? I've become curious because this seems to be a growing trend recently, and if this is all coming from the same source I want to see what I can do about stopping it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T04:33:45.837", "Id": "25679", "Score": "0", "body": "Thank you sir now i know but the 2nd part of the paragraph os bit confusing sorry hehe i am still practicing in this PL and here's my sample output hehe ^^ i really neeed some advices to help me improve http://badworkx.comze.com" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T13:50:33.080", "Id": "15767", "ParentId": "15755", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T06:56:17.660", "Id": "15755", "Score": "1", "Tags": [ "php", "sql", "mysql", "pdo", "battle-simulation" ], "Title": "Storing, fetching, and deleting battle simulation results" }
15755
<p>How can I improve this code?</p> <p><strong>jQuery:</strong> </p> <pre><code>$.ajax({ url: "get_attributes.php", type: "post", datatype: "json", data: { wtype: red_type }, success: function (data) { var toAppend = ''; if (typeof data === "object") { toAppend += "&lt;tbody&gt;"; toAppend += "&lt;tr&gt;&lt;/td&gt;&lt;td class=datalabel&gt;Type:&lt;/td&gt;&lt;td&gt;" + data['type'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Health:&lt;/td&gt;&lt;td&gt;" + data['health'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Attack:&lt;/td&gt;&lt;td&gt;" + data['attack'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Defense:&lt;/td&gt;&lt;td&gt;" + data['defense'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Speed:&lt;/td&gt;&lt;td&gt;" + data['speed'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Evade:&lt;/td&gt;&lt;td&gt;" + data['evade'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;tr&gt;&lt;td class=datalabel&gt;Special:&lt;/td&gt;&lt;td&gt;" + data['special'] + "&lt;/td&gt;&lt;/tr&gt;"; toAppend += "&lt;/tbody&gt;"; $("tbody").remove(); $("#red_form table").append(toAppend); } } }); </code></pre> <p><strong>PHP:</strong></p> <pre><code> &lt;?php header("Content-Type: application/json"); $wtype = $_POST['wtype']; $attributes = array(); if($wtype == 'Ninja'){ $attributes['type'] = 'Ninja'; $attributes['health'] = '40-60'; $attributes['attack'] = '60-70'; $attributes['defense'] = '20-30'; $attributes['speed'] = '90-100'; $attributes['evade'] = '0.3-0.5'; $attributes['special'] = 'There is a 5% chance of 2x attack'; } else if($wtype == 'Samurai'){ $attributes['type'] = 'Samurai'; $attributes['health'] = '60-100'; $attributes['attack'] = '75-80'; $attributes['defense'] = '35-40'; $attributes['speed'] = '60-80'; $attributes['evade'] = '0.3-0.4'; $attributes['special'] = '10% chance of restoring +10 health when evade is successful'; } else if($wtype == 'Brawler'){ $attributes['type'] = 'Brawler'; $attributes['health'] = '90-100'; $attributes['attack'] = '65-75'; $attributes['defense'] = '40-50'; $attributes['speed'] = '40-65'; $attributes['evade'] = '0.3-0.35'; $attributes['special'] = 'increased +10 defense when health is below 20%'; } echo json_encode($attributes); ?&gt; </code></pre>
[]
[ { "body": "<p>There are a few improvements that come to my mind for the given code:</p>\n\n<ol>\n<li><p>you may want to return an status code for your JSON output instead of checking whether the result is an object. It would allow you to handle error messages and such in a more convenient manner.</p></li>\n<li><p>as a minor improvement, you can use <a href=\"http://api.jquery.com/replaceWith/\" rel=\"nofollow\">replaceWith()</a> to replace the table body instead of removing it and then appending a new one to the table.</p></li>\n<li><p>you don't have an error handler to your script... if you won't ever need it, that's cool, but it's always best to know when a script fails :)</p></li>\n<li><p>to improve concatenation performance, you might want to use <a href=\"http://www.w3schools.com/jsref/jsref_join.asp\" rel=\"nofollow\">Array's join() method</a> instead of doing <code>+=</code> for each table row.</p></li>\n<li><p>you're now removing <strong>all table bodies</strong> on the whole page, which could be kind of risky if you have more than one table there. Furthermore, the selector is extensively <em>greedy</em>, as jQuery has to find all table bodies on the whole page. It's better to use <strong>ID selectors</strong> when possible, as they are the fastest one to execute.</p></li>\n<li><p>PHP-wise, you don't handle invalid $wtype, so if no condition is met, you won't know what went wrong, since nothing relevant will be returned</p></li>\n</ol>\n\n<p>Enough of the theory, this is what I have in mind:</p>\n\n<pre><code>$.ajax({\n url: \"get_attributes.php\",\n type: \"post\",\n datatype: \"json\",\n data: {wtype: red_type},\n success: function(data) {\n if (data[\"status\"] == 200) {\n var toAppend = [];\n toAppend.push(\n \"&lt;tbody&gt;\",\n \"&lt;tr&gt;&lt;/td&gt;&lt;td class=datalabel&gt;Type:&lt;/td&gt;&lt;td&gt;\"+data['type']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Health:&lt;/td&gt;&lt;td&gt;\"+data['health']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Attack:&lt;/td&gt;&lt;td&gt;\"+data['attack']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Defense:&lt;/td&gt;&lt;td&gt;\"+data['defense']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Speed:&lt;/td&gt;&lt;td&gt;\"+data['speed']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Evade:&lt;/td&gt;&lt;td&gt;\"+data['evade']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;tr&gt;&lt;td class=datalabel&gt;Special:&lt;/td&gt;&lt;td&gt;\"+data['special']+\"&lt;/td&gt;&lt;/tr&gt;\",\n \"&lt;/tbody&gt;\"\n );\n $(\"#red_form table tbody\").replaceWith(toAppend.join(\"\"));\n } else {\n alert('An error has occured. Please try again.');\n console.log('Status: ' + data[\"status\"] + ', message: ' + data[\"message\"]);\n }\n },\n error: function(jqXHR, textStatus, errorThrown) {\n alert('An error has occured. Please try again.');\n console.log('ErrStatus: ' + textStatus + ', error: ' + errorThrown);\n }\n });\n</code></pre>\n\n<p>And the PHP:</p>\n\n<pre><code>&lt;?php\nheader(\"Content-Type: application/json\");\n$wtype = (isset($_POST['wtype']) ? $_POST['wtype'] : 'unknown');\n$attributes = array('status' =&gt; 200, 'message' =&gt; 'ok', 'type' =&gt; $wtype);\n\nswitch ($wtype) {\n case 'Ninja':\n $attributes['health'] = '40-60';\n $attributes['attack'] = '60-70';\n $attributes['defense'] = '20-30';\n $attributes['speed'] = '90-100';\n $attributes['evade'] = '0.3-0.5';\n $attributes['special'] = 'There is a 5% chance of 2x attack';\n break;\n\n case 'Samurai':\n $attributes['health'] = '60-100';\n $attributes['attack'] = '75-80';\n $attributes['defense'] = '35-40';\n $attributes['speed'] = '60-80';\n $attributes['evade'] = '0.3-0.4';\n $attributes['special'] = '10% chance of restoring +10 health when evade is successful';\n break;\n\n case 'Brawler':\n $attributes['health'] = '90-100';\n $attributes['attack'] = '65-75';\n $attributes['defense'] = '40-50';\n $attributes['speed'] = '40-65';\n $attributes['evade'] = '0.3-0.35';\n $attributes['special'] = 'increased +10 defense when health is below 20%';\n break;\n\n default: $attributes['status'] = 400;\n $attributes['message'] = 'Invalid class info has been requested.';\n}\n\necho json_encode($attributes);\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T08:15:27.797", "Id": "25638", "Score": "0", "body": "whats with the status? 200? 400? Thanks! this is this applicable right if my php example get the array values through foreach right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T09:05:00.320", "Id": "25641", "Score": "0", "body": "status is just a variable telling jQuery (in the success function) whether or not everything was processed ok... I've updated the code to use data[\"status\"] notation which is probably closer to your coding style... if for instance someone will fake the $wtype, they'll get an alert saying that they picked an invalid character class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T09:05:54.657", "Id": "25642", "Score": "0", "body": "also, I don't understand your other part of question about foreach" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T04:18:32.617", "Id": "25678", "Score": "0", "body": "example: $array = array(); foreach($stmt as $values){ $array[] = $values; } echo json_encode($array); Can I still implement the same of jquery code of yours? Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T06:51:35.543", "Id": "25687", "Score": "1", "body": "thanks for the clarification... you certainly can reuse the login with a `foreach()` statement, however the `switch` portion of the code might not be usable there in this form... it really depends on your user case" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:42:19.960", "Id": "15758", "ParentId": "15756", "Score": "5" } }, { "body": "<p>+1 To Zathrus, an excellent review. Just wanted to add a few of things about the PHP. Can't really help you with the jquery.</p>\n\n<p>First, to clarify why he is using a switch here instead of if/elseif statements. This because they are a bit cleaner and a bit faster. The first I'm sure you are able to see from his implementation, but the second won't be as noticeable without profiling.</p>\n\n<p>If we follow the DRY principle, that I mentioned from my answer to your last question, then we know only to set the type once since it is a repeated task that can easily be abstracted.</p>\n\n<pre><code>//after switch\n$attributes[ 'type' ] = $wtype;\n</code></pre>\n\n<p>But we can take that a step further. Even though its hard to see how we can fix it, the list of attributes also violates the DRY principle. Since all you are doing is creating a JSON object to return to the web page, why not just start off with one from the very beginning? Create a JSON file for every \"type\" of warrior and then you can do everything with just a single line:</p>\n\n<pre><code>return file_get_contents( \"path/to/json/$wtype.json\" );\n</code></pre>\n\n<p>You could also change this so that its just one JSON file for all warriors and you select which type after loading the file, but the above allows for the immediate return of a JSON object.</p>\n\n<p>But, as Zathrus mentioned, you might also want to return the status. So this is just to give you some ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T04:15:37.427", "Id": "25677", "Score": "0", "body": "Hi, thank you. I still not familiar with json how can I able to implement this? thanks! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T12:42:48.820", "Id": "25711", "Score": "0", "body": "@brainedwashed: Try outputting json_encode on one of your current arrays to get an idea of what it should look like, then save that string to a json file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T14:24:42.543", "Id": "15769", "ParentId": "15756", "Score": "3" } }, { "body": "<p>How about this? I moved the repeated code in <code>$attributes</code> to its own function. Also, +1 to Zathrus' review as well as mseancole's additions. Predefined json files might not be a bad idea. </p>\n\n<pre><code>header(\"Content-Type: application/json\");\n$wtype = (isset($_POST['wtype']) ? $_POST['wtype'] : 'unknown');\n\n/**\n * Set attributes for character type\n * \n * return array\n */\nfunction setAttributes($health, $attack, $defense, $speed, $evade, $special, $wtype){\n $attributes['health'] = $health;\n $attributes['attack'] = $attack;\n $attributes['defense'] = $defense;\n $attributes['speed'] = $speed;\n $attributes['evade'] = $evade;\n $attributes['special'] = $special;\n $attributes['status'] = 200;\n $attributes['message'] = 'ok';\n $attributes['type'] = $wtype;\n return $attributes;\n}\n\nswitch ($wtype) {\n case 'Ninja' : $attributes = setAttributes('40-60', '60-70', '20-30', '90-100', '0.3-0.5', $wtype, \n 'There is a 5% chance of 2x attack'); break;\n\n case 'Samurai': $attributes = setAttributes('60-100', '75-80', '35-40', '60-80', '0.3-0.4', $wtype, \n '10% chance of restoring +10 health when evade is successful'); break;\n\n case 'Brawler': $attributes = setAttributes('90-100', '65-75', '40-50', '40-65', '0.3-0.35', $wtype, \n 'increased +10 defense when health is below 20%'); break;\n\n default: $attributes['status'] = 400;\n $attributes['message'] = 'Invalid class info has been requested.';\n}\n\necho json_encode($attributes);\n</code></pre>\n\n<p>And here's the code with mseancole's method of using predefined json files:</p>\n\n<pre><code>header(\"Content-Type: application/json\");\n$wtype = (isset($_POST['wtype']) ? $_POST['wtype'] : 'unknown');\n\nswitch ($wtype) {\n case 'unknown': {\n $attributes['status'] = 400;\n $attributes['message'] = 'Invalid class info has been requested.';\n return json_encode($attributes);\n }\n default return file_get_contents( \"path/to/json/\" . strtolower($wtype) . \".json\" );\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T15:40:11.257", "Id": "15809", "ParentId": "15756", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T07:06:24.700", "Id": "15756", "Score": "3", "Tags": [ "javascript", "php", "jquery" ], "Title": "Getting JSON and putting it in a table using jQuery and PHP" }
15756
<p>I plan to use the following approach to audit the tables that represent user-editable configuration of an automated system (over the course of system's life these will be inevitably extended in their numbers and stuffed with more columns). This approach will not be applied to main data tables as those are automatically updated.</p> <p>SQL Server 2005+, based on <a href="http://www.sqlservercentral.com/Forums/Topic294216-314-3.aspx" rel="nofollow">this</a>. Suggestions?</p> <pre><code>CREATE TABLE [dbo].[audit] ( [id] [bigint] IDENTITY(1,1) NOT NULL, [time] [datetime] NOT NULL, [username] [nvarchar](128) NOT NULL, [useraddress] [nvarchar](48) NULL, [tablename] [nvarchar](128) NULL, [operation] AS (case when [oldvalue] IS NULL then 'I' when [newvalue] IS NULL then 'D' else 'U' end), [oldvalue] [xml] NULL, [newvalue] [xml] NULL ) GO ALTER TABLE [dbo].[audit] ADD CONSTRAINT [DF_audit_time] DEFAULT (sysutcdatetime()) FOR [time] GO CREATE PROCEDURE [dbo].[save_audit] @old_values xml, @new_values xml, @tablename nvarchar(128) AS BEGIN SET NOCOUNT ON; IF @old_values IS NOT NULL OR @new_values IS NOT NULL BEGIN DECLARE @username nvarchar(128), @useraddress varchar(48) SELECT @username = original_login_name FROM sys.dm_exec_sessions WHERE session_id = @@SPID SELECT @useraddress = client_net_address FROM sys.dm_exec_connections WHERE session_id = @@SPID INSERT INTO audit (username, useraddress, tablename, oldvalue, newvalue) VALUES (@username, @useraddress, @tablename, @old_values, @new_values) END END GO CREATE TRIGGER [dbo].[audit_tablename] ON [dbo].[tablename] AFTER INSERT,DELETE,UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @i xml, @d xml, @t nvarchar(128) SET @i = (SELECT * FROM inserted FOR XML AUTO) SET @d = (SELECT * FROM deleted FOR XML AUTO) SET @t = (SELECT OBJECT_NAME(parent_object_id) FROM sys.objects WHERE object_id = @@PROCID) EXEC save_audit @d, @i, @t END </code></pre> <p><strong>EDIT:</strong> Table name detection was found unreliable on 2005, fixed.</p> <p><strong>EDIT2:</strong> Not all versions of SQL Server 2005 have <code>original_login_name</code> column in <code>sys.dm_exec_sessions</code> (it was added with SP2, apparently), will have to use <code>login_name</code> if targeting all versions (the meaning is different, though).</p>
[]
[ { "body": "<p>Looks Like a nice, straight forward solution.</p>\n\n<p>The only suggestion that I have , and while this is an unlikely situation, if the database were hosted on a failover cluster and the user were to connect to the instance locally (i.e. from anyone of the servers in the cluster), you wouldn't know which computer they logged in from. The value of <code>@useraddress</code> would be set as <code>'&lt;local machine&gt;'</code>.</p>\n\n<p>This would also be the case when a user connects locally to the SQL Server instance, but if there's only one instance (i.e. not in a cluster), then it's not really a big deal, since you know which computer that is.</p>\n\n<p>Although, to play it safe, why not modify the code to set the value for <code>@useraddess</code> like this, which will give you the computer name instead of <code>'&lt;local machine&gt;'</code>:</p>\n\n<pre><code>DECLARE @useraddress nvarchar(128); --&lt;== Originally set as varchar(48)\n\nSELECT @useraddress = REPLACE(client_net_address\n ,'&lt;local machine&gt;'\n ,CAST(SERVERPROPERTY('MachineName') AS nvarchar(128)))\n FROM sys.dm_exec_connections\n WHERE session_id = @@SPID;\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms174396.aspx\" rel=\"nofollow\">SERVERPROPERTY (Transact-SQL)</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:24:44.173", "Id": "18351", "ParentId": "15760", "Score": "2" } } ]
{ "AcceptedAnswerId": "18351", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T08:47:57.763", "Id": "15760", "Score": "7", "Tags": [ "sql", "sql-server" ], "Title": "Auditing a complex mix of reasonably small tables" }
15760
<p>I am using <a href="http://scrapy.org/">scrapy</a> framework for data scraping and dumping item in MySQL database.</p> <p>Here is my pipeline that is inserting output to MySQL, but its taking so much time. Any suggestions on how to optimize this?</p> <pre><code>class MysqlOutputPipeline(object): def __init__(self): dispatcher.connect(self.spider_opened, signals.spider_opened) dispatcher.connect(self.spider_closed, signals.spider_closed) def connect(self): try: self.conn = MySQLdb.connect( host='some_host', user='user', passwd='pwd', db='my_db', port=22) except (AttributeError, MySQLdb.OperationalError), e: raise e def query(self, sql, params=()): try: cursor = self.conn.cursor() cursor.execute(sql, params) except (AttributeError, MySQLdb.OperationalError) as e: print 'exception generated during sql connection: ', e self.connect() cursor = self.conn.cursor() cursor.execute(sql, params) return cursor def spider_opened(self, spider): self.connect() def process_item(self, item, spider): # clean_name clean_name = ''.join(e for e in item['store'] if e.isalnum()).lower() # conditional insertion in store_meta sql = """SELECT * FROM store_meta WHERE clean_name = %s""" curr = self.query(sql, clean_name) if not curr.fetchone(): sql = """INSERT INTO store_meta (clean_name) VALUES (%s)""" self.query(sql, clean_name) self.conn.commit() # getting clean_id sql = """SELECT clean_id FROM store_meta WHERE clean_name = %s""" curr = self.query(sql, clean_name) clean_id = curr.fetchone() # conditional insertion in all_stores sql = """SELECT * FROM all_stores WHERE store_name = %s""" curr = self.query(sql, item['store']) if not curr.fetchone(): sql = """INSERT INTO all_stores (store_name,clean_id) VALUES (%s,%s)""" self.query(sql, (item['store'], clean_id[0])) self.conn.commit() # getting store_id sql = """SELECT store_id FROM all_stores WHERE store_name =%s""" curr = self.query(sql, item['store']) store_id = curr.fetchone() if item and not item['is_coupon'] and (item['store'] in ['null', ''] or item['bonus'] in ['null', '']): raise DropItem(item) if item and not item['is_coupon']:# conditional insertion in discounts table sql = """SELECT * FROM discounts WHERE mall=%s AND store_id=%s AND bonus=%s AND deal_url=%s""" curr = self.query( sql, ( item['mall'], store_id[0], item['bonus'], item['deal_url'] ) ) if not curr.fetchone(): self.query( "INSERT INTO discounts (mall,store_id,bonus,per_action,more_than,up_to,deal_url) VALUES (%s,%s,%s,%s,%s,%s,%s)", (item['mall'], store_id[0], item['bonus'], item['per_action'], item['more_than'], item['up_to'], item['deal_url']), ) self.conn.commit() # conditional insertion in crawl_coupons table elif spider.name not in COUPONS_LESS_STORE: if item['expiration'] is not 'null': item['expiration']=datetime.strptime(item['expiration'],'%m/%d/%Y').date() sql = """SELECT * FROM crawl_coupons WHERE mall=%s AND clean_id=(SELECT clean_id FROM store_meta WHERE clean_name = %s) AND coupon_code=%s AND coupon_text=%s AND expiry_date=%s""" curr = self.query( sql, ( item['mall'], clean_name, item['code'], self.conn.escape_string(item['discount']), item['expiration'] ) ) if not curr.fetchone(): sql = """INSERT INTO crawl_coupons (mall,clean_id,coupon_code,coupon_text,expiry_date) VALUES ( %s, (SELECT clean_id FROM store_meta WHERE clean_name = %s), %s, %s, %s )""" self.query( sql, ( item['mall'], clean_name, item['code'], self.conn.escape_string(item['discount']), item['expiration'] ) ) self.conn.commit() return item </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T16:31:44.650", "Id": "25885", "Score": "0", "body": "What makes you think this code is the bottleneck?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T16:34:13.647", "Id": "25886", "Score": "0", "body": "on mysql queries part , other then that should i use adbapi ?" } ]
[ { "body": "<p>It's hard to analyze the bottle neck without performance data on where the bottleneck is occurring. You should consider running the program several ways and comparing. Ie </p>\n\n<ul>\n<li>run program as is</li>\n<li>run program spider only with no db</li>\n</ul>\n\n<p>This should tell you the problem is in your code as you suspect. If not you are crawling something that is slow to crawl. Your program can't control that, although you can look into why it's slow. Maybe you are hitting a tar pit (ie websites put in controls to allow normal users regular access but to impede crawlers) which would affect how you crawl.</p>\n\n<p>If it is your program</p>\n\n<ul>\n<li>run program as is</li>\n<li>run program spider with just all your conditional code but no writes</li>\n</ul>\n\n<p>My suspicion is that the writes are not the issue. You can then can analyze your conditions and try to optimize. </p>\n\n<p>You are reading the db alot before writing. Whether any of those reads could be cached is data dependent on what you are crawling. If that has any predictability (eg it appears you are crawling malls and stores so I would assume alot of predictability) then maybe save at least the most recent q/a for each condition in ram so you don't need to go out to the db if you already have the answer. My guess is just caching most recent will be sufficient since crawler most likely walks 'near' items next. But if that isn't enough, analyze the db you've already gotten from your slow runs. If 90% of the db results are for Macy's then just cache Macy's condition results. Or you could put in more effort and put in a full caching class</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T12:15:03.893", "Id": "16008", "ParentId": "15763", "Score": "3" } } ]
{ "AcceptedAnswerId": "16008", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T10:20:07.620", "Id": "15763", "Score": "7", "Tags": [ "python", "optimization", "mysql", "scrapy" ], "Title": "How to optimize a pipline for storing item in mysql?" }
15763
<p>I have two classes one base Foo class and one derived Bar class. </p> <p>Each class has its own associated settings class that can create a new instance from the Load method. This way all derived class settings can be stored in one list of FooSettings.</p> <pre><code>public abstract class FooSettings { public int a; public int b; public float c; public abstract Foo Load(); } public class BarSettings : FooSettings { public float d; public override Foo Load() { return new Bar(this); } } </code></pre> <p>The classes themselves have their settings as an argument for the constructor and are created from their associated settings class (null = default settings class state)</p> <pre><code>public abstract class Foo { private int a = 0; private int b = 1; private float c = 1.2f; public Foo() { } public abstract FooSettings WriteSettings(); protected void WriteBaseFooSettings(ref FooSettings settings) { settings.a = a; settings.b = b; settings.c = c; } public int A { get { return a; } set { a = value; } } public int B { get { return b; } set { c = value; } } public float C { get { return c; } set { c = value; } } } public class Bar : Foo { float d = 0.9f; public Bar() : base() { } // METHOD A public override BaseFooSettings WriteSettings() { DerivedBarSettings settings = new DerivedBarSettings(); settings.a = A; settings.b = B; settings.c = C; settings.d = d; return settings; } // METHOD B public override FooSettings WriteSettings() { var settings = new BarSettings(); // Write base settings var baseSettings = settings as FooSettings; WriteBaseFooSettings(ref baseSettings); // Write derived/local settings settings.d = d; return settings; } } </code></pre> <p>The problem with this setup is that I found it somewhat wasteful to have to rewrite the base class settings in the derived class method each time I wrote the derived class settings (METHOD A).</p> <p>In order to get around this problem I went with METHOD B but I am not certain as to whether this is a good solution. Some advice on improving METHOD B or a better alternative would be welcome.</p>
[]
[ { "body": "<p>I think this is the right way to do it. If you have some code that should be used from the base class and all its derived classes, it should be in the base class. Which is exactly what you're doing.</p>\n\n<p>But I would make a modification in your code. You don't need to use <code>ref</code>. In C#, classes are reference types, which means that the values in the object will change, even if you don't use <code>ref</code>. And if you remove the <code>ref</code>, you won't need the <code>baseSettings</code> variable anymore, making the code shorter:</p>\n\n<pre><code>protected void WriteBaseFooSettings(FooSettings settings)\n{\n // set the properties, same as before\n}\n\n…\n\npublic override FooSettings WriteSettings()\n{\n var settings = new BarSettings();\n\n WriteBaseFooSettings(settings);\n\n // Write derived/local settings\n settings.d = d;\n\n return settings;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T12:42:44.513", "Id": "25648", "Score": "0", "body": "+1 Good answer, thank you. I was also wondering if I could make the WriteSettings method virtual in the base class and call it with `base.WriteSettings(settings)` or something similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T12:43:18.133", "Id": "25649", "Score": "0", "body": "I don't have permission to vote yet, apparently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T13:56:48.733", "Id": "25651", "Score": "0", "body": "I don't think making `WriteSetting()` would work, because that method has to create the settings object, and the base method doesn't know which type the created object should be." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T11:15:34.407", "Id": "15765", "ParentId": "15764", "Score": "5" } } ]
{ "AcceptedAnswerId": "15765", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T10:27:30.570", "Id": "15764", "Score": "4", "Tags": [ "c#", "classes" ], "Title": "Avoid explicitly writing base class state in a derived class. Suggestions for my method" }
15764
<p>please review my implementation of a FIFO data structure that guarantees thread-safe access without locking.</p> <p>I removed the license header block and all Doxygen comments. The original version (along with some tests) is available from here: <a href="https://github.com/fat-lobyte/atomic_queue">https://github.com/fat-lobyte/atomic_queue</a></p> <p>It should compile with</p> <ul> <li>Clang >= 3.1, with -stdlib=libc++</li> <li>GCC => 4.7, with -D_GLIBCXX_USE_SCHED_YIELD</li> <li>Visual Studio >= 2012 (_MSC_VER >= 1700), without emplace_back() member function</li> </ul> <p>I would ask you to check if</p> <ul> <li>It actually <em>is</em> thread safe (this is the main concern)</li> <li>It is compliant with the C++11 standard</li> <li>It performs reasonably and no resources are wasted</li> <li>If its possible to implement it more simple without losing performance or flexibility</li> </ul> <p>Additionally, if someone is a real pro in lock-free programming, they can help me answer the following question: Can I relax some of the load/store/exchange operations memory ordering constraints (pass an std::memory_order constant)? I do not understand the memory model properly, and quite frankly I find it is a really difficult to grasp.</p> <p>Help would be very appreciated. Thanks in advance!</p> <pre><code>#ifndef ATOMIC_QUEUE_HPP_INCLUDED #define ATOMIC_QUEUE_HPP_INCLUDED #include &lt;cstddef&gt; #include &lt;memory&gt; #include &lt;atomic&gt; #include &lt;thread&gt; // At the time of writing, MSVC didn't know noexcept #if defined(_MSC_VER) &amp;&amp; _MSC_VER &lt;= 1700 # define noexcept throw() #endif namespace aq { namespace detail { /** A node in the linked list. */ template &lt;typename T&gt; struct node { T t /**&lt; Value */; std::atomic&lt;node&lt;T&gt;*&gt; next /**&lt; Next node in list */; }; template &lt;typename T, typename Allocator = std::allocator&lt;T&gt; &gt; class atomic_queue_base { public: atomic_queue_base(const Allocator&amp; alc = Allocator()) noexcept : size_(0u), front_(nullptr), back_(nullptr), alc_(alc) { } ~atomic_queue_base() noexcept { node&lt;T&gt;* fr = front_; while(fr) { node&lt;T&gt;* next = fr-&gt;next; NodeAllocatorTraits::destroy(alc_, fr); NodeAllocatorTraits::deallocate(alc_, fr, 1); fr = next; } } void push_back(const T&amp; t) { auto new_node = NodeAllocatorTraits::allocate(alc_, 1); try { ValueAllocator alc(alc_); ValueAllocatorTraits::construct( alc, &amp;new_node-&gt;t, t ); } catch(...) { NodeAllocatorTraits::deallocate(alc_, new_node, 1); throw; } new_node-&gt;next = nullptr; push_node(new_node); } void push_back(T&amp;&amp; t) { auto new_node = NodeAllocatorTraits::allocate(alc_, 1); try { ValueAllocator alc(alc_); ValueAllocatorTraits::construct( alc, &amp;new_node-&gt;t, std::move(t) ); } catch(...) { NodeAllocatorTraits::deallocate(alc_, new_node, 1); throw; } new_node-&gt;next = nullptr; push_node(new_node); } #if !(defined(_MSC_VER) &amp;&amp; _MSC_VER &lt;= 1700) template&lt;typename... Args&gt; void emplace_back(Args&amp;&amp;... args) { auto new_node = NodeAllocatorTraits::allocate(alc_, 1); try { ValueAllocator alc(alc_); ValueAllocatorTraits::construct( alc, &amp;new_node-&gt;t, std::forward&lt;Args&gt;(args)... ); } catch(...) { NodeAllocatorTraits::deallocate(alc_, new_node, 1); throw; } new_node-&gt;next = nullptr; push_node(new_node); } #endif T* pop_front() noexcept { node&lt;T&gt;* old_front = front_; node&lt;T&gt;* new_front; do { if (!old_front) return nullptr; // nothing to pop new_front = old_front-&gt;next; } while(!front_.compare_exchange_weak(old_front, new_front)); --size_; // if the old front was also the back, the queue is now empty. new_front = old_front; if(back_.compare_exchange_strong(new_front, nullptr)) old_front-&gt;next = old_front; return reinterpret_cast&lt;T*&gt;(old_front); } void deallocate(T* obj) noexcept { if (!obj) return; // call destructor NodeAllocatorTraits::destroy(alc_, reinterpret_cast&lt;node&lt;T&gt;*&gt;(obj)); // nodes with next == 0 are still referenced by an executing // push_back() function and the next ptr will be modified. // Since we don't want push_back() to write to deallocated memory, we hang // in a loop until the node has a non-zero next ptr. while(!reinterpret_cast&lt;node&lt;T&gt;*&gt;(obj)-&gt;next.load()) std::this_thread::yield(); NodeAllocatorTraits::deallocate( alc_, reinterpret_cast&lt;node&lt;T&gt;*&gt;(obj), 1 ); } std::size_t size() const noexcept { return size_; } protected: void push_node(node&lt;T&gt;* new_node) noexcept { node&lt;T&gt;* old_back = back_.exchange(new_node); node&lt;T&gt;* null_node = nullptr; // if front_ was set to null (no node yet), we have to update the front_ // pointer. if(!front_.compare_exchange_strong(null_node, new_node)) // if front_ is not null, then there was a previous node. // We have to update this nodes next pointer. old_back-&gt;next = new_node; ++size_; } typedef Allocator ValueAllocator; typedef std::allocator_traits&lt;ValueAllocator&gt; ValueAllocatorTraits; // Rebind allocator traits for ValueAllocator to our own NodeAllocator typedef typename ValueAllocatorTraits::template rebind_traits&lt;node&lt;T&gt; &gt; #if defined(_MSC_VER) &amp;&amp; _MSC_VER &lt;= 1700 ::other #endif NodeAllocatorTraits; // Get actual allocator type from traits typedef typename NodeAllocatorTraits::allocator_type NodeAllocator; std::atomic_size_t size_ /**&lt; Current size of queue. Not reliable. */; std::atomic&lt;node&lt;T&gt;*&gt; front_ /**&lt; Front of the queue. */; std::atomic&lt;node&lt;T&gt;*&gt; back_ /**&lt; Back of the queue. */; NodeAllocator alc_ /**&lt; Allocator for node&lt;T&gt; objects. */; }; } // namespace detail using detail::atomic_queue_base; } // namespace aq #endif // ifndef ATOMIC_QUEUE_HPP_INCLUDED </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T17:52:05.730", "Id": "25659", "Score": "0", "body": "Note: By posting code on this site you are making it available under the creatives common license (see the bottom line on the page)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:42:54.857", "Id": "25691", "Score": "0", "body": "@LokiAstari: Thanks for the info. The original license is BSD-style, and I don't really care as long as people can use it freely and I'm accredited." } ]
[ { "body": "<p>Pretty sure this is broken in multi-threaded code:</p>\n\n<pre><code> do\n {\n // Point A.\n if (!old_front) return nullptr;\n new_front = old_front-&gt;next; \n }\n while(!front_.compare_exchange_weak(old_front, new_front));\n</code></pre>\n\n<p>What happens if:</p>\n\n<ol>\n<li>Thread A. Reaches point A</li>\n<li>Thread A is de-scheduled and is not currently running.</li>\n<li>Thread B. runs through the above code and works</li>\n<li>Thread B. destroyes the node it poped off the front.</li>\n<li>Thread A. Is re-scheduled to run. </li>\n<li>Thread A. Any use of <code>old_front</code> is invalid as it points at a node that was deleted by <code>Thread B</code></li>\n<li>Thread A. Even if the node was not destroyed it is no longer the head of the list.<br>\nThus any usage of next is suspect.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:50:46.483", "Id": "25692", "Score": "0", "body": "Thanks for looking through it!\nTechnically you are right: The old_front node might be destroyed and I could read deallocated memory which is likely to be garbage.\nBUT: the value read from old_front can be used if and only if front_ did *not* change (compare_exchange!). If front_ is the same, the old_front node *must* be alive and valid, if it is not the same, the value obtained is not written.\nI expect this to work as long as no compiler/processor starts complaining about reading deallocated memory.\nDo you see another alternative that performs acceptably?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T08:09:49.323", "Id": "25693", "Score": "0", "body": "Damn. There is another problem however. Image the following situation: The queue has two nodes: Q1, Q2, `Q1->next` points to Q2. Thread A calls pop, reads `old_front->next` and gets suspended. Then Thread B calls pop two times and succeeds. Thread B pushes another node that by chance gets allocated in the same address as Q1. Thread A gets resumed, and since `front_ == old_front`, sets `front_` to Q2 which is non-existant, and BOOM. :-( Do you see a way around this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T08:27:26.970", "Id": "25694", "Score": "0", "body": "Seems like I'm not the only one having this problem: http://en.wikipedia.org/wiki/ABA_problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T16:31:57.357", "Id": "25735", "Score": "1", "body": "@fat-lobyte: You miss the point. When `A` resumes and does `new_front = old_front->next;` you have committed `undefined behavior`. Does not matter what happens next you just broke your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T10:39:04.547", "Id": "25791", "Score": "0", "body": "You are right, this code is broken. I'll have to go back \"to the drawing board\". Thanks for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-07T14:56:04.957", "Id": "488016", "Score": "0", "body": "Here is an article on this very problem being discussed at CppCon 2014, including a solution and links to detail videos: https://www.infoq.com/news/2014/10/cpp-lock-free-programming/" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T20:39:01.083", "Id": "15775", "ParentId": "15768", "Score": "4" } }, { "body": "<p>I think the design is not very useful (apart from any possible thread safety issues). <code>pop()</code> just returns a pointer and the user is trusted with eventually de-allocating it. This cannot be exception safe (leaking memory when an exception is thrown and the pointer returned by <code>pop()</code> lost). This makes the code useless in many situations where you want to use a threadsafe stack (and is exactly what you don't want to do in C++, it smells like C).</p>\n\n<p>Anthony Williams (in \"C++ concurrency in action\") implements a lock-free stack that returns a <code>std::shared_ptr&lt;T&gt;</code> in <code>pop()</code>. I have no experience with that, but implementing <code>std::shared_ptr</code> to be threadsafe and lock-free cannot be trivial (I don't know how good the implementations provided in the various libstdc++ are).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T10:43:06.013", "Id": "26111", "Score": "0", "body": "Hi, thanks for your review!\nI know that this is a little \"raw\", but I wanted to give maximum control for minimum requirements.\nBy returning a pointer, the type does not have to be CopyConstructible or MoveConstructible and it does not create the shared_ptr overhead. Returning a pointer and requiring the user to deallocate it itself is the *minimum* required overhead. I figured that this was fair for a minimal implementation.\nNote that this class is called \"atomic_queue_base\" for a reason: a \"real\" implementation might derive from it and provide additional comforts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T10:43:21.023", "Id": "26112", "Score": "0", "body": "How is this not thread safe? pop() is noexcept, so why can't the user just \"watch out\" in the client code? There's nothing that prevents the user from putting the deallocate() call into a try block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T22:21:19.143", "Id": "26132", "Score": "0", "body": "@fat-lobyte I didn't say its not thread safe." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T09:45:35.720", "Id": "16004", "ParentId": "15768", "Score": "1" } } ]
{ "AcceptedAnswerId": "15775", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T13:53:10.520", "Id": "15768", "Score": "8", "Tags": [ "c++", "multithreading", "c++11", "atomic" ], "Title": "atomic_queue - thread-safe and lock-free implementation of the FIFO data structure pattern" }
15768
<pre><code>def sieve_of_erastothenes(number): """Constructs all primes below the number""" big_list = [2] + range(3, number+1, 2) # ignore even numbers except 2 i = 1 # start at n=3, we've already done the even numbers while True: try: # use the next number that has not been removed already n = big_list[i] except IndexError: # if we've reached the end of big_list we're done here return big_list # keep only numbers that are smaller than n or not multiples of n big_list = [m for m in big_list if m&lt;=n or m%n != 0] i += 1 </code></pre> <p>On my computer, this code takes about half a second to calculate all primes below 10,000, fifteen seconds to do 100,000, and a very long time to calculate primes up to one million. I'm pretty sure it's correct (the first few numbers in the returned sequence are right), so what can I do to optimise it?</p> <p>I've tried a version that removes the relevant numbers in-place but that takes even longer (since it takes \$O(n)\$ to move all the remaining numbers down).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:36:05.073", "Id": "25666", "Score": "0", "body": "I know this could do with more tags but I'm not allowed to create them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T05:01:23.687", "Id": "25682", "Score": "1", "body": "I'm not very familiar with Python, but I might try using an array of i -> true/false (true meaning it's a prime, false meaning it's not). Your code would then go over this array and mark numbers as non-prime. I think your large growth in time is coming from copying the modified list over and over again. If you modify an array in place (modify the values, not remove them) and then generate a list based on that, I have a very strong hunch that it will be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:48:52.623", "Id": "89646", "Score": "0", "body": "There are links to much faster Python implementations from [this post](http://codereview.stackexchange.com/questions/6477/sieve-of-eratosthenes-making-it-quicker). You can compare many different implementations [on Ideone](http://ideone.com/5YJkw), with the fastest one that was cited from the other post being available [here](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188)." } ]
[ { "body": "<p>The problem is that the way this is set up, the time complexity is (close to) \\$O(n**2)\\$. For each remaining prime, you run over the entire list.</p>\n\n<p>In the last case, where you want to check for prime numbers up to 1,000,000 you end up iterating over your list 78,498 ** 2 times. 6,161,936,004 iterations is a lot to process.</p>\n\n<p>Below is an approach that crosses off the numbers instead, editing the large list of numbers in-place. This makes for a \\$O(n)\\$ solution, which times as such: </p>\n\n<ul>\n<li>range 10,000 : 549 usec per loop</li>\n<li>range 100,000 : 14.8 msec per loop</li>\n<li>range 1,000,000: 269 msec per loop</li>\n<li>range 10,000,000: 3.26 sec per loop</li>\n</ul>\n\n<hr>\n\n<pre><code>def sieve_of_erastothenes(limit):\n \"\"\"Create a list of all numbers up to `number`, mark all non-primes 0,\n leave all the primes in place. Filter out non-primes in the last step.\n \"\"\"\n sieve = range(limit + 1)\n\n # There are no prime factors larger than sqrt(number):\n test_max = int(math.ceil(limit ** 0.5))\n\n # We know 1 is not a prime factor\n sieve[1] = 0\n\n # The next is a cheat which allows us to not even consider even numbers\n # in the main loop of the program. You can leave this out and replace the\n # current xrange(3, test_max, 2) with xrange(2, test_max)\n\n # All multiples of 2 are not prime numbers, except for 2 itself:\n sieve[4::2] = (limit / 2 - 1) * [0]\n\n for prime in xrange(3, test_max, 2):\n if sieve[prime]:\n # If the number hasn't been marked a composite, it is prime.\n # For each prime number, we now mark its multiples as non-prime.\n multiples_count = limit / prime - (prime - 1)\n sieve[prime * prime::prime] = multiples_count * [0]\n # Filter out all the zeroes, we are left with only the primes\n return filter(None, sieve)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:55:29.763", "Id": "15790", "ParentId": "15777", "Score": "7" } } ]
{ "AcceptedAnswerId": "15790", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:35:29.987", "Id": "15777", "Score": "8", "Tags": [ "python", "optimization", "performance", "primes", "sieve-of-eratosthenes" ], "Title": "Why does my implementation of the Sieve of Eratosthenes take so long?" }
15777
<p>I'm teaching myself code using Zed Shaw's <a href="http://learnpythonthehardway.org/" rel="nofollow"><em>Learn Python The Hard Way</em></a>, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS. </p> <p>How can I make this code better? Is there anything stupid I'm doing? </p> <pre><code>import random name = raw_input('Please Type in your name &gt; ') print "\nHello %s &amp; welcome to the Random D20 Number Generator by Ray Weiss.\n" % (name) first_number = random.randint(1, 20) print first_number prompt = (""" Do you need another number? Please type yes or no. """) answer = raw_input(prompt) while answer == "yes": print random.randint(1, 20) answer = raw_input(prompt) if answer == "no": print "\nThank you %s for using the D20 RNG by Ray Weiss! Goodbye!\n" % (name) </code></pre> <p>Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T20:58:44.750", "Id": "38503", "Score": "0", "body": "Maybe incorporate some of the stuff in this answer: http://gamedev.stackexchange.com/questions/24656/random-calculations-for-strategy-based-games-in-java/24681#24681" } ]
[ { "body": "<p>Here's my take:</p>\n\n<pre><code>from random import randint\nname = raw_input('Please Type in your name &gt; ')\n\nprint \"\"\"\nHello {} &amp; welcome to the Random Number Generator by Ray Weiss.\n\"\"\".format(name)\nupper = int(raw_input('Enter the upper limit &gt; '))\nn = int(raw_input(\"How many D{} you'd like to roll? \".format(upper)))\n\nfor _ in xrange(n):\n print randint(1, upper)\nprint \"\"\"\nThank you {} for using the D{} RNG by Ray Weiss! Goodbye!\n\"\"\".format(name, upper)\n</code></pre>\n\n<p>Changes as compared to your version:</p>\n\n<ul>\n<li>directly import <code>randint</code> because it's the only function you use in <code>random</code>;</li>\n<li>use the new string formatting method (<code>str.format</code>);</li>\n<li>take the upper bound from user instead of hard-coding 20;</li>\n<li>take the number of rolls from user instead of repeatedly asking if that's enough;</li>\n<li>use a loop to make the repetition actually work. The self-repeating code asking the user if we should continue is now gone.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T21:41:46.293", "Id": "25672", "Score": "0", "body": "Thank you! This is cool, im gonna play around with it so that it continues to ask you if you want to roll more dice, some new stuff here i havent seen before. mind me asking what the _ in xrange(n) does? I can kind of discern the rest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T21:44:57.630", "Id": "25673", "Score": "1", "body": "@lerugray Here's the doc on [`xrange`](http://docs.python.org/library/functions.html#xrange). I just use it to run the loop body `n` times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T17:42:44.963", "Id": "25739", "Score": "1", "body": "@lerugray, _ in haskell means an empty name (you use it when you must supply a variable which is useless - like in this loop). I suppose it has the same meaning in python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T20:12:41.943", "Id": "25749", "Score": "0", "body": "@Aleksandar Technically, it's a fully legit name, so it _can_ be used inside the loop, but you got the idea right. I didn't know it came from Haskell (and don't know Haskell), but it makes a lot of sense." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T19:27:25.283", "Id": "15779", "ParentId": "15778", "Score": "8" } }, { "body": "<p>I don't have much to say on the style side, which is good. I think my only real comment would be that I personally find using newline characters simpler than triple-quotes for multiline strings, especially when you just want to make sure of the spacing between lines.</p>\n\n<p>I like that you're using <code>randint</code> for the rolls, instead of <code>randrange</code> or some other structure: it's inclusive for start and stop, and that exactly matches the real-world function that you're recreating here, so there's no need to fudge the parameters or the results with +1.</p>\n\n<p>Design-wise, I would split the front-end stuff, which takes input from the user and gives back information, from the actual dice-rolling. That would let you reuse the dice roller for other purposes (off the top of my head, a random treasure generator), extend the interface logic with additional kinds of functionality, or rework your logic without ripping apart the whole structure.</p>\n\n<p>And as long as you're doing that, think bigger -- 'I need to roll a d20' is just a single case of 'I need to roll some dice', and <em>that</em> problem's not much harder to solve. So here's how I would approach it:</p>\n\n<pre><code>def play():\n \"\"\"\n This function is just the user interface.\n It handles the input and output, and does not return anything.\n \"\"\"\n\n name = raw_input('Please Type in your name &gt; ')\n\n print \"\\nHello {}, &amp; welcome to the Random D20 Number Generator by Ray Weiss.\\n\".format(name)\n print \"Please type your rolls as 'NdX' (N=number of dice, X=size of dice), or 'Q' to quit.\\n\"\n\n while True:\n dice = raw_input(\"What dice do you want to roll? \").lower()\n if dice == 'q':\n break\n else:\n try:\n number, size = dice.split('d')\n results = roll_dice(int(number), int(size))\n except ValueError:\n # This will catch errors from dice.split() or roll_dice(),\n # but either case means there's a problem with the user's input.\n print \"I don't understand that roll.\\n\"\n else:\n print 'You rolled {!s}: {!s}\\n'.format(sum(results), results)\n\n print \"\\nThank you {} for using the D20 RNG by Ray Weiss! Goodbye!\\n\".format(name)\n\n\ndef roll_dice(number, size):\n \"\"\"\n number: any int; &lt; 1 is allowed, but returns an empty list.\n size: any int &gt; 1\n\n Returns: a list with `number` elements, of dice rolls from 1 to `size`\n \"\"\"\n from random import randint\n\n return [randint(1, size) for n in range(number)]\n</code></pre>\n\n<p>One functionality you would probably want to add would be modifying <code>roll_dice()</code> to accept a modifier (+ or - some amount). And if you really want to get fancy, you can start checking the results to highlight 1s or 20s, or other roll results that have special values in your game.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T18:25:34.123", "Id": "24917", "ParentId": "15778", "Score": "3" } } ]
{ "AcceptedAnswerId": "15779", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T19:02:05.540", "Id": "15778", "Score": "12", "Tags": [ "python", "beginner", "random", "simulation", "dice" ], "Title": "Random D20 number generator" }
15778
<p>I've written a Base64 encoder/decoder, which works great. Now I want to see if I can get it working better. I've optimized as much as I can think of, but it may be missing some things. The encoder can encode a 160 MB file in 30 seconds, but the decoder takes nearly 60.</p> <p>So far the optimizations I've done are:</p> <ol> <li>Pre-allocated the file size using the <a href="http://en.wikipedia.org/wiki/Base64#Padding" rel="noreferrer">formula on Wikipedia</a> for encoding.</li> <li>Pre-allocate the file size using the reciprocal of the encoding formula for decoding.</li> <li>Use bitwise operations for byte and symbol manipulation.</li> <li>Use a in-memory array for encoding.</li> </ol> <p>One possible optimization that I don't know how to make better is the use of a <code>std::map</code> for decoding. O(log n) for searching and O(log n) for inserting for building the map (albeit only once).</p> <p><strong>Encoder:</strong></p> <pre><code>#include "Base64Encoder.h" #include &lt;fstream&gt; #include &lt;algorithm&gt; const char Base64Encoder::EncodingTable[64] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', //0-25 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', //26-51 '0','1','2','3','4','5','6','7','8','9', //52-61 '+','/'}; //62-63 const char Base64Encoder::PADDING_CHAR = '='; Base64Encoder::Base64Encoder() { /* DO NOTHING */ } Base64Encoder::~Base64Encoder() { /* DO NOTHING */ } int Base64Encoder::GetFirstSymbolIndex(char* encoding_buffer) { return ((encoding_buffer[0] &amp; 0xFC) &gt;&gt; 2); } int Base64Encoder::GetSecondSymbolIndex(char* encoding_buffer) { return (((encoding_buffer[0] &amp; 0x03) &lt;&lt; 4) | ((encoding_buffer[1] &amp; 0xF0) &gt;&gt; 4)); } int Base64Encoder::GetThirdSymbolIndex(char* encoding_buffer) { return (((encoding_buffer[1] &amp; 0x0F) &lt;&lt; 2) | ((encoding_buffer[2] &amp; 0xC0) &gt;&gt; 6)); } int Base64Encoder::GetFourthSymbolIndex(char* encoding_buffer) { return (encoding_buffer[2] &amp; 0x3F); } //Gets the 6 most significant digits of the first byte. char Base64Encoder::GetFirstSymbol(char* encoding_buffer) { return Base64Encoder::EncodingTable[Base64Encoder::GetFirstSymbolIndex(encoding_buffer)]; } //Gets the 2 least significant digits from previous (first) byte and 4 most significant from the second byte. char Base64Encoder::GetSecondSymbol(char* encoding_buffer) { return Base64Encoder::EncodingTable[Base64Encoder::GetSecondSymbolIndex(encoding_buffer)]; } //Gets the 4 least significant digits from previous (second) byte and 2 least significant from the third byte. char Base64Encoder::GetThirdSymbol(char* encoding_buffer) { return Base64Encoder::EncodingTable[Base64Encoder::GetThirdSymbolIndex(encoding_buffer)]; } //Gets the 6 least significant digits from the third byte. char Base64Encoder::GetFourthSymbol(char* encoding_buffer) { return Base64Encoder::EncodingTable[Base64Encoder::GetFourthSymbolIndex(encoding_buffer)]; } std::string Base64Encoder::Encode(const std::string&amp; file_path) { std::string output; std::ifstream ifs; ifs.open(file_path.c_str(), std::ios_base::binary); try { output = Encode(ifs); ifs.close(); } catch(...) { ifs.close(); } return output; } std::string Base64Encoder::Encode(std::istream&amp; input_stream) { if(input_stream.fail()) return ""; unsigned long file_size = 0; char encoding_buffer[3] = {'\0', '\0', '\0'}; input_stream.seekg(0, std::ios::end); file_size = static_cast&lt;unsigned long&gt;(input_stream.tellg()); input_stream.seekg(0); std::string output(static_cast&lt;unsigned long&gt;(4 * std::ceil(file_size / 3.0)), '\0'); if(file_size == 0) { output.clear(); input_stream.clear(); return output; } while(input_stream.read(reinterpret_cast&lt;char*&gt;(encoding_buffer), sizeof(encoding_buffer))) { char firstsymbol = GetFirstSymbol(encoding_buffer); char secondsymbol = GetSecondSymbol(encoding_buffer); char thirdsymbol = GetThirdSymbol(encoding_buffer); char fourthsymbol = GetFourthSymbol(encoding_buffer); unsigned long s = 4 * static_cast&lt;unsigned long&gt;(input_stream.tellg()) / 3; output[s - 4] = firstsymbol; output[s - 3] = secondsymbol; output[s - 2] = thirdsymbol; output[s - 1] = fourthsymbol; } output.erase(output.find_first_of('\0')); if(input_stream.fail()) { switch(input_stream.gcount()) { case 0: /* DO NOTHING. Evenly divisible by 4. */ break; case 1: { /* Only one byte read */ encoding_buffer[2] = 0; encoding_buffer[1] = 0; char firstsymbol = GetFirstSymbol(encoding_buffer); char secondsymbol = GetSecondSymbol(encoding_buffer); char thirdsymbol = GetThirdSymbol(encoding_buffer); char fourthsymbol = GetFourthSymbol(encoding_buffer); output.push_back(firstsymbol); output.push_back(secondsymbol); output.push_back(Base64Encoder::PADDING_CHAR); output.push_back(Base64Encoder::PADDING_CHAR); break; } case 2: { /* Only two bytes read */ encoding_buffer[2] = 0; char firstsymbol = GetFirstSymbol(encoding_buffer); char secondsymbol = GetSecondSymbol(encoding_buffer); char thirdsymbol = GetThirdSymbol(encoding_buffer); char fourthsymbol = GetFourthSymbol(encoding_buffer); output.push_back(firstsymbol); output.push_back(secondsymbol); output.push_back(thirdsymbol); output.push_back(Base64Encoder::PADDING_CHAR); break; } case 3: /* DO NOTHING All three bytes read. */ break; default: /* DO NOTHING */; } } input_stream.clear(); return output; } std::string Base64Encoder::Execute(std::istream&amp; input_stream) { return Encode(input_stream); } std::string Base64Encoder::Execute(const std::string&amp; file_path) { return Encode(file_path); } </code></pre> <p><strong>Decoder:</strong></p> <pre><code>#include "Base64Decoder.h" #include &lt;fstream&gt; const char Base64Decoder::PADDING_CHAR = '='; Base64Decoder::DecodingMap Base64Decoder::DecodingTable; Base64Decoder::Base64Decoder() { BuildDecodingTable(DecodingTable); } Base64Decoder::~Base64Decoder() { } void Base64Decoder::BuildDecodingTable(DecodingMap&amp; table) { table.clear(); char cur_char = 'A'; for(int i = 0; i &lt; 26; ++i) { table.insert(std::make_pair(cur_char++, i)); } cur_char = 'a'; for(int i = 26; i &lt; 52; ++i) { table.insert(std::make_pair(cur_char++, i)); } cur_char = '0'; for(int i = 52; i &lt; 62; ++i) { table.insert(std::make_pair(cur_char++, i)); } table.insert(std::make_pair('+', 62)); table.insert(std::make_pair('/', 63)); } //First Byte is all 6 of first symbol and 2 most significant bits of second symbol. char Base64Decoder::GetFirstByte(char* decoding_buffer) { DecodingMap::iterator first_iter = DecodingTable.find(decoding_buffer[0]); DecodingMap::iterator second_iter = DecodingTable.find(decoding_buffer[1]); int first_index; if(first_iter == DecodingTable.end()) { first_index = decoding_buffer[0]; } else { first_index = (*first_iter).second; } int second_index; if(second_iter == DecodingTable.end()) { second_index = decoding_buffer[1]; } else { second_index = (*second_iter).second; } first_index = (first_index &amp; 0x3F) &lt;&lt; 2; second_index = (second_index &amp; 0x30) &gt;&gt; 4; int result = first_index | second_index; return result; } //Second Byte is 4 least significant bits of second symbol and 4 most significant bits of third symbol. char Base64Decoder::GetSecondByte(char* decoding_buffer) { DecodingMap::iterator second_iter = DecodingTable.find(decoding_buffer[1]); DecodingMap::iterator third_iter = DecodingTable.find(decoding_buffer[2]); int second_index; if(second_iter == DecodingTable.end()) { second_index = decoding_buffer[1]; } else { second_index = (*second_iter).second; } int third_index; if(third_iter == DecodingTable.end()) { third_index = decoding_buffer[2]; } else { third_index = (*third_iter).second; } second_index = (second_index &amp; 0x0F) &lt;&lt; 4; third_index = (third_index &amp; 0x3C) &gt;&gt; 2; int result = second_index | third_index; return result; } //Third Byte is 2 least significant bits of third symbol and all of fourth symbol. char Base64Decoder::GetThirdByte(char* decoding_buffer) { DecodingMap::iterator third_iter = DecodingTable.find(decoding_buffer[2]); DecodingMap::iterator fourth_iter = DecodingTable.find(decoding_buffer[3]); int third_index; if(third_iter == DecodingTable.end()) { third_index = decoding_buffer[2]; } else { third_index = (*third_iter).second; } int fourth_index; if(fourth_iter == DecodingTable.end()) { fourth_index = decoding_buffer[3]; } else { fourth_index = (*fourth_iter).second; } third_index = (third_index &amp; 0x03) &lt;&lt; 6; fourth_index = fourth_index &amp; 0x3F; int result = third_index | fourth_index; return result; } std::string Base64Decoder::Decode(const std::string&amp; file_path) { std::string output; std::ifstream ifs; ifs.open(file_path.c_str(), std::ios_base::binary); try { output = Decode(ifs); ifs.close(); } catch(...) { ifs.close(); } return output; } std::string Base64Decoder::Decode(std::istream&amp; input_stream) { if(input_stream.fail()) return ""; unsigned long file_size = 0; char decoding_buffer[4] = {'\0', '\0', '\0', '\0'}; input_stream.seekg(0, std::ios::end); file_size = static_cast&lt;unsigned long&gt;(input_stream.tellg()); input_stream.seekg(0); std::string output(static_cast&lt;unsigned long&gt;(3 * std::ceil(file_size / 4.0)) + (file_size % 3), '\0'); if(file_size == 0) { output.clear(); input_stream.clear(); return ""; } while(input_stream.read(reinterpret_cast&lt;char*&gt;(decoding_buffer), sizeof(decoding_buffer))) { char firstbyte = GetFirstByte(decoding_buffer); char secondbyte = GetSecondByte(decoding_buffer); char thirdbyte = GetThirdByte(decoding_buffer); unsigned long s = static_cast&lt;unsigned long&gt;(3 * std::ceil(static_cast&lt;unsigned long&gt;(input_stream.tellg()) / 4.0)); if(firstbyte != PADDING_CHAR) output[s - 3] = firstbyte; if(secondbyte != PADDING_CHAR) output[s - 2] = secondbyte; if(thirdbyte != PADDING_CHAR) output[s - 1] = thirdbyte; decoding_buffer[0] = '\0'; decoding_buffer[1] = '\0'; decoding_buffer[2] = '\0'; decoding_buffer[3] = '\0'; } //Erase extraneous null chars. output.erase(output.find_first_of('\0')); if(input_stream.fail()) { if(decoding_buffer[2] == PADDING_CHAR) { //Third character is PADDING_CHAR. Only one in decoding_buffer. char firstbyte = GetFirstByte(decoding_buffer); char secondbyte = GetSecondByte(decoding_buffer); char thirdbyte = GetThirdByte(decoding_buffer); output.push_back(firstbyte); } else if(decoding_buffer[3] == PADDING_CHAR) { //Fourth character is PADDING_CHAR. Only two in decoding_buffer. char firstbyte = GetFirstByte(decoding_buffer); char secondbyte = GetSecondByte(decoding_buffer); char thirdbyte = GetThirdByte(decoding_buffer); output.push_back(firstbyte); output.push_back(secondbyte); } else { /* DO NOTHING */ } } input_stream.clear(); return output; } std::string Base64Decoder::Execute(std::istream&amp; input_stream) { return Decode(input_stream); } std::string Base64Decoder::Execute(const std::string&amp; file_path) { return Decode(file_path); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-30T20:54:20.397", "Id": "318129", "Score": "0", "body": "Have a look at the Java source code for the java.util.Base64, java.util.Base64.Decoder and java.util.Base64.Endoder for ideas." } ]
[ { "body": "<p>FOA, code looks clear and clean, well indented and formatted. Thumbs up!!</p>\n\n<p>Now, to the comments:</p>\n\n<ul>\n<li>Some of the variable names might have more significant names: <code>is</code> can be changed to <code>input_stream</code>, for instance.</li>\n<li>File size: it looks like you try to get the file size out of the stream by fetching the stream until reaching its end. I'd change that to an explicit call to a function provider by the hosting OS' API (see <code>stat</code>), or by a library that implements it, like <em>boost</em>.</li>\n<li>Extract file size calculation to a function, to achieve code reuse.</li>\n<li>Base64 format should convert a byte array (or a binary stream) to an ASCII string. It has nothing to do with Bitmap format in specific. I'd recommend you create some test cases using a C++ unit testing framework (<a href=\"https://encrypted.google.com/search?q=c%2b%2b%20unit%20testing&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t\" rel=\"nofollow\">there are some</a>) and find the bug, if such exists.</li>\n</ul>\n\n<p>Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:26:49.407", "Id": "78450", "Score": "0", "body": "I've edited the question, if you want to take a further look at it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T08:56:53.157", "Id": "15795", "ParentId": "15780", "Score": "1" } }, { "body": "<p>I realise this is an old post but just came across it and couldn't help but notice the following pattern in the original post which was not addressed in the review:</p>\n\n<blockquote>\n<pre><code>encoding_buffer[1] &amp; 0xF0) &gt;&gt; 4\n</code></pre>\n</blockquote>\n\n<p>Constructs like that are dangerous as the data type of the <code>encoding_buffer</code> is <code>char</code> instead of <code>unsigned char</code> and it's up to the compiler to decide whether to use arithmetic (repeat the leftmost bit on the left) or logical (fill 0s to the left) right shift. Far safer would be to rewrite the expression as:</p>\n\n<pre><code>(encoding_buffer[1] &gt;&gt; 4) &amp; 0x0F\n</code></pre>\n\n<p>As a general rule it's better to do the shift first and apply the mask later.</p>\n\n<p>The original code may or may not work on the designated platform but is certainly not portable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-30T19:35:14.617", "Id": "167076", "ParentId": "15780", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T00:54:13.800", "Id": "15780", "Score": "9", "Tags": [ "c++", "performance", "base64" ], "Title": "Base64 encoder/decoder optimizations" }
15780
<p>This function is used to get the mime type of any given file. The intended purpose was to have it working within any of our servers that vary from the latest PHP version down to PHP 4.</p> <pre><code>/** * Get the mime type for any given file. * * @param str $filename Path to the file including the filename * * @return mixed bol|arr Either false or the array provided by the PHP function */ function getMimeType($filename) { $mimetype = false; if (function_exists('finfo_fopen')) { $mimetype = finfo_fopen($filename); } elseif (function_exists('getimagesize')) { $mimetype = getimagesize($filename); } elseif (function_exists('exif_imagetype')) { $mimetype = exif_imagetype($filename); } elseif (function_exists('mime_content_type')) { $mimetype = mime_content_type($filename); } return $mimetype; } </code></pre> <p>While the function is already tested on different PHP versions, I'm trying to ascertain if the methodology implemented can be improved, thus leading to code reduction and preventing any redundant verifications.</p> <p>Can this function receive any type of improvement?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T04:54:00.297", "Id": "25681", "Score": "0", "body": "In my opinion, this code is broken and should be revised before being reviewed. In particular: `@return mixed bol|arr Either false or the array provided by the PHP function` That's a major flaw. How is the consumer of this function to know what to expect? Also, the documentation is a lie. exif_imagetype returns an integer, not an array. Similarly, finfo_fopen returns a resource, and you're calling it incorrectly. It's basically impossible to use this function unless you repeat the if-elseif tree in the consuming code to know how to interpret the return value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:17:05.210", "Id": "25716", "Score": "0", "body": "This is an old function that was on the \"storage\", while in production on several projects, you're right, there are several issues to be solved before it can be properly reviewed. Thank you for your time, I'll update my answer as soon as I deal with this." } ]
[ { "body": "<h2>General Issues</h2>\n<p>If you are going to call something getMimeType then it should return exactly that. This is probably best defined by Multipurpose Internet Mail Extensions <a href=\"https://www.rfc-editor.org/rfc/rfc2046\" rel=\"nofollow noreferrer\">RFC 2046</a>. Read the <a href=\"http://en.wikipedia.org/wiki/MIME\" rel=\"nofollow noreferrer\">wikipedia page</a> for more general information and related RFCs.</p>\n<p>As Corbin commented on this implementation is broken due to the number of assumptions that are required to consume the information provided by this function. You really should return just a string with the mime type or an array with the primary type and subtype. Whatever you return should be consistent with your documentation.</p>\n<p>You could consider some of the following instead of returning false:</p>\n<ul>\n<li>Throw an exception.</li>\n<li>Trigger an error and default the MIME type.</li>\n<li>Create a second function hasMimeType to avoid exception/errors.</li>\n</ul>\n<h2>Specific Issues</h2>\n<p><strong>finfo_fopen</strong></p>\n<p>I think <code>finfo_fopen</code> should probably be <code>finfo_open</code>.</p>\n<p>Its usage is something like:</p>\n<pre><code>$finfo = finfo_open(FILEINFO_MIME_TYPE);\nreturn finfo_file($finfo, $filename);\n</code></pre>\n<p>However there are some catches. FILEINFO_MIME_TYPE has only been <a href=\"http://php.net/manual/en/fileinfo.constants.php\" rel=\"nofollow noreferrer\">defined since PHP 5.3.0</a>. You can use <code>version_compare</code> to determine which version of php you are using (If the <code>version_compare</code> function doesn't exist you are using PHP &lt; 4.1.0).</p>\n<pre><code>if (version_compare(PHP_VERSION, '5.3.0') &gt;= 0) { /* Do Stuff */ }\n</code></pre>\n<p><strong>getimagesize</strong></p>\n<p>Only the <code>mime</code> index from the returned array should be used.</p>\n<p><strong>exif_imagetype</strong></p>\n<p>The string returned from this does not conform to the MIME type format. You will have to massage this data to return something appropriate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:19:56.297", "Id": "25717", "Score": "0", "body": "Thank you for the analysis, I'll be updating my question taking into consideration your notes. The function is old and isn't properly structured. I'll have to deal with it and run some tests before returning to this topic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T05:42:33.373", "Id": "15784", "ParentId": "15782", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T02:00:19.020", "Id": "15782", "Score": "3", "Tags": [ "php" ], "Title": "Detecting the mime type using an agnostic method" }
15782
<p>I have written an code to find if a given tree is a BST. Need help in refactoring it. Some of the things I am looking are.</p> <ol> <li>Getting Rid of temp variables (As suggested by Martin Fowler)</li> <li>Combining leftTreeMax and RighTreeMin methods</li> <li>Better naming of methods.</li> </ol> <p>Also it will be great if someone can suggest other refactorings which i can do. </p> <pre><code>package com.cc.bst; import com.cc.queue.Queue; import com.cc.trees.BinaryTreeNode; public class IsBinaryTreeBST { public static boolean binaryTreeBST ( BinaryTreeNode root) { if (root == null) { return false; } int maxVal = leftTreeMax(root.getLeft()); int minVal = rightTreeMin(root.getRight()); int rootVal = root.getData(); if (maxVal == 0 || minVal == 0 ) { return false; } if (rootVal &gt; maxVal &amp;&amp; rootVal &lt; minVal) { return true; } return false; } private static int leftTreeMax (BinaryTreeNode node) { if (node == null) { return 0; } Queue nodeQueue = new Queue(); nodeQueue.enqueue(node); int maxValue = node.getData(); while (!nodeQueue.isEmpty()) { BinaryTreeNode tempNode = (BinaryTreeNode) nodeQueue.dequeue(); BinaryTreeNode left = tempNode.getLeft(); BinaryTreeNode right = tempNode.getRight(); if (left != null ) { if (left.getData() &gt; tempNode.getData()) { return 0; } nodeQueue.enqueue(left); } if (right != null) { if ( tempNode.getData() &gt; right.getData()) { return 0; } nodeQueue.enqueue(right); } if (tempNode.getData() &gt; maxValue) { maxValue = tempNode.getData(); } } System.out.println("---------- maxVal --------&gt;" + maxValue); return maxValue; } private static int rightTreeMin(BinaryTreeNode node) { if (node == null) { return 0; } Queue nodeQueue = new Queue(); nodeQueue.enqueue(node); int minValue = node.getData(); while (!nodeQueue.isEmpty()) { BinaryTreeNode tempNode = (BinaryTreeNode) nodeQueue.dequeue(); BinaryTreeNode left = tempNode.getLeft(); BinaryTreeNode right = tempNode.getRight(); System.out.println("---------- tempNode --------&gt;" + tempNode.getData()); if (left != null ) { System.out.println("---------- left --------&gt;" + left.getData()); if (left.getData() &gt; tempNode.getData()) { return 0; } nodeQueue.enqueue(left); } if (right != null) { if ( tempNode.getData() &gt; right.getData()) { return 0; } System.out.println("---------- right --------&gt;" + right.getData()); nodeQueue.enqueue(right); } if (tempNode.getData() &lt; minValue) { minValue = tempNode.getData(); } } System.out.println("---------- minVal --------&gt;" + minValue); return minValue; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:27:05.057", "Id": "25690", "Score": "0", "body": "You're returning 0 as a flag that the level failed (and thus the tree is not a BST). That's problematic though since 0 is a possible value." } ]
[ { "body": "<p>1) You would like to get rid of the <code>System.out.println()</code> inside methods. Noone expects a method to write to the console unless the method has <code>print</code> in the name.</p>\n\n<p>2) Just comparing the <code>root</code> with <code>left tree max</code> and <code>right tree min</code> can lead to wrong result. Consider,</p>\n\n<pre><code> 12\n / \\\n 9 15\n / \\\n3 5\n</code></pre>\n\n<p>Here the left sub-tree is not a BST but <code>12 &gt; 9</code> and <code>15 &gt; 12</code>. You must also ensure that <code>left-subtree</code> and <code>right-subtree</code> of <code>root</code> are also <code>BST</code>.</p>\n\n<p>3) <code>BinaryTreeBST</code> is kind of redundant. Consider naming the class <code>IsBSTCheck</code> or <code>IsBinarySearchTreeCheck</code>. Also change the method name <code>binaryTreeBST</code> to <code>isBST</code> or <code>isBinarySearchTree</code> to reflect what the method does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T06:58:52.887", "Id": "15787", "ParentId": "15785", "Score": "2" } } ]
{ "AcceptedAnswerId": "15787", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T05:59:21.053", "Id": "15785", "Score": "4", "Tags": [ "java" ], "Title": "Refactoring code finding if Binary Tree is BST" }
15785
<p>Problem statement:</p> <blockquote> <p>Write a <code>CashWithDrawal</code> function from an ATM which, based on user specified amount, dispenses bank notes. Ensure that the following is taken care of:</p> <ul> <li>Minimum number of bank notes are dispensed</li> <li>Availability of various denominations in the ATM is maintained</li> </ul> <p>Code should support parallel withdrawals (i.e two or more customers can withdraw money simultaneously). Take care of exceptional situations.</p> </blockquote> <pre><code>public class ATMMachine { private Map&lt;Integer, Integer&gt; notes; public ATMMachine(Map&lt;Integer, Integer&gt; notesMap){ notes = notesMap; } private boolean isCorrectAmt(int amt){ return amt%10==0 ? true : false; } private synchronized void reduceBalance(int denomination, int noToReduce){ int amt = notes.get(denomination); notes.remove(denomination); notes.put(denomination, amt-noToReduce); } public synchronized Integer getATMBalance(){ int balance = 0; for(Integer denominator: notes.keySet()){ balance = balance + (denominator * notes.get(denominator)); } return balance; } public synchronized Map&lt;Integer, Integer&gt; withdrawAmt(int amt){ Map&lt;Integer, Integer&gt; returnedMap = new HashMap&lt;Integer, Integer&gt;(); if(!isCorrectAmt(amt)){ System.out.println("Please enter amount in multiple of 10"); return returnedMap; } //get sorted denominations TreeSet&lt;Integer&gt; denominations = new TreeSet&lt;Integer&gt;(notes.keySet()); Iterator&lt;Integer&gt; iter = denominations.descendingIterator(); while(amt &gt; 0 ){ int denomination = iter.next(); int noOfNotes = amt&lt; denomination ? 0 : amt/denomination; returnedMap.put(denomination, noOfNotes); amt = amt - (denomination * noOfNotes); reduceBalance(denomination, noOfNotes); } return returnedMap; } public static void main(String agrs[]){ Map&lt;Integer, Integer&gt; notesMap = new HashMap&lt;Integer, Integer&gt;(); notesMap.put(500, 10); notesMap.put(100, 20); notesMap.put(50, 50); notesMap.put(10, 30); ATMMachine atm = new ATMMachine(notesMap); System.out.println("Current balance is : " + atm.getATMBalance()); System.out.println("withdraw amt 200" + atm.withdrawAmt(800)); System.out.println("balance after withdrawing " + atm.getATMBalance()); ATMUser user = new ATMUser(atm, 4000); Thread userThread1 = new Thread(user); Thread userThread2 = new Thread(user); userThread1.start(); userThread2.start(); } } public class ATMUser implements Runnable { ATMMachine atm; int amtToWithdraw; public ATMUser(ATMMachine atm, int amtToWithdraw){ this.atm = atm; this.amtToWithdraw = amtToWithdraw; } @Override public void run() { System.out.println("Balance in ATM is " + atm.getATMBalance()); System.out.println("withdrawin amt : " + amtToWithdraw); System.out.println("withdrawn : " + atm.withdrawAmt(amtToWithdraw)); System.out.println("Balance after withdraw is : " + atm.getATMBalance()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T06:52:00.223", "Id": "25790", "Score": "1", "body": "`ATM` stands for Automatic Teller Machine, so your class is called `Automatic Teller Machine Machine`?" } ]
[ { "body": "<p>First of all, it's considered better practice to implement <code>isCorrectAmount</code> as follows:</p>\n\n<pre><code>private boolean isCorrectAmt(int amt){\n return amt%10 == 0;\n}\n</code></pre>\n\n<p>Next, if you want to update the value of an existing key in a <code>Map</code>, it's not necessary to remove the mapping for the key and then reinsert it. You can just call <code>put</code>, and if the map already contains a mapping for the key it will simply update the key's value. So with that in mind, I would suggest changing the body of <code>reduceBalance</code> as follows:</p>\n\n<pre><code>private synchronized void reduceBalance(int denomination, int noToReduce){\n int amt = notes.get(denomination);\n notes.put(denomination, amt-noToReduce);\n}\n</code></pre>\n\n<p>The next thing I thought about questioning was your choice of a <code>TreeSet</code> for maintaining an order collection of denominations. Normally you should collect items in a <code>List</code> if you are interested in keeping them in order, and use a <code>Set</code> if you want to stop your collection from containing duplicates. <code>TreeSet</code> just happens to be a collection implementation that offers both features. Overall however I think using <code>TreeSet</code> here allows you to achieve your goal in as little code as possible, so in the end this is fine by me.</p>\n\n<p>By using a <code>TreeSet</code>, one thing you could do is use the advanced methods on its API to fast-forward through the denominations that are greater than your amount. This is probably not really worth doing as the gains are minimal, and I must stress that I haven't tested this out, but you could conceivably do this:</p>\n\n<pre><code>//get sorted denominations\nTreeSet&lt;Integer&gt; denominations = new TreeSet&lt;Integer&gt;(notes.keySet());\nInteger start = denominations.floor(amt);\ndenominations = denominations.headSet(start, true);\nIterator&lt;Integer&gt; iter = denominations.descendingIterator();\n</code></pre>\n\n<p>Your main issues in terms of the functional correctness of your code are:</p>\n\n<ul>\n<li><code>withdrawAmt</code> needs to perform more validation on its input. As well as checking that the input is a multiple of 10, it needs to check that it is non-negative and also less than or equal to the total amount in the machine.</li>\n<li>Your while loop in <code>withdrawAmt</code> needs to account for the situation where there are not enough notes in the machine to pay out the requested amount. What if somebody wants to withdraw $30 but there are only 2 $10 notes left? Think about what your code currently does in this situation.</li>\n</ul>\n\n<p>Finally, by making the main entry point into the <code>ATMMachine</code> class synchronized (as well as most of the other methods), concurrent requests to withdraw money will pretty much proceed in series, one after the other. In all fairness this may have to be the case. One of the first things that the machine needs to check is that it has enough cash to service the current user, and it can't establish this for sure if there's another user currently in the middle of a withdrawal. </p>\n\n<p>Nevertheless, given that your focus is on Java's collections, it may be worth looking at the concurrent collection classes and seeing if making <code>notes</code> a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html\" rel=\"nofollow\">ConcurrentHashMap</a> might allow you to perform some actions in parallel. I'll have a look myself and update this answer if I can propose some code that would result in less blocking.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T05:41:17.307", "Id": "26504", "Score": "0", "body": "Thanks Avik for the review comments. I will try to rework on the problem using concurrent classes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T20:35:50.010", "Id": "15838", "ParentId": "15786", "Score": "2" } }, { "body": "<p>I'm going to mention some nitpicks, as they leap out at me as I read the code:</p>\n\n<ul>\n<li><p><code>isCorrectAmt()</code> does not check if the amount is correct. It checks if it is a valid amount. There's only one correct amount but many possible valid amounts. </p></li>\n<li><p><code>isCorrectAmt()</code> hardcodes a rule as to what is valid. This will make localization harder. It's generally better to get this from configuration. Note that in this case, the 10 is also the smallest denomination. So you might consider having the function check against the smallest denomination rather than a separate value. Of course, that would fail if the smallest denomination were a 2 and the next smallest a 5. But your code doesn't really work in that situation anyway. There's an implicit assumption that you can always grab as much of the largest denomination as you can. I.e. that large denominations are multiples of smaller denominations. </p></li>\n<li><p>In my opinion, you use abbreviations more than is necessary. For example, amt rather than amount. This is especially bad here because you have both <code>amt</code> and <code>atm</code>. </p></li>\n<li><p>In <code>reduceBalance()</code>, you use amt to refer to a quantity of notes. Elsewhere you use it to represent a currency amount. It's often better to stick with a single definition of a variable name. </p></li>\n<li><p>In <code>getATMBalance()</code>, you use denominator where elsewhere you use denomination. I found this distracting, as denominator is also the bottom part of a fraction. Using denomination here would make it more obvious that you are iterating over the same set as elsewhere. </p></li>\n<li><p><code>withdrawAmt()</code> returns a <code>Map</code> of denominations and quantities. Why? You don't seem to use it for anything. </p></li>\n<li><p>In <code>withdrawAmt()</code>, you name a variable <code>returnedMap</code>, but that doesn't seem to describe what it is. It is the map that you will return, not the one that has been returned. It's also not descriptive. I might go with <code>withdrawalDenominationQuantities</code> or just <code>quantitiesOfDenominations</code> or even just <code>quantitiesOf</code>. </p></li>\n<li><p><code>withdrawAmt()</code> should probably throw exceptions when there's a problem. For example, if there isn't enough money to support a particular withdrawal. </p></li>\n<li><p>In <code>withdrawAmt()</code>, you name an <code>Iterator</code> as <code>iter</code>. Generally it is better to use a descriptive name if possible. In this case, I would suggest <code>nextDenomination</code>. </p></li>\n<li><p>In <code>withdrawAmt()</code>, do you need to put denominations with quantities of 0 in the map to return? Currently it puts a 0 only for large denominations. Once the withdrawal amount is reached, it stops adding them. This gives two ways to get a zero quantity: an explicit value of 0 or a missing entry. Why not pick one? You could iterate over all the denominations if you want 0s, or you could continue when you encounter a denomination that doesn't fit. </p>\n\n<p>That is:</p>\n\n<pre><code>if ( amt &lt; denomination ) {\n continue;\n}\n</code></pre></li>\n<li><p>The map that you return would make more sense if you were generating the denominations to withdraw in one function and then actually withdrawing them in a different function. That would also allow you to handle problems more cleanly. In particular, you could reject a withdrawal that can't be fulfilled in total. Currently, you do a partial withdrawal, which is not the normal behavior. </p>\n\n<p>This would allow you to have a <code>processWithdrawalRequest()</code> which would call other functions to check if the withdrawal amount is valid, generate a list of denomination quantities to withdraw, actually do the withdrawal, and give the money to the user. Currently your <code>withdrawAmt()</code> function tries to do some of these itself. It would be better if the function that tried to do multiple things would delegate while the acting functions would each do only one thing. This will also make it easier to unit test, as the acting functions are only doing single units of work. </p></li>\n<li><p>In <code>System.out.println(\"withdraw amt 200\" + atm.withdrawAmt(800));</code> you have two different numbers. If you write this as something like</p>\n\n<pre><code>System.out.println(\"withdraw amt \" + withdrawalAmount + \": \" + atm.withdrawAmt(withdrawalAmount));\n</code></pre>\n\n<p>you might find it easier to keep these consistent. </p></li>\n<li><p>In general, you could use a test class that you could initialize with the appropriate balances, withdrawal amounts, etc. You're currently doing this directly in <code>main()</code>, which leads to having to edit code in several places when you want to change your test. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-11T13:00:38.550", "Id": "65348", "ParentId": "15786", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T06:15:55.120", "Id": "15786", "Score": "1", "Tags": [ "java", "multithreading", "collections", "finance" ], "Title": "ATM problem using collections" }
15786
<p>Between .NET's built-in collection libraries and LINQ extension methods, I never have to use arrays. An unfortunate consequence of this is that I am probably less competent in working with this very important Type than I should be. To help myself get a better grip on the <code>Array</code> class, I wrote some C# helper methods that mimic the "Mutator" methods in the JavaScript array type. These methods are documented thoroughly at <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" rel="nofollow">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array</a> . I omitted the methods that already have analogous implementations in .NET, (including <code>reverse</code> and <code>sort</code>). I also tried to avoid using LINQ, on which I have grown pretty dependent. (LINQ also manipulates arrays under the hood, so a properly written direct approach should perform better).</p> <p>I appreciate : (1) any feedback and/or highlighting of anywhere I may have messed up, (2) highlighting of any errors that may not necessarily but could potentially cause problems (such as thread-safety issues); (3) any optimization techniques that I should have used; and, (4) anything I did that was generally stupid.</p> <p><em>I use an <code>IsNullOrEmpty</code> extension method that is equivalent to <code>ReferenceEquals(array,null) || array.Length == 0</code></em></p> <pre><code>public static class ArrayMutator { public static T Pop&lt;T&gt;(ref T[] array) { Contract.Requires&lt;ArgumentException&gt;(!array.IsNullOrEmpty()); T result = array[array.Length - 1]; if (array.Length == 1) { array = new T[0]; } else { var popped = new T[array.Length - 1]; System.Array.Copy(array, 0, popped, 0, array.Length - 1); array = popped; } return result; } public static int Push&lt;T&gt;(ref T[] array, T element) { if (array.IsNullOrEmpty()) { array = new T[1] {element}; return 1; } var pushed = new T[array.Length + 1]; array.CopyTo(pushed, 0); pushed[array.Length] = element; array = pushed; return pushed.Length; } public static int Push&lt;T&gt;(ref T[] array, params T[] elements) { if (array.IsNullOrEmpty()) { if (elements.IsNullOrEmpty()) { array = new T[0]; return 0; } else { var elementsCopy = new T[elements.Length]; elements.CopyTo(elementsCopy, 0); array = elementsCopy; return elementsCopy.Length; } } if (elements.IsNullOrEmpty()) { return array.Length; } int total = array.Length + elements.Length; var pushed = new T[total]; array.CopyTo(pushed, 0); elements.CopyTo(pushed, array.Length); array = pushed; return total; } public static T Shift&lt;T&gt;(ref T[] array) { Contract.Requires&lt;ArgumentException&gt;(!array.IsNullOrEmpty()); T result = array[0]; if (array.Length == 1) { array = new T[0]; } else { var shifted = new T[array.Length - 1]; System.Array.Copy(array, 1, shifted, 0, array.Length - 1); array = shifted; } return result; } public static T[] Splice&lt;T&gt;(ref T[] array, int index, int removeCount, params T[] elements) { Contract.Requires&lt;ArgumentNullException&gt;(!ReferenceEquals(array, null)); Contract.Requires&lt;ArgumentOutOfRangeException&gt;(array.Length &gt; Math.Abs(index) || (array.Length == 0 &amp;&amp; index == 0)); Contract.Requires&lt;ArgumentOutOfRangeException&gt;(removeCount &gt;= 0 &amp;&amp; (Math.Abs(index) + removeCount) &lt; array.Length); T[] local = array; int addCount = ReferenceEquals(elements, null) ? 0 : elements.Length; if (index &lt; 0) index = local.Length - index; var spliced = new T[local.Length - removeCount + addCount]; var removed = new T[removeCount]; if (index == 0) { if (removeCount == 0) { local.CopyTo(spliced, 0); if (addCount &gt; 0) { elements.CopyTo(spliced, local.Length); } } else { System.Array.Copy(local, removeCount, spliced, 0, local.Length - removeCount); if (addCount &gt; 0) { elements.CopyTo(spliced, local.Length - removeCount); } } } else { if (removeCount == 0 &amp;&amp; addCount == 0) local.CopyTo(spliced, 0); else { System.Array.Copy( local, 0, spliced, 0, index + 1); if (addCount &gt; 0) { elements.CopyTo(spliced, index); } System.Array.Copy( local, index + removeCount, spliced, index + addCount, local.Length - index - removeCount ); } } array = local; return removed; } public static int Unshift&lt;T&gt;(ref T[] array, T element) { if (array.IsNullOrEmpty()) { array = new T[1] {element}; return 1; } var unshifted = new T[array.Length + 1]; unshifted[0] = element; array.CopyTo(unshifted, 1); array = unshifted; return unshifted.Length; } public static int Unshift&lt;T&gt;(ref T[] array, params T[] elements) { if (array.IsNullOrEmpty()) { if (elements.IsNullOrEmpty()) { array = new T[0]; return 0; } else { var elementsCopy = new T[elements.Length]; elements.CopyTo(elementsCopy, 0); array = elementsCopy; return elementsCopy.Length; } } if (elements.IsNullOrEmpty()) { return array.Length; } int total = array.Length + elements.Length; var unshifted = new T[total]; elements.CopyTo(unshifted, 0); array.CopyTo(unshifted, elements.Length); array = unshifted; return total; } } </code></pre> <h1>Revisions</h1> <ol> <li>Replaced all occurrences of <code>Array.ConstrainedCopy</code> with <code>Array.Copy</code>, thanks to @svick's suggestion</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T08:45:11.160", "Id": "25695", "Score": "1", "body": "As a learning excercise, this is valid. But for production, [**Arrays are usually the wrong approach**](http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T08:49:55.607", "Id": "25696", "Score": "0", "body": "@codesparkle, I am very aware of this. However, there are cases where arrays can be used safely, (such as within the internals of custom data structures). In any event, my reason for posting this is to try to learn more about proper use of arrays, as I am already very competent with more production friendly C# alternatives. One problem is that not every language offers the same high-level richness that C# does, and I think it is bad programming practice to abuse our tools to the point that they restrict our programming paradigm." } ]
[ { "body": "<p>Your code seems fine to me, just a few things I would do differently:</p>\n<ol>\n<li><p>Your usage of <code>ConstrainedCopy()</code>, instead of normal <code>Copy()</code>, doesn't make sense to me. This method is useful if you want to guarantee that the target array is in a consistent state even if an error happens during processing. But you're always modifying a temporary array, so you don't care about its state after an error.</p>\n<p>Using <code>ConstrainedCopy()</code> will be less performant (although probably not significantly) and it's more confusing (it makes me think why you didn't use normal <code>Copy()</code>).</p>\n</li>\n<li><p>When creating an array using array initializer, you don't need to specify the size: <code>new T[] {element}</code> works fine.</p>\n</li>\n</ol>\n<p>Also, if you used your methods a lot, your application would have bad performance because of all that copying. If you ever wanted to actually use something like this, you should do what <code>List&lt;T&gt;</code> does: when adding, resize to twice the size of the original array, so that you don't have to copy the whole array the next time you add to it. But you're probably aware of this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:31:46.600", "Id": "25699", "Score": "0", "body": "+1 Thanks - Re # 1, I did not realize that `Array.Copy` had overloads with the same signature as `Array.ConstrainedCopy`, and I incorrectly assumed that `ConstrainedCopy` was used to set bounds as to what elements were copied" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:33:01.480", "Id": "25700", "Score": "0", "body": "Re #2, I am aware of this, but I'm pretty sure the compiler ends up emitting the same IL regardless. - Just validated this with LINQPad" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T10:21:21.300", "Id": "25704", "Score": "0", "body": "Yes, but IL is not all that matters. And not having to specify the size means shorter code, better readability and better maintainability, even if it is by a tiny little bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T12:58:02.693", "Id": "25712", "Score": "0", "body": "That's a fair point. I'm pretty comfortable with my understanding of code readability and API design, so I'm more concerned about the actual functionality of the code in this sample, but I would agree that what you say is valid." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:27:57.400", "Id": "15798", "ParentId": "15789", "Score": "3" } } ]
{ "AcceptedAnswerId": "15798", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:53:07.697", "Id": "15789", "Score": "3", "Tags": [ "c#", "javascript", "optimization", "array", "thread-safety" ], "Title": "C# Array Mutator Methods to mimic JavaScript Array Mutator Methods" }
15789
<p>I have created this extension method that can be used to run a function with a timeout applied to it. Is this a sensible way of doing it?</p> <pre><code>public static class FuncExtensions { public static T RunUntil&lt;T&gt;(this Func&lt;T&gt; predicate, TimeSpan timeout, string taskName) { var result = default(T); Action runTask = () =&gt; result = predicate(); try { var task = Task.Factory.StartNew(runTask); if (task.Wait(timeout)) { return result; } throw new TaskTimeoutException(string.Format("'{0}' timed out after {1}", taskName, timeout)); } catch (AggregateException aggregateException) { throw aggregateException.InnerException; } } } </code></pre> <p>Which can be used like this:</p> <pre><code>Func&lt;int&gt; task = () =&gt; { //some slow service }; var serviceResponse = task.RunUntil(_serviceTimeout, "Name of Task"); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:15:50.110", "Id": "25715", "Score": "1", "body": "I don't see the code which should stop the task if it goes over on time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T14:43:13.810", "Id": "25729", "Score": "0", "body": "The `if(task.Wait(timeout))` line as documented here: http://msdn.microsoft.com/en-us/library/dd235606.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T14:44:37.347", "Id": "25731", "Score": "6", "body": "Yes, but it doesn't *cancel the executing task* if you go over the wait time. It'll still be running." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T10:10:21.990", "Id": "27915", "Score": "1", "body": "How to do the cancelling is described here [Task Cancellation](http://msdn.microsoft.com/en-us/library/dd997396.aspx) and additionaly [How to: Cancel a Task and Its Children](http://msdn.microsoft.com/en-us/library/dd537607.aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T12:59:23.347", "Id": "27919", "Score": "0", "body": "This article describes the kind of problem I was dealing with: http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T15:23:34.413", "Id": "62828", "Score": "0", "body": "The best solution I've found is on this blog: http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T17:55:23.440", "Id": "135099", "Score": "0", "body": "According to this: http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx , you can't cancel a non-cancelable task. You can only ignore it and stop waiting for an answer from it. I wonder what would happen if you ran it on a separate thread, waited for the timeout and then aborted the thread?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T18:01:16.337", "Id": "135100", "Score": "0", "body": "But if you run it in a thread and abort the thread you wont be able to get any return values..." } ]
[ { "body": "<p>I think that his question would suit more on SO as it doesn't require explicitly a code review. This question is more about of how to correctly cancel a task instead of fixing apointing good pracrises, etc.. However you have made a great quest that deserves an answer: </p>\n\n<blockquote>\n<pre><code>if (task.Wait(timeout))\n{\n return result;\n}\n\nthrow new TaskTimeoutException(string.Format(\"'{0}' timed out after {1}\", taskName, timeout));\n</code></pre>\n</blockquote>\n\n<p>This will wait timeout milliseconds for the task completion however, the task may still continue, like <a href=\"https://codereview.stackexchange.com/users/6172/jesse-c-slicer\">@Jesse</a> pointed out.</p>\n\n<p>In tasks you are only able to cancel a task with a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">Cancelation Token Source</a>. With a cancellation token source you will be getting a token that you may then use to cancel the task. That token must be passed through all methods, this also includes the method that makes the long computation you were interested to cancel. This is because that you must actively check if there was a cancelation request. You can do this by calling the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.throwifcancellationrequested(v=vs.110).aspx\" rel=\"nofollow noreferrer\">ThrowIfCancellationRequested</a> method.</p>\n\n<p>So, in the end, you won't be able to cancel your previous code without at least adding a Cancellation token parameter and check for the cancellation with that.</p>\n\n<p>Here follows the pattern of a method that supports cancellation:</p>\n\n<pre><code>public static int Sum(int[] values, CancellationToken token){\n int acc = 0;\n for(int i = 0; i &lt; values.Length; ++i){\n acc += values[i]; \n token.ThrowIfCancellationRequested(); //you may wish to do this verification less often, doing this every iteration will reduce performance\n Thread.Sleep(100); //just simulate a longer task so you may know that it may be canceled before completing. \n }\n return acc;\n}\n</code></pre>\n\n<p>And here is how you could request a cancelation:</p>\n\n<pre><code>public static void Main(string[] args){\n CancellationTokenSource cancelSource = new CancellationTokenSource ();\n CancellationToken token = cancelSource.Token;\n int[] values = Enumerable.Range(0, 1000).ToArray();\n Task.Factory.StartNew(()=&gt; Sum(values, token), token)\n .ContinueWith(t =&gt; {\n if(!t.IsCanceled){ // you need to check canceled, otherwise a cancelation exception will be raised when getting Result\n Console.WriteLine(t.Result);\n }\n });\n cancelSource.Cancel();\n}\n</code></pre>\n\n<p><strong>Edit</strong> I noticed that I only talked about the cancellation and skipped the timeout, which was your real problem. Well, now that you know about how a task may be canceled you can use a technique similar to the one you were using: Wait with the timeout, and request a cancellation:</p>\n\n<pre><code>int[] values = Enumerable.Range(0, 1000).ToArray();\nvar src = new CancellationTokenSource();\nTask.Factory.StartNew(() =&gt; Sum(values, src.Token), src.Token).Wait(timeout);\nsrc.Cancel();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T18:32:32.640", "Id": "74314", "ParentId": "15796", "Score": "8" } }, { "body": "<p>Here is how I achieved something similar. </p>\n\n<pre><code>static void Main(string[] args)\n {\n Console.BufferHeight = Int16.MaxValue-1;\n RunWithTaskApproach();\n Console.WriteLine(\"Started calculating stuff!\");\n RunUntil(() =&gt; Calculatestuff(), TimeSpan.FromSeconds(10));\n Console.ReadLine();\n }\n\n\n\npublic static void RunUntil(Action predicate,TimeSpan timeout)\n {\n Thread thread = new Thread(new ThreadStart(predicate));\n thread.Name = \"My Little Thready\";\n thread.Start();\n Task.Run(() =&gt; Thread.Sleep(timeout))\n .ContinueWith((r) =&gt; \n {\n thread.Abort();\n Console.WriteLine(\"Calculating stuff timed out!\"); \n });\n }\n\npublic static void Calculatestuff()\n {\n BigInteger number = new BigInteger(1);\n while(true)\n {\n Console.WriteLine(ShortenNumber(number,20));\n if (number.IsEven)\n number += number + 1;\n else\n number *= 2;\n }\n }\n</code></pre>\n\n<p>Bruno's answer does the same with tasks with the added benefit that you can get a return value instead of having to use global variables or printing on the console/using a static class and all that. I still decided to post this since I had some fun writing it and I think it does work as an alternate solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T18:53:26.157", "Id": "74316", "ParentId": "15796", "Score": "-1" } }, { "body": "<ul>\n<li><p>Instead of calling <code>var task = Task.Factory.StartNew(runTask);</code> or like <a href=\"https://codereview.stackexchange.com/users/22270/bruno-costa\">Bruno Costa</a> correctly suggested with a <code>CancellationToken</code> like <code>var task = Task.Factory.StartNew(runTask, cancellationToken);</code> you can here use for NET 4.5 the overloaded <code>Task.Run(Action, CancellationToken)</code> method, \nwhich can be seen as a simplified call to <code>Task.Factory.StartNew()</code>. </p>\n\n<p>See also : <a href=\"https://stackoverflow.com/a/22087211\">https://stackoverflow.com/a/22087211</a> </p></li>\n<li><p>By providing a default value for <code>taskName</code> the message of a thrown <code>TaskTimeoutException</code> would look better. </p></li>\n<li><p>Early checking if <code>TimeSpan timeout</code> is in the given range, will reduce overhead. </p></li>\n<li><p><code>Action runTask</code> should be renamed to <code>runAction</code> or better to just <code>action</code>. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-25T12:37:43.243", "Id": "74861", "ParentId": "15796", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:12:20.737", "Id": "15796", "Score": "14", "Tags": [ "c#", ".net", "timeout" ], "Title": "Timing out a method" }
15796
<p>First I tried to fetch this program as close to pseudo code where I must follow all imported items, all method definitions, and all defined variables; anything else was my choice.</p> <p>After I created working program that best represent the sample run of output we were provided in my homework documentation, I decided to create checks for data input such as correct number input.</p> <p>Now, is my code (sorry for expression) idiot-proof, meaning that whatever user inputs will not effect program's outputs?</p> <p>What can I do to ensure that this code will not fail because of user input?</p> <p>In my program I am trying to use <code>while</code> loops as much as possible to let user to re-enter data if data that was entered is not appropriate. But is this enough?</p> <pre><code>import java.io.*; public class CalculatePayroll { public static final double TAX_SOCIAL = 0.10; public static final double TAX_STATE = 0.10; public static final double TAX_FEDERAL = 0.10; public static void main(String[] args) { String inputName = null, mustBeNumeric = "[-+]?\\d+(\\.\\d+)?"; char inputStatus = 0, inputAskRepeat = 0; double inputSalary = 0, inputRate = 0, inputHours = 0; boolean boolRepeat = true; BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Payroll Calculator"); while (boolRepeat == true) { boolean boolAskRepeat = true; boolean boolAskStatus = true; System.out.print("\nLast Name: "); try {inputName = input.readLine(); } catch (IOException e) { e.printStackTrace(); } while (boolAskStatus == true) { System.out.print("Status (F or P): "); try { inputStatus = input.readLine().toLowerCase().charAt(0); } catch (IOException e) { e.printStackTrace(); } if (inputStatus == "f".charAt(0)) { boolAskStatus = false; String stringCheckSalary = null; boolean boolCheckSalary = true; while (boolCheckSalary == true) { System.out.print("Salary: "); try { stringCheckSalary = input.readLine(); } catch (IOException e) { e.printStackTrace(); } if (stringCheckSalary.matches(mustBeNumeric)) { boolCheckSalary = false; inputSalary = Double.parseDouble(stringCheckSalary); } else boolCheckSalary = true; } outputData(inputName, inputStatus, calculateFullTimePay(inputSalary)); } else if (inputStatus == "p".charAt(0)) { boolAskStatus = false; String stringCheckRate = null; boolean boolCheckRate = true; while (boolCheckRate == true) { System.out.print("Rate: "); try { stringCheckRate = input.readLine(); } catch (IOException e) { e.printStackTrace(); } if (stringCheckRate.matches(mustBeNumeric)) { boolCheckRate = false; inputRate = Double.parseDouble(stringCheckRate); } else boolCheckRate = true; } String stringCheckHours = null; boolean boolCheckHours = true; while (boolCheckHours == true) { System.out.print("Hours: "); try { stringCheckHours = input.readLine(); } catch (IOException e) { e.printStackTrace(); } if (stringCheckHours.matches(mustBeNumeric)) { boolCheckHours = false; inputHours = Double.parseDouble(stringCheckRate); } else boolCheckHours = true; } outputData(inputName, inputStatus, calculatePartTimePay(inputRate, inputHours)); } else boolAskStatus = true; } while (boolAskRepeat == true) { System.out.print("Another payroll? (Y or N): "); try { inputAskRepeat = input.readLine().toLowerCase().charAt(0); } catch (IOException e) { e.printStackTrace(); } if (inputAskRepeat == "n".charAt(0)) { boolAskRepeat = false; boolRepeat = false; } else if (inputAskRepeat == "y".charAt(0)) { boolAskRepeat = false; boolRepeat = true; } else boolAskRepeat = true; } } System.out.print("\nProgram terminated..."); } private static double calculateTaxes(double weeklyPay) { return weeklyPay * (TAX_SOCIAL + TAX_STATE + TAX_FEDERAL); } private static double calculatePartTimePay(double rate, double hours) { double pay = 0; if (hours &lt;= 40) pay = rate * hours; else if (hours &gt; 40) pay = (rate * 40) + ((hours - 40) * (rate * 1.5)); return pay; } private static double calculateFullTimePay(double salary) { return salary / 52; } private static void outputData(String name, char status, double pay) { if (status == "p".charAt(0)) { System.out.println("-------------------------------------------------------"); System.out.println("Name\tStatus\t\tGross\tTaxes\tNet"); System.out.printf("%s\tPart Time\t%.2f\t%.2f\t%.2f\n\n", name, roundDouble(pay), roundDouble(calculateTaxes(pay)), roundDouble(pay - calculateTaxes(pay))); } else if (status == "f".charAt(0)) { System.out.println("-------------------------------------------------------"); System.out.println("Name\tStatus\t\tGross\tTaxes\tNet"); System.out.printf("%s\tFull Time\t%.2f\t%.2f\t%.2f\n\n", name, roundDouble(pay), roundDouble(calculateTaxes(pay)), roundDouble(pay - calculateTaxes(pay))); } } private static double roundDouble(double number) { return Double.parseDouble(String.valueOf((int)(number * 100))) / 100; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T10:33:03.783", "Id": "25705", "Score": "7", "body": "I'll put this as a comment as it's not really answering your question of idiot-proofness, but money shouldn't be represented in `double` or `float`, because they can't accurately represent most base 10 numbers. You should use either `BigDecimal`, `int` or `long`, with `int` and `long` representing pennies, cents or their equivalents. More info here -> http://www.javapractices.com/topic/TopicAction.do?Id=13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T12:58:41.007", "Id": "25713", "Score": "5", "body": "If you build an idiot proof program, they will build a better idiot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:38:26.663", "Id": "25719", "Score": "0", "body": "\"f\" is a number in exadecimal. Silly doesn'it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T01:21:56.713", "Id": "25757", "Score": "0", "body": "The input statement which asks for character input is not idiot-proof, as I noticed. It cannot handle empty or too long string, but I have fixed that." } ]
[ { "body": "<p><code>mustBeNumeric</code> is a regular expression that will not change. It is better declared as a <code>static final</code> field, rather than a mutable variable within a method scope.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T02:11:15.847", "Id": "25799", "Score": "2", "body": "Added for future reference: [How to check a String is a numeric type in java](http://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:02:28.570", "Id": "15804", "ParentId": "15800", "Score": "6" } }, { "body": "<h1>\"User Proofing\"</h1>\n\n<ol>\n<li><h2>Don't use double</h2>\n\n<p>As already mentioned by toofarsideways in the comments, storing currency values as float or double is problematic. Floating point cannot represent all numbers; it will get you close though.<br>\nIt is highly recommended that you use another option better suited for accuracy (like <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html\"><code>BigDecimal</code></a>) </p></li>\n<li><h2>0-length input</h2>\n\n<ul>\n<li><h2>Optional last name</h2>\n\n<p>A user can skip entering a last name by pressing enter.</p></li>\n<li><h2>StringIndexOutOfBoundsException</h2>\n\n<p>A user that skips entering any other value will result in a thrown <code>StringIndexOutOfBoundsException</code>. I find myself wondering if it's necessary to only check the first character </p>\n\n<p>Why not just compare <code>Strings</code> with <code>equalsIgnoreCase(String)</code>? </p>\n\n<pre><code>if(\"f\".equalsIgnoreCase(inputStatus)) {\n // ... full-time\n}\n</code></pre></li>\n<li><h2>NullPointerException</h2>\n\n<p><code>readLine()</code> can return <code>null</code> if the user presses <kbd>CTRL</kbd>+<kbd>C</kbd>. Typically <kbd>CTRL</kbd>+<kbd>C</kbd> will kill your program anyways, but still nice to avoid <code>NullPointerExceptions</code>.</p></li>\n</ul></li>\n<li><h2>Unchecked numeric values</h2>\n\n<p>A user can submit whatever numeric value they want for salary, rate, or hours without any special checks/sanitzation. </p>\n\n<ul>\n<li><h2>Negative values</h2>\n\n<p>A user can submit a negative salary, rate, or hours. </p>\n\n<p>Instead of using regex to validate the input, I would rely on the built-in <code>Double.parseDouble(String)</code> method to deal with the validation. You only have to worry about handling the <code>NumberFormatException</code>.</p>\n\n<pre><code>System.out.print(\"Salary: \");\ntry { \n stringCheckSalary = input.readLine(); \n inputSalary = Double.parseDouble(stringCheckSalary);\n boolCheckSalary = false;\n} catch (IOException e) {\n e.printStackTrace();\n} catch(NumberFormatException ex) {\n System.out.printf(\"Please try again. Invalid number: '%s'\\n\", stringCheckSalary);\n}\n</code></pre>\n\n<p>The same idea works for <code>BigDecimal</code> as well.</p></li>\n<li><h2>Unbounded numbers</h2>\n\n<p>You should validate the submitted values and make sure they make sense. Currently a user can input a salary of 700 trillion dollars, or maybe 400 hours of part time work in a week. </p>\n\n<p>As an example to validate the number of hours, you might use </p>\n\n<pre><code>final int HOURS_IN_A_WEEK = 7 * 24; // should be static\nboolCheckHours = (inputHours &lt; 0 || inputHours &gt; HOURS_IN_A_WEEK);\n</code></pre></li>\n</ul></li>\n<li><h2>Unclear error handling (usability)</h2>\n\n<p>When a user submits an unexpected value, you print the same request again without any indication of what went wrong.<br>\nYou should print an error message detailing the problem before reasking for input. </p>\n\n<p>For example,</p>\n\n<blockquote>\n <p>Please try again. Invalid number: 'one hundred'</p>\n</blockquote></li>\n<li><h2>inputHours Bug</h2>\n\n<p>You accidentally parse checkRate as <code>inputHours</code>. So the rate and hours for part-time will always be the same. </p>\n\n<pre><code>inputHours = Double.parseDouble(stringCheckRate);\n</code></pre></li>\n</ol>\n\n<p><br /></p>\n\n<h1>Other Code Comments</h1>\n\n<p>Since I'm at it I'll throw in a few comments on the code as well</p>\n\n<ol>\n<li><h2>roundDouble(double)</h2>\n\n<p>If you go with <code>BigDecimal</code> this will likely be a moot point. </p>\n\n<p><code>roundDouble(double)</code> is unecessarily complicated. In general you need to be careful when converting between <code>double</code> and <code>int</code> values. The loss of precision can cause some pretty serious problems in a real application. </p>\n\n<p>If you're running Java 6+ then you can use <code>DecimalFormat.setRoundingMode(RoundingMode)</code>, </p>\n\n<pre><code>DecimalFormat formatter = new DecimalFormat(\"0.00\");\nformatter.setRoundingMode(RoundingMode.DOWN);\nSystem.out.println(\"-------------------------------------------------------\");\nSystem.out.println(\"Name\\tStatus\\t\\tGross\\tTaxes\\tNet\");\nSystem.out.printf(\"%s\\tPart Time\\t%s\\t%s\\t%s\\n\\n\",\n name,\n formatter.format(pay),\n formatter.format(calculateTaxes(pay)),\n formatter.format(pay - calculateTaxes(pay))); \n</code></pre>\n\n<p>If you're not running at least Java 6, you can simplify this method very easily as </p>\n\n<pre><code>private static double roundDouble(double number) {\n return Math.floor(number * 100.0) / 100.0;\n}\n</code></pre>\n\n<p>Or if you're a fan of reusable methods,</p>\n\n<pre><code>private static double roundDown(double number, int precision) {\n // floorWithPrecision(2.617, 2) =&gt; Math.floor(2.617 * 100.0) / 100.0 =&gt; 2.61\n final double shiftValue = Math.pow(10, precision);\n return Math.floor(number * shiftValue) / shiftValue;\n}\n</code></pre></li>\n<li><h2>String.charAt(0)</h2>\n\n<p>Instead of using <code>\"f\".charAt(0)</code> to retrieve a single character you should use the char primitive <code>'f'</code></p>\n\n<pre><code>if (inputStatus == 'f')\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T21:09:01.603", "Id": "25797", "Score": "0", "body": "You have posten many things that I agree on. There was few things I coded there and I didn't agree too but part of this program was my homework. I just went further and tried to make this program as fail-proof as I could. I like bit of criticism on my coding :) Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T16:51:04.203", "Id": "25821", "Score": "2", "body": "`readLine()` returns `null` if the user presses CTRL+D (too). (It works on Linux.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T16:55:30.570", "Id": "25822", "Score": "2", "body": "@Palacsint I had a feeling about CTRL+D as well. My Linux box is down so I couldn't try it there. On windows it didn't seem to do anything especially noticeable." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T07:16:20.003", "Id": "15826", "ParentId": "15800", "Score": "11" } }, { "body": "<p>Not related to the idiot-proof aspect of your code is the fact that it is structured badly, more precisely, it is not structured at all. At the very least your main function should be broken down into several smaller functions. Given that this is java, you should probably create one or more nested classes that handle input and/or validation.</p>\n\n<p>Related to idiot proof, you should create a generic method of asking your question and verifying that the answer is acceptable, you do that and it will be idiot proof.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T20:27:49.273", "Id": "25899", "Score": "0", "body": "I agree, the program, in fact, was not planned to be OOP so I just fetched it together and tried to make it fail safe :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T21:31:43.477", "Id": "15859", "ParentId": "15800", "Score": "7" } }, { "body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>You could remove some duplication from the <code>outputData</code> method:</p>\n\n<pre><code>private static void outputData(final String name, final char status, final double pay) {\n final String statusString;\n if (status == 'p') {\n statusString = \"Part Time\";\n } else if (status == 'f') {\n statusString = \"Full Time\";\n } else {\n throw new IllegalStateException(\"Invalid status: \" + status);\n }\n System.out.println(\"-------------------------------------------------------\");\n System.out.println(\"Name\\tStatus\\t\\tGross\\tTaxes\\tNet\");\n System.out.printf(\"%s\\t%s\\t%.2f\\t%.2f\\t%.2f\\n\\n\", statusString, name, roundDouble(pay),\n roundDouble(calculateTaxes(pay)), roundDouble(pay - calculateTaxes(pay)));\n}\n</code></pre>\n\n<p>I guess you could replace the similar <code>if-else</code> structures with polymorphism. Two useful reading:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional with Polymorphism</a></li>\n</ul></li>\n<li><p><code>52</code>, <code>40</code> etc. should be named constant instead of magic numbers.</p></li>\n<li><pre><code>while (boolAskStatus == true)\n</code></pre>\n\n<p>could be simply:</p>\n\n<pre><code>while (boolAskStatus)\n</code></pre>\n\n<p>From Code Complete, 2nd Edition, p433:</p>\n\n<blockquote>\n <p>Compare <code>boolean</code> values to <code>true</code> and <code>false</code> implicitly</p>\n \n <p>[...]</p>\n \n <p>Using implicit comparisons reduces the number of terms that someone reading your\n code has to keep in mind, and the resulting expressions read more like conversational English.</p>\n</blockquote></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T17:54:10.443", "Id": "15880", "ParentId": "15800", "Score": "2" } } ]
{ "AcceptedAnswerId": "15826", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T10:09:07.760", "Id": "15800", "Score": "10", "Tags": [ "java", "homework", "finance" ], "Title": "Payroll calculator" }
15800
<p>The following program is supposed to be a (command line) calculator that parses expression following syntax similar to <a href="http://en.wikipedia.org/wiki/S-expression" rel="nofollow noreferrer">Lisp's S-expressions</a>.</p> <p>Some examples:</p> <blockquote> <p>$ echo &quot;(+ 5 5)&quot; | ./a.out</p> <p>10.000000</p> <p>$ echo &quot;(+ (- 3 2) (* 9 2))&quot; | ./a.out</p> <p>19.000000</p> <p>$ echo &quot;(/ 24 6 2)&quot; | ./a.out</p> <p>2.000000</p> <p>$ echo &quot;(/ 24 (/ 6 2))&quot; | ./a.out</p> <p>8.000000</p> </blockquote> <ul> <li><p>The program is not supposed to deal with error handling (invalid S-expr, division by zero, ...). We assume the input is always valid. (The program is meant as an exercise and is not going to production).</p> </li> <li><p>Separators can be space, tabs or newline characters.</p> </li> <li><p>The only operations considered are <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code></p> </li> <li><p>The program is supposed to deal with integers and float input.</p> </li> </ul> <p>Here's my headers file:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; #define NUMBER '0' #define OPERATOR '+' #define MAX_NUM_SIZE 100 #define MAX_DEPTH 100 typedef double (*doublefun_t) (); double add (double a, double b) { return a+b;} double sub (double a, double b) { return a-b;} double mul (double a, double b) { return a*b;} double dvs (double a, double b) { return a/b;} typedef struct args args_t; struct args { double value; args_t *next; }; typedef struct sexpr sexpr_t; struct sexpr { char operation; args_t *arguments; }; sexpr_t sstack[MAX_DEPTH]; /* Initial value is -1 because the stack is empty. Will be incremented to 0 by the first opening paren. */ int current_level = -1; double final_result = 0; int getop(char s[]); void create_sexpr(); void add_operation(char op); void add_argument(double a); void evaluate_sexpr(); </code></pre> <p>And the actual code:</p> <pre><code>int main(int argc, char *argv[]) { int type; char s[MAX_NUM_SIZE]; while ((type = tokenize(s)) != EOF) { switch(type) { case '(': create_sexpr(); break; case OPERATOR: add_operation(s[0]); break; case NUMBER: add_argument(atof(s)); break; case ')': evaluate_sexpr(); break; default: break; /* Purposfully ignoring error handling */ } if (current_level &lt; 0) break; } printf(&quot;%f\n&quot;, final_result); return 0; } /* Parses input from stdin. returns NUMBERS for numbers or ascii value for any of ( ) + - * / */ int tokenize(char s[]) { int c; static int buf = EOF; if (isalnum(buf)) { c = buf; buf = EOF; return c; } if (buf == EOF || buf == ' ' || buf == '\t') while ((*s = c = getchar()) == ' ' || c == '\t') ; else *s = c = buf; buf = EOF; *(s + 1) = '\0'; if (c == 42 || c == 43 || c == 45 || c == 47) return OPERATOR; if (!isdigit(c) &amp;&amp; c != '.') return c; /* not a number */ if (isdigit(c)) /* collect integer part */ while (isdigit(*++s = c = getchar())) ; if (c == '.') /* collect fraction part */ while (isdigit(*++s = c = getchar())) ; *s++ = '\0'; buf = c; return NUMBER; } /* Create new sexpr and put it on the sstack. increment current_level index */ void create_sexpr() { sexpr_t *new = malloc(sizeof(sexpr_t)); new-&gt;arguments = NULL; sstack[++current_level] = *new; } void add_operation(char op) { sstack[current_level].operation = op; } void add_argument(double a) { args_t *new_argument = malloc(sizeof(args_t)); args_t *args_iterator = sstack[current_level].arguments; new_argument-&gt;value = a; new_argument-&gt;next = NULL; if (args_iterator == NULL) sstack[current_level].arguments = new_argument; else { while (args_iterator-&gt;next != NULL) args_iterator = args_iterator-&gt;next; args_iterator-&gt;next=new_argument; } } void evaluate_sexpr() { char op = sstack[current_level].operation; doublefun_t f = NULL; /* variable holders used for the accumulation */ double a, b; args_t *new_argument = NULL; args_t *args_iterator = sstack[current_level].arguments; a = args_iterator-&gt;value; switch(op) { case '+': f = &amp;add; break; case '-': f = &amp;sub; break; case '*': f = &amp;mul; break; case '/': f = &amp;dvs; break; } while (args_iterator-&gt;next) { b = args_iterator-&gt;next-&gt;value; a = (*f)(a, b); args_iterator = args_iterator-&gt;next; } if (--current_level &gt;= 0) { new_argument = malloc(sizeof(args_t)); new_argument-&gt;value = a; new_argument-&gt;next = NULL; if (sstack[current_level].arguments == NULL) { sstack[current_level].arguments = new_argument; } else { args_iterator = sstack[current_level].arguments; while (args_iterator-&gt;next != NULL) args_iterator = args_iterator-&gt;next; args_iterator-&gt;next= new_argument; } } else { final_result = a; } } </code></pre> <p>I would like to know how to improve the readability of the code, how to make it easier for other programmers to pick it up and understand it.</p> <p>I am notably unsure about my use of function pointers. It's literally the first time I've ever used them (although it was pretty trivial).</p> <p>Of course, any general remark about my coding style would be highly appreciated.</p>
[]
[ { "body": "<p>I don't know why nobody commented on this question as there is lots to be\nsaid. I'll go through what I found from the top down:</p>\n\n<p>Your typedef for the functions should be complete with the types of call\nparameters. The name <code>doublefun_t</code> is the operation to be performed, so the\nword 'operation' might be approriate. Also the suffix <code>_t</code> is reserved by\nPOSIX so is best avoided. I prefer to upper-case the first letter of types:</p>\n\n<pre><code>typedef double (*Operation) (double, double);\ntypedef struct arg Arg;\ntypedef struct sexpr Sexpr;\n</code></pre>\n\n<p>Functions and global variables should be <code>static</code> wherever possible - here\nthat means everything at global scope except <code>main</code>. this does not really\nmatter for single-file programs but it is best to get used to defaulting to\n<code>static</code> for bigger programs where it can improve optimization possibilities\nand reduce name-space pollution.</p>\n\n<p>I would call your expression stack simply <code>stack</code>. The <code>current_level</code>\nvariable, which indicates the level of the stack, would be better if the name\nidentified its connection to the stack, eg <code>stack_level</code>. You could\nalternatively put these two variables into a structure to keep them together.\nNote that using globals such as these is not generally considered to be good\npractice. Normally variables are defined local to a function and passed\naround as call parameters. Globals are an easy alternative that rapidly\nbecome an unsupportable mess in larger programs. Your <code>final_result</code> \nis a case where a global is definitely unnecessary (return a value from\n<code>evaluate_sexpr</code> instead).</p>\n\n<p>Put <code>main</code> at the end to avoid the need for prototypes of local functions.\nAlso your functions without parameters should have ` void parameter list:</p>\n\n<pre><code>static void create_sexpr(void)\n</code></pre>\n\n<p>Your function <code>tokenize</code> would be more naturally named <code>get_token</code> (as it gets\na token from <code>stdin</code>). It is also rather a mess. Firstly, note that you can\npush a character back into <code>stdin</code> using <code>ungetc()</code>. Using this you can avoid\nthe need for a static variable to hold the last-read character between calls.\nSome other issues with the function are:</p>\n\n<ul>\n<li><p>repeated space-test conditions:</p>\n\n<pre><code>if (buf == EOF || buf == ' ' || buf == '\\t')\n while ((*s = c = getchar()) == ' ' || c == '\\t')\n ;\n</code></pre>\n\n<p>note that <code>isspace</code> is often better than explicit tests for characters</p></li>\n<li><p>embedded numeric constants </p>\n\n<pre><code>if (c == 42 || c == 43 || c == 45 || c == 47)\n return OPERATOR;\n</code></pre>\n\n<p>(use '+', '-', '*', '/' instead of the numbers)</p></li>\n<li><p>your double assignments are better avoided:</p>\n\n<pre><code>while (isdigit(*++s = c = getchar()))\n</code></pre>\n\n<p>note that <code>s</code> has type <code>char</code> while <code>c</code> has the type <code>int</code> so a cast would\nbe better here anyway. </p></li>\n<li><p>there is no check for overflowing the output buffer</p></li>\n</ul>\n\n<p>Your function <code>create_sexpr</code> is wrong. It allocates a new expression\nstructure and then assigns that new struct to the existing stack variable:</p>\n\n<pre><code>void create_sexpr()\n{\n sexpr_t *new = malloc(sizeof(sexpr_t));\n new-&gt;arguments = NULL;\n sstack[++current_level] = *new;\n}\n</code></pre>\n\n<p>Notice the '*' in the the assignment on the last line. The malloced memory\njust gets leaked on return from the function. As the stack is preassigned\n(it is a static array), all the function needs to do is:</p>\n\n<pre><code>static void create_sexpr(void)\n{\n stack[++stack_level].arguments = NULL;\n}\n</code></pre>\n\n<p>Function <code>evaluate_sexpr</code> can be improved in a number of ways. For a start,\nas indicated above, it should return the expression value, not set a global\nresult. Your use of function pointers is correct but the syntax can be\nsimplified. you don't need to take the address of a function and you don't\nneed to de-reference a function pointer. So with a function pointer <code>f</code> of\ntype <code>doublefun_t</code>, instead of:</p>\n\n<pre><code>f = &amp;add;\n...\na = (*f)(a, b);\n</code></pre>\n\n<p>You can write simply:</p>\n\n<pre><code>f = add;\n...\na = (*f)(a, b);\n</code></pre>\n\n<p>I would also extract the <code>switch</code> that determines the necessary function into\na separate function returning a function pointer:</p>\n\n<pre><code>typedef double (*Operation) (double, double);\n\nstatic Operation get_operation(int op)\n{\n switch(op) {\n case '+': return add;\n case '-': return sub;\n case '*': return mul;\n case '/': return dvs;\n }\n return NULL;\n}\n</code></pre>\n\n<p>And note that the code segment enclosed in the condition:</p>\n\n<pre><code>if (--current_level &gt;= 0) {\n new_argument = malloc(sizeof(args_t));\n new_argument-&gt;value = a;\n new_argument-&gt;next = NULL;\n\n if (sstack[current_level].arguments == NULL) {\n sstack[current_level].arguments = new_argument;\n } else {\n args_iterator = sstack[current_level].arguments;\n\n while (args_iterator-&gt;next != NULL)\n args_iterator = args_iterator-&gt;next;\n\n args_iterator-&gt;next= new_argument;\n }\n}\n</code></pre>\n\n<p>is exactly the same as calling your <code>add_argument(a)</code></p>\n\n<p>I hope there is something above that you can use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T17:47:17.743", "Id": "37973", "ParentId": "15802", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T10:50:19.280", "Id": "15802", "Score": "3", "Tags": [ "c", "parsing", "console", "math-expression-eval", "calculator" ], "Title": "Calculator parsing S-expressions" }
15802
<p>I'm quite new to Python and would love to gather feedback on my code. I've written a piece a script that allows me to search all file or directory names within a folder matching a particular pattern. The caller can specify if the function should be recursive or not.</p> <p>It's only a basic script I would love to know how it could be improved!</p> <pre><code>import sys import os import string def rename(source, pattern, replacement, dirs = False, recurse = False): """ Rename a file or directory source = source directory pattern = old string replacement = new string dirs = apply to directorys recurse = move recursivley """ dir = os.path.abspath(source) for item in os.listdir(dir): # Get the full path item = os.path.join(source, item) if os.path.isfile(item) and pattern in item: os.rename(item, string.replace(item, pattern, replacement)) elif os.path.isdir(item): if recurse: # Move to the next level, before renaming rename_items(item, pattern, replacement, dirs, recurse) if pattern in item and dirs: os.rename(item, string.replace(item, pattern, replacement)) if __name__ == '__main__': source = sys.argv[1] pattern = sys.argv[2] replacement = sys.argv[3] rename(source, pattern, replacement, True, True) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T14:39:47.710", "Id": "25728", "Score": "0", "body": "The only problem I found with your script is that you shouldn't name your variable `dir` as it is the name of a global function." } ]
[ { "body": "<p>What if the script renames file \"a.zip\" to \"b.zip\", and both files \"a.zip\" and \"b.zip\" exist in the same directory?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T21:45:17.960", "Id": "15841", "ParentId": "15805", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T13:08:23.867", "Id": "15805", "Score": "4", "Tags": [ "python", "file-system" ], "Title": "Renaming Files and/or Directory" }
15805
<p>I am a high-school freshman who is kinda new to Ruby, and I am doing a small project on Ruby. One of the big things that I want to get out of this project is how to follow the "Ruby standards" that programmers should follow. Being as new as I am, I have no clue what I should/shouldn't do with this program. Can anybody tell me what I could do to improve it to fit the community's standards?</p> <pre><code>require 'tk' $point_A = [0,0] $point_B = [750,750] $rate = 1.5 $i=0 circs=Array.new def before_drawing() $point_A = [] temp_a = $point_B[0]**1/$rate temp_b = $point_B[1]**1/$rate $point_A &lt;&lt; temp_a $point_A &lt;&lt; temp_b end def after_drawing() $point_B = [] $point_B = $point_A end canvas = TkCanvas.new(:width=&gt;800, :height=&gt;800).pack('fill' =&gt; 'both', 'expand'=&gt;true) while $i&lt;10 do before_drawing() circs[$i] = TkcOval.new(canvas, $point_A, $point_B) if $i%2==0 then circs[$i][:fill] = 'blue' else circs[$i][:fill] = 'red' end after_drawing() $i+=1 end Tk.mainloop </code></pre>
[]
[ { "body": "<p>You should define arrays with <code>[]</code> not <code>Array.new</code></p>\n\n<p><code>circs</code> should be <code>$circs</code> in case you wrap your loop in some function.</p>\n\n<p>Before drawing can be turned into this :</p>\n\n<pre><code>def before_drawing()\n temp_a = $point_B[0] ** 1 / $rate\n temp_b = $point_B[1] ** 1 / $rate\n $point_A = [temp_a, temp_b]\nend\n</code></pre>\n\n<p>You should turn <code>$i</code> into a local variable for the loop. There is no need for it to be global.</p>\n\n<p>Then replace the loop with <code>upto</code>.</p>\n\n<pre><code>0.upto(10) do |i|\n before_drawing()\n\n circs[i] = TkcOval.new(canvas, $point_A, $point_B)\n # As suggested using ternary operator\n # circs [i] [:fill] = i % 2 == 0 ? 'blue' : 'red'\n\n if i % 2 == 0 then\n circs[i][:fill] = 'blue'\n else\n circs[i][:fill] = 'red'\n end\n\n after_drawing()\nend\n</code></pre>\n\n<p>You seem to use too many global variables. My advice would be to prefer local variables whenever you can (Like i in the loop). All your global variables can also be made local to the loop (or function in case you wrap the loop in some function).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T14:07:46.060", "Id": "25816", "Score": "0", "body": "Alrighty, that makes sense.. I had no idea that something like `upto` existed, and I was afraid to use `x.times{}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-04T20:07:59.720", "Id": "32227", "Score": "0", "body": "I would recommend to change `if i % 2 == 0 then circs[i][:fill] = 'blue' else circs[i][:fill] = 'red' end` to `circs[i][:fill] = (i % 2 == 0 ? 'blue' : 'red')` or even `circs[i][:fill] = %w{blue red}[i % 2]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T10:38:47.370", "Id": "32244", "Score": "0", "body": "Using the ternary operator isn't a bad idea." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T18:01:25.237", "Id": "15810", "ParentId": "15806", "Score": "5" } }, { "body": "<p>Some notes:</p>\n\n<ol>\n<li><p>Use tabspace=2.</p></li>\n<li><p>Don't use global variables. When programming you should use functions in the same sense than you do in maths. That's a real function: <code>f(x, y) = x + y</code>, note that it takes arguments and returns some output (no globals, no states, no updates to variables outside the function). </p></li>\n<li><p>Ruby is a OOP language, so we usually define a class (or module) to contain our code.</p></li>\n<li><p>Don't overuse statements, use expressions. This code uses statements: <code>x = []; x &lt;&lt; 1; x &lt;&lt; 2</code>, this one uses expressions: <code>x = [1, 2]</code>.</p></li>\n<li><p>You are writing a loop where the output is the input of the next iteration. That can be written with <code>Enumerable#inject</code> (this method is somewhat difficult to grasp at first, study the docs carefully).</p></li>\n</ol>\n\n<p>A more idiomatic Ruby approach would be:</p>\n\n<pre><code>require 'tk'\n\nclass Example\n def initialize(options = {}) \n @rate = options[:rate] || 1.5\n @start_point = options[:start_point] || [750, 750]\n @canvas_size = options[:canvas_size] || [800, 800]\n end\n\n def run\n canvas = TkCanvas.new(:width =&gt; @canvas_size[0], :height =&gt; @canvas_size[1])\n canvas.pack('fill' =&gt; 'both', 'expand' =&gt; true)\n\n 1.upto(10).inject(@start_point) do |point, index|\n # get_next_point is a one-liner and could be written here,\n # but let's show how to use arguments to call functions/methods.\n point2 = get_next_point(point, @rate)\n circle = TkcOval.new(canvas, point, point2)\n circle[:fill] = (index % 2) == 0 ? \"red\" : \"blue\"\n point2\n end\n Tk.mainloop\n end\n\n def get_next_point(point, rate)\n [point[0] / rate, point[1] / rate]\n end\nend\n\nif __FILE__ == $0\n example = Example.new(:rate =&gt; 1.5, :start_point =&gt; [750, 750])\n example.run\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T03:18:49.523", "Id": "32293", "Score": "0", "body": "Ruby may be OOP, but it's also a scripting language designed for building small purpose-built scripts. There is no need to shoe-horn in a class definition for such a small program, but if this is meant to be the foundation of a larger app then it's definitely a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T09:52:45.937", "Id": "32298", "Score": "0", "body": "@meagar, I agree, but as you say I tried to show good practices for medium/large scripts." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T14:00:56.187", "Id": "15832", "ParentId": "15806", "Score": "3" } }, { "body": "<p>This is slightly late, but I feel like the existing answers are somewhat over-wrought.</p>\n\n<p>A few points:</p>\n\n<ul>\n<li><code>10.times</code>, as others have mentioned</li>\n<li>You're not using <code>**</code> correctly: <code>x ** 1 / rate</code> is the same as <code>(x ** 1) / rate</code>, and <code>x ** 1</code> equals <code>x</code>. So, things are cleaned up right away by replacing <code>** 1 / rate</code> with <code>/ rate</code></li>\n<li>You can pass <code>:fill</code> directly to the constructor of <code>TkcOval</code>, meaning you don't need to store your circles at all</li>\n<li>If you <em>do</em> need to store the circles, you can use <code>circles = (0..9).map { |i| ...}</code> instead of <code>10.times</code> and return the circle from the block</li>\n<li>You can compute color on one line using the ternary operator, or, better yet, store the colors in an array (<code>colors = %w(blue red)</code>) which can ban indexed by <code>i % 2</code></li>\n<li>Because we're dealing with maths, I prefer to store the points outside an array as <code>(x1, y1)</code> and <code>(x2, y2)</code>. I think this makes things clearer than using arrays. Clearer still would be using points with <code>.x</code> and <code>.y</code> members like <code>p1.x, p1.y</code>, but that isn't supported</li>\n<li>There is no need for your before/after methods, because they're doing next to nothing. They should be written as single lines of code.</li>\n</ul>\n\n<p>Here's the results, about 10 lines of extremely concise and idiomatic code:</p>\n\n<pre><code>require 'tk'\n\ncanvas = TkCanvas.new(:width =&gt; 800, :height =&gt; 800).pack('fill' =&gt; 'both', 'expand' =&gt; true)\n\nx1, y1, rate = 750, 750, 1.5\n\ncolors = %w(blue red)\n\n10.times do |i|\n x2, y2 = x1 / rate, y1 / rate\n TkcOval.new(canvas, [x1, y1], [x2, y2], :fill =&gt; colors[i % 2])\n x1, y1 = x2, y2\nend\n\nTk.mainloop\n</code></pre>\n\n<p>Note that we could get even shorter and ditch x2/y2, but I feel this starts to verge on code-golf rather than simply writing concise code:</p>\n\n<pre><code>require 'tk'\n\ncanvas = TkCanvas.new(:width =&gt; 800, :height =&gt; 800).pack('fill' =&gt; 'both', 'expand' =&gt; true)\n\nx, y, colors, rate = 750, 750, %w(blue red), 1.5\n\n10.times do |i|\n TkcOval.new(canvas, [x, y], [x /= rate, y /= rate], :fill =&gt; colors[i % 2])\nend\n\nTk.mainloop\n</code></pre>\n\n<p>Furthermore, note some style issues:</p>\n\n<ul>\n<li><em>two spaces</em> for indentation, no more no less</li>\n<li><em>don't prefix your variables with <code>$</code></em>, you're making global variables needlessly.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T02:50:50.097", "Id": "20203", "ParentId": "15806", "Score": "2" } } ]
{ "AcceptedAnswerId": "15810", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T14:24:03.223", "Id": "15806", "Score": "3", "Tags": [ "beginner", "ruby", "graphics", "tk" ], "Title": "Drawing colored circles using Ruby and Tk" }
15806
<p>I saw that one of the interview questions could be building a <a href="http://en.wikipedia.org/wiki/Pascal%27s_triangle">pascal triangle</a>. Is there anything wrong with this particular solution I came up with?</p> <pre><code>function pascal_r($r){ $local = array(); if($r == 1){ return array(array(1)); } else { $previous = pascal_r($r - 1); array_push($local, 1); for($i = 0; $i &lt; $r - 2 &amp;&amp; $r &gt; 2; $i++){ array_push($local, $previous[$r-2][$i] + $previous[$r-2][$i + 1]); } array_push($local, 1); } array_push($previous, $local); return $previous; } print_r(pascal_r(100)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T15:17:08.090", "Id": "26025", "Score": "0", "body": "Edited my post with new information you might find interesting." } ]
[ { "body": "<p>In regards to the comments: Yes, this is a good place for this so long as it works as is and you are asking about the code and not the algorithm. If you are asking about the algorithm this should have stayed on programmers.SE. If you are asking if this will work, then you should test it first, then if you can't find a solution you should post this to SO. Now, assuming this works and you're not asking about the algorithm, here are my thoughts:</p>\n\n<p>A number of these points may be nitpicking, but the interviewers are likely to nitpick as well since they have so little code to review to determine how good you are. First example of this are your variable and function names, which could stand to be a bit more descriptive. I can guess what \"r\" might be, but spelling it out wouldn't hurt, especially if that variable might get lost in layers of code. It makes your code \"self-documenting\", this means less actual documentation and easier future integration.</p>\n\n<p>Unless you have to add a number of elements on to an array at the same time, don't use <code>array_push()</code>. There is no need to call a function to do something that can be done without one. This is also explicitly explained on the PHP documentation for this function should you need further proof.</p>\n\n<pre><code>$local[] = 1;//good\n\narray_push( $local,\n 1,\n 2,\n //etc...\n);//also good\n\narray_push( $local, 1 );//bad\n</code></pre>\n\n<p>Watch your indentation. That for loop is needlessly indented. Needless whitespace and indentation add \"weight\" to your documents. Not much at any one time, but a weight that can build up steadily, especially if you are of the faction that uses spaces instead of tabs. This isn't ever likely to cause any real world difficulties, except maybe slightly larger file sizes, but again, I'm nitpicking.</p>\n\n<p>Something else you are going to get tagged on is all of these magic numbers. Where are these 1's and 2's coming from? If those numbers mean something, then you should create constants or variables to define it. Constants if immutable, variables if mutable. If, as in your first return statement you are merely returning the value of <code>$r</code>, as it appears, then you can just typecast it.</p>\n\n<pre><code>if( $r == 1 ) {\n return array( ( array ) $r );\n}\n</code></pre>\n\n<p>Instead of doing the same operation, <code>$r - 2</code>, over and over again, set the value to a variable and use that instead. Its overhead may be slight, and again a nitpick, but it still adds up if done enough. Besides, it makes for much more legible code.</p>\n\n<pre><code>$r2 = $r - 2;//horrible name, don't use this\nfor( $i = 0; $i &lt; $r2 &amp;&amp; $r &gt; 2; $i++ ) {\n</code></pre>\n\n<p>This next suggestion is similar to one I've already given. Watch your indentation. You have an if/else statement when you could really get away with just an if statement. Since it has an early return, you can drop the else statement, this removes one layer of indentation across six lines of code. In larger systems this could easily add up to quite a bit more and is easily one of the easiest, most visual, refactoring you can do.</p>\n\n<p>The last bit of advice would be to use <code>var_dump()</code> over <code>print_r()</code>. While this may be a matter of preference, I find the type output beneficial, especially in cases where you could somehow get an empty array or FALSE value.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Interesting coincidence here, but I'm taking a course on Coursera (Functional Programming in Scala), and one of the things we were required to do was find the value of a given coordinate on a pascal triangle. This assignment reminded me of this post so I thought I'd revisit it, but I wanted to wait until the deadline had been reached before posting this. Below is the code I used to <em>functionally</em> find the value.</p>\n\n<ul>\n<li><strong>Note:</strong> I'm using spoilers to give you a chance to work it out. Try and do these yourself before peeking.</li>\n</ul>\n\n<blockquote class=\"spoiler\">\n <p><pre> function pascal( $col, $row ) {\n if( $col == 0 || $col == $row ) {\n return 1;\n } else if( $col == 1 || $col == $row ) {\n return $row;\n } else {\n return pascal( $col, $row - 1 ) + pascal( $col - 1, $row - 1 );\n }\n }</pre></p>\n</blockquote>\n\n<ul>\n<li><strong>Note:</strong> I stressed functional, but there are other ways of doing this. I'm merely keeping with my assignment's guidelines.</li>\n<li><strong>Note:</strong> I know I'm violating some of my own advice. The instructions I was given in my assignment stressed not to use variables, so I'm not.</li>\n</ul>\n\n<p>So, given we can now find a value at any given coordinate, we should easily be able to use this to <em>print</em> a pascal triangle too. All we need is to determine how big we want our triangle to be and we can loop for it. I'm going to use 10, but you can change that amount to any value you want and it will still work. Again, no peeking!</p>\n\n<blockquote class=\"spoiler\">\n <p><pre> for( $i = 0; $i &lt; 10; $i++ ) {\n for( $j = 0; $j &lt;= $i; $j++ ) {\n echo pascal( $j, $i ) . ' ';\n }\n echo '&lt;br /&gt;';\n }</pre></p>\n</blockquote>\n\n<p>There you have it. Not only have you printed a pascal triangle, but you've also created a function that can be reused to serve a better purpose, namely finding a coordinate value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T19:50:45.220", "Id": "15817", "ParentId": "15812", "Score": "5" } }, { "body": "<blockquote>\n <p>Is there anything wrong with this particular solution I came up with?</p>\n</blockquote>\n\n<p>As mseancole points out, your answer does not highlight your ability to write readable code.</p>\n\n<p>I am going to add one thing and suggest an alternate solution.</p>\n\n<h2>Needs a Comment</h2>\n\n<p>A function like this should have a comment at the top of it. It should describe what your function does. In this case I would also add in your comment that this function is unlikely to work for large triangles!</p>\n\n<h2>Why won't it work?</h2>\n\n<p>Computations of this sort can run into <strong>fatal</strong> limits:</p>\n\n<ul>\n<li>Memory usage is too high (<a href=\"http://php.net/manual/en/ini.core.php#ini.sect.resource-limits\" rel=\"nofollow\">default configuration is 128MB</a>). This is consumed by approximately 1340 levels.</li>\n<li>Execution Time</li>\n</ul>\n\n<p>If you use xdebug you would also have:</p>\n\n<ul>\n<li>Nesting level too great (default configuration is 100)</li>\n</ul>\n\n<p>One way to avoid deep nesting is to use an iterative solution rather than a recursive one. To me, the iterative solution is easier to understand here because each pascal number is the addition of the previous level's elements that are to the left and right of the number.</p>\n\n<pre><code>/**\n * Get a pascal triangle of the specified depth.\n *\n * Large triangles require a lot of memory, be sure to set the memory limits\n * appropriately for the size of triangles you need to allocate.\n *\n * @param int The depth of the triangle to generate.\n * @return int[] The pascal triangle.\n */\nfunction get_pascal_triangle($depth)\n{\n $triangle = array();\n\n for ($level = 0; $level &lt; $depth; $level++)\n {\n $prevLevel = $level - 1;\n\n for ($pos = 0; $pos &lt; $level + 1; $pos++)\n {\n $triangle[$level][$pos] =\n isset($triangle[$prevLevel][$pos - 1],\n $triangle[$prevLevel][$pos]) ?\n $triangle[$prevLevel][$pos - 1] + $triangle[$prevLevel][$pos] :\n 1;\n }\n }\n\n return $triangle;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T17:48:54.300", "Id": "26090", "Score": "0", "body": "Indeed, there are many different ways this could be accomplished, and I actually prefer one similar to this. Although, I have to say I am a bit put off by that ternary statement. Don't get me wrong, I like ternary, but that one is a poor example of where to use it. That being said, there are some very good points in here, so a big +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T11:47:28.543", "Id": "16031", "ParentId": "15812", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T17:11:12.550", "Id": "15812", "Score": "7", "Tags": [ "php", "interview-questions", "recursion" ], "Title": "Pascal's triangle for an interview in PHP" }
15812
<p>This is sort of a follow up to my post <a href="https://codereview.stackexchange.com/questions/15778/how-can-i-make-this-code-better">yesterday</a>. I'm a relative newbie to Python and before I made a d20 dice roller for RPGs. Now I've made a dice roller for any type of dice, and I would love some feedback on this code.</p> <pre><code>from random import randint def roll(sides, number_of_dice): """Rolls Dice.""" return [randint(1, sides) for i in range(num_of_dice)] prompt = """ Would you like to roll the same combination of dice {}? Please type 'yes', 'no', or 'quit' """ # Main Program name = raw_input("\nPlease tell me your name &gt; ") print """ Hello {} and welcome to an RPG Dice Roller by Ray Weiss. Please type quit when prompted to exit or use CNTRL-C. Thanks to everyone at Stack Overflow etc. for the help. """.format(name) sides = input("\nHow many sides do you want on your dice? &gt; ") num_of_dice = input("\nHow many {} sided dice do you want to roll? &gt;".format(sides)) results = roll(sides, num_of_dice) print results roll_again = raw_input(prompt.format(name)) while True: if roll_again == "yes": results = roll(sides, num_of_dice) print results roll_again = raw_input(prompt.format(name)) if roll_again == "no": sides = input("How many sides do you want on your dice? &gt; ") num_of_dice = input("\nHow many {} sided dice do you want to roll? &gt;".format(sides)) results = roll(sides, num_of_dice) print results roll_again = raw_input(prompt.format(name)) if roll_again == "quit": print """ Thank you {} for using this RPG Dice Roller by Ray Weiss! Goodbye! """.format(name) break </code></pre>
[]
[ { "body": "<p>I think the big thing here is to <strong>beware of external data</strong>. Assume that it could be garbage.</p>\n\n<p>For instance:</p>\n\n<ul>\n<li>What happens if the user doesn't enter a name? -> Actually, not much apart from 2 spaces (rather than 1) in messages - relatively benign.</li>\n<li>What happens if the user enters \"rabbit\" sides? -> This value in any case needs to be transformed to an int for <code>roll</code> to work correctly otherwise a TypeError will be thrown. <code>int(\"rabbit\")</code> will throw a ValueError (see last item)</li>\n<li>Similarly, <code>num_of_dice</code> also have to be validated as a positive integer (non-zero).</li>\n<li>If the user enters something wrong for <code>roll_again</code> (say, \"of course!\"), you'll enter an infinite loop - The question probably needs to be brought inside the loop.</li>\n<li>You'll want to use <code>raw_input</code> rather than <code>input</code> in python2. <code>Input</code> evaluates an expression, which does what you want here (enter a number, get an int back (unless of course it's a float!)), but should be regarded as <em>avoid if at all possible</em>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T12:47:32.633", "Id": "25776", "Score": "0", "body": "Thanks! I'm not so sure how to do many of these things as a newbie but its more for me to learn! I appreciate it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T21:50:19.127", "Id": "15821", "ParentId": "15816", "Score": "6" } } ]
{ "AcceptedAnswerId": "15821", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T19:11:14.383", "Id": "15816", "Score": "6", "Tags": [ "python", "beginner", "random", "simulation", "dice" ], "Title": "RPG Dice Roller" }
15816
<p>I'm learning C, specifically OOP in C. As practice, I wrote a dynamically-expanding array.</p> <p><strong>dynarray.h</strong></p> <pre><code>#ifndef DYNARRAY_H #define DYNARRAY_H typedef struct DynArray { int length, capacity, *arr; void (*extend)(struct DynArray *dynArr); void (*insert)(struct DynArray *dynArr, int val); void (*print) (struct DynArray *dynArr); } DynArray; void DynArray_extend(DynArray* dynArr); void DynArray_insert(DynArray* dynArr, int value); void DynArray_print(DynArray* dynArr); #endif </code></pre> <p><strong>dynarray.c</strong></p> <pre><code>#include &lt;stdlib.h&gt; #include "dynarray.h" DynArray* createDynArray() { DynArray* newDynArray = malloc(sizeof(DynArray)); newDynArray-&gt;capacity = 10; newDynArray-&gt;arr = malloc(sizeof(int)*newDynArray-&gt;capacity); newDynArray-&gt;length = 0; newDynArray-&gt;extend = DynArray_extend; newDynArray-&gt;insert = DynArray_insert; newDynArray-&gt;print = DynArray_print; } void DynArray_extend(DynArray* dynArr) { int newCapacity = dynArr-&gt;capacity * 2, *newArr = malloc(sizeof(int)*newCapacity), i; dynArr-&gt;capacity = newCapacity; for (i = 0; i &lt; dynArr-&gt;length; i++) { newArr[i] = dynArr-&gt;arr[i]; } } void DynArray_insert(DynArray* dynArr, int val) { if (dynArr-&gt;length == dynArr-&gt;capacity) { dynArr-&gt;extend(dynArr); } dynArr-&gt;arr[dynArr-&gt;length] = val; dynArr-&gt;length = dynArr-&gt;length + 1; } void DynArray_print(DynArray* dynArr) { int i; for (i = 0; i &lt; dynArr-&gt;length; i++) { printf("%d\n", dynArr-&gt;arr[i]); } } </code></pre> <p>And this is an example application of the dynamic array (<code>program.c</code>):</p> <pre><code>#include &lt;stdio.h&gt; #include "dynarray.c" int main( void ) { int i = 0; DynArray* someDynArray = createDynArray(); printf("Length : %d\n", someDynArray-&gt;length); printf("Capacity: %d\n", someDynArray-&gt;capacity); for (i = 0; i &lt; 80; i++) { someDynArray-&gt;insert(someDynArray, i); } someDynArray-&gt;print(someDynArray); } </code></pre> <p>I would like to know if there are any flaws in the style of implementing the abstract data type of the dynamically expanding array.</p>
[]
[ { "body": "<p>My 2 cents:</p>\n\n<ol>\n<li>I believe <code>createDynArray</code> should return something.</li>\n<li>The returned value of <code>createDynArray</code> might have a special value of <code>NULL</code> in case that one of the <code>malloc</code>s calls failed (this scenario should be covered by the code).</li>\n<li>In the implementation of extend - consider using <code>realloc</code> instead of <code>malloc</code> and manual copy. If you insist on <code>malloc</code> perhaps using <code>memcpy</code> might be more elegant than a manual copy.</li>\n<li>I'd move magic numbers to <code>#define</code>s: Initial Capacity (hard-coded to 10) and Growth Factor (2). Alternatively, they could be parameters to the <code>createDynArray</code> function</li>\n<li>How would you free this struct? Perhaps you should add a \"destructor\" to be called before calling <code>free</code> with the struct pointer as a parameter.</li>\n<li>In terms of functionality, other than printing this \"array\", how would the consuming programmer could get (or set) a specific item in this \"array\"?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T01:45:46.797", "Id": "25758", "Score": "0", "body": "Woah, I just realized that I forgot to call return. Thanks for pointing that out in point 1. But I have no clue how it still manages to run without it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T00:31:02.947", "Id": "15822", "ParentId": "15819", "Score": "6" } }, { "body": "<p>Ron Klein covered it pretty well, but here's a few more things:</p>\n\n<hr>\n\n<p><strong>Consider the struct an implementation detail, not part of the API</strong></p>\n\n<p>The consumer of your vector shouldn't need to be concerned with what the struct looks like. Nothing in the struct should ever be directly accessed by the user. In fact, I woudln't even expose the struct to the user. I would just forward declare it in the header, and not fully declare it except for in the implementation file.</p>\n\n<p><code>.h</code>:</p>\n\n<pre><code>struct DynArray;\n\ntypedef struct DynArray DynArray;\n</code></pre>\n\n<p><code>.c</code>:</p>\n\n<pre><code>struct DynArray {\n ...\n};\n</code></pre>\n\n<p>A consumer of the API should never need to know what is in the struct.</p>\n\n<hr>\n\n<p><strong>Stop trying to emulate objects</strong></p>\n\n<p><code>someDynArray-&gt;insert(someDynArray, i);</code> is silly. Just use <code>DynArray_insert</code> (and others) directly:</p>\n\n<p><code>DynArray_insert(someDynArray, i);</code></p>\n\n<p>Note that storing function pointers in the struct is fine, but the user should never be calling them directly.</p>\n\n<hr>\n\n<p><strong>Your print function shouldn't exist</strong></p>\n\n<p>There's nothing wrong with a print function, but it shouldn't be part of the library. Imagine if you were to bundle this code up and distribute it. Do you think everyone who used it would want exactly the same format? There's no point in having a bundled print function.</p>\n\n<hr>\n\n<p><strong><code>DynArray_extend</code> is wrong</strong></p>\n\n<p>You never have <code>dynArr-&gt;arr = newArr;</code>.</p>\n\n<hr>\n\n<p><strong>Multi-Variable Declaration</strong></p>\n\n<pre><code>int newCapacity = dynArr-&gt;capacity * 2,\n *newArr = malloc(sizeof(int)*newCapacity),\n i;\n</code></pre>\n\n<p>There's nothing technically wrong with this, but it's fairly standard to only have one variable per declaration. Multi-variable declarations can get quite nasty and confusing when values/pointers/const/non-const all come into play in the same statement.</p>\n\n<hr>\n\n<p><strong>Consistent Naming</strong></p>\n\n<p>Why is <code>createDynArray</code> named how it is, yet everything else is named <code>DynArray_*</code>? I would go with <code>DynArray_create</code>.</p>\n\n<hr>\n\n<p><strong>There's no reason to dynamically allocate the DynArray</strong></p>\n\n<p>There will of course be situations where it's necessary, but there's no reason to force dynamic allocation.</p>\n\n<p>Consider instead a usage like this:</p>\n\n<pre><code>DynArray da;\nif (DynArray_Init(&amp;da)) {\n //Success (or you could alternatively return 0 on success and then use non-zero for error codes)\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Raw memory functions should only be paired with each other</strong></p>\n\n<p>This is completely opinion, but I believe that the low(ish) level memory functions should only be used together.</p>\n\n<p>What I mean by this is that you shouldn't have a function for creating your struct and no function for freeing it. You actually need a function to free it for correctness, but even if you did not, it would be a good idea.</p>\n\n<p>Abstracting away the freeing allows you to change the free-ing method at a later time seamlessly.</p>\n\n<hr>\n\n<p><strong>Consider Extending it to be Generic</strong></p>\n\n<p>You could easily extend this to be generic. It would make the API a bit more awkward to use, but it would be worth the reuse.</p>\n\n<p>If you don't know where to start on that, <a href=\"http://www.youtube.com/watch?v=73Z7gaAvovQ&amp;feature=BFa&amp;list=EC9D558D49CA734A02\" rel=\"nofollow\">this video</a> should help. About 37 or 38 minutes in is when it becomes relevant (though the professor is doing a stack, not a vector). (I actually quite love that entire lecture series... :D)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T02:52:02.217", "Id": "25760", "Score": "0", "body": "@skizeey No problem :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T05:48:40.093", "Id": "25763", "Score": "0", "body": "For the record, it's **Ron** Klein :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T07:55:45.327", "Id": "25764", "Score": "0", "body": "@RonKlein Whoops! Sorry, seems my vision is starting to go :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T01:18:20.963", "Id": "15823", "ParentId": "15819", "Score": "6" } }, { "body": "<p>In addition to what others have mentioned (good points raised by others), I'd like to talk about function pointers and vtables for a moment.</p>\n\n<p>The first suggestion would be to not use them in this case. I would avoid using function pointers in the struct unless you <em>really</em> want the behavior to change at runtime from one buffer to another (i.e. the allocation strategy of buffer subclass A is different from B -- seems unlikely that you'd want this). Otherwise using the function pointers will cost you in CPU time, memory overhead, and source code readability.</p>\n\n<p>If you did want to go the \"function pointer in the struct\" route, you can save memory by using more of a \"vtable\" approach. This pattern is used extensively by the Linux kernel, by COM, and by many C++ compilers when they implement virtual methods.</p>\n\n<p>Instead of:</p>\n\n<pre><code>typedef struct DynArray\n{\n // ...\n\n void (*extend)(struct DynArray *dynArr);\n void (*insert)(struct DynArray *dynArr, int val);\n void (*print) (struct DynArray *dynArr);\n} DynArray;\n</code></pre>\n\n<p>You can do:</p>\n\n<pre><code>typedef struct\n{\n void (*extend)(struct DynArray *dynArr);\n void (*insert)(struct DynArray *dynArr, int val);\n void (*print) (struct DynArray *dynArr);\n} DynArrayOps;\n\ntypedef struct DynArray\n{\n // ...\n\n DynArrayOps *ops;\n} DynArray;\n</code></pre>\n\n<p>This means that there can be only <em>one</em> instance of <code>DynArrayOps</code> (maybe make it a static object in your <code>.c</code> file), and the memory overhead per <code>DynArray</code> is 1 pointer. (3 times less than your code).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T19:46:10.570", "Id": "15855", "ParentId": "15819", "Score": "2" } } ]
{ "AcceptedAnswerId": "15822", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T20:17:50.170", "Id": "15819", "Score": "6", "Tags": [ "c", "object-oriented", "array" ], "Title": "Dynamically-expanding array in C" }
15819
<p>I recently started to learn more about OOP in PHP and I created a website for testing. I have 4 classes: <code>database</code>, <code>user</code>, <code>posts</code>, <code>comments</code>. This is a simple <code>database.class.php</code>:</p> <pre><code>class DB { protected $pdo; protected $engine = 'mysql'; protected $host = 'localhost'; protected $db_name = 'test'; protected $db_user = 'root'; protected $db_passwd = ''; public function connect() { try { $this-&gt;pdo = new PDO($this-&gt;engine.':host='.$this-&gt;host.';dbname='.$this-&gt;db_name,$this-&gt;db_user,$this-&gt;db_passwd); $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this-&gt;pdo; } catch(PDOException $e) { die($e-&gt;getMessage()); } } } </code></pre> <p>Then, every other class starts like this:</p> <pre><code>class user { public $link; public function __construct() { $pdoObj = new DB(); $this-&gt;link = $pdoObj-&gt;connect(); return $this-&gt;link; } } </code></pre> <p>I use <code>$link</code> as a reference to the pdo object so I can use all the methods associated with PDO. My question is: is this wrong? </p> <p>I saw a lot of source codes and most of them used 'static' and didn't instantiated the class with <code>new Class();</code> but just <code>ClassName::foo();</code> Is it wrong to instantiate every class and work with instances? I always do:</p> <pre><code>$obj = new user(); $obj-&gt;SelectAll(); // and so on.. </code></pre> <p>If my way is wrong, how can I move my code to <code>static</code>?</p> <p>Here is an example of a method:</p> <pre><code>public function register($username, $email, $passwd, $re_passwd) { # fix email and passwd regex $reg_error = array(); $regex_username = '/[a-zA-Z0-9-._]{6,20}$/'; $regex_email = '/[a-zA-Z0-9._-]{3,}@[a-zA-Z0-9]{3,}.[a-zA-Z.]{2,}$/'; if (empty($username) || empty($email) || empty($passwd) || empty($re_passwd)) { $reg_error['fields'] = 'All fields are required'; } else { if (!preg_match($regex_username, $username)) { $reg_error['username'] = 'Username must be at least 6 characters'; } if (!preg_match($regex_email, $email)) { $reg_error['email'] = 'Invalid email'; } if(strlen($passwd) &lt;= 6) { $reg_error['passwd'] = 'Password must be at least 6 characters long and must contain at least 1 uppercase, 1 lowercase and 1 digit value'; } if ($re_passwd !== $passwd) { $reg_error['match'] = 'Passwords do not match'; } if($this-&gt;usernameExists($username)) { $reg_error['username_exists'] = 'Username: ' .$username. ' already exists'; } if($this-&gt;emailExists($email)) { $reg_error['email_exists'] = 'Email: ' .$email. ' already exists in our database'; } } if (!empty($reg_error)) { foreach($reg_error as $error =&gt; $er) { echo 'Error: '.$er.'&lt;br /&gt;'; } } else { try { $query = $this-&gt;link-&gt;prepare("INSERT INTO users(username, email, password, ip_address, activation_code) VALUES(:username, :email, :passwd, :ip_addr, :code)"); $passwd = hash('sha512', $passwd); $ip_addr = $_SERVER['REMOTE_ADDR']; $code = substr( hash('sha512', md5(rand(999, 9999))) , 15, 40); $params = array(':username' =&gt; $username, ':email' =&gt; $email, ':passwd' =&gt; $passwd, ':ip_addr' =&gt; $ip_addr, ':code' =&gt; $code); $query-&gt;execute($params); if ($query-&gt;rowCount() != 0) { redirect('index.php?lastid='.$this-&gt;lastId()); } else { return 'There\'s been a tehnical problem during the registration process, please try again later.'; } } catch (PDOException $e) { die($e-&gt;getMessage()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T06:14:48.453", "Id": "25787", "Score": "1", "body": "I'm too lazy to write a full response, especially since Yannis covered it very well, but your DB class shouldn't exist. It's basically a glorified PDO factory, but I really doubt you want to be opening a new DB connection every time you need a DB connection. (Instead, you should do as he said and pass the PDO instance to the constructor of any class that needs it.)" } ]
[ { "body": "<h2>What happens if you change your database credentials?</h2>\n\n<p>Right now your class is tied to a specific set of database credentials, and you'll need to change it if:</p>\n\n<ul>\n<li>you want to use a different engine,</li>\n<li>or a different host,</li>\n<li>or a different user,</li>\n<li>or a different password,</li>\n<li>or any combination of the above.</li>\n</ul>\n\n<p>This is why PDO requires you to pass the dsn and the credentials through its constructor, and you should do the same. Then of course your class wouldn't be much different than PDO itself, if you don't have any additional functionality, just forget about it and use PDO. </p>\n\n<p>If you want to keep your class, just store your credentials in a configuration file. A simplistic solution would be an INI file, let's call it <code>database.ini</code>:</p>\n\n<pre><code>engine = \"mysql\"\nhost = \"localhost\"\nname = \"test\"\nuser = \"root\"\npassword = \"\"\n</code></pre>\n\n<p>Your database class could then be: </p>\n\n<pre><code>class DB {\n private $pdo;\n private $engine;\n private $host;\n private $db_name;\n private $db_user;\n private $db_passwd;\n\n public function _construct($path) {\n if(!is_file($path)) {\n throw new InvalidArgumentException(\"Hey, that's not a file!\");\n }\n\n $credentials = @parse_ini_file($path);\n\n if(empty($credentials)) { \n throw new InvalidArgumentException(\"Hey, that's a file, but it's not a valid INI file!\");\n }\n\n $this-&gt;engine = $credentials[\"engine\"];\n $this-&gt;host = $credentials[\"host\"];\n $this-&gt;db_name = $credentials[\"name\"];\n $this-&gt;db_user = $credentials[\"user\"];\n $this-&gt;db_passwd = $credentials[\"password\"];\n\n try {\n $this-&gt;pdo = new PDO($this-&gt;engine.':host='.$this-&gt;host.';dbname='.$this-&gt;db_name,$this-&gt;db_user,$this-&gt;db_passwd);\n $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n return $this-&gt;pdo;\n } catch(PDOException $e) {\n throw new Exception(\"Boo, wrong credentials!\");\n } \n }\n\n}\n</code></pre>\n\n<p>Looks like a lot of work? Well, it is, and it's <em>not</em> finished, but changing any of your credentials is now as simple as changing its value in <code>database.ini</code>. All you need to do to instantiate your class is: </p>\n\n<pre><code>$db = new DB(\"database.ini\");\n</code></pre>\n\n<p>Let's go quickly through the main parts of the class:</p>\n\n<ol>\n<li><p><strong>Don't protect what should be private</strong></p>\n\n<p>Don't declare your class properties and methods as protected if you don't need to. <a href=\"http://php.net/manual/en/language.oop5.visibility.php\" rel=\"nofollow noreferrer\">Protected means</a>: </p>\n\n<blockquote>\n <p>Members declared protected can be accessed only within the class itself and by inherited and parent classes</p>\n</blockquote>\n\n<p>If you are not going to <a href=\"http://php.net/manual/en/language.oop5.inheritance.php\" rel=\"nofollow noreferrer\">extend the class</a>, there's absolutely no reason to go with protected instead of private:</p>\n\n<blockquote>\n <p>Members declared as private may only be accessed by the class that defines the member.</p>\n</blockquote>\n\n<p>This might seem extremely pedantic, the world won't stop spinning because your properties are protected, but since you're a fresher, better avoid this common bad habit. </p></li>\n<li><p><strong>Connect? Why, let's construct instead!</strong></p>\n\n<p>The database class is useless if we don't run <code>connect()</code>, calling the method is a prerequisite for the class to do <em>anything</em> else. When that happens, it's a good sign that our method should either be called in the class constructor, or be the constructor itself. If it's absolutely necessary for the method to be called, then it makes sense to be the one function that gets called by default when we create an instance of our class, doesn't it? </p></li>\n<li><p><strong>Check your arguments</strong></p>\n\n<p>I'm doing two checks on our <code>$path</code> argument, first if it's a valid file and then if <a href=\"http://php.net/manual/en/function.parse-ini-file.php\" rel=\"nofollow noreferrer\"><code>parse_ini_file</code></a> returned an array (that would signify that the INI file was succesfully parsed). Throw <a href=\"http://php.net/manual/en/spl.exceptions.php\" rel=\"nofollow noreferrer\">appropriate exceptions</a> if there are problems. </p></li>\n<li><p><strong>The <em>unfinished</em> part</strong> </p>\n\n<pre><code>$this-&gt;engine = $credentials[\"engine\"];\n$this-&gt;host = $credentials[\"host\"];\n$this-&gt;db_name = $credentials[\"name\"];\n$this-&gt;db_user = $credentials[\"user\"];\n$this-&gt;db_passwd = $credentials[\"password\"];\n</code></pre>\n\n<p>What I'm <em>not</em> doing here is check whether the indices exists in the <code>$credentials</code> array. That's your homework ;)</p></li>\n<li><p><strong>The exception</strong></p>\n\n<p>Your original code was:</p>\n\n<pre><code>} catch(PDOException $e) {\n die($e-&gt;getMessage());\n}\n</code></pre>\n\n<p>That doesn't make sense, you catch the exception and then die with the same message? Not catching the exception will have exactly the same effect, the script will stop, so why catch it? You should catch exceptions <em>only</em> when you can do something productive with them, if not, just let the script fail. Usually \"something productive\" means gracefully recover from the error, but that's not always possible. In my code I'm doing something that might seem minor but it's very important: </p>\n\n<pre><code>} catch(PDOException $e) {\n throw new Exception(\"Boo, wrong credentials!\");\n} \n</code></pre>\n\n<p>Yes, the only thing I'm doing is changing the message of the exception, the script will still fail. However PDO's constructor exception reveals your database credentials (except your password), so catching that and rethrowing it with a more generic message minimizes the risk of your database username (for example) falling in the wrong hands. Can't gracefully recover from the failure, but at least we plugged a potential security hole.</p></li>\n</ol>\n\n<h2>How about some setters and getters?</h2>\n\n<p>If you are still reading this, I'm sorry to inform you that your code doesn't work. This: </p>\n\n<pre><code>public function __construct() {\n $pdoObj = new DB();\n $this-&gt;link = $pdoObj-&gt;connect();\n return $this-&gt;link;\n}\n</code></pre>\n\n<p>does set your database object in the <code>$link</code> property but it's your database object, <em>not</em> your PDO object. Your database object does <em>not</em> have a <code>prepare()</code> method, so this: </p>\n\n<pre><code>$query = $this-&gt;link-&gt;prepare(\"INSERT INTO users(username, email, password, ip_address, activation_code)\n VALUES(:username, :email, :passwd, :ip_addr, :code)\");\n</code></pre>\n\n<p>will simply fail. What you need to do is pass your PDO object to your <code>User</code> class: </p>\n\n<pre><code>class DB {\n\n ...\n\n public function getPDO() {\n return $this-&gt;pdo;\n } \n}\n</code></pre>\n\n<p>So this simple function will always return the database's internal PDO object. Your <code>User</code> constructor would now be:</p>\n\n<pre><code>public function __construct() {\n $database = new DB(\"database.ini\");\n\n $this-&gt;link = $database-&gt;getPDO();\n}\n</code></pre>\n\n<p>Notice how I removed <code>return $this-&gt;link;</code>? Well, don't do that, a constructor returns the object it instantiates by default, there's absolutely no sense in returning anything else, it wouldn't be a constructor if it didn't give us what it constructed, would it?</p>\n\n<h2>Wait! There's a dependency!</h2>\n\n<p>This line:</p>\n\n<pre><code>$database = new DB(\"database.ini\");\n</code></pre>\n\n<p>means that we don't have the option of renaming our INI file. Ever! That's not good, that's an unwanted dependency and we really don't like those. After all we went through a lot to get our database class to not be dependent on its credentials, we can't introduce another dependency now. What we are going to do is use a method called Constructor Dependency Injection, that's the simplest way to achieve <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a>. It's extremely simple, all we need to do is: </p>\n\n<pre><code>public function __construct(DB $database) { \n $this-&gt;link = $database-&gt;getPDO();\n}\n</code></pre>\n\n<p>That's right, pass the database as a parameter in the constructor, that's all there is to it. Now, to instantiate our user class all we need to do is: </p>\n\n<pre><code>$database = new DB(\"database.ini\"); \n$user = new User($database);\n</code></pre>\n\n<p>...and our classes are dependency free! To get an idea why this is good, assume you have two databases, and you need to use them both. All you need to do is: </p>\n\n<pre><code>$database1 = new DB(\"database1.ini\"); \n$user1 = new User($database1);\n\n$database2 = new DB(\"database2.ini\"); \n$user2 = new User($database2);\n</code></pre>\n\n<h2>Does your database only have users?</h2>\n\n<p>If your database has any other table, and you want to model them as classes, it might be worth looking at <a href=\"http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)\" rel=\"nofollow noreferrer\">inheritance</a>. All your table classes have a common dependency, the database, and you don't really have to write the same constructor every time: </p>\n\n<pre><code>class Table {\n protected $database;\n\n public function __construct(DB $database) { \n $this-&gt;database = $database-&gt;getPDO();\n }\n}\n\nclass User extends Table {\n\n // only user specific functions here\n\n}\n\nclass Article extends Table {\n\n // only article specific functions here\n\n}\n\nclass Comment extends Table {\n\n // only comment specific functions here\n\n}\n</code></pre>\n\n<p>The <code>User</code>, <code>Article</code>, and <code>Comment</code> classes have inherited the same constructor from <code>Table</code>, no need to write the method more than once. As you probably already noticed, I've declared <code>$database</code> protected, it makes sense now as we need it to be available to the child classes. By the way that's your old <code>$link</code> property, since it holds a database object, makes sense to call it <code>$database</code>.</p>\n\n<h2>The register function</h2>\n\n<p>Sorry for being blunt, but this is a horrible mess: </p>\n\n<ol>\n<li><p><strong>Indendation is messed up.</strong> </p>\n\n<p>Learn to format your code properly. Better yet, equip yourself with a decent tool to do it for you.</p></li>\n<li><p><strong>Your function should either return something or echo something, not both.</strong></p>\n\n<p>Preferably return something. Echoing HTML from your functions is a very poor practice, read up on <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a>. Simply put your function is where you put logic, and you shouldn't mix presentation with logic.</p></li>\n<li><p><strong>You catch an exception and die with the same message <em>again</em>.</strong></p>\n\n<p>Don't do that. </p></li>\n</ol>\n\n<p>Since we've now have a handy getter in our database class, the way to get the reference to the PDO object in your function is: </p>\n\n<pre><code>class User {\n\n public function register($username, $email, $passwd, $re_passwd) {\n $link = $this-&gt;database-&gt;getPDO();\n\n ...\n\n $query = $link-&gt;prepare( ... );\n\n ...\n }\n\n} \n</code></pre>\n\n<h2>And what about static?</h2>\n\n<p>Well, don't worry about it. Most of the time is used as a convenience, and it's not really the better way to do things. Instantiate your objects properly, and then pass them around via one of the dependency injection techniques, you're passing around the same instance, you are not instantiating it again and again.</p>\n\n<h2>Further reading</h2>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/language.oop5.php\" rel=\"nofollow noreferrer\">Classes and Objects</a> in the manual. Yes, you need to read <em>everything</em>.</li>\n<li><a href=\"http://php.net/manual/en/book.filter.php\" rel=\"nofollow noreferrer\">Data Filtering</a> in the manual. Again, you need to read <em>everything</em>.</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Mutator_method\" rel=\"nofollow noreferrer\">Mutator methods</a>.</li>\n<li><a href=\"http://en.wikipedia.org/wiki/SOLID_&#40;object-oriented_design&#41;\" rel=\"nofollow noreferrer\">SOLID</a> - Don't cheat, read all the linked articles.</li>\n<li><a href=\"http://martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">Inversion of Control Containers and the Dependency Injection pattern</a></li>\n<li><a href=\"http://www.codinghorror.com/blog/2004/10/kiss-and-yagni.html\" rel=\"nofollow noreferrer\">KISS and YAGNI</a></li>\n</ul>\n\n<h2>Addendum</h2>\n\n<p><a href=\"https://codereview.stackexchange.com/users/7308/corbin\">Corbin</a> <a href=\"https://codereview.stackexchange.com/questions/15825/help-improve-my-first-php-class/15827#comment25788_15827\">raises two important issues</a> in a comment: </p>\n\n<blockquote>\n <p>(1) The exception shouldn't be masked. What if consuming code wants the details? A different part of code should be responsible for hiding potentially sensitive exceptions. (2) If Table (and other classes) need a PDO instance, they should accept a PDO instance, not a DB instance. There's no reason to accept the object just to call a single getter. (I also believe that this Database class shouldn't even exist though. It's pointless.)</p>\n</blockquote>\n\n<p>My thoughts: </p>\n\n<ol>\n<li><p>Your database class is pointless if it doesn't have any additional functionality you didn't tell us about. </p>\n\n<p>As it is, it's just a wrapper for PDO that doesn't do <em>anything</em> more than PDO itself does, and in my answer I've assumed (hoped?) that you do have a reason for it and would further develop it to enhance PDO (perhaps adding a query cache, or a log?). But if you don't have any further plans for it, then it would be preferable to just scrap it and just use PDO and just feed your PDO object in <code>Table::__construct()</code>.</p></li>\n<li><p>You shouldn't be catching exceptions if you can't do anything productive, preferably gracefully recovering from the error. </p>\n\n<p>Now, I do suggest that you should catch the <code>PDOException</code> just in case your database credentials are leaked, but that's more of a scare tactic than a solid suggestion. I've seen one too many new developers do similar mistakes, and perhaps my suggestion there was a bit drastic. </p>\n\n<p>What you need to keep in mind is that this particular <code>PDOException</code> <strong>should not reach the end user</strong>. If there's other code in between your database instantiation and the end user (a top level script, perhaps), it would make much more sense to deal with the exception there, and if you can't recover from it do something like throwing a 404 or 503 error (whichever applies). </p>\n\n<p>Take my suggestion to hide the details of the connection <code>PDOException</code> with a grain of salt, I'm just tired of dealing with the same crap again and again. There was a time when such an exception created a world of trouble for me, but in a typical production environment it shouldn't be easy for anyone to do anything particularly harmful just because they caught a glimpse of your database username.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T08:54:00.620", "Id": "25765", "Score": "0", "body": "Sir, thank you very much for your time and help. One more thing I would like to know is my original question: is the instantiating method bad practice, should I move to static? Like so: User::Login($variables) instead of: $user = new User(); $user->Login($variables);?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T08:55:43.077", "Id": "25766", "Score": "0", "body": "@Ovidiu No, don't move to static, I've already talked about this in my answer. Only use static when you fully understand what it's about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T06:17:28.637", "Id": "25788", "Score": "1", "body": "@YannisRizos +1, but two things bothered me. (1) The exception shouldn't be masked. What if consuming code *wants* the details? A different part of code should be responsible for hiding potentially sensitive exceptions. (2) If `Table` (and other classes) need a PDO instance, they should accept a PDO instance, not a DB instance. There's no reason to accept the object just to call a single getter. (I also believe that this Database class shouldn't even exist though. It's pointless.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T06:45:33.003", "Id": "25789", "Score": "0", "body": "@Corbin No disagreement for (2), I do mention somewhere in there that the database class is useless, but from that point on I'm assuming it has some additional functionality we don't know about, that justifies its existence and why `Table` needs it. As for (1), I've been burned before by database credentials reaching the user, and I'm a bit dogmatic about it. Obviously you are right, but 8/10 developers I've worked with let sensitive data reach end users through errors/exceptions, and now I prefer to scare people into catching them as soon as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T19:23:05.197", "Id": "25796", "Score": "0", "body": "@YannisRizos (2) Ah sorry, guess I missed that. (1) That's the same logic that created the abomination known as magic quotes... I agree that it could be annoying to have DB credentials reach the end user (though a DB should never be world-connectable), but it seems like an abuse of exceptions. (Also, a production server should never be configured to display errors to the end user.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T06:40:24.870", "Id": "25806", "Score": "0", "body": "@Corbin You're right, updated the answer to point out that my suggestion is more a product of fatigue than logic ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T17:14:40.227", "Id": "25823", "Score": "1", "body": "+1 Very well thought out, and explained. Nice to see new people in the neighborhood :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T07:44:00.497", "Id": "15827", "ParentId": "15825", "Score": "10" } } ]
{ "AcceptedAnswerId": "15827", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T05:39:56.027", "Id": "15825", "Score": "2", "Tags": [ "php", "object-oriented", "classes" ], "Title": "Help improve my first PHP class" }
15825
<p>I could use some review on this Auth class, as I'm sure it could use many improvements!</p> <p>I wrote this fairly quickly, so please forgive any overseen bugs.</p> <p><strong>Example usage:</strong></p> <pre><code>// Login a user if (Auth::attempt($_POST['username'], $_POST['password'])) { echo 'You have successfully logged in.'; } // Check if the user is a guest if (Auth::guest()) { echo 'Please log in to see this page.'; } // Logout a user Auth::logout(); </code></pre> <p><strong>Source code:</strong></p> <pre><code>&lt;?php class Auth { /** * Whether or not the user is currently logged in * * @var bool */ public static $user; /** * Attempts to log a user in with the given credentials * * @param string $username * @param string $password * @return bool */ public static function attempt($username, $password) { global $db; $stmt = $db-&gt;prepare('SELECT * FROM `users` WHERE `username` = :username AND `password` = :password'); $stmt-&gt;execute(array(':username' =&gt; $username, ':password' =&gt; $password)); if ($user = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { static::$user = $user; static::login($user['id']); return true; } return false; } /** * Login the user with the given id * * @param int $user_id * @return void */ public static function login($user_id) { if ($user_id) { $_SESSION['user_id'] = $user_id; } } /** * Log out the current user * * @return void */ public static function logout() { static::$user = null; $_SESSION = array(); unset($_SESSION['user_id']); session_destroy(); } /** * Checks if a user is currently logged in * * @return bool */ public static function check() { return isset($_SESSION['user_id']); } /** * Checks if the current user is a guest * * @return bool */ public static function guest() { return ! isset($_SESSION['user_id']); } } </code></pre> <p>I'm also not sure if using all static methods in the class could lead to problems later on?</p> <p><em>I know there is currently no password hashing - I'm still working on the hashing method.</em></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T09:51:41.817", "Id": "25767", "Score": "1", "body": "What's up with static? It's really unnecessary, this reads like you are writing procedural code with classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T09:59:10.727", "Id": "25769", "Score": "1", "body": "Using a static method is faster than instantiating an object and then calling the method, but it's _not_ noticeably faster. You are hurting the testability and readability of your code for a fraction of a millisecond." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T16:59:54.310", "Id": "25777", "Score": "0", "body": "When it's ready, I would be interested in seeing the final version including proper password hashing (not encryption). Authentication can be tricky, so getting it reviewed is always a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T08:33:49.930", "Id": "25810", "Score": "0", "body": "@Bethesda for password hashing, look no further than ITSec.SE. This [search](http://security.stackexchange.com/search?q=password+hashing) might prove useful..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T11:38:01.423", "Id": "25812", "Score": "0", "body": "PHPASS is a good choice (with an unfortunate name ;). You might also find [this SO question](http://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords) interesting... The top voted answer was written in 2008, but from quickly reading it it doesn't seem outdated (but you should read it more thoroughly than I did)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T04:10:27.150", "Id": "59185", "Score": "0", "body": "possible duplicate of [PHP Config Class](http://codereview.stackexchange.com/questions/15348/php-config-class)" } ]
[ { "body": "<h2>What's up with static?</h2>\n<p>Your class is build like a <a href=\"http://c2.com/cgi/wiki?UtilityClasses\" rel=\"noreferrer\">utility class</a>:</p>\n<blockquote>\n<p>UtilityClasses are classes that have only static methods that perform some operation on the objects passed as parameters. Such classes typically have no state.</p>\n</blockquote>\n<p>but it's not really one as it has state, you have a <code>$user</code> property you need to pass around, and your functions depend on it. You are writing procedural code using classes, and there really isn't any reason for that, if procedural programming feels more natural with you, go with it, object orientation is <em>not</em> the one true paradigm. PHP supports both paradigms equally, and they are both equally valid.</p>\n<p>The <em>only</em> benefit of using static like this is namespacing your functions, but that's not a real benefit as PHP supports <a href=\"http://php.net/manual/en/language.namespaces.php\" rel=\"noreferrer\">namespaces</a>. You should either write your class as an object oriented class, or a set of namespaced utility functions, everything in between is just bad form.</p>\n<p>Since you mentioned execution speed, yes calling a static function is faster than instantiating an object and then calling the function, but the difference is in the range of a fraction of a millisecond. A more convincing argument for using static would be memory use, not execution speed, as the instantiated object will take up some memory. Still the argument is moot as there's absolutely no reason to write procedural code with classes, other than perhaps a misguided notion that everything needs to be object oriented.</p>\n<h2>Public properties</h2>\n<pre><code>public static $user;\n</code></pre>\n<p>Assuming you rewrite this to be an object oriented class you should avoid public properties, or you'd be breaking <a href=\"http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)\" rel=\"noreferrer\">encapsulation</a>. All your class properties should be private and accessible through getters and setters, you should even avoid protected if you are not going to extend the class.</p>\n<h2>Global</h2>\n<pre><code>global $db;\n</code></pre>\n<p>Don't. Please forget the <code>global</code> keyword even exists, and pass your dependencies through method parameters:</p>\n<pre><code>public static function attempt(PDO $db, $username, $password) {\n ...\n}\n</code></pre>\n<p>Note the added benefit of <a href=\"http://php.net/manual/en/language.oop5.typehinting.php\" rel=\"noreferrer\">type hinting</a>. If you need that PDO object anywhere else in your class, then you should really transform this into an object oriented class and feed the dependency through its constructor:</p>\n<pre><code>class Auth {\n\n private $pdo; \n \n public function __construct(PDO $pdo) {\n $this-&gt;setPDO($pdo);\n }\n \n public function setPDO(PDO $pdo) {\n $this-&gt;pdo = $pdo;\n \n return $this;\n }\n \n public function getPDO() {\n return $this-&gt;pdo;\n }\n\n ... \n\n}\n</code></pre>\n<p><code>Auth::setPDO()</code> and <code>Auth::getPDO()</code> are <a href=\"http://en.wikipedia.org/wiki/Mutator_method\" rel=\"noreferrer\">mutator methods</a>, keeping the class in line with encapsulation and any half decent IDE can generate them automatically for you. Notice that I <code>return $this;</code> in the setter? That's because I like <a href=\"https://stackoverflow.com/questions/3724112/php-method-chaining\">chaining my methods</a>, up to you if you want to follow my style.</p>\n<h2>Session</h2>\n<p><code>$_SESSION</code> is also a global, and suffers from everything <code>global</code> variables do, but given that it's a native (almost) always on global, we can live with it. Obviously your class would be useless if at some point you decide to store session information in a different storage, but let's worry about than when and if it happens. However you need to keep in mind that <code>$_SESSION</code> is an external dependency, and your class needs to compensate for the rare occasion that you forgot to call <code>session_start()</code>. For example this:</p>\n<pre><code>public static function login($user_id)\n{\n if ($user_id)\n {\n $_SESSION['user_id'] = $user_id;\n }\n}\n</code></pre>\n<p>will fail. Either call <code>session_start()</code> before your class definition <em>or</em> in the constructor. In either case, do check if <code>$_SESSION</code> already exists before calling it.</p>\n<h2>Further reading</h2>\n<ul>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil\">Why is Global State so Evil?</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"noreferrer\">SOLID</a> - Don't cheat, read all the linked articles.</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"noreferrer\">Dependency inversion principle</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Dependency_Injection\" rel=\"noreferrer\">Dependency injection</a></li>\n<li><a href=\"http://martinfowler.com/articles/injection.html\" rel=\"noreferrer\">Inversion of Control Containers and the Dependency Injection pattern</a></li>\n<li><a href=\"https://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp\">When to Use Static Classes in C#</a> - Not really C# specific, at least not the top voted answer.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T11:08:59.817", "Id": "25773", "Score": "0", "body": "@Bethesda I imagined you did call `session_start()` somewhere, but your class can't live without it, so it would make sense to write something like `if(!isset($_SESSION)) { session_start() }` at the top of the file or in the constructor. This way, when you'll need to re-use your class in another project, you won't have to worry about re-writing / copying the init file, your class will just work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T11:13:28.907", "Id": "25775", "Score": "0", "body": "@Bethesda Either move away from static and go full OO, or go procedural, both are equally valid, mixing the two not so much. You could leave all your functions that don't deal with state (`$_SESSION` and `$user`) static, but you wouldn't be gaining anything. Your class works as it is, you can even leave it as it is, most of my answer is concerned with its future re-usability and testability. If you take those out of the equation, it serves its purpose just fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T17:21:35.177", "Id": "25824", "Score": "0", "body": "I don't think you stressed the \"don't use globals\" point enough. They are bad everywhere and should be abolished from the language, but besides that, another +1 for you sir :) One more thing that might be of interest here: Helper functions are still quite beneficial, even in OOP, though many OOP enthusiasts think functions are the plague, this is not true. A helper function file would be of more use, IMO, than any \"utility class\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T10:51:06.370", "Id": "15829", "ParentId": "15828", "Score": "13" } } ]
{ "AcceptedAnswerId": "15829", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T09:48:11.977", "Id": "15828", "Score": "11", "Tags": [ "php", "object-oriented" ], "Title": "PHP Authentication Class" }
15828
<p>I really don't like the so many <code>return</code> statements. Anyone think that this could be refactored more?</p> <pre class="lang-php prettyprint-override"><code>public function validate($value, Constraint $constraint) { if('' === $value || null === $value) { return; } if(!preg_match('/^[0-9]{7}([0-9]{3})[0-9]{1}$/', $value, $matches)) { $this-&gt;context-&gt;addViolation($constraint-&gt;message, array( '{{ value }}' =&gt; $value )); return; } // Fast Luhn check $vatin = (string) $matches[0]; $luhn = array(0, 2, 4, 6, 8, 1, 3, 5, 7, 9); $sum = 0; for($i = 0; $i &lt; strlen($vatin); $i++) { $dgt = (int) substr($vatin, $i, 1); $sum += (0 === $i % 2) ? $dgt : $luhn[$dgt]; } if(0 !== ($sum % 10)) { $this-&gt;context-&gt;addViolation($constraint-&gt;message, array( '{{ value }}' =&gt; $value )); return; } // Province check $provinceCode = $matches[1]; if(!in_array((int) $provinceCode, range(1, 121) + array(888, 999))) { $this-&gt;context-&gt;addViolation($constraint-&gt;provinceMessage, array( '{{ value }}' =&gt; $provinceCode )); } } </code></pre>
[]
[ { "body": "<p>Ah, the yoda syntax, don't see that too often. Anyways, on to the subject at hand. Here are a few ways you can refactor it, I'll address your specific question towards the end.</p>\n\n<p>You can use the <code>empty()</code> function in your first comparison, it will return TRUE if the value is any FALSE value ('', 0, NULL, FALSE, \"false\", etc...), so it does the same thing but is a little cleaner.</p>\n\n<pre><code>if( empty( $value ) ) {\n return;\n}\n</code></pre>\n\n<p>Another possible refactor, is to not use typecasting unless necessary. For instance, below you have a string typecast that is converting the element of an array to a string. This is unnecessary, at least if I'm reading the doc page on <code>preg_match()</code> properly. The 0th element will already contain a string, so this is redundant. Below that is another typecast that converts a string to an integer. This also seems unnecessary. PHP is a very loosely typed language, meaning transitioning from a integer to a string, or vice-versa, doesn't require any special type-casting or syntax. BTW: below each example is also another way to refactor the statement that may be a little better.</p>\n\n<pre><code>$vatin = (string) $matches[0];\n$vatin = $matches[ 0 ];//the same\n$vatin = array_shift( $matches );//avoids magic numbers, even though most will know where the 0 comes from\n\n$dgt = (int) substr($vatin, $i, 1);\n$dgt = substr( $vatin, $i, 1 );//the same\n$dgt = $vatin[ $i ];//string array syntax avoids the unnecessary function call\n</code></pre>\n\n<p>Avoid calling functions in for or while loop parameter lists. Both of these loops call any parameter functions on every iteration, meaning more overhead. Set the value before the loop. I'd also suggest doing the same in foreach loops, but its not as important.</p>\n\n<pre><code>$length = strlen($vatin);\nfor( $i = 0; $i &lt; $length; $i++ ) {\n</code></pre>\n\n<p>Another problem you have here is that you are violating \"Don't Repeat Yourself\" (DRY) by using the same, or almost the same values in the <code>addViolation()</code> method so many times. A better way would be to set up a default, then log it once. There are probably a few different ways to go about this, but here's an example of one.</p>\n\n<pre><code>//in class\n$violation = array(\n $constrain-&gt;message,\n $value\n);\n\nif( ! preg_match() ) {\n return $violation;\n}\n//repeat or return different violation as necessary\n\n//implementation\n$violation = $instance-&gt;validate( $value, $constraint );\nif( is_array( $violation ) ) {\n list( $message, $value ) = $violation;\n\n $instance-&gt;context-&gt;addViolation( $message, array(\n '{{ value }}' =&gt; $value\n ) );\n}\n</code></pre>\n\n<p>Now, the question you are asking about is more or less a style choice. The one-return vs many. At least if I am understanding your question correctly. I used to be of the first camp, but I think I'm leaning a little more towards the other now. Sometimes it makes sense to use a single return, but its a matter of context. For instance, if I found what I was looking for in the middle of a loop, its better to return from the loop early rather than finish it and then test a few other things. Your code can quite easily get skewed or convoluted or redundant when trying to maintain a single return.</p>\n\n<p>So, while it may seem undesirable, your code is actually benefiting from these multiple return statement. I wouldn't try refactoring them out, but if you absolutely must, you can modify the <code>$violation</code> array I showed you above so that the value is only set if an error occured, then, at the end of your function, if it has been set you can return the array.</p>\n\n<p>The only other solution I can think of, and perhaps a better one, would be to not use returns at all, but to throw errors instead. That appears to be very close to what you are doing anyways, so you might want to seriously contemplate this switch.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T06:42:55.240", "Id": "26050", "Score": "0", "body": "Regarding `strnlen` function inside the loop, I'm pretty sure that the upper condition is computed just one time, at least in `foreach`. Going to investigate further about `for` loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T13:11:21.107", "Id": "26083", "Score": "0", "body": "@Gremo: Corbin and I have already had this argument and both of us walked away having learned something. If you are interested in the results, take a look at [these comments](http://codereview.stackexchange.com/questions/12652/modifying-an-array-during-a-foreach-loop/12699#comment20530_12699). I believe I said in the above review that foreach was not the same, but it does still do *something* extra when using the function in the loop instead of defining it before hand. Usually that something extra is ignored, but its still a good idea to remove it, IMHO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T17:04:00.340", "Id": "15877", "ParentId": "15833", "Score": "2" } }, { "body": "<ul>\n<li><p>Why are you passing the <code>Constraint</code> instance to the function, it it is there only for you to extract <code>$constraint-&gt;message</code> from it? </p>\n\n<p>This use violates the <a href=\"http://c2.com/cgi/wiki?LawOfDemeter\" rel=\"nofollow\">LoD</a> and you seem to be leaking the encapsulation too.</p></li>\n<li><p>It seems to me that validation process consists of multiple independent stages. Each of those should be in a separate method. </p>\n\n<p>You might find <a href=\"https://vimeo.com/12643301\" rel=\"nofollow\">this lecture</a> relevant.</p></li>\n<li><p>The process seems very convoluted. </p>\n\n<p>You are manipulating some other <code>$this-&gt;context</code> object and terminating the execution after first manipulation. Why not instead return the array and execute the method directly? </p>\n\n<pre><code>$response = $foobar-&gt;validate( $value );\nif ( ! empty( $repsones ) )\n{\n $context-&gt;addViolation( $constraint-&gt;message, $respone );\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T06:37:32.343", "Id": "26049", "Score": "0", "body": "1) because I'm extending `Validation` class by Symfony 2 framework and `Constraint` class holds the options. 2) Good one, i can do this! 3) See point 1 :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T00:55:09.187", "Id": "15896", "ParentId": "15833", "Score": "0" } } ]
{ "AcceptedAnswerId": "15877", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T14:20:00.937", "Id": "15833", "Score": "3", "Tags": [ "php", "php5" ], "Title": "Would be possible to refactor this PHP code more?" }
15833
<p>I'm trying to come up with a scalable way of TDD'ing my Scala code, in particular managing dependencies. In this example, I've TDD'd part of the classic river crossing problem where we have people on each side of a river and move people from one bank to another.</p> <p>I wanted to unit test the smaller functions on their own to avoid over-complicated tests. To be able to test the top level function, I've injected the functions it uses so that I can unit test them. Finally, I provide a method that does the dependency injection for external code.</p> <p>Could a Scala pro comment on whether this is a reasonable thing to do?</p> <pre class="lang-scala prettyprint-override"><code>package me.geoff.river_crossing import me.geoff.library.ListExtensions._ object WorldTransform { def transform(world: World, move: Move): World = { transformF(world, move, getNewBoatPosition, updateBankWithMove) } type updateBankType = (List[Person], List[Person], Bank, Bank) =&gt; List[Person] def transformF(world: World, move: Move, getBank: Bank =&gt; Bank, updateBank: updateBankType): World = { val newBank = getBank(world.boatPosition) val leftBank = updateBank(world.leftBank, move.people, LeftBank(), world.boatPosition) val rightBank = updateBank(world.rightBank, move.people, RightBank(), world.boatPosition) World(leftBank, rightBank, newBank) } def getNewBoatPosition(bank: Bank): Bank = bank match { case LeftBank() =&gt; RightBank() case RightBank() =&gt; LeftBank() } def updateBankWithMove(bank: List[Person], people: List[Person], currentBank: Bank, thisBank: Bank): List[Person] = { if (currentBank == thisBank) bank.removeItems(people) else bank ++ people } } </code></pre> <p>And the tests:</p> <pre class="lang-scala prettyprint-override"><code>package me.geoff.river_crossing import org.scalatest._ import org.scalatest.matchers.ShouldMatchers import org.scalamock.scalatest.MockFactory class TestWorldTransform extends FlatSpec with MockFactory with ShouldMatchers { trait Fixture { val mockGetBank = mockFunction[Bank, Bank] val mockUpdateBank = mockFunction[List[Person], List[Person], Bank, Bank, List[Person]] val leftBank = List(Cannibal()) val rightBank = List(Missionary()) val world = World(leftBank, rightBank, LeftBank()) val move = Move(List(Cannibal())) def run() = { mockGetBank expects (LeftBank()) returning (RightBank()) mockUpdateBank expects (leftBank, move.people, LeftBank(), LeftBank()) returning (List()) mockUpdateBank expects (rightBank, move.people, RightBank(), LeftBank()) returning (List(Missionary(), Cannibal())) WorldTransform.transformF(world, move, mockGetBank, mockUpdateBank) } } "Transform" should "add result of getBank to result" in new Fixture { run().boatPosition should equal (RightBank()) } it should "add result of left bank update to left bank" in new Fixture { run().leftBank should equal (List()) } it should "add result of right bank update to right bank" in new Fixture { run().rightBank should equal (List(Missionary(), Cannibal())) } } class TestUpdateBankWithMove extends FlatSpec with ShouldMatchers { import WorldTransform.updateBankWithMove "Updating current bank" should "remove person from bank" in { val result = updateBankWithMove(List(Missionary()), List(Missionary()), LeftBank(), LeftBank()) result should equal (Nil) } it should "leave person not in move" in { val result = updateBankWithMove(List(Missionary(), Cannibal()), List(Missionary()), LeftBank(), LeftBank()) result should equal (List(Cannibal())) } "Updating opposite bank" should "add person to bank" in { val result = updateBankWithMove(List(), List(Missionary()), LeftBank(), RightBank()) result should equal (List(Missionary())) } it should "include people already on bank" in { val result = updateBankWithMove(List(Cannibal()), List(Missionary()), LeftBank(), RightBank()) result should equal (List(Cannibal(), Missionary())) } } class TestGetNewBoatPosition extends FlatSpec with ShouldMatchers { import WorldTransform.getNewBoatPosition "Get new boat position " should "return right bank for left bank" in { getNewBoatPosition(LeftBank()) should equal (RightBank()) } it should "return left bank for right bank" in { getNewBoatPosition(RightBank()) should equal (LeftBank()) } } </code></pre>
[]
[ { "body": "<p>I'm no Scala Pro, but I'll try to give my two cents anyway:</p>\n\n<p>Your decision to \"inject the functions\" (pass them as parameters) in order to be able to test them resulted in awkward code, and complicated an otherwise simple method.</p>\n\n<p>As for the tests you chose to make of the resulting method, they seem to only check that the functions are called - these tests are very brittle, since they assume implementation, and don't add much to actually test the code, they simply echo it...</p>\n\n<p>Better tests would be to make a move on a starting state, and then check if the resulting state is as expected. This would also make redundant the need to use function injection in production code...</p>\n\n<p>Also, if you really need to stub out functions within your code, I believe there are better ways to do it using <a href=\"http://www.scalatest.org/user_guide/testing_with_mock_objects#generatedMocks\" rel=\"nofollow\">generated mocks</a> or <a href=\"https://code.google.com/p/specs/wiki/UsingMockito#Spies\" rel=\"nofollow\">spies</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T16:39:02.983", "Id": "42435", "ParentId": "15834", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T14:46:25.863", "Id": "15834", "Score": "16", "Tags": [ "unit-testing", "scala" ], "Title": "TDD and function injection" }
15834
<p>I understand that this animation code is outdated:</p> <pre><code>[UIView beginAnimations:@"Move" context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; [UIView setAnimationDelay:0.08]; self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [UIView commitAnimations]; </code></pre> <p>What are the modern best practices for achieving the same result?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T00:13:08.023", "Id": "94974", "Score": "0", "body": "In the future, please leave a comment on what version of iOS the code comes from and what version of iOS you're looking to upgrade to. Nearly 2 years later, this question-and-answer is purely meaningless because there's no documentation as to what iOS versions we're discussing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T11:25:01.383", "Id": "95048", "Score": "0", "body": "The answer certainly wasn't meaningless for me at the time. The question is still open to someone providing a new answer for even more recent versions of iOS. Thanks for your contribution though, it certainly adds more meaning to this discussion.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T11:32:23.157", "Id": "95050", "Score": "0", "body": "At the time, it certainly isn't meaningless, I agree. But without some sort of documentation as to what version of iOS we're talking about, it's problematic. Particularly if/when the current answer becomes irrelevant. Yes, I can return and add an updated answer, but the current answer has the green check mark, and if neither you or the current answerer returns to update that answer or its \"Accept\" status, that will be the first answer people try, as there's nothing to warn them \"Hey, this is for iOS 6 and we're on iOS 11.\"" } ]
[ { "body": "<p>In iOS 4 and later you are encouraged to use <a href=\"http://developer.apple.com/library/ios/documentation/windowsviews/conceptual/viewpg_iphoneos/AnimatingViews/AnimatingViews.html#//apple_ref/doc/uid/TP40009503-CH6-SW4\">animation blocks</a>.</p>\n\n<pre><code>[UIView animateWithDuration: 0.5f\n delay: 0.08f\n options: UIViewAnimationCurveEaseIn\n animations: ^{\n self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);\n }\n completion: ^(BOOL finished){\n // any code you want to be executed upon animation completion\n }\n];\n</code></pre>\n\n<p>One advantage of using block-based animation is that</p>\n\n<blockquote>\n <p>When this code executes, the specified animations are started immediately on another thread so as to avoid blocking the current thread or your application’s main thread.</p>\n</blockquote>\n\n<p>This means that the rest of your application will not be \"locked up\" while your animation is executing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T02:54:49.083", "Id": "15847", "ParentId": "15835", "Score": "10" } } ]
{ "AcceptedAnswerId": "15847", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T17:15:54.853", "Id": "15835", "Score": "7", "Tags": [ "objective-c", "ios", "animation", "cocoa-touch" ], "Title": "Upgrading animation code" }
15835
<p>I have two projects, a native C++ DLL (pinvokelib.dll), and a C# console application (pinvoketest.exe) which calls the DLL. I'm curious if the way I do P/Invoke is considered best practice.</p> <p>Here is my C++ code:</p> <pre><code>extern "C" __declspec(dllexport) int test(int val); int test(int val) { return val * 2; } </code></pre> <p>And my C#:</p> <pre><code>using System; using System.Runtime.InteropServices; namespace pinvoketest { class Program { static void Main(string[] args) { Console.WriteLine(test(42)); Console.ReadLine(); } [DllImport("pinvokelib.dll", CallingConvention=CallingConvention.Cdecl)] static extern int test(int val); } } </code></pre> <p>I'm using Visual Studio 2012 Express to compile both.</p> <p>Is there any way that the code can be improved? Is there something redundant? I'm especially unsure about the first line of the C++ code, since I don't understand everything about it very well.</p>
[]
[ { "body": "<p>If you don't call your function recursively from C, you don't need to have separate defition and declaration:</p>\n\n<pre><code>extern \"C\" __declspec(dllexport) int test(int val)\n{\n return val * 2;\n}\n</code></pre>\n\n<p>And if you have more than one function you want to export, you can use <code>extern \"C\"</code> as a block:</p>\n\n<pre><code>extern \"C\"\n{\n __declspec(dllexport) int test(int val)\n {\n return val * 2;\n }\n\n // more functions here\n}\n</code></pre>\n\n<p>As to what does it all mean:</p>\n\n<ul>\n<li><code>extern \"C\"</code> tells the compiler not to mangle the name of the function; this is normally necessary to support C++ function overloading</li>\n<li><code>__declspec(dllexport)</code> means that this function will be exported from the DLL, so that you can use it from outside this library</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T20:43:52.163", "Id": "25780", "Score": "0", "body": "Thanks. If I would put structs or classes inside the `extern \"C\"` block, would it affect them? I wouldn't need them outside of the DLL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T22:12:51.843", "Id": "25783", "Score": "0", "body": "Well, names of types are not exported anyway, so it wouldn't make a difference even if `extern \"C\"` did affect them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T20:38:59.097", "Id": "15839", "ParentId": "15836", "Score": "5" } } ]
{ "AcceptedAnswerId": "15839", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T20:00:57.007", "Id": "15836", "Score": "3", "Tags": [ "c#", "c++" ], "Title": "Is this P/Invoke code standard?" }
15836
<p>How can I improve this?</p> <p><strong>jQuery</strong></p> <pre><code>$(function() { $('button').button(); $('#tabs').tabs(); $('.ui-state-error').hide(); $('.btnlogin').click(function() { $('#login .ui-state-error').hide(); if($('#login_email').val().trim() == ''){ $('#login_email').focus(); } else if($('#login_password').val().trim() == ''){ $('#login_password').focus(); } else { $.ajax({ url:'login.php', type:'post', data: { email: $('#login_email').val().trim(), password: $('#login_password').val().trim() }, success: function(data) { if(data == 'Success'){ window.location = 'main.php'; } else { $('#login .ui-state-error p strong').html(data); $('#login .ui-state-error').show(); } } }); } }); }); </code></pre> <p><strong>HTML</strong></p> <pre><code> &lt;!DOCTYPE HTML&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Social Networking&lt;/title&gt; &lt;link rel="stylesheet" href="css/ui-lightness/jquery-ui-1.8.23.custom.css" type="text/css"&gt; &lt;link rel="stylesheet" href="css/reset.css" type="text/css"&gt; &lt;script src="js/jquery-1.8.0.min.js"&gt;&lt;/script&gt; &lt;script src="js/jquery-ui-1.8.23.custom.min.js"&gt;&lt;/script&gt; &lt;script src="js/login.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;section&gt; &lt;article&gt; &lt;div id="tabs" class="tabs"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#login"&gt;Login&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#register"&gt;Register&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="login"&gt; &lt;div class="ui-state-error ui-corner-all"&gt; &lt;p&gt;&lt;span class="ui-icon ui-icon-alert"&gt;&lt;/span&gt; &lt;strong&gt;&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;label for="login_email"&gt;E-mail:&lt;/label&gt; &lt;input id="login_email" type="email"&gt; &lt;label for="login_password"&gt;Password:&lt;/label&gt; &lt;input id="login_password" type="password"&gt; &lt;label&gt;&lt;/label&gt; &lt;button class='btnlogin'&gt;Log in&lt;/button&gt; &lt;/div&gt; &lt;div id="register"&gt; &lt;div class="ui-state-error ui-corner-all"&gt; &lt;p&gt;&lt;span class="ui-icon ui-icon-alert"&gt;&lt;/span&gt; &lt;strong&gt;&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;label for="reg_name"&gt;Name:&lt;/label&gt; &lt;input id="reg_name" type="text"&gt; &lt;label for="reg_email"&gt;E-mail:&lt;/label&gt; &lt;input id="reg_email" type="email"&gt; &lt;label for="reg_password"&gt;Password:&lt;/label&gt; &lt;input id="reg_password" type="password"&gt; &lt;label for="reg_cpassword"&gt;Confirm:&lt;/label&gt; &lt;input id="reg_cpassword" type="password"&gt; &lt;label&gt;&lt;/label&gt; &lt;button class='btnregister'&gt;Register&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;/section&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>One thing I would recommend is to put all of the login code into a distinct function called <code>login()</code>, for example. Then the click binding would look like this:</p>\n\n<pre><code>$('.btnlogin').click(login)\n</code></pre>\n\n<p>This would do a few things for you. First, it would improve the readability of the code. Since the login code is more than just a few lines, it will be more clear to anyone who may read the code (including you in the future) what its purpose is.</p>\n\n<p>Second, it will improve the code's reusability. Let's say in the future you want to trigger a login by some means other than just a click -- a return keypress, for example. Then you can just call the same login function without having to rewrite the code.</p>\n\n<p>Lastly, it will be easier to find potential errors if the function is not anonymous because you will be able to see the function's signature (<code>login()</code>) in the stack trace.</p>\n\n<p>I know this is just one small suggestion, but keeping this in mind as you write other code in the future could prevent a lot of headaches.</p>\n\n<p>-- edit --</p>\n\n<p>By the way, <a href=\"http://api.jquery.com/jQuery.trim/\" rel=\"nofollow\">jQuery.trim()</a> is meant to be used as <code>$.trim(string)</code> rather than <code>$(stringEl).trim()</code>. You might be able to get away with what you have in some browsers because there is a native <code>trim()</code> method for JavaScript Strings. But in some browsers (IE) that won't work.</p>\n\n<p>So I would recommend changing things like this:</p>\n\n<pre><code>$('#login_email').val().trim()\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>$.trim( $('#login_email').val() )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-24T03:37:47.693", "Id": "25804", "Score": "0", "body": "Added one more suggestion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T00:01:59.843", "Id": "15844", "ParentId": "15843", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T23:09:56.757", "Id": "15843", "Score": "0", "Tags": [ "javascript", "jquery", "html", "validation", "jquery-ui" ], "Title": "jQuery login code" }
15843
<p>I am working on a Rails 3.2.6 app for a friend which implements some message board functionality. Users can post messages into a categories. Each user also has a list of other users they have friended.</p> <p>I got a feature request recently to display the number of unread posts made by the current user's friends next to each category. This is tracked on a category basis, not a per post basis, since the posts are displayed on a main newsfeed and you can't read a single post. So the feature request states that when a user clicks a category, which filters posts by that category, it will reset the unread count for that category.</p> <p>I've implemented the unread counter by adding a database table that tracks the last time a user "read" all the messages. The table contains <code>user_id</code>, <code>category_id</code>, and <code>last_read_time</code>.</p> <p>Now I am trying to implement the unread counters. I set up some scopes in my Post model (some of these are used in different places, which is why they are separate scopes):</p> <pre><code>scope :by_users, lambda { |users| where("user_id IN (?)", users) unless users.nil? } scope :by_categories, lambda { |categories| where("category_id IN (?)", categories) unless categories.nil? } scope :since, lambda { |date| where("updated_at &gt; ?", date) unless date.nil? } </code></pre> <p>Here is my first crack at an unread method (also in the Post model):</p> <pre><code>def self.unread_count(user, category) read_time = ReadStatus.where("user_id = ? AND category_id = ?", user.id, category.id).first if read_time.nil? #handle it end #if user has no friends, there will be no unread posts displayed if user.friends.count == 0 return else friends = user.friends end unread = by_users(friends).since(read_time.last_read_time).by_categories(category.id).count unless unread == 0 "(" + unread.to_s + " new)" end end </code></pre> <p>This works fine, but I would like to make this more efficient. Right now, there are 81 categories users can post in. This means when the homepage loads there are 81 count queries firing off, and this is repeated anytime the homepage is re-loaded. I can't think of any way to cache this value or eliminate these queries, since the unread count can change at any given moment and needs to be refreshed when the page is reloaded.</p> <p>Any tips/tricks/Rails pixie dust to make this better? Every solution I think of either results in stale counter values or a large DB hit (for what I feel is a fairly trivial "feature").</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T01:17:01.310", "Id": "15845", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Displaying number of unread posts for a message board" }
15845
<p>Currently, I have this code snippet, but it's a little bit slow:</p> <pre><code>% input image input_matrix = imread('placa.bmp'); [rows cols] = size(input_matrix); % rotation degree = 30; radians = (pi * degree) / 180; theta = radians; % output matrix t_matrix = input_matrix; t_matrix(t_matrix == input_matrix) = NaN; % transformation matrix T = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 1; 0 0 1]; % loop over each input_matrix coordinate for n = 1:numel(input_matrix) % current coordinate [x y] = ind2sub([rows cols], n); % transpose v = [x y 1]'; % homogeneous coordinate v = T*v; % transponse again v = v'; % only integer values a = floor(v(1)); b = floor(v(2)); if a &gt; 0 &amp;&amp; b &gt; 0 % replace in t_matrix t_matrix(a,b) = input_matrix(x,y); end end % get only a part of t_matrix t_matrix = t_matrix(1:rows, 1:cols); figure; imshow(input_matrix); % original image figure; imshow(t_matrix) </code></pre> <p>How can I improve it? </p> <p>Condition: keep using this matrix: </p> <pre><code>% transformation matrix T = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 1; 0 0 1]; </code></pre>
[]
[ { "body": "<p>Rather than looping over all x and y values you could put them into a vector, that should speed things up considerably.</p>\n\n<pre><code>y=repmat(1:cols,rows,1)\nx=repmat((1:rows)',cols,1)\n\nM=[x(:) y(:) ones(rows*cols,1)];\n</code></pre>\n\n<p>Now you just need to multiply <code>M</code> or <code>M'</code> with <code>T</code> or <code>T'</code> and you have subsitituted that part of the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T11:01:12.557", "Id": "29615", "Score": "0", "body": "It would help if you posted an example along with an explanation instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T12:16:29.417", "Id": "29616", "Score": "0", "body": "Added the improved code part" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T10:28:53.683", "Id": "18593", "ParentId": "15846", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T00:46:33.607", "Id": "15846", "Score": "7", "Tags": [ "matrix", "image", "matlab", "coordinate-system" ], "Title": "Using homogeneous coordinates to rotate an image" }
15846
<p>I am doing a project where I use DLL's as run-time modules or plugins. To do this, I use the Windows <code>LoadLibrary()</code> and <code>FreeLibrary()</code> API calls to call two functions exported by the DLL. I decided to make a class so dealing with the DLL's would be easier. Is there anything I can add to my class to make it better, is there anything I'm doing wrong? Feel free to criticize anything you want. </p> <p><strong>SaModule.h</strong><hr /></p> <pre><code>#ifndef SAMODULE_H__ #define SAMODULE_H__ #include &lt;Windows.h&gt; #include &lt;string&gt; #include &lt;exception&gt; #include "WinException.h" class SaModule { private: typedef const char* (*LPFNGETNAME)(); typedef bool (*LPFNDOSCAN)(std::string&amp;, std::string&amp;); HINSTANCE hInstance; std::string path; public: SaModule(); SaModule(const std::string&amp; path); ~SaModule(); void Load(const std::string&amp; path); void Unload(); LPFNDOSCAN DoScan; LPFNGETNAME GetName; HINSTANCE GetHandle() const; operator HINSTANCE() const; }; #endif//SAMODULE_H__ </code></pre> <p><br /> <strong>SaModule.cpp</strong><hr /></p> <pre><code>#include "SaModule.h" #include "WinException.h" #include &lt;sstream&gt; #include &lt;iomanip&gt; SaModule::SaModule(): path(), hInstance(NULL) { //Nothing... } SaModule::SaModule(const std::string&amp; path): path(path), hInstance(NULL) { Load(path); } SaModule::~SaModule() { Unload(); } void SaModule::Load(const std::string&amp; path) { this-&gt;path = path; if( NULL == (hInstance=LoadLibrary(path.c_str())) ) throw WinException(); if( NULL == (GetName=reinterpret_cast&lt;LPFNGETNAME&gt;(GetProcAddress(hInstance,"GetName"))) ) throw WinException(); if( NULL == (DoScan=reinterpret_cast&lt;LPFNDOSCAN&gt;(GetProcAddress(hInstance, "DoScan"))) ) throw WinException(); } void SaModule::Unload() { FreeLibrary(hInstance); } HINSTANCE SaModule::GetHandle() const { return hInstance; } SaModule::operator HINSTANCE() const { return hInstance; } </code></pre> <p><br /> <strong>WinException.h</strong><hr /></p> <pre><code>#ifndef WINEXCEPTION_H__ #define WINEXCEPTION_H__ #include &lt;Windows.h&gt; #include &lt;exception&gt; #include &lt;string&gt; class WinException: public std::exception { private: DWORD dwError; std::string errMsg; public: WinException(); const char* what() const; }; #endif//WINEXCEPTION_H__ </code></pre> <p><br /> <strong>WinException.cpp</strong><hr /></p> <pre><code>#include "WinException.h" #include &lt;sstream&gt; #include &lt;iomanip&gt; WinException::WinException() { std::ostringstream ss; dwError = GetLastError(); LPVOID lpMsgBuf = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast&lt;LPTSTR&gt;(&amp;lpMsgBuf), 0, NULL); ss &lt;&lt; "Error: 0x" &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(8) &lt;&lt; dwError &lt;&lt; std::endl &lt;&lt; reinterpret_cast&lt;LPTSTR&gt;(lpMsgBuf); errMsg = ss.str(); LocalFree(lpMsgBuf); } const char* WinException::what() const { return errMsg.c_str(); } </code></pre> <p><br /> <strong>Example Usage</strong><hr /></p> <pre><code>#include &lt;iostream&gt; #include "SaModule.h" int main(int argc, char* argv[]) { try { SaModule mod("some.sa.dll"); std::cout &lt;&lt; "Loaded Module: " &lt;&lt; mod.GetName() &lt;&lt; std::endl; } catch( WinException&amp; ex ) { std::cout &lt;&lt; ex.what() &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T06:08:04.013", "Id": "26239", "Score": "0", "body": "I don't think anyone mentioned this, but those double underscores in `SAMODULE_H__` cause the identifier to infringe upon the reserved ones. Even if you've seen this, read the double underscores part carefully: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier" } ]
[ { "body": "<p>Just a couple of quick thoughts.</p>\n\n<ol>\n<li><code>DoScan</code> and <code>GetName</code> probably should be initialised to NULL as well.</li>\n<li><code>Load</code> doesn't call <code>Unload</code> for any previous loaded dlls. If Load should be called once only per <code>SaModule</code>, that should be detected.</li>\n<li>A more informative exception could be thrown. \"...during attempted insertion of plugin xyz\", for example.</li>\n<li>Beware of function name decoration, if that could be an issue.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T07:12:05.010", "Id": "15849", "ParentId": "15848", "Score": "3" } }, { "body": "<p>First thing that pops out at me:</p>\n\n<pre><code>if( NULL == (hInstance=LoadLibrary(path.c_str())) )\n</code></pre>\n\n<p>When programming for Windows, you should almost <em>never</em> want to use the \"<code>A</code>\"/\"ANSI\" versions of functions. This is legacy from Win9x and you should be using Unicode. Windows is not like Unix where the C library can assume UTF-8 and everything can keep chugging along with the full set of Unicode chars accesible: by restricting yourself to the \"multi-byte\" encodings you will (1) see inconsistent behavior depending on what the user sets their language to and (2) not be able to access some Unicode filenames that the user may have on their filesystem. You should define the <code>UNICODE</code> and <code>_UNICODE</code> macros and use <code>WCHAR</code> instead of 8-bit chars. (Since it seems you want to use the C++ classes I believe <code>wstring</code> works instead of <code>string</code> here.)</p>\n\n<p>Second:</p>\n\n<p>The <code>WinException</code> class looks weird to me. Not all Windows APIs use <code>GetLastError</code> - some of them may return <code>HRESULT</code> or do something else. From that perspective you have not captured the full generality of Windows errors.</p>\n\n<p>I would also say, perhaps controversially since this is not the path everybody has taken, that wrapping Win32 errors with exceptions is a bad idea. There are some Win32 errors that are not error conditions at all, for example <code>FindNextFile</code> will fail with <code>ERROR_NO_MORE_ITEMS</code> when you reach the end of a directory, or I/O will fail with <code>ERROR_IO_PENDING</code> to indicate that the I/O is happening asynchronously. A Win32 program will occasionally have to react to such errors and I would say the way you've done it loses some of that information, or makes it less convenient to work with.</p>\n\n<p>But maybe it's OK for your use. YMMV.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T20:20:34.720", "Id": "26041", "Score": "4", "body": "Instead of roll-your-own `WinException`, should be using `system_error` and the Windows-specific `system_category` of errors. The best article I've found about this is at [Chris Kohlkoff's blog](http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-1.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T20:31:36.013", "Id": "26042", "Score": "0", "body": "@MikeC - Interesting, didn't know about this addition to C++11. +1" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T19:34:54.317", "Id": "15854", "ParentId": "15848", "Score": "3" } }, { "body": "<p>As MikeC suggested, the WinException class could be replaced by <a href=\"http://en.cppreference.com/w/cpp/error/system_error/system_error\" rel=\"nofollow\"><code>std::system_error</code></a>. This original came from the <a href=\"http://www.boost.org/doc/libs/1_51_0/libs/system/doc/index.html\" rel=\"nofollow\"><code>boost::system</code></a> library and was included into the C++0x specification with a few changes (mainly some of the names). </p>\n\n<p><strong>Example for <code>throw</code>:</strong></p>\n\n<pre><code>throw std::system_error(std::error_code(::GetLastError(), \n std::system_category()), \"SaModule::Load()\");\n</code></pre>\n\n<p><strong>Example for <code>catch</code>:</strong></p>\n\n<pre><code>//...\ncatch( std::system_error&amp; se )\n{\n std::cout &lt;&lt; \"Error: \" &lt;&lt; se.code().value() &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"Message: \" &lt;&lt; se.code().message() &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"What: \" &lt;&lt; se.what() &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p><strong>Example output for <code>ERROR_FILE_NOT_FOUND</code>:</strong></p>\n\n<blockquote>\n <p>Error: 2 <br />\n Message: No such file or directory <br />\n What: SaModule::Load() <br /></p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T06:36:40.043", "Id": "16256", "ParentId": "15848", "Score": "3" } } ]
{ "AcceptedAnswerId": "15849", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T05:09:14.337", "Id": "15848", "Score": "2", "Tags": [ "c++", "object-oriented", "windows" ], "Title": "Windows DLL Module Class" }
15848