body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Vimscript is based on the <em>ex</em> language of the original vi editor. However, Vimscript extends ex in many ways, including: support for control flow; function definitions; and advanced datatypes including lists and associative arrays (dictionaries).</p> <p>Vimscript files use the <code>.vim</code> file extension and they may be executed by using the <code>:source</code> command. </p> <p>Vim <a href="http://www.vim.org/scripts/index.php" rel="nofollow">plugins</a> (also known as <em>scripts</em>) can be written entirely or partially in Vimscript, with the option of embedding other languages such as <a href="http://stackoverflow.com/tags/python/info">Python</a> or <a href="http://stackoverflow.com/tags/perl/info">Perl</a>.</p> <h2>Resources for learning Vimscript</h2> <ul> <li><a href="http://learnvimscriptthehardway.stevelosh.com/" rel="nofollow">Learn Vimscript the hard way</a></li> <li><a href="http://andrewscala.com/vimscript/" rel="nofollow">Five Minute Vimscript</a></li> <li><a href="http://www.ibm.com/developerworks/linux/library/l-vim-script-1/index.html" rel="nofollow">Scripting the Vim editor</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T03:25:46.700", "Id": "38663", "Score": "0", "Tags": null, "Title": null }
38663
Vimscript is the scripting language built into the text editor Vim. It can also be referred to as "Vim Language" or "VimL".
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T03:25:46.700", "Id": "38664", "Score": "0", "Tags": null, "Title": null }
38664
<p>TeX is a typesetting system, where the output is defined by command-sequences. It was invented by Donald Knuth.</p> <p>There is <a href="http://tex.stackexchange.com">a Stack Exchange site dedicated to TeX</a>, which is a good place to ask any TeX-related questions.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T03:26:16.983", "Id": "38665", "Score": "0", "Tags": null, "Title": null }
38665
TeX is a typesetting system, where the output is defined by command-sequences. Note that http://tex.stackexchange.com is specifically dedicated to TeX questions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T03:26:16.983", "Id": "38666", "Score": "0", "Tags": null, "Title": null }
38666
<p>I wrote a program that finds empty folders and subfolders in a directory. It's the first program I've ever written in Java, and I'd like some critique. I feel like I'm not utilizing classes in a very coherent manner. Also, I think I'm naming variables poorly, because as I write my program I find myself constantly having to rename methods/classes/variables to clarify their meaning.</p> <p>Part 1: Under the Hood</p> <pre><code>package emptyfolders; import java.io.File; import java.util.*; public class EmptyFolders { public static void main(String[] args) { } private List seekEmpty(String dirname, List emptyFoldersTemp) { // This method goes through all folders that are directly contained in a // directory, and appends them to a list if they are empty. Used // recursively for directories containing multiple folders // Get the appropriate directory from user input File dir = new File(dirname); // Populate an array with files/folders in the directory File[] folderContents = dir.listFiles(); // Iterate through every file/folder for (File currentContent : folderContents) { // Disregard files, acquire folders if (currentContent.isDirectory()) { // If this folder is empty, add it to the list if (currentContent.listFiles().length == 0) { emptyFoldersTemp.add(currentContent); // If not, run this method on the folder } else if (currentContent.listFiles().length &gt;= 1) { seekEmpty(currentContent.toString(),emptyFoldersTemp); } } } // Return a list containing all empty folders currently found return emptyFoldersTemp; } List listLooper(String folder) { // An outer program that helps seekEmpty with its recursion, instantiate EmptyFolders directory = new EmptyFolders(); // Create a temporary list that holds empty folders List emptyFoldersTemp = new ArrayList(); //Run seekEmpty List emptyFolders = directory.seekEmpty(folder, emptyFoldersTemp); //Return the list of empty subfolders return emptyFolders; } } </code></pre> <p><code>listLooper</code> feels redundant, especially the part where it causes the program to return the List Object through two methods. All the stuff there was originally in the main method, but I needed the method to take a single String (for reasons you will see later, it grabs a directory from a UI). Should I get rid of it, and if so, how?</p> <p>Part 2: The UI</p> <pre><code>private void listButtonActionPerformed(java.awt.event.ActionEvent evt) { // When the "List" button is pressed, pull the directory from the // text field, and search that directory for empty folders and subfolders //Get directory from directory field and double all the backslashes so //for functional purposes, note that since backslashes are literals, //they are doubled in the "replace" method String targetDirectory = directoryField.getText().replace("\\","\\\\"); //Instantiate an instance of the EmptyFolder finder EmptyFolders emptyFolderFinder = new EmptyFolders(); //Run the empty folder finder recursive method (separate file) List emptyFolders = emptyFolderFinder.listLooper(targetDirectory); //Clear the text area, if it contains text if (! emptyFoldersArea.getText().equals("")) { emptyFoldersArea.setText(""); } for (Object emptyFolder : emptyFolders) { //Append all empty folders found in the target directory emptyFoldersArea.append(emptyFolder.toString() + "\n"); } } private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) { // When the "Browse..." button is pressed, the UI prompts the user to // select the directory he or she wants to check for empty folders, and // the program calls a method to do so //Instantiate an instance of the file browser JFileChooser fileBrowser = new JFileChooser(); //Rename title, specify that we are only concerned with folders fileBrowser.setDialogTitle("Select target directory"); fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Return the directory on affirmation and write it to UI int returnValue = fileBrowser.showDialog(this, null); if (returnValue == JFileChooser.APPROVE_OPTION) { String targetDirectory = fileBrowser.getSelectedFile().toString(); directoryField.setText(targetDirectory); } else { } } </code></pre> <p>I built a Swing UI using Netbeans, so I'm cutting that code out. What I care about are two buttons in the UI. One is a browse button that the user uses to pick a directory, and the other is a button that runs the program. The list of empty folders is displayed in an empty area. I don't know how to better integrate this with my program, I feel like it sticks out in a way that doesn't flow with the rest of my program.</p> <p>I'm taking college programming classes when I come back from the break, so this was my way of exposing myself to Java early, so any advice before I get started is appreciated (fingers crossed that CS is right for me).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T08:35:51.913", "Id": "64536", "Score": "1", "body": "You're currently in danger of infinite recursion if the folder structure is cyclical (eg, a shortcut for Desktop is placed on the Desktop...). I doubt Windows or other OSs have any of these by default, but you can't guarantee that some random program (or person) has at some point (actually, Win7 has an option to show a link to the User directory on the desktop, which would do this). The common strategy is to retain a list of all items visited (linked lists have similar problems). Also, you probably want `Set`, as there's no reason to store a folder more than once." } ]
[ { "body": "<p>There are a few small items, and a couple of larger ones that concern me in your code...</p>\n\n<ul>\n<li>You have an empty <code>main</code> method under your hood.... it serves no purpose, so remove it ;-)</li>\n<li><p>you are not using the generic typing for your List. In this case, your code should look like:</p>\n\n<pre><code>List&lt;File&gt; emptyFolders = emptyFolderFinder.listLooper(targetDirectory);\n</code></pre>\n\n<p>and the <code>listLooper</code> method should return <code>List&lt;File&gt;</code>.</p></li>\n<li><p>in your <code>listLooper</code> method you declare your <code>List&lt;File&gt;</code> and then pass it in to the <code>seelEmpty</code> method. This method returns the exact same <code>List</code> instance back, so it should not have to return a value at all. The input <code>List&lt;File&gt;</code> is an 'accumulator' that you add things to. There is no reason to return it as well.</p></li>\n<li><code>seekEmpty</code> takes a String <code>dirname</code> as a parameter. This should not be a String, but a <code>File</code>. You already have the file when you call the method, so you convert the file to String, and then immediately convert it back. just keep it as a File the whole time.</li>\n<li><p>in <code>seekEmpty</code> (again) you have the code which checks for the number of files in a Directory:</p>\n\n<p>if (currentContent.listFiles().length == 0) {\n ....\n } else if (currentContent.listFiles().length >= 1) {\n ...\n }</p>\n\n<p>the else-if makes no sense because, if the length is not <code>== 0</code> then it can only be <code>&gt;= 1</code>. It should be a simple <code>} else {</code> and not have an <code>else if</code> at all. </p></li>\n</ul>\n\n<p>OK, now for some of the bigger things...</p>\n\n<p>You ask whether you should get rid of the <code>listLooper</code> method. The answer is probably <code>no</code>. You are setting up a recursive call chain with the <code>seekEmpty</code> method. You often need an 'entry' to a recursive method, and the <code>listLooper</code> is this method. The method will pre-and-post process the data required by, and created by the recursion.</p>\n\n<p>Right, you want to find directories which have no files....</p>\n\n<p>What I don't like about your code is that it calls 'listFiles()` twice. We can fix that with/in the recursion....</p>\n\n<p>A method like the following will serve you better, I think:</p>\n\n<pre><code>/** This method goes through all folders that are directly contained in a\n * directory, and appends them to a list if they are empty. Used\n * recursively for directories containing multiple folders\n *\n * @param dir is the directory to check for content\n * @param emptyFolders is he List we add empty folders to.\n */\nprivate void seekEmpty(File dir, List&lt;File&gt; emptyFolders) {\n\n // Populate an array with files/folders in the directory\n File[] folderContents = dir.listFiles();\n if (folderContents.length == 0) {\n // we are empty, add us.\n emptyFolders.add(dir);\n }\n\n // Iterate through every file/folder\n for (File content : folderContents) {\n // Disregard files, acquire folders\n if (content.isDirectory()) {\n // check if this folder is empty\n seekEmpty(content, emptyFolders);\n }\n }\n}\n</code></pre>\n\n<p>This significantly simplifies the recursion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T06:36:05.177", "Id": "64828", "Score": "0", "body": "Thanks! You've helped realize the importance of coding with increased emphasis on efficiency and, IMO, maintainability. Are there any resources on good coding practices that you can recommend?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T06:44:46.723", "Id": "64829", "Score": "2", "body": "@Zapurdead Joshua Bloch ... Effective Java, then Java Concurrency In Practice ... can't go wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T04:37:28.983", "Id": "38670", "ParentId": "38667", "Score": "7" } } ]
{ "AcceptedAnswerId": "38670", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T03:27:25.920", "Id": "38667", "Score": "5", "Tags": [ "java", "recursion", "file-system", "swing" ], "Title": "Finding empty folders" }
38667
<p>My question is regarding a rather inelegant solution to a problem that I came up with a while ago.</p> <p>I was making a Winform Application to access active directory among other things and needed to thread my application to stop my UI from freezing. </p> <p>Although I have little knowledge of actual threading (I kept hitting cross-thread access issues), I've built a little function that allowed me to pass an object, act on it in a separate thread and then once it returned to the UI CurrentContext I could act on it again to update the view. </p> <p>TL;DR</p> <p>The below function sends a Generic Item to a separate thread, then once acted upon, returns the item and acts on it again. </p> <pre><code>public static void doThreadedQuery&lt;T&gt;(Func&lt;T&gt; processQuery, Action&lt;T&gt; onComplete) { TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task&lt;T&gt; doQuery = new Task&lt;T&gt;(processQuery); doQuery.ContinueWith((results) =&gt; { if (onComplete != null) onComplete(results.Result); }, scheduler); doQuery.Start(); } </code></pre> <p>An example usage for something similar is pass an <code>activeDirectory</code> <code>SearchResultCollection</code>, parse through it and generate a TreeView/Grid. Then return the populated grid and UI updated without freezing. </p> <p>Now I have done variants with a progress function/cancellation token etc, but I suppose my question is: on a base level, is there some horrible inefficiency or simple equivalent I am unaware of (aside from the Background Worker I am not overly fond of)?</p> <p>I feel like I'm re-inventing the wheel here.</p>
[]
[ { "body": "<p>You shouldn't <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx\" rel=\"nofollow noreferrer\">usually</a> use <code>Task</code> constructor directly, use <code>Task.Factory.StartNew</code> (or <code>Run</code>).</p>\n\n<p>I also don't understand why you want to have a separate method for starting a task. It is completely superficial. It's just as useless as adding <code>Print</code> method that calls <code>Console.WriteLine</code> instead of using <code>Console.WriteLine</code> directly.</p>\n\n<p>Normally, you just do this:</p>\n\n<pre><code>void SomeUICode ()\n{\n Task.Factory.StartNew (() =&gt; {\n // This will run on thread pool\n return DoSomeExpensiveWork ();\n }).ContinueWith (result =&gt; {\n // This will run on UI thread\n UpdateUI (result);\n }, TaskScheduler.FromCurrentSynchronizationContext ());\n}\n</code></pre>\n\n<p>It's basically the same thing you wrote, but without abstracting it away <code>doThreadedQuery</code> <strong>since there's nothing to abstract away here</strong>. </p>\n\n<p>However, if you don't mind using C# 5, you can simplify things with <a href=\"http://msdn.microsoft.com/en-us/library/hh191443.aspx\" rel=\"nofollow noreferrer\"><code>async</code>/<code>await</code></a> operators:</p>\n\n<pre><code>async void SomeUICode ()\n{\n var result = await Task.Factory.Run (() =&gt; {\n // This will run on thread pool\n return DoSomeExpensiveWork ();\n });\n\n // The rest of this method will be scheduled on UI thread:\n UpdateUI (result);\n}\n</code></pre>\n\n<p>Note the <code>await</code> keyword that “splits” the method and schedules the rest of it as a continuation on current synchronization context (exactly the same thing you did manually).</p>\n\n<p>I declared the function as <code>async void</code> but <a href=\"https://stackoverflow.com/a/19415703/458193\">you should only do this for event handlers</a> (which have to be <code>void</code>). In all other cases, <strong>declare the function as <code>async Task</code> so the calling code has a chance to wait for it to finish</strong>:</p>\n\n<pre><code>async Task SomeUICode ()\n{\n // ...\n}\n</code></pre>\n\n<p>On a side note, <code>doThreadedQuery</code> is a rather unfortunate name because</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229043(v=vs.100).aspx\" rel=\"nofollow noreferrer\">.NET method names should be PascalCase, not camelCase</a>;</li>\n<li>There's no “query” being performed, you're just scheduling an operation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:25:53.690", "Id": "64555", "Score": "0", "body": "I think he was just indicating (by example name) a process running a structured Query language operation. But otherwise, nice examples!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:34:18.120", "Id": "64556", "Score": "0", "body": "@Spiked: Perhaps, but his method doesn't really “know” whether function passed to it does a LINQ query or something else, so it's still a bad naming decision." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:46:27.887", "Id": "64560", "Score": "1", "body": "`async void` [should be avoided](http://msdn.microsoft.com/en-us/magazine/jj991977.aspx) (in most cases)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:49:33.793", "Id": "64561", "Score": "0", "body": "@Dave: Thanks for the remark, I amended my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T17:37:35.393", "Id": "64606", "Score": "0", "body": "I forgot to change the example name when I took it from the project, it was doing an ActiveDirectory query and T was defined hence the name." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T11:44:45.370", "Id": "38682", "ParentId": "38673", "Score": "5" } } ]
{ "AcceptedAnswerId": "38682", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T09:24:34.483", "Id": "38673", "Score": "6", "Tags": [ "c#", "multithreading", "task-parallel-library" ], "Title": "Using Task<T> and actions for simple threading?" }
38673
<p>I am using the following function to check if a MySQL connection is in an invalid state or if it has reached a predefined maximum operation count:</p> <pre><code> /// &lt;summary&gt; /// Holds the amount of operations for the currently mysql-connection open /// &lt;/summary&gt; private int connectionUsageCount = 0; /// &lt;summary&gt; /// The maximum usage count of the connection until it has to be refreshed /// &lt;/summary&gt; private const int MAX_CONNECTION_USAGE_COUNT = 100; /// &lt;summary&gt; /// Holds the cached MySql Connection to the databse server. /// &lt;/summary&gt; private MySqlConnection mySqlConnection; /// &lt;summary&gt; /// Checks the status of the sql connection and refreshes it when necessary. /// &lt;/summary&gt; private void CheckSqlConnection() { // Check if the connection is in an invalid state or // the connection has to be refreshed and refresh it // when necessary if (mySqlConnection == null || mySqlConnection.State == System.Data.ConnectionState.Broken || mySqlConnection.State == System.Data.ConnectionState.Closed || connectionUsageCount &gt;= MAX_CONNECTION_USAGE_COUNT) { // If the connection was already initialized, close and dispose it if (mySqlConnection != null) { // If connection is open, close it if (mySqlConnection.State != System.Data.ConnectionState.Broken &amp;&amp; mySqlConnection.State != System.Data.ConnectionState.Closed) { mySqlConnection.Close(); } mySqlConnection.Dispose(); mySqlConnection = null; } // Create new connection mySqlConnection = new MySqlConnection(this.ConnectionString.ToString()); } } </code></pre> <p>Can anyone review this piece of code and tell provide me with some feedback? I am not sure if I have covered all possibilities that would cause an error when using the <code>mySqlConnection</code>.</p>
[]
[ { "body": "<ol>\n<li><p>As per <a href=\"https://stackoverflow.com/questions/5567097/using-mysqlconnection-in-c-sharp-does-not-close-properly\">this SO question</a> you need to be aware that calling <code>Close</code> will not necessarily actually close the connection but only put it back into the connection pool.</p></li>\n<li><p>There is no reason to do <code>mySqlConnection = null;</code>. You assign a new value to <code>mySqlConnection</code> in the next statement so setting it to <code>null</code> achieves nothing.</p></li>\n<li><p><a href=\"http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html#connector-net-examples-mysqlconnection-close\" rel=\"nofollow noreferrer\">These docs</a> might be somewhat out-dated but they state that you can call <code>Close</code> multiple times and that no exception is generated so you can probably skip the check and just call <code>Close</code> unconditionally.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-12T12:27:29.063", "Id": "357492", "Score": "0", "body": "how about a simple re-binder\n\n if (MySQLcon.State != System.Data.ConnectionState.Open) MySQLcon.Open();" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T10:02:45.520", "Id": "38676", "ParentId": "38675", "Score": "2" } } ]
{ "AcceptedAnswerId": "38676", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T09:39:49.917", "Id": "38675", "Score": "2", "Tags": [ "c#", "mysql" ], "Title": "Checking a MySQL connection and refreshing it" }
38675
<p>I have some Scala code that uses Internet to authorize a user. Therefore, it can throw Exceptions like <code>IOException</code> in the method.</p> <p>The original code was written in Java. So, yes, it uses variables, not <code>val</code>. Also it "returns early" many times if some condition is not satisfied.</p> <p>The following is an example. (The actual code is, of course, a little more complicated.)</p> <pre><code>def connect(): (IdInfo, PasswordInfo, ConnectionInfo) = { var idInfo: IdInfo = null var pwdInfo: PasswordInfo = null var connInfo: ConnectionInfo = null try { idInfo = calcIdInfo() } catch { case ex: IOException =&gt; return null } try { pwdInfo = calcPwdInfo(idInfo) } catch { case ex: AuthorizationException =&gt; return null } try { connInfo = calcConnInfo(idInfo, pwdInfo) } catch { case ex: IOException =&gt; return null } try { verify(idInfo, pwdInfo, connInfo) } catch { case ex: IOException =&gt; return null case ex: AuthorizationException =&gt; return null } (idInfo, pwdInfo, connInfo) } </code></pre> <p>I'm trying to rewrite the code in the functional style. What I did was</p> <ol> <li>Use <code>val</code>s instead of <code>var</code>s</li> <li>Remove "return early"</li> <li>Use <code>None</code> instead of <code>null</code></li> </ol> <p>I tried to use methods like <code>fold</code>, but at each stage, the types of input or the types of output are different - <code>IdInfo</code>, <code>(IdInfo, PasswordInfo)</code>, <code>(IdInfo, PasswordInfo, ConnectionInfo)</code> are all different types - and, what each stage does is also diffrent from each other, so I couldn't use such method.</p> <pre><code>def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val idInfoOpt = try { Some(calcIdInfo()) } catch { case ex: IOException =&gt; None } idInfoOpt map (idInfo =&gt; { val pwdInfoOpt = try { Some(calcPwdInfo(idInfo)) } catch { case ex: AuthorizationException =&gt; None } pwdInfoOpt map (pwdInfo =&gt; { val connInfoOpt = try { Some(calcConnInfo(idInfo, pwdInfo)) } catch { case ex: IOException =&gt; None } connInfoOpt map (connInfo =&gt; { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException =&gt; None case ex: AuthorizationException =&gt; None } }) getOrElse None }) getOrElse None }) getOrElse None } </code></pre> <p>The resultant code is more complex than the original one. There are deeper indentations, and the type of each value is not easy to determine (A lot of <code>Option</code>s and <code>map</code> and <code>getOrElse</code>). In the above example, the code has <code>calc***Info()</code> methods, but in reality the code is more complex since it has more statements between each stage, so there seems almost no reason to use the actual resultant code instead of the original one.</p> <p>I think that the procedural style is better than the functional style in this case. Or not? The more complex the code is, the more chance of errors there will be. Are there better ways to get rid of vars and early returns?</p> <p>For ease, here are compilable source codes (although it does nothing):<br/> The first one: <a href="http://ideone.com/KJS1tn">http://ideone.com/KJS1tn</a><br/> The second one: <a href="http://ideone.com/gulzgs">http://ideone.com/gulzgs</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:35:10.780", "Id": "64557", "Score": "0", "body": "I'm taking a look at Scala right now, so I'm also very interested in an answer. Thanks for asking!" } ]
[ { "body": "<p>After reading the code, I assume these are the signatures of the building blocks of your code</p>\n\n<pre><code>class IdInfo\nclass PasswordInfo\nclass ConnectionInfo\n\ndef calcIdInfo:IdInfo=???\ndef calcPwdInfo(idInfo:IdInfo):PasswordInfo=???\ndef calcConnInfo(idInfo:IdInfo,pwdInfo:PasswordInfo):PasswordInfo=???\n</code></pre>\n\n<p>I left out the implementations for the calc as they don't really matter.</p>\n\n<p>There are several possible variations to improve on the current code. Let's have a look at the last call to map in connect : </p>\n\n<pre><code> connInfoOpt map (connInfo =&gt; {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n }) getOrElse None\n</code></pre>\n\n<p>The try expression has type Option[(IdInfo, PasswordInfo, ConnectionInfo)] which is the type you want as the output of the function <code>connect</code>. As the name connInfoOpt suggests, it is also an option. Map on option has a signature roughly equivalent to : </p>\n\n<pre><code>map(f:A=&gt;B):Option[B]\n</code></pre>\n\n<p>Where A is the type which is wrapped in the original option, and B is the type wrapped in the resulting option. </p>\n\n<p>Thus let's say connInfoOpt has type Option[ConnectionInfo] we get </p>\n\n<pre><code>A = ConnectionInfo\nB = Option[(IdInfo, PasswordInfo, ConnectionInfo)]\n</code></pre>\n\n<p>Therefore the return type of the map expression is <code>Option[B]</code> which can be expanded to </p>\n\n<pre><code>Option[Option[(IdInfo, PasswordInfo, ConnectionInfo)]]\n</code></pre>\n\n<p>Here lies the first problem : to get the Option[(IdInfo, PasswordInfo, ConnectionInfo)] out, you use getOrElse None. A slightly shorter way to express that is to call <code>flatten</code>. </p>\n\n<p>The original expression can thus be rewritten as: </p>\n\n<pre><code> connInfoOpt map (connInfo =&gt; {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n }) flatten\n</code></pre>\n\n<p>which has type Option[(IdInfo, PasswordInfo, ConnectionInfo)]. The next step is to study the option type and see that it has a <code>flatMap</code> method which has the following signature :</p>\n\n<pre><code>flatMap(f:A=&gt;Option[B]):Option[B]\n// for comparison with map which was \nmap(f:A=&gt;B):Option[B]\n</code></pre>\n\n<p>Then notice that each intermediary is step is of the form : </p>\n\n<pre><code>option map { A=&gt; Option[B] } flatten\n</code></pre>\n\n<p>for instance: </p>\n\n<pre><code>connInfoOpt map (connInfo =&gt; {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n}) flatten\n</code></pre>\n\n<p>can be rewritten as : </p>\n\n<pre><code>connInfoOpt flatMap (connInfo =&gt; {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n})\n</code></pre>\n\n<p>Which means the whole function can now be simplified to : </p>\n\n<pre><code> def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {\n val idInfoOpt = try {\n Some(calcIdInfo())\n } catch {\n case ex: IOException =&gt; None\n }\n\n idInfoOpt flatMap (idInfo =&gt; {\n val pwdInfoOpt = try {\n Some(calcPwdInfo(idInfo))\n } catch {\n case ex: AuthorizationException =&gt; None\n }\n\n pwdInfoOpt flatMap (pwdInfo =&gt; {\n val connInfoOpt = try {\n Some(calcConnInfo(idInfo, pwdInfo))\n } catch {\n case ex: IOException =&gt; None\n }\n\n connInfoOpt flatMap (connInfo =&gt; {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n })\n })\n })\n }\n</code></pre>\n\n<p>We got rid of the 3 getOrElse but this still isn't so nice. Let's extract a few methods next to make the code easier to read :</p>\n\n<pre><code>def safeIdInfo():Option[IdInfo]={\n try {\n Some(calcIdInfo())\n } catch {\n case ex: IOException =&gt; None\n }\n}\n\ndef verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {\n try {\n verify(idInfo, pwdInfo, connInfo)\n Some(idInfo, pwdInfo, connInfo)\n } catch {\n case ex: IOException =&gt; None\n case ex: AuthorizationException =&gt; None\n }\n}\n\ndef safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Option[ConnectionInfo] = {\n try {\n Some(calcConnInfo(idInfo, pwdInfo))\n } catch {\n case ex: IOException =&gt; None\n }\n}\n\ndef safePwdInfo(idInfo: IdInfo): Option[PasswordInfo] = {\n try {\n Some(calcPwdInfo(idInfo))\n } catch {\n case ex: AuthorizationException =&gt; None\n }\n}\n</code></pre>\n\n<p>then the connect method looks like : </p>\n\n<pre><code>def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {\n safeIdInfo() flatMap (idInfo =&gt;\n safePwdInfo(idInfo) flatMap (pwdInfo=&gt;\n safeConnInfo(idInfo, pwdInfo) flatMap (connInfo =&gt;\n verifyConnInfo(idInfo, pwdInfo, connInfo)\n )\n )\n )\n}\n</code></pre>\n\n<p>Which is better but not perfect. Let's apply some scala syntactic sugar : </p>\n\n<pre><code>def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { \n for{\n idInfo &lt;- safeIdInfo()\n pwdInfo &lt;- safePwdInfo(idInfo)\n connInfo &lt;- safeConnInfo(idInfo, pwdInfo)\n verified &lt;- verifyConnInfo(idInfo, pwdInfo, connInfo)\n } yield verified \n} \n</code></pre>\n\n<p>The connect method is much better (I think) but we end up with repetition in the \"safe\" methods. Actually, Scala offers a type to reduce this duplication, the <code>Try</code> type which we will use to replace the Option type in the \"safe\" methods :</p>\n\n<pre><code>def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try {\n verify(idInfo, pwdInfo, connInfo)\n (idInfo, pwdInfo, connInfo)\n}\ndef safeIdInfo():Try[IdInfo]=Try(calcIdInfo()) \ndef safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo))\ndef safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo))\n</code></pre>\n\n<p>Of course doing this, the <code>connect</code> method is no longer valid at the type level it needs to be adapted. To match the exact behavior of the original code the adaptation will look like : </p>\n\n<pre><code> def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { \n val tryVerified = for{\n idInfo &lt;- safeIdInfo()\n pwdInfo &lt;- safePwdInfo(idInfo)\n connInfo &lt;- safeConnInfo(idInfo, pwdInfo)\n verified &lt;- verifyConnInfo(idInfo, pwdInfo, connInfo)\n } yield verified\n\n tryVerified match {\n case Success(value) =&gt; Some(value)\n case Failure(authException:AuthorizationException)=&gt; None\n case Failure(ioException:IOException)=&gt; None\n case Failure(failed)=&gt; throw failed\n }\n } \n</code></pre>\n\n<p>However I will suppose that you don't really want to rethrow unknown runtime exceptions and instead want to return None for any error, in which case the following form of connect should work : </p>\n\n<pre><code> def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { \n val tryVerified = for{\n idInfo &lt;- safeIdInfo()\n pwdInfo &lt;- safePwdInfo(idInfo)\n connInfo &lt;- safeConnInfo(idInfo, pwdInfo)\n verified &lt;- verifyConnInfo(idInfo, pwdInfo, connInfo)\n } yield verified\n\n tryVerified.toOption\n } \n</code></pre>\n\n<p>The complete code is now :</p>\n\n<pre><code> def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try {\n verify(idInfo, pwdInfo, connInfo)\n (idInfo, pwdInfo, connInfo)\n }\n def safeIdInfo():Try[IdInfo]=Try(calcIdInfo())\n def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo))\n def safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo))\n\n def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { \n val tryVerified = for{\n idInfo &lt;- safeIdInfo()\n pwdInfo &lt;- safePwdInfo(idInfo)\n connInfo &lt;- safeConnInfo(idInfo, pwdInfo)\n verified &lt;- verifyConnInfo(idInfo, pwdInfo, connInfo)\n } yield verified\n\n tryVerified.toOption\n } \n</code></pre>\n\n<p>Using the right types, a functional style and some syntactic sugar can go a long way to simplify your code :)</p>\n\n<p>For further reference, check the scala doc for <a href=\"http://www.scala-lang.org/api/current/index.html#scala.Option\">Option</a> and <a href=\"http://www.scala-lang.org/api/current/index.html#scala.util.Try\">Try</a>, also check out the <a href=\"http://docs.scala-lang.org/tutorials/FAQ/yield.html\">FAQ on yield</a> for more explanations on the for-expression syntactic sugar. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:07:10.877", "Id": "64585", "Score": "1", "body": "It's far tidier than I expected. I haven't seen any codes with scala.util.Try (maybe because it is new in scala 2.10), and it also seems good to know about. Thanks for the detailed answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:16:12.527", "Id": "64589", "Score": "0", "body": "Great answer. I was working on something similar, but you beat me to the punch (and wrote it up much better anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:22:01.440", "Id": "64590", "Score": "0", "body": "Try is indeed new in scala 2.10, it is not very widely used for a few reasons : functional programming usually avoids using exceptions and there are better types than Try to handle success/failure when the failure is not an exception. The Future type is more widely used, handles exceptions _and_ asynchronous computation. In many places the code which interacts with java was written before try was available and was not rewritten. You can find occurrences of Try in the akka and playframework code bases if you look for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T11:10:48.880", "Id": "67477", "Score": "0", "body": "Very nice solution. I'd suggest inlining all the methods and the `tryVerified` as I don't see what they add and are short enough to be inlined. You can then remove the curly braces from `connect` resulting in a one line, and readable, solution." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T14:44:59.857", "Id": "38698", "ParentId": "38689", "Score": "19" } } ]
{ "AcceptedAnswerId": "38698", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:25:53.763", "Id": "38689", "Score": "20", "Tags": [ "functional-programming", "scala" ], "Title": "Code with many \"early returns (exits)\" into the functional style" }
38689
<p>By outer-package, I mean outside of this package - this can be the DOM or other packages. This package has a basic event system and a basic registry. It also has a debugger which allows you to fiddle with the DOM by removing and adding entire sets of tags. Later it might have things which allow it to Debug / Configure the server via ajax.</p> <p>Please review all aspects of this code.</p> <pre><code>/*************************************************************************************************** **COMS ** provides registry, event system, debugger ... ** reduces dependencies ***************************************************************************************************/ (function () { "use strict"; var $A, // public $P = {}; // require utility (function manageGlobal() { if (window.$A &amp;&amp; window.$A.pack &amp;&amp; window.$A.pack.utility) { $A = window.$A; $A.pack.comms = true; } else { throw "comms requires utility module"; } }()); $P.Debug = (function () { var publik = {}, hold = {}; publik.addTags = function (tag) { if (hold[tag]) { $A.someIndex(hold[tag], function (val) { if (tag === 'script' || tag === 'style') { document.head.appendChild(val); } else { document.body.appendChild(val); } }); } }; publik.removeTags = function (tag) { var styles = document.getElementsByTagName(tag), i; hold[tag] = []; for (i = styles.length; i; i--) { hold[tag][i] = styles[i]; $A.removeElement((styles[i])); } }; publik.removeStorage = function () { localStorage.clear(); sessionStorage.clear(); }; return publik; }()); // a basic registry pattern with get/set and getMany/setMany $P.Reg = (function () { var publik = {}, register = {}; publik.get = function (key) { return register[key]; }; publik.set = function (key, value) { register[key] = value; }; publik.setMany = function (o) { $A.someKey(o, function (val, key) { register[key] = val; }); }; publik.getMany = function () { return register; }; return publik; }()); // a basic event system using an internal bus $P.Event = (function () { var publik = {}, events = {}; publik.add = function (name, callback) { if (!events[name]) { events[name] = []; } events[name].push(callback); }; publik.remove = function (name, callback) { if (name &amp;&amp; callback) { delete events[name][callback]; } else if (name) { delete events[name]; } }; publik.trigger = function (name) { if (events[name]) { $A.someIndex(events[name], function (val) { val(); }); } }; return publik; }()); window.$A = $A.extendSafe($A, $P); }()); </code></pre>
[]
[ { "body": "<p>The below code would be cleaner with object literal notation :</p>\n\n<pre><code> // a basic registry pattern with get/set and getMany/setMany\n $P.Reg = (function () {\n var publik = {},\n register = {};\n publik.get = function (key) {\n return register[key];\n };\n publik.set = function (key, value) {\n register[key] = value;\n };\n publik.setMany = function (o) {\n $A.someKey(o, function (val, key) {\n register[key] = val;\n });\n };\n publik.getMany = function () {\n return register;\n };\n return publik;\n }());\n</code></pre>\n\n<p>would be</p>\n\n<pre><code> // a basic registry pattern with get/set and getMany/setMany\n $P.Reg = (function () {\n var register = {};\n return {\n get : function (key) {\n return register[key];\n },\n set : function (key, value) {\n register[key] = value;\n },\n setMany : function (o) {\n $A.someKey(o, function (val, key) {\n register[key] = val;\n });\n },\n getMany : function () {\n return register;\n }\n };\n }());\n</code></pre>\n\n<p>I also note that</p>\n\n<ul>\n<li>getMany is wrongly named, getAll perhaps ?</li>\n<li>not sure what <code>someKey</code> does, is it any different from <code>for( var key in o)</code> ?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T14:58:33.277", "Id": "64582", "Score": "1", "body": "`some()` applies a test before executing the callback, you seem to have cloned `forEach()`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T14:43:21.703", "Id": "38697", "ParentId": "38692", "Score": "3" } }, { "body": "<p>I agree <a href=\"https://codereview.stackexchange.com/a/38697/2634\">object notation would look cleaner</a> in this case.</p>\n\n<p>I don't see why you need <code>Reg</code>. It's a very thin wrapper over an object.<br>\nThere's no need to implement “registry pattern” in JS because every JS object already <em>is</em> a “registry”.</p>\n\n<p>I'm not sure why you need a <code>Debug</code> helper that loads and unloads external scripts or styles. In fact, I don't understand its purpose at all: <code>addTags</code> accepts a <code>tag</code> parameter, which presumably is a string (you're using it as a key), but supposedly the first call will do nothing, since <code>hold[tag]</code> will be empty. Do I need to call <code>removeTags</code> first? What is a tag anyway? The code seems simple, but I fail to understand what it does and how you use it. Maybe you need to ditch simple names in favor of more descriptive ones?</p>\n\n<p>As for putting these utilities under a common umbrella of a “package for outer-package communications”, I stay unconvinced. These utilities have little to do with each other, and the way you describe it, grouping them doesn't sound convincing.</p>\n\n<blockquote>\n <p>By outer-package, I mean outside of this package - this can be the DOM or other packages. This package has a basic event system and a basic registry. It also has a debugger which allows you to fiddle with the DOM by removing and adding entire sets of tags. Later it might have things which allow it to Debug / Configure the server via ajax.</p>\n</blockquote>\n\n<p>It may <em>seem</em> like each module needs a registry, or some debug tools, or event system, but you can already achieve this without grouping them:</p>\n\n<ul>\n<li><p>put Pubsub separately and make it a mixin like <a href=\"http://backbonejs.org/#Events\" rel=\"nofollow noreferrer\">Backbone.Events</a>;</p></li>\n<li><p>debug tools can also be kept separately;</p></li>\n<li><p>any JS object is a “registry” so no real need for that.</p></li>\n</ul>\n\n<p>Otherwise, to me, this package looks like a “<a href=\"http://en.wikipedia.org/wiki/God_object\" rel=\"nofollow noreferrer\">God</a> module”. </p>\n\n<p>Not that there's something wrong with it, if you <em>meant</em> it to be all-the-utilities-I-will-ever-need kind of module. I wasn't sure from your question if you meant it.</p>\n\n<p>The nice thing about separating even small utilities is that you can</p>\n\n<ul>\n<li><p>open source them because they are decoupled from your code, and others can hack on them;</p></li>\n<li><p>replace them one by one with different implementations;</p></li>\n<li><p>they are immune to “specifics creep”, i.e. the situation when over time your once-generic utilities become too tightly coupled to one specific project, and grow too difficult to disentangle so you have to rewrite them once again for your next project.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T20:56:34.287", "Id": "38717", "ParentId": "38692", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T13:28:11.597", "Id": "38692", "Score": "2", "Tags": [ "javascript", "library" ], "Title": "A package for outer-package communications" }
38692
<p>Compare to <a href="http://underscorejs.org/" rel="nofollow">underscorejs</a> if it pleases you. Once again, I hope this is well commented. Please let me know what comments/improvements I can add.</p> <p>Please review all aspects of this code.</p> <pre><code>/*************************************************************************************************** **UTILITY - additional coverage for looping, type checking, extending ... - consistent ordering, naming conventions ... - fewer function branches - increased type checking and modularity - vector based unit testing ***************************************************************************************************/ // self used to hold client or server side global ( window or exports ) (function (self, undef) { "use strict"; // holds (P)ublic properties var $P = {}, // holds p(R)ivate properties $R = {}, // native methods (alphabetical order) nativeFilter = Array.prototype.filter, nativeIsArray = Array.isArray, nativeSlice = Array.prototype.slice, nativeSome = Array.prototype.some, nativeToString = Object.prototype.toString; $P.noConflict = (function () { // $R.g holds the single global variable, used to hold all packages // methods $R.g = '$A'; $R.previous = self[$R.g]; // utility is required by all other packages // start the "pack"age list $P.pack = { utility: true }; return function () { var temp = self[$R.g]; self[$R.g] = $R.previous; return temp; }; }()); $P.isType = function (type, obj) { return $P.getType(obj) === type; }; // returns type in a captialized string form // typeof is only accurate for function, string, number, boolean, and // undefined. null and array are both incorrectly reported as object $P.getType = function (obj) { return nativeToString.call(obj).slice(8, -1); }; $P.isFalse = function (obj) { return obj === false; }; $P.isUndefined = function (obj) { return obj === undef; }; $P.isNull = function (obj) { return obj === null; }; $P.isNumber = function (value) { return (typeof value === 'number') &amp;&amp; isFinite(value); }; // detects null or undefined $P.isGone = function (obj) { return obj == null; }; // detects anything but null or undefined $P.isHere = function (obj) { return obj != null; }; // detects null, undefined, NaN, ('' ""), 0, -0, false $P.isFalsy = function (obj) { return !obj; }; // detects any thing but null, undefined, NaN, ('' ""), 0, -0, false $P.isTruthy = function (obj) { return !!obj; }; // shortcut as their are only two primitive boolean values // detects a "boxed" boolean as well $P.isBoolean = function (obj) { return obj === true || obj === false || nativeToString.call(obj) === '[object Boolean]'; }; // delegates to native $P.isArray = nativeIsArray || function (obj) { return nativeToString.call(obj) === '[object Array]'; }; // jslint prefers {}.constructor(obj) over Object(obj) $P.isObjectAbstract = function (obj) { // return obj === Object(obj); return !!(obj &amp;&amp; (obj === {}.constructor(obj))); }; // has a numeric length property $P.isArrayAbstract = function (obj) { return !!(obj &amp;&amp; obj.length === +obj.length); }; $P.someIndex = function (arr, func, con) { var ind, len; // prevent type errors, note function is validated if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) { return; } // delegate to native some() if (nativeSome &amp;&amp; arr.some === nativeSome) { return arr.some(func, con); } // if the function passes back a truthy value, the loop will terminate for (ind = 0, len = arr.length; ind &lt; len; ind++) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; $P.someKey = function (obj, func, con) { var key; // prevent type errors // for-in will filter out null and undefined if ((obj == null) || (typeof func !== 'function')) { return; } for (key in obj) { if (obj.hasOwnProperty(key)) { // if the function passes back a truthy value, // the loop will terminate if (func.call(con, obj[key], key, obj)) { return true; } } } return false; }; // loop through space separated "tokens" in a string $P.eachString = function (str, func, con) { // prevent type errors if (typeof str !== 'string' || str === "" || typeof func !== 'function') { return; } $P.someIndex(str.split(/\s+/), func, con); }; // does not extend through the prototype chain // implemented for objects only $P.extend = function (obj) { // loop througth elements beyond obj $P.someIndex(nativeSlice.call(arguments, 1), function (val) { // extend it $P.someKey(val, function (val_inner, key) { obj[key] = val_inner; }); }); return obj; }; // extends non-prototype properties from obj2 on to obj1 $P.extendSafe = function (obj1, obj2) { var key; for (key in obj2) { if (obj2.hasOwnProperty(key)) { if (obj1.hasOwnProperty(key)) { throw "naming collision: " + key; } obj1[key] = obj2[key]; } } return obj1; }; // if incorrect types are passed, it will return an empty array // arrays only $P.filter = function (arr, func, con) { var results = []; if ((arr == null) || (typeof func !== 'function')) { return results; } if (nativeFilter &amp;&amp; arr.filter === nativeFilter) { return arr.filter(func, con); } $P.someIndex(arr, function (val, ind, arr) { if (func.call(con, val, ind, arr)) { results.push(val); } }); return results; }; $P.clone = function (obj) { return $P.extend({}, obj); }; $P.someIndex(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object'], function (val) { $P['is' + val] = function (obj) { return $P.isType(val, obj); }; }); $P.addU = function (str, suf) { return str + '_' + suf; }; $P.removeU = function (str) { if (typeof str !== 'string' || str === "") { return false; } return str.slice(str, str.lastIndexOf("_")); }; $P.removeSuffix = function (str, len) { if (typeof str !== 'string' || str === "") { return false; } return str.slice(0, -len); }; // equivalent to IIFE but "nicer" syntax $P.runTest = (function () { var tests = {}; return function (name, arr, func) { tests[name] = func.apply(this, arr); }; }()); self[$R.g] = $P.extendSafe($P, {}); // this will hold the global object - window or exports }(this)); </code></pre> <p><strong><code>someIndex()</code> and <code>someKey()</code> compared to underscore <code>each()</code></strong></p> <p>So the way I chose to write <code>someIndex()</code> and <code>someKey()</code> was organically or as a process. I wanted to abstract the looping idioms I got tired of writing into methods. Because <code>for</code> and <code>for-in</code> can be broke out of I decided that <code>some()</code> was a better building block then <code>each()</code> from my perspective. After, I did this I compared what I had to underscore. My design choices were different in other ways as well. -- Please note, if you need speed just use a for or for-in loop, if you need clean concise code, use the abstraction -- The other way I diverged from underscore is that I wrote some separately for arrays and objects, because when I code I always know which one I am looping through, hence I wanted to express this knowledge in my code - someIndex() and someKey(). Another way I diverged was that I type check all the inputs in one line, for some reason underscore chooses not to type check the callback function. The other way I diverged is I don't check for any internal breaks, that are internal use only, in underscore this is shown as an equality check for <code>breaker</code>. Also, as in all my code b.c. JS is not block scoped yet, I put my var definitions up top.</p> <p>Also, regarding elegance, I feel my code is more elegant, as the type checking is consistent and consolidated, my var declarations are more naturally inline with how the interpreter reads them, and comments, white space, and a 4 space indent level make the code easier to read.</p> <p>That's the gist of it, please let me know if I can elaborate more.</p> <p>Below is the code for both:</p> <pre><code> $P.someIndex = function (arr, func, con) { var ind, len; // prevent type errors, note function is validated if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) { return; } // delegate to native some() if (nativeSome &amp;&amp; arr.some === nativeSome) { return arr.some(func, con); } // if the function passes back a truthy value, the loop will terminate for (ind = 0, len = arr.length; ind &lt; len; ind++) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach &amp;&amp; obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i &lt; length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i &lt; length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } }; </code></pre>
[]
[ { "body": "<p>The code itself looks somewhat clean, but I'd say it lacks the <a href=\"http://underscorejs.org/docs/underscore.html\" rel=\"nofollow\">elegancy of Underscore</a>.</p>\n\n<p>Your (P)ublic / P(r)ivate convention is very weird; I can't train my eyes to tell <code>$R</code> from <code>$P</code> quickly.<br>\nDid you invent it yourself? Why do you use it at all? Private functions are hidden by scope anyway.</p>\n\n<p>Don't throw strings for errors, throw <code>new Error(message)</code> instead. Errors preserve stack trace.</p>\n\n<p>Also, I'd say the design goal isn't clear. </p>\n\n<p>Underscore positions itself as <em>the</em> minimal toolset for manipulating JS basic types (objects, arrays, functions). Lo-dash positions itself as Underscore with options (e.g. it has deep cloning)—some like it, some think it does too much and lacks Underscore's simplicity.</p>\n\n<p>These are two very different approaches, and different developers choose different libs. </p>\n\n<p>Where does your library stand on this spectrum? Is this a learning project? On one hand, you have “basic” Underscorish functions like <code>isArray</code> and <code>extend</code>, but then you also offer arguably exotic functions like <code>eachString</code>, <code>someKey</code> or <code>addU</code>. They are hardly “minimal toolset”, and honestly, I don't understand what they do.</p>\n\n<p>So what was your design goal?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T18:51:26.817", "Id": "38712", "ParentId": "38695", "Score": "3" } }, { "body": "<p>I don't use underscore, so I am more or less naive about what you're meaning to accomplish and how it might look otherwise. Instead, from a consumer perspective, I am comparing/contrasting this utility with not having it only.</p>\n\n<p>I am assuming \"all aspects\" includes code quality from the perspective of maintaining, reading, or extending the code as well, and I'll start there. </p>\n\n<p>Reading this is made somewhat more challenging due to the similar-looking <code>$P</code> and <code>$R</code>. I believe this has been mentioned by another reviewer, but I would like to offer some workarounds. I assume that you do need an object for <code>$R</code> - if you don't, you should follow a previous reviewer's advice and be rid of it - to loop over its keys or use it as a prototype or dump it on the console at some point. It's okay to provide an abbreviated global name to consumers (<code>$A</code> for your library), but it doesn't pay to do it in your own scope. Even <code>pub</code> and <code>priv</code> are more easily distinguishable, immediately clear in their purpose, and if you count the shift key, it only costs you one keystroke per typed pair.</p>\n\n<p>Speaking of saving and losing keystrokes, <code>foo === false</code> actually requires fewer keystrokes than <code>$A.isFalse(foo)</code>. The same goes for <code>isUndefined</code>, <code>isNull</code>, <code>isHere</code>, and <code>isGone</code>. I've seen some other libraries do stuff like that, so you're not alone in this, but I've never found a use for any of it. That goes double, though, for <code>isTruthy</code> and <code>isFalsy</code>. I can't imagine wanting to spell that out. Just curious - why is there an explicit spell-it-out test function for everything but <code>true</code>? I guess if I was trying to maintain code written by real neanderthals that I didn't trust at all, it would be reassuring to see what they were intending to test explicitly in every conditional. In any case, it's more bondage &amp; discipline than utility, and you can tell by how little use you get out of these functions throughout the rest of the code.</p>\n\n<p>There are lots of opportunities to use those functions. There are <em>many</em> cases where the body of those <code>isFoo</code> functions as well as <code>getType</code> and <code>isType</code> appear repeated verbatim, with precisely the same intent. Normally, I would say it's overkill to call repeated simple boolean expressions a failure to DRY, but that's the point of your library, right? You wrote those functions because they're useful code, so <em>use</em> them.</p>\n\n<p>The function <code>isNumber</code> returns false for boxed numbers. If there's a reason for that, you should probably add a comment about it and document it somewhere, or someone might assume that if <code>$A.getType(n) === 'Number'</code> then <code>$A.isNumber(n) === true</code>, since if <code>$A.getType(b) === 'Boolean'</code> then <code>$A.isBoolean(b) === true</code>.</p>\n\n<p>I would rather see <code>Object.keys(obj).forEach</code> in <code>someKey</code> instead of using native for-in and filtering with <code>hasOwnProperty</code>. It takes up less vertical space, restricts the scope of <code>key</code> to the block that should be using it, and does the very same thing. I can read what you have, and it works, though. Just a matter of preference.</p>\n\n<p>If I understand it correctly, the difference between <code>Array.prototype.forEach</code> and your <code>someIndex</code> is that the iteration of <code>someIndex</code> can be ceased from within the callback by returning truth-y. I would then expect, when I read code that uses <code>someIndex</code> and not <code>forEach</code>, that you are scanning an array to find something and intend to stop at some point. However, you go on to use the <code>some</code> functions in <code>extend</code> and <code>filter</code> where the intent of the loop is to iterate over all keys or array elements. It does show that you have a useful function, but it also reads a little hack-y. Each time I read it, I spend a second or two looking for a <code>return</code> to determine what you're looking for, only to realize that you just aren't using <code>forEach</code>.</p>\n\n<p>I can't really comment on all the suffixes and underscores because, if they belong in the utility at all, they're tools specific to the rest of the project. Seeing <code>slice</code>, tokenizing, and meaningful underscores with no regex or grammar in sight makes me a little nervous (long story, code-based parsers are bad) but I have no idea what you're really using it for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:27:48.270", "Id": "38751", "ParentId": "38695", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T13:41:22.740", "Id": "38695", "Score": "0", "Tags": [ "javascript", "underscore.js" ], "Title": "Utility package comparable to underscores.js" }
38695
<p>Can this be improved?</p> <pre><code>foreach (Gift gift in usedGifts) { foreach (GiftTransaction GiftTransaction in gift.GiftTransactions) { if (!string.IsNullOrEmpty(giftTransaction.GiftId) &amp;&amp; !orderList.Where(b =&gt; b.GiftId == giftTransaction.GiftId).Any()) { Order order = OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, giftTransaction.GiftId); if (order != null) orderList.Add(order); } } giftReferenceList.Add(gift.GiftReference); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:09:26.163", "Id": "64587", "Score": "2", "body": "please provide more information on what you want improved. and probably more surrounding code for context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:24:42.843", "Id": "64593", "Score": "1", "body": "Optimizing for performance? Your question is not really clear here. Fairly common refactoring ideas could be found in questions like http://stackoverflow.com/questions/2433679/refactoring-nested-foreach-statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:28:19.530", "Id": "64595", "Score": "0", "body": "I want to improve the speed for the query... but I will try to provide more details soon" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:54:48.850", "Id": "64598", "Score": "1", "body": "You can replace the line `!orderList.Where(b => b.GiftId == giftTransaction.GiftId).Any()` with `!orderList.Any(b => b.GiftId == giftTransaction.GiftId)` for what it's worth." } ]
[ { "body": "<p>I'm not sure if it will make your query faster but here is my take on it:</p>\n\n<p>If I read the code correctly you want to create orders for all gift transactions related to gift ids which are not covered by an order yet.</p>\n\n<pre><code>usedGifts.SelectMany(g =&gt; g.GiftTransactions)\n .Select(gt =&gt; gt.GiftId)\n .Where(gi =&gt; !string.IsNullOrEmpty(gi))\n .Except(orderList.Select(o =&gt; o.GiftId)) // This will yield all gift ids which are not covered by an order\n .Select(gi =&gt; OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, gi)) // generate the orders\n .Where(o =&gt; o != null)\n .ToList();\n</code></pre>\n\n<p>Unfortunately this requires an extra pass over the <code>usedGifts</code> list to add all the references</p>\n\n<pre><code>giftReferenceList.AddRange(usedGifts.Select(g =&gt; g.GiftReference));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T19:40:20.433", "Id": "38715", "ParentId": "38700", "Score": "7" } } ]
{ "AcceptedAnswerId": "38715", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T15:04:42.860", "Id": "38700", "Score": "3", "Tags": [ "c#" ], "Title": "Creating orders for gift transactions" }
38700
<p>I recently had the need of "reflecting" multiple <code>enum class</code> constructs in order to get their elements' names as <code>std::string</code> objects or their element count. I came up with a C++11 variadic macro solution:</p> <pre><code>namespace ssvu { namespace Internal { inline std::vector&lt;std::string&gt; getSplittedEnumVarArgs(const std::string&amp; mEnumVarArgs) { std::vector&lt;std::string&gt; result; // getSplit returns a collection of substrings split at a certain token // Example: "a,b,c" -&gt; {"a", "b", "c"} // getTrimmedStrLR removes whitespace from the beginning and the end of a string // Example: " abc " -&gt; "abc" for(const auto&amp; s : getSplit(mEnumVarArgs, ',')) result.emplace_back(getTrimmedStrLR(std::string(std::begin(s), find(s, '=')))); return result; } template&lt;typename&gt; struct ReflectedEnumImpl; template&lt;template&lt;typename&gt; class T, typename TEnum&gt; struct ReflectedEnumImpl&lt;T&lt;TEnum&gt;&gt; { using EnumType = T&lt;TEnum&gt;; inline static const std::vector&lt;std::string&gt;&amp; getElementsAsStrings() noexcept { static std::vector&lt;std::string&gt; result(getSplittedEnumVarArgs(EnumType::getEnumString())); return result; } inline static std::size_t getElementCount() noexcept { return getElementsAsStrings().size(); } inline static const std::string&amp; getElementAsString(TEnum mElement) noexcept { // If the user changed the default enum values by using the `= ...' // syntax, this function will return wrong values and possibly // go out of bounds. Maybe this should throw an exception. assert(!contains(EnumType::getEnumString(), '=')); return getElementsAsStrings()[std::size_t(mElement)]; } }; } #define SSVU_REFLECTED_ENUM_DEFINE_MANAGER(mName) template&lt;typename&gt; class mName #define SSVU_REFLECTED_ENUM(mManagerName, mName, mUnderlying, ...) enum class mName : mUnderlying { __VA_ARGS__ }; \ template&lt;&gt; class mManagerName&lt;mName&gt; : public ssvu::Internal::ReflectedEnumImpl&lt;mManagerName&lt;mName&gt;&gt; \ { \ friend ssvu::Internal::ReflectedEnumImpl&lt;mManagerName&lt;mName&gt;&gt;; \ inline static const std::string&amp; getEnumString(){ static std::string result{#__VA_ARGS__}; return result; } \ } } </code></pre> <hr> <p>Example usage:</p> <pre><code>SSVU_REFLECTED_ENUM_DEFINE_MANAGER(ReflectedEnum); SSVU_REFLECTED_ENUM(ReflectedEnum, Colors, int, Red, Yellow, Green); void tests() { assert(int(Colors::Red) == 0); assert(int(Colors::Yellow) == 1); assert(int(Colors::Green) == 2); assert(ReflectedEnum&lt;Colors&gt;::getElementAsString(Colors::Red) == "Red"); assert(ReflectedEnum&lt;Colors&gt;::getElementAsString(Colors::Yellow) == "Yellow"); assert(ReflectedEnum&lt;Colors&gt;::getElementAsString(Colors::Green) == "Green"); } </code></pre> <hr> <p>What do you think?</p> <p>Thoughts/questions:</p> <ul> <li><p>Consider the case where the user defines custom values for the enum elements:</p> <pre><code>SSVU_REFLECTED_ENUM(ReflectedEnum, Test, int, A = -2, B = 15, C = 0); </code></pre> <p>Getting element count would still be possible, as it's easy to count variadic macro elements. However, getting an element's name as a string would require using a <code>std::map</code> instead of an array. Should I figure out a way to detect if the enum has custom values? Or should I ditch the array for an <code>std::map</code> altogheter?</p> <p>Or would an alternative syntax be better? Example:</p> <pre><code>SSVU_REFLECTED_CUSTOM_ENUM(ReflectedEnum, Test, int, A, -2, B, 15, C, 0); </code></pre> <p>Maybe this would be more flexible and easier to work with.</p></li> <li><p>I have macro variadic args iteration facilities in my <a href="https://github.com/SuperV1234/SSVUtils">ssvu library</a>. Do you think it's worthwhile figuring out a way to generate the enum string elements array at compile-time with macro metaprogramming? Or is the current solution good enough?</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T18:07:48.483", "Id": "64608", "Score": "0", "body": "[**Abusing the preprocessor is a lot of fun**](http://pastebin.com/0qjynriq)" } ]
[ { "body": "<p>Just a few things to point out:</p>\n\n<ul>\n<li><p>There's no need to use <code>inline</code> yourself. For modern compilers, it merely serves as a suggestion, but they can otherwise determine if and when it's really needed. Read <a href=\"https://stackoverflow.com/questions/145838/benefits-of-inline-functions-in-c\">this</a> for more info.</p></li>\n<li><p>You should use consistent naming for your <code>namespace</code>s (one is lowercase and the other is uppercase). I'd <em>not</em> use uppercase as it's commonly used for user-defined types.</p></li>\n<li><p><code>getElementCount()</code>, like the other accessors here, should also return <code>const</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T08:24:13.027", "Id": "80689", "Score": "1", "body": "I would even recommand to use the name `details` instead of `Internal`. It is commonly used to hide implementation details." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T03:09:00.233", "Id": "46229", "ParentId": "38703", "Score": "9" } } ]
{ "AcceptedAnswerId": "46229", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T16:15:23.993", "Id": "38703", "Score": "8", "Tags": [ "c++", "c++11", "reflection", "enum", "macros" ], "Title": "Variadic macro enum class \"reflection\" in C++11" }
38703
<p>I have been trying to solve <a href="http://projecteuler.net/problem=35">Project Euler problem number 35</a>. The problem is to find:</p> <blockquote> <p>How many circular primes are there below one million?</p> </blockquote> <p>A circular prime is a prime where all the rotations of its digits are primes too. E.g. 197 is a circular prime as 197, 971, and 719 are all primes too.</p> <p>Initially I was "brute-forcing" it by checking for divisors of the number up to its square root. However, I've realised how inefficient this was when the browser crashed above 10,000. Then I've tried using the Sieve of Eratosthenes, and now it can calculate the primes up to 1 million in ~4 seconds.</p> <p>However, the part that is still to inefficient is the function to check if the primes are circular. I have made a few changes, but the browser still crashes above 100,000. What extra changes can I make?</p> <pre><code>//Erastosthenes sieve function findPrimes(range) { var numbers = [1]; var prime = 2; var primesArr = [2] //Stop searching once prime is as big as range while(prime &lt; range) { //Fill var numbers all mulitipes of prime for(var i = 1; i &lt;= range &amp;&amp; prime * i &lt;= range ; ++i) { numbers[prime * i - 1] = prime * i; } //Move onto the next prime while(numbers[prime-1] !== undefined) { ++prime; } //Add current prime to the array primesArr.push(prime); } //Delete the last prime which is bigger than range primesArr.pop(); return primesArr; } //Find primes within range which are circular primes function findCircularPrimes(range) { //Generate array of primes from findPrimes array var primes = findPrimes(range); var circularPrimes = []; //Loop through each of the primes for(var i = 0; i &lt; primes.length; ++i) { //Split current prime into an array var numArr = primes[i].toString().split(''); var truefalse = true; //Cycle through each of the digits and check if its a prime (and therefore a member of primes) for (var j = 0; j &lt; numArr.length; ++j) { numArr.push(numArr.shift()); //If current rotation is not a prime break the loop and 'return' false if (primes.indexOf(Number(numArr.join(''))) === -1) { truefalse = false; break; } } //If truefalse variable is true add circular prime to array if(truefalse) { circularPrimes.push(primes[i]); } } return circularPrimes; } var then = Date.now(); var primes = findCircularPrimes(100000).length alert(primes); </code></pre>
[]
[ { "body": "<p><strong>Updated</strong> since reading the <a href=\"http://en.wikipedia.org/wiki/Circular_prime\" rel=\"nofollow noreferrer\">wikipedia definition of circular prime</a> </p>\n\n<p>There are a few things I would recommend you change in your <code>findCircularPrimes</code> algorithm. First, you should note the algorithm is <code>O(d*n^2)</code> where <code>d</code> is the length of the max digit. If we use a hash instead of an array to store all the primes we can stop using <code>.indexOf()</code> to check if a number is prime, making our algorithm <code>O(d*n)</code>. </p>\n\n<p>Another note is that javascript will represent large numbers in scientific notation. This is probably not important as your algorithm will crash the browser before it becomes an issue :)</p>\n\n<p>I've re-implemented your algorithm using <code>es5</code> methods <code>reduce</code> to create the <code>primeHash</code> and <code>filter</code> to produce the <code>circularPrime</code> list, but your old approach will work as well.</p>\n\n<p><strong>Edit</strong> stole <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">@200_success</a> much faster <code>rotate</code> function to make the comparison a bit fairer and updated the jsperf :)</p>\n\n<pre><code>var LN10 = Math.log(10);\n// Rotates the least-significant base-10 digit to the front\nfunction rotate(number) {\n return (number / 10 &gt;&gt; 0) +\n (number % 10) * Math.pow(10, Math.floor(Math.log(number) / LN10));\n}\n//Find primes within range which are circular primes\nfunction findCircularPrimes(range) {\n\n var primes = findPrimes(range);\n\n //use a hash of primes for faster lookup\n var primeHash = primes.reduce(function(memo, prime) {\n memo[prime] = true;\n return memo;\n }, {});\n\n //use a hash of primes for faster lookup\n var circularPrimes = primes.filter(function(prime) {\n //check ciruclar primes\n var nextDigit = prime;\n while( (nextDigit = rotate(nextDigit)) !== prime) {\n if(! (nextDigit in primeHash)) {\n return false;\n }\n }\n\n return true;\n });\n\n return circularPrimes;\n}\n</code></pre>\n\n<p><a href=\"http://jsperf.com/circular-primes/3\" rel=\"nofollow noreferrer\">Performance test of your implementation vs mine</a> (<a href=\"http://jsbin.com/iMUWIQU/1\" rel=\"nofollow noreferrer\">original set of tests</a>)</p>\n\n<p><img src=\"https://i.stack.imgur.com/YpOvo.png\" alt=\"Chrome perf\">\n<img src=\"https://i.stack.imgur.com/fOClM.png\" alt=\"Firefox perf\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T00:12:29.590", "Id": "64663", "Score": "0", "body": "The Project Euler question asks for circular primes below 1,000,000. Your jsPerf only goes up to 100,000. I've added my code to your jsPerf in [Rev 2](http://jsperf.com/circular-primes/2), keeping the 100,000 upper bound for consistency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T00:13:37.767", "Id": "64664", "Score": "2", "body": "@200_success couldn't test his on 1,000,00 elements because it takes around 5 seconds for his to compute" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T22:29:46.420", "Id": "38725", "ParentId": "38718", "Score": "6" } }, { "body": "<p>Three performance killers, I believe, are:</p>\n\n<ul>\n<li><p>Rotating numbers via stringification</p>\n\n<p>Rotating the digits of a number using math operations turns out to be <a href=\"http://jsperf.com/digit-rotation\">about 50⨉ faster</a> than what you are doing.</p></li>\n<li><p>Failing to pre-allocate the Sieve of Eratosthenes array</p>\n\n<p>Whenever you build a large array, it's better to ask for the memory all at once than to ask for a little bit at a time.</p></li>\n<li><p>Taking results out of the Sieve of Eratosthenes array</p>\n\n<p>While a hash does give constant-time lookup, so does an array — and arrays are simpler. Since you've already built the array, it's fastest to use it as is.</p></li>\n</ul>\n\n<p>Here is a solution, which is optimized more for performance than for clarity.</p>\n\n<pre><code>// Erastosthenes sieve; range is exclusive upper bound.\n// Returns an array where element [n] is falsy if n is prime.\nfunction sieve(range) {\n var nonPrime = [];\n nonPrime.length = range; // Allocate the array all at once\n nonPrime[0] = nonPrime[1] = true;\n\n for (var i = 2; i &lt; nonPrime.length; i++) {\n if (!nonPrime[i]) {\n for (var j = i * i; j &lt; nonPrime.length; j += i) {\n nonPrime[j] = true;\n }\n }\n }\n return nonPrime;\n}\n\nvar LN10 = Math.log(10);\n\n// Rotates the least-significant base-10 digit to the front\nfunction rotate(number) {\n return (number / 10 &gt;&gt; 0) +\n (number % 10) * Math.pow(10, Math.floor(Math.log(number) / LN10));\n}\n\n// Count circular primes less than an upper bound; the range must be a power of 10.\nfunction countCircularPrimes(range) {\n // Array where element [n] is true if n is non-prime.\n // Later, we will also eliminate numbers that fail the digit circularity test.\n var eliminated = sieve(range);\n\n var circularPrimeCount = 0;\n for (var candidate = 0; candidate &lt; eliminated.length; ++candidate) {\n if (!eliminated[candidate]) {\n var c = 1;\n for (var n = rotate(candidate); n != candidate; n = rotate(n)) {\n if (eliminated[n]) { c = 0; break; }\n c++;\n eliminated[n] = true;\n }\n // If c &gt; 0, then a cycle was detected\n // if (c) console.log(\"\" + c + \" circular primes for \" + candidate);\n circularPrimeCount += c;\n } \n }\n return circularPrimeCount;\n}\n\ncountCircularPrimes(1000000);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T00:14:30.957", "Id": "64665", "Score": "5", "body": "Your sieve would be significantly faster if you limited `i` to the square-root of `nonPrime.length`, and faster again if you treat 2 as a special-case, and start `i` at `3`, and then increment `i` by 2 instead of 1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T00:06:01.707", "Id": "38728", "ParentId": "38718", "Score": "6" } } ]
{ "AcceptedAnswerId": "38725", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T21:13:45.030", "Id": "38718", "Score": "8", "Tags": [ "javascript", "algorithm", "project-euler", "primes" ], "Title": "Checking for circular primes - Project Euler Problem 35" }
38718
<p>For a few reasons I had to use EJS on a specific page in my Express project. This was previously like 13 lines of code with MustacheJS and a small JSON file. But now that it is hard-coded, it is a monstrous 289 lines of code (not counting lines in the includes). What can I do here? </p> <pre><code>&lt;!doctype html&gt; &lt;html class="no-js" lang="en"&gt; &lt;head&gt; &lt;% include includes/default-head %&gt; &lt;title&gt;BruxZir Solid Zirconia Crowns &amp;amp; Bridges - Before &amp;amp; After Case Gallery&lt;/title&gt; &lt;meta name="description" content="BruxZir Solid Zirconia crowns &amp;amp; bridges are monolithic zirconia restorations fabricated using the precision of CAD/CAM. BruxZir has no porcelain overlay, which makes it virtually chip proof. Prescribe BruxZir instead of metal occlusal PFMs and cast gold restorations. Its virtually unbreakable states makes it an ideal restoration for bruxers and grinders." /&gt; &lt;meta name="keywords" content="zirconia crowns, zirconia restoration, zirconium crowns, zirconia dentistry, all-zirconia, zirconia dental crown, dental zirconia, zirconium dental, zirconia ceramic, zirconia bridges, dental bridge, tooth crowns, bruxing solution, grinding solution, clenching solution" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;% include includes/header %&gt; &lt;div class="block push"&gt; &lt;div id="mainContent" class="row"&gt; &lt;div class="large-12 columns"&gt; &lt;h1&gt;Before &amp;amp; After Case Gallery&lt;/h1&gt; &lt;div class="casesContainer"&gt; &lt;div class="caseTitle"&gt; &lt;span class="caseNumber"&gt;Case&lt;/span&gt; &lt;div class="wrap"&gt; &lt;span class="caseBack" onclick='mySwipe.prev()'&gt;Back&lt;/span&gt; &lt;span class="caseForward" onclick='mySwipe.next()'&gt;Forward&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='caseSlider' class='swipe'&gt; &lt;div class='swipe-wrap'&gt; &lt;!-- case 1 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/1_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/1_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;&lt;strong&gt;Before:&lt;/strong&gt; This patient had an endodontic procedure through this lower molar PFM crown. The patient had never been particularly happy about the gray hue of the PFM, and he didn't like having a hole at the top of the crown, even though it was patched with composite.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;After:&lt;/strong&gt; as concerned as the patient was about the esthetics of the new crown, I was more concerned with the strength of the restoration I would be placing on this lower first molar. According to lab statistics, crowns on first molars fracture more than any other crown, so I chose a BruxZir&lt;sup&gt;&amp;reg;&lt;/sup&gt; Shaded crown for its combination of strength and esthetics. Nearly all of the more than 200 Authorized BruxZir Labs now exclusively use the BruxZir Shaded material.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 2 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/2_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/2_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;&lt;strong&gt;Before:&lt;/strong&gt; This patient had an existing all-ceramic crown that was a little too translucent for this endodontically treated central incisor. Despite being bonded with an opaque resin cement, it was allowing some of the dark prep shade through an otherwise esthetic crown. I placed this crown, and I remember how gorgeous it was outside the mouth. After three years, however, the patient wanted to try a different restoration.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;After:&lt;/strong&gt; The patient wanted to switch the crown to something that would block out the dark stump shade, while still being an all-ceramic material. I decided to try a BruxZir&lt;sup&gt;&amp;reg;&lt;/sup&gt; crown, which I have seen block out the darkest of preps, especially when the margin is placed 0.5mm subgingivally. While perhaps not as esthetic as the previous restoration, the BruxZir shaded crown succeeds in blocking out the undesirable prep shade, which was the patient's chief complaint.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 3 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/3_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/3_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This patient had a lingual fracture of the ceramic fused to zirconia restoration on tooth #8 and it needed replacement. The tooth had a previous root canal with a tooth colored build-up. BruxZir provided a natural looking result due to its unique translucent effect.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 4 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;The BruxZir crowns were done on tooth #8 and #9. As you can see in the non-retracted before photo, the patient had two pre-existing high value PFM's. As I cut through them the copings appeared to be base metal. When you look at the condition of the gingiva in the before photo, was this possibly a base metal allergy? It helped with my decision to go with BruxZir all-ceramic (solid zirconia) crowns.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 4lateral --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4lateral_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4lateral_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;As you view the crowns in the lateral smile view, you will notice that flat facial profiles of these crowns.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 4lateral2 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4lateral2_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/4lateral2_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This is much more difficult to achieve with bi-layered restorations such as porcelain fused to metal or porcelain fused to zirconia. Since a BruxZir zirconia restoration is monolithic (one layer), it is much easier to achieve desirable contours.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 5 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/5_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/5_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;A broken composite inlay was replaced with a high strength BruxZir inlay. BruxZir can be used for inlays and onlays, as well as crowns &amp;amp; bridges.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 6 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/6_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/6_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This patient fractured off the distolingual cusp. A monolithic BruxZir Zirconia crown was placed.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 7 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/7_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/7_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;When a patient generates enough occlusal force to break a PFM, BruxZir is a great choice as a replacement crown.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 8 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/8_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/8_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This patient fractured a porcelain all-ceramic crown on the second molar and chipped the first molar. Both crowns were replaced with BruxZir.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 9 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/9_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/9_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;The patient had always disliked the metal occlusal on this PFM. When it became necessary to replace it, tooth-colored BruxZir was chosen.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 10 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/10_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/10_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;An endodontically treated tooth had a fractured mesial marginal ridge and multiple fractures. A monolithic BruxZir zirconia crown was placed.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 11 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/11_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/11_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This endodontically treated molar had a large amalgam and several fractures, necessitating a full-coverage BruxZir crown.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 12 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/12_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/12_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This patient had chipped the distal surface of this PFM. It was replaced with a high-strength BruxZir crown.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 13 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/13_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/13_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;When this patient required an onlay to replace a broken cusp, cast gold was suggested but the patient declined. BruxZir was used instead due to its impressive strength and improved esthetics.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 14 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/14_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/14_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This female patient presented with a predominantly cast metal bridge, which her dentist prescribed after she fractured the porcelain on each of the abutment teeth on the previous restoration. The patient always disliked how it looked and desired a more esthetic, long-term option. Because her PFM restorations had fractured before, a high-strength BruxZir Solid Zirconia bridge was prescribed. It provides the patient with the best combination of strength and esthetics.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 15 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/15_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/15_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;The patient presented with a fractured Maryland bridge. He ruled out implants because it would require a large bone graft. Instead, a digital impression (IOS FastScan) was taken to fabricate a conventional BruxZir bridge.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 16 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/16_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/16_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;This patient had a number of existing PFM restorations in the anterior, but teeth #8 and #9 had a previous root canal and lingual fracture next to the access openings. It was decided that the best option was a full-coverage anterior BruxZir crown.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- case 17 --&gt; &lt;div&gt; &lt;div class="casesContainer"&gt; &lt;div class="imagesContainer"&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/17_b_300.jpg" /&gt; &lt;img src="/images/content/images-bruxzir-zirconia-dental-crown/cases/17_a_300.jpg" /&gt; &lt;/div&gt; &lt;div class="descriptionContainer"&gt; &lt;p&gt;As you can see in the after photos, the BruxZir bridge has acceptable esthetics, although it won't be mistaken for IPS Empress anytime soon! Because BruxZir is virtually unbreakable and because the patient had already broken two PFM bridges in the past, this was the most appealing solution.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- swipeWrap --&gt; &lt;/div&gt; &lt;!-- caseSlider --&gt; &lt;/div&gt; &lt;!-- casesContainer --&gt; &lt;/div&gt; &lt;!-- end of columns --&gt; &lt;/div&gt; &lt;!-- end of row --&gt; &lt;/div&gt; &lt;!-- end of block --&gt; &lt;% include includes/footer %&gt; &lt;/div&gt; &lt;% include includes/default-scripts %&gt; &lt;script src="/javascripts/swipe.js"&gt;&lt;/script&gt; &lt;script&gt; var elem = document.getElementById('caseSlider'); window.mySwipe = Swipe(elem, { startSlide: 0, // auto: 3000, // continuous: true, // disableScroll: true, // stopPropagation: true, // callback: function(index, element) {}, // transitionEnd: function(index, element) {} }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Sorry to tell you, but unfortunately it is near impossible to dry html in itself if you want to keep the elements in the same way.</p>\n<p>As far as I can see, you already use only the minimum amount of elements.</p>\n<h1>Move on, your code is fine</h1>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T17:39:58.410", "Id": "43231", "ParentId": "38730", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T03:04:13.083", "Id": "38730", "Score": "4", "Tags": [ "html", "node.js", "express.js" ], "Title": "Using EJS for a web page" }
38730
<p>I've written this <code>ActionResult</code> to model an Order that goes through. I couldn't think of another way to write this without using context <code>Db&lt;Sets&gt;</code>. It runs kinda slow, taking around 4 seconds to complete. Is there way to optimize the code or is this kinda has to happen since I'm doing so many inserts?</p> <pre><code>public ActionResult New(CustomerOrderModel model) { ViewBag.LimitNotExceeded = checkLimit(); if (ModelState.IsValid) { int prepaid; int userIdLoggedIn = WebSecurity.CurrentUserId; try { // //Add Customer using (var ctx = new CustomerContext()) { ctx.CustomerInfos.Add(model.CustomerModel); ctx.SaveChanges(); } // //Add Order model.OrderInfo.UserProfileUserID = userIdLoggedIn; model.OrderInfo.Customer_id = model.CustomerModel.id; model.OrderInfo.DateCreated = DateTime.Now.ToLocalTime(); using (var ctx = new OrdersContext()) { ctx.OrderInfos.Add(model.OrderInfo); ctx.SaveChanges(); } // //Add Code key = "s121sd"; KeyCode TheKey = new KeyCode(); TheKey.code = key; TheKey.Customer_id = model.CustomerModel.id; TheKey.nif = model.CustomerModel.nif; TheKey.UserProfileUserId = userIdLoggedIn; TheKey.DateCreated = DateTime.Now.ToLocalTime(); using (var ctx = new CodesContext()) { ctx.CodesInfos.Add(TheKey); ctx.SaveChanges(); } // //Assign and Create debts using (var ctx = new UsersContext()) using (var dbx = new DebtsContext()) { prepaid = ctx.UserProfiles.Find(userIdLoggedIn).Prepaid; if (prepaid &gt; 0) { --prepaid; string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';"; ctx.Database.ExecuteSqlCommand(query); } else { Debts NewDebt = new Debts(); NewDebt.paid = false; NewDebt.DateCreated = DateTime.Now.ToLocalTime(); NewDebt.UserProfileUserId = userIdLoggedIn; NewDebt.Order_id = model.OrderInfo.id; dbx.DebtInfos.Add(NewDebt); int debts = dbx.DebtInfos.Count(q =&gt; q.UserProfileUserId == userIdLoggedIn); if (debts &lt;= ctx.UserProfiles.Find(userIdLoggedIn).MaxDebt) { // //Warn them when they reach their last } dbx.SaveChanges(); string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';"; ctx.Database.ExecuteSqlCommand(query); } } //DateTime a = DateTime.FromBinary(model.OrderInfo.Timestamp); return RedirectToAction("Index", "Home"); } catch (DataException ex) { ViewBag.ChangeResult = ex; ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } } return View(model); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:44:19.713", "Id": "64708", "Score": "0", "body": "I think you could go with wrapping the context in a \"Unit Of Work\" and the UnitOfWork in a \"Repository\" patterns.\n\nhttp://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:52:40.777", "Id": "64836", "Score": "0", "body": "Just want to mention that DbContext is an implementation of the repository and unitofwork patterns in itself." } ]
[ { "body": "<p>I'm not sure i understand exactly why you have multiple contexts. If you keep to one context you can do one SaveChanges(). That should save you some time in storing data. </p>\n\n<p>Do all your SaveChanges() take equal amount of time? </p>\n\n<p>You could add a timer inside the contexts to print out a console message with time to confirm how long a using statement takes to come to an end.</p>\n\n<p>If you are relying on how long it takes to show in the view, i suggest using a tool like Glimpse or MiniProfiler to give you feedback on time spent rendering/servertime.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:49:18.637", "Id": "64778", "Score": "0", "body": "My understanding of having multiple context is so I can access/store models from/into the DB. So some `SaveChanges()` take longer than others. I was sceptical of using so many context in one ActionResult so I posted here. Is this even the correct way to do inserts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:50:49.847", "Id": "64834", "Score": "0", "body": "if you let your view sit around and wait for the respons for this I dont think its a good idea. With so many separate contexts you could let them work in threads as long as they dont interfere with eachother." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:57:02.360", "Id": "64838", "Score": "0", "body": "I think that the usage of SQL queries in the controller isent the best option. If you make your own repository/unitofwork you use it to handle such special cases. In my mind this break with single responsibility principle (SRP) and separation of concerns." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T07:08:33.360", "Id": "38734", "ParentId": "38732", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T06:26:20.063", "Id": "38732", "Score": "1", "Tags": [ "c#", "entity-framework", "asp.net-mvc-4", "controller" ], "Title": "Inserting using multiple contexts into LocalDB" }
38732
<p>I've just completed <a href="http://see.stanford.edu/materials/icspmcs106a/07-assignment-1-karel.pdf" rel="nofollow">the 3rd task of the 1st assignment offered by Stanford's programming methodologies</a> (see the <a href="http://see.stanford.edu/see/materials/icspmcs106a/assignments.aspx" rel="nofollow">full resources for it here</a> too).</p> <p>I just need some helpful feedback on how my code can be better (decomposition-wise) and whether or not my code is comprehensible and readable.</p> <p>I'm also unsure about the pre-conditions and post-conditions. Can someone please elaborate more on that? Is a pre-condition basically where the program is at when attempting the method and the post-condition just a result of the actual method?</p> <p>I need all the criticism and feedback I can get.</p> <pre><code> /* File: CheckboardKarel.java * --------------------------- * This program will basically go through an entire row and land checkers on every 2nd cell. * This process will be alternated on each row. */ import stanford.karel.*; public class CheckerboardKarel extends SuperKarel { public void run() { while (facingWest() || facingEast()) { if (frontIsBlocked()) { turnKarelNorth(); } //end if transverseRow(); transverseEvenRow(); } //end while } /* * Method: turnKarelNorth * ---------------------- * Pre-condition: The program is in a 8x1 (1 column) world and Karel has no choice but to turn north * Post-condition: This makes Karel turn left and face north */ private void turnKarelNorth() { putBeeper(); turnLeft(); moveUpwards(); } /* * Method: moveUpwards * ---------------------- * This makes Karel lay down the beepers every 2 moves */ private void moveUpwards() { while (facingNorth()) { move(); move(); putBeeper(); } } /* * Method: transverseRow * ---------------------- * Pre-Condition:Karel is facing east and is ready to place the beeprs on the first odd row * Post-Condition: Karel places all the beepers every 2 steps on the first row */ private void transverseRow() { while (facingEast()) { putBeeper(); move(); isFrontClear(); isFrontBlocked(); } // end while } /* * Method: isFrontClear (if statements) * ---------------------- * This checks whether Karel is being obstructed. * She takes anther move if the front is clear. * Otherwise, if she is blocked, she executes placeBeeperOnNextRow */ private void isFrontClear() { if (frontIsClear()) { move(); } // end if else if (frontIsBlocked()) { placeBeeperOnNextRow(); } // end else } /* * Method: isFrontBlocked (if statement) * ---------------------- * This checks whether Karel is being obstructed. * She puts the beeper and places a final beeper on the row. */ private void isFrontBlocked() { if (frontIsBlocked()) { putBeeper(); placeLastBeeperOnRow(); } } /* * Method: placeLastBeeperOnRow (if statement) * ---------------------- * This checks if Karel is facing east */ private void placeLastBeeperOnRow() { if (facingEast()) { ascendOnOddColumn(); } } /* * Method: placeBeeperOnNextRow (if) * ---------------------- * This method makes Karel ascend at the end of an even column only if she is facing east */ private void placeBeeperOnNextRow() { if (facingEast()) { ascendOnEvenColumn(); } } /* * Method: ascendOnEvenColumn * ---------------------- * This method makes Karel climb up the row and place a beeper on the new row */ private void ascendOnEvenColumn() { turnLeft(); move(); putBeeper(); turnLeft(); move(); } /* * Method: ascendOnOddColumn * ---------------------- * This method makes Karel * climb up the row and place a beeper on the new row */ private void ascendOnOddColumn() { turnLeft(); move(); turnLeft(); } /* * Method: transverseEvenRow * ---------------------- * Pre-condition: Karel lays the checkers on the first row and is now on the 2nd row * Post-condition: Karel lays the checkers alternately on every 2 steps */ private void transverseEvenRow() { while (facingWest()) { move(); putBeeper(); isFrontClear(); isFrontBlockedForEvenRow(); } } /* * Method: isFrontBlockedForEvenRow * ---------------------- * This checks whether Karel (on an even row) is being blocked * It is in between the steps to help Karel move step-by-step without hitting a wall (which would break the loop) * * */ private void isFrontBlockedForEvenRow() { if (frontIsBlocked()) { turnRight(); move(); turnRight(); } //end if } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T11:49:22.097", "Id": "64695", "Score": "1", "body": "Your JavaDoc style is extremely odd, was that a requirement/template from them? Oh, it's not JavaDoc at all...[you'd better read up on that one](http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T23:28:18.277", "Id": "64802", "Score": "0", "body": "The available instruction set is documented in Appendix A of [_Karel the Robot Learns Java_](http://www.stanford.edu/class/archive/cs/cs106a/cs106a.1124/handouts/karel-the-robot-learns-java.pdf)." } ]
[ { "body": "<p>Overall, your code looks pretty good! I'd say if you want a more thorough code review of your abilities, you should write up some code that doesn't simply call these external methods. It's hard to get a good feel of whether you know good programming/Java habits when all of your methods only call other methods that have been written for you.</p>\n\n<p>With that said, my primary qualm is with your method names. In general, you should always design your methods with the idea that someone else will be using them in the future. That means they should be as self-explanatory and intuitive as possible.</p>\n\n<p>For example:</p>\n\n<pre><code>private void turnKarelNorth() {\n putBeeper();\n turnLeft();\n moveUpwards();\n}\n</code></pre>\n\n<p>As a developer, I would assume that the <code>turnKarelNorth()</code> method did exactly that -- turned her North. But it doesn't actually do that explicitly; <strong><em>you</em></strong> only know that it will always turn her North because of the specific problem presented in the PDF. What it actually does is turn her <em>left</em>, which may or may not be North-facing depending on her current state.</p>\n\n<p>For this reason, I would also extract the <code>moveUpwards()</code> call from this method. You can't guarantee when it's called that she will actually be <em>facing</em> \"upwards\", which again makes your design a bit inconsistent and much less flexible. Also, the method name <code>turnKarelNorth()</code> implies a directional adjustment, <em>not</em> a positional adjustment. In other words, a developer would assume that this just shifted where Karel was facing rather than actually moving her to another grid location.</p>\n\n<p>Consistency is a big concern as well with method names. You have <code>turnKarelNorth()</code>, but then you have <code>moveUpwards()</code>. Choose one: either cardinal directions or up-down/left-right, but don't mix and match. It makes your code that much harder to follow.</p>\n\n<pre><code>private void isFrontClear() {\n if (frontIsClear()) {\n move();\n } // end if\n else if (frontIsBlocked()) {\n placeBeeperOnNextRow();\n } // end else\n}\n</code></pre>\n\n<p>To follow Java convention, any method that begins with \"is\" should return a <code>boolean</code>. This is a standard which again allows for consistency across applications and across the language as a whole. Again, the name implies getting a piece of information, not actually affecting anything (as you do when you call <code>move()</code>).</p>\n\n<p>Everything I've said applies to most of your code. So to summarize, when designing methods:</p>\n\n<ul>\n<li>Make sure the method name reflects what the method actually does;</li>\n<li>Make your method as flexible as possible to make your API more powerful and prevent the need for complete rewrites in the future;</li>\n<li>Have your method <a href=\"http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html\" rel=\"nofollow\">do one thing, and do it well</a>;</li>\n<li>Be as consistent as you possibly can within your API; and</li>\n<li>Follow Java naming conventions</li>\n</ul>\n\n<p>Also, as a side note, I think you meant <a href=\"https://www.google.com/search?q=define%3Atraverse\" rel=\"nofollow\">traverse</a> rather than <a href=\"https://www.google.com/search?q=define%3Atransverse\" rel=\"nofollow\">transverse</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:19:36.830", "Id": "64791", "Score": "1", "body": "To elaborate on the Java convention, any method whose name begins with `is` or `has` should return a `boolean` _and have no visible side effects_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T22:09:47.397", "Id": "64793", "Score": "0", "body": "That was really insightful ! Thanks for the great feedback." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:37:19.983", "Id": "38755", "ParentId": "38741", "Score": "4" } }, { "body": "<p>There are a several strategies for generating paths that the robot could take to create the pattern of beepers. Judging from the robot's final position in the two illustrated examples, a boustrophedon path along rows is correct. That's a good start.</p>\n\n<p>Since this is an exercise in creating a state machine without any variables, the only good way to encode the state information in the orientation of the robot. (There are hackish ways as well, but let's not get into that.) Therefore, it is crucial to think about what the state of the robot can be before and after each function call.</p>\n\n<p>You often <code>move()</code> without first checking whether such a move would fall off the edge of the board. Since every move should be preceded by a check, I would define an <code>advance()</code> function:</p>\n\n<pre><code>/**\n * Advance along a boustrophedon path.\n *\n * Precondition: Karel is either\n * (a) facing north, and the path is complete, or\n * (b) facing east, and can advance east, or\n * (c) facing east at the eastern edge, and needs to move one\n * square north then turn to face west, or\n * (d) facing west, and can advance west, or\n * (e) facing west at the western edge, and needs to move one\n * square north then turn to face east.\n *\n * Postcondition: Karel is either\n * (A) facing north, and the path is complete, or\n * (B) facing east, or\n * (C) facing west.\n */\nprivate void advance() {\n if (frontIsClear()) {\n move();\n } else if (facingEast()) {\n turnLeft();\n if (frontIsClear()) {\n move();\n turnLeft();\n }\n } else if (facingWest()) {\n turnRight();\n if (frontIsClear()) {\n move();\n turnRight();\n }\n }\n}\n</code></pre>\n\n<p>Once that function is defined, the <code>run()</code> function is trivial, and you should need no other functions. Since it is a homework question, I'll omit the solution.</p>\n\n<hr>\n\n<h3>Addendum</h3>\n\n<p>Just as important as seeing what to do is realizing what <em>not</em> to do. Perhaps surprisingly, it turns out to be unhelpful to define a function for traversing a row. Why? Think about what it means to lay out a checkerboard pattern — describe the task in half a dozen words. The \"edge of the board\" is not really part of that description.</p>\n\n<p>Now, consider what traversing a row entails — it means you move forward until you hit an eastern or western edge, then make a U-turn onto the next row. Then what? Should your next action involve laying down a beeper or not? The answer is, it depends! That's why there is so much code in your question: you have to handle eastbound and westbound cases of odd-length and even-length rows. The fundamental design issue is that the row-traversal functions terminate with a condition (hitting the edge of the board) that is irrelevant to the task (laying down a beeper on every other square).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T23:24:42.827", "Id": "38801", "ParentId": "38741", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T10:56:20.427", "Id": "38741", "Score": "6", "Tags": [ "java", "homework", "state-machine" ], "Title": "Design feedback for automaton to draw a checkerboard pattern" }
38741
<p>I am modifying Volley for Android a bit and Findbugs complains about the data flow and I am a bit lost. First the code:</p> <pre><code>String userAgent; try { String packageName = getPackageName(); PackageInfo info = getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; // DD } catch (PackageManager.NameNotFoundException e) { userAgent = "volley/0"; } HttpStack stack; if (Build.VERSION.SDK_INT &gt;= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } </code></pre> <p>So I thought that findbugs would differ between definition and declaration of a variable which should make the DD gone.</p> <p>I also tried to predefine the userAgent with the content from the catch but an empty catch is bad practice as well. Also findbugs just complains with the data flow anomalies just on different places...</p> <p>So what would be a good solid way to prevent the findbugs reports?</p>
[]
[ { "body": "<p>It would be bad practice to silently <em>swallow</em> an exception. However, I think the following code would be acceptable:</p>\n\n<pre><code>String userAgent = \"volley/0\"; // Default value\ntry {\n String packageName = getPackageName();\n PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);\n userAgent = packageName + \"/\" + info.versionCode;\n} catch (PackageManager.NameNotFoundException justUseDefaultUserAgent) {\n}\n</code></pre>\n\n<p>For the second snippet, I would use a ternary conditional to emphasize the goal of assigning <code>stack</code> a value no matter what.</p>\n\n<pre><code>HttpStack stack = (Build.VERSION.SDK_INT &gt;= 9) ? new HurlStack() :\n new HttpClientStack(AndroidHttpClient.newInstance(userAgent));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:01:44.983", "Id": "64703", "Score": "0", "body": "Personally I don't like the ternary conditional and I just wanted to show where the userAgent is used for better understanding. Anyway it seems I will go with the empty catch and comment that it is intentionally left blank (tools like Sonar are complaining about empty blocks as well...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:45:04.523", "Id": "64714", "Score": "0", "body": "If your tools are complaining about obviously valid code, making you contort your writing into a style that is arguably worse, then it's time to get better tools." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T11:59:12.660", "Id": "38743", "ParentId": "38742", "Score": "2" } } ]
{ "AcceptedAnswerId": "38743", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T11:11:57.983", "Id": "38742", "Score": "5", "Tags": [ "java", "android" ], "Title": "Data flow anomaly: how to do it correct?" }
38742
<p>What could be a better implementation, following the Scala way of doing it?</p> <pre><code>class Node(itemValue: Object, nextItem:Node){ val value = itemValue val next = nextItem } class MyList() { var start: Node =null def add(value:Object){ val cache = start this.start = new Node(value,cache) } def print:Unit = { var n = start; println(n.value) while(n != null){ println(n.value) n = n.next; } } } </code></pre>
[]
[ { "body": "<p>A list is just a wrapper for an element that also contains a pointer to another list, thus its definition is straightforward:</p>\n\n<pre><code>scala&gt; abstract class MyList[+A]\ndefined class MyList\n\nscala&gt; case class MyCons[A](head: A, tail: MyList[A]) extends MyList[A]\ndefined class MyCons\n\nscala&gt; case object MyNil extends MyList[Nothing]\ndefined object MyNil\n\nscala&gt; val xs = MyCons(1, MyCons(2, MyCons(3, MyNil)))\nxs: MyList[Int] = MyCons(1,MyCons(2,MyCons(3,MyNil)))\n\nscala&gt; xs.head\nres2: Int = 1\n\nscala&gt; xs.tail\nres3: MyList[Int] = MyCons(2,MyCons(3,MyNil))\n</code></pre>\n\n<p>This list is completely immutable. Because of the polymorphic type <code>A</code> it can take any type of element and because it is covariant <code>+A</code>, it can also take the subtypes of an element:</p>\n\n<pre><code>scala&gt; trait T\ndefined trait T\n\nscala&gt; class X extends T\ndefined class X\n\nscala&gt; val xs: MyList[T] = MyCons(new X, MyNil)\nxs: MyList[T] = MyCons(X@56a13ea6,MyNil)\n</code></pre>\n\n<p>The covariant nature of type <code>A</code> also allows the definition of <code>MyNil</code>, which would not be possible otherwise because it is parameterized with type <code>Nothing</code>, Scalas bottom type.</p>\n\n<p>This single linked list definition is also the actual implementation of type <code>List</code> in the stdlib of Scala, although this implementation contains some more <code>optimization</code> details and <code>MyCons</code> is called <code>::</code>.</p>\n\n<p>If you also want to access the members <code>head</code> and <code>tail</code> when you only have type <code>MyList</code> instead of the more concrete type <code>MyCons</code> then you have to declare them directly in the supertype:</p>\n\n<pre><code>abstract class MyList[+A] {\n def head: A\n def tail: MyList[A]\n}\n\ncase class MyCons[A](head: A, tail: MyList[A]) extends MyList[A]\n\ncase object MyNil extends MyList[Nothing] {\n def head = throw new NoSuchElementException(\"MyNil.head\")\n def tail = throw new NoSuchElementException(\"MyNil.tail\")\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T03:56:56.247", "Id": "64822", "Score": "0", "body": "thanks for the wonderful explanation, but is it required to always have a immutable List implementation, what if i need to dynamically add close to millions of data in the list by parsing some text file? won't it would be good to have a mutable list which can have O(1) complexity for add" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:11:02.307", "Id": "64840", "Score": "3", "body": "the prepend operation is O(1). And if you need to append, then you should use a different data structure. At least when you want to stay functional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T07:04:42.227", "Id": "68260", "Score": "0", "body": "Prepends plus a destructive reverse at the end will get you pretty good performance, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T14:03:59.040", "Id": "68331", "Score": "0", "body": "@DilumRanatunga prepend+reverse is O(n). For a lot of cases that is not pretty good performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T15:53:28.617", "Id": "68361", "Score": "0", "body": "Agreed its a factor of two worse, but simply prepending to build the list is O(n) too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T18:32:20.920", "Id": "68382", "Score": "0", "body": "@DilumRanatunga prepend is O(1) when the list is immutable" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:16:32.763", "Id": "68400", "Score": "0", "body": "Constructing a list out of N elements using prepend is O(N). Reversing that same list afterwards is another O(N). So the whole thing is O(N)… Just a factor of 2x separates the performance characteristics." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:33:12.240", "Id": "38754", "ParentId": "38744", "Score": "3" } } ]
{ "AcceptedAnswerId": "38754", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T12:30:39.000", "Id": "38744", "Score": "5", "Tags": [ "scala" ], "Title": "Singly linked list implementation in Scala" }
38744
<p>I want to import in python some ascii file ( from tecplot, software for cfd post processing). Rules for those files are (at least, for those that I need to import): -The file is divided in several section -Each section has two lines as header like:</p> <pre><code>VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen" ZONE T="Window(s) : E_W_Block0002_ALL", I=29, J=17, K=25, F=BLOCK </code></pre> <ul> <li><p>Each section has a set of variable given by the first line. When a section ends, a new section starts with two similar lines.</p></li> <li><p>For each variable there are I*J*K values.</p></li> <li>Each variable is a continous block of values.</li> <li>There are a fixed number of values per row (6).</li> <li>When a variable ends,the next one start in a new line.</li> <li>Variables are "IJK ordered data".The I-index varies the fastest; the J-index the next fastest; the K-index the slowest. The I-index should be the inner loop, the K-index shoould be the outer loop, and the J-index the loop in between.</li> </ul> <p>Here an example of data:</p> <pre><code>VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen" ZONE T="Window(s) : E_W_Block0002_ALL", I=29, J=17, K=25, F=BLOCK -3.9999999E+00 -3.3327306E+00 -2.7760824E+00 -2.3117116E+00 -1.9243209E+00 -1.6011492E+00 [...] 0.0000000E+00 #fin first variable -4.3532482E-02 -4.3584235E-02 -4.3627592E-02 -4.3663762E-02 -4.3693815E-02 -4.3718831E-02 #second variable, 'y' [...] 1.0738781E-01 #end of second variable [...] [...] VARIABLES = "x" "y" "z" "ro" "rovx" "rovy" "rovz" "roE" "M" "p" "Pi" "tsta" "tgen" #next zone ZONE T="Window(s) : E_W_Block0003_ALL", I=17, J=17, K=25, F=BLOCK </code></pre> <p>I am quite new at python and I have written a code to import the data to a dictionary, writing the variables as 3d numpy.array . Those files could be very big, (up to Gb). How can I make this code faster?(or more generally, how can I import such files as fast as possible)?. </p> <pre><code>import numpy as * from numpy.linalg import norm import re def vectorr(I, J, K): arr = empty((I*J*K, 3), int) arr[:,0] = tile(arange(I), J*K) arr[:,1] = tile(repeat(arange(J), I), K) arr[:,2] = repeat(arange(K), I*J) return arr def all_data(pathfilename,NumberCol = 6): with open(pathfilename) as a: filelist = a.readlines() Count = 0 data = dict() leng = len(filelist) Countzone = 0 while Count &lt; leng: strVARIABLES = re.findall('VARIABLES', filelist[Count]) variables = re.findall(r'"(.*?)"', filelist[Count]) Countzone = Countzone+1 data[Countzone] = {key:[] for key in variables} Count = Count+1 strI = re.findall('I=....', filelist[Count]) strI = re.findall(r'\d+', strI[0]) I = int(strI[0]) strJ = re.findall('J=....', filelist[Count]) strJ = re.findall(r'\d+', strJ[0]) J = int(strJ[0]) strK = re.findall('K=....', filelist[Count]) strK = re.findall(r'\d+', strK[0]) K = int(strK[0]) data[Countzone]['indmax'] = array([I, J, K]) pr = prod(data[Countzone]['indmax']) lin = pr // NumberCol if pr % NumberCol != 0 : lin = lin+1 vect = vectorr(I, J, K) for key in variables: init = zeros((I, J, K)) for ii in range(0, lin): Count = Count+1 temp = [ float(x.replace('D', 'E')) for x in filelist[Count].split() ] for iii in range(0, len(temp)): init.itemset(tuple(vect[ii*NumberCol+iii]), temp[iii]) data[Countzone][key] = init Count = Count+1 return data </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T12:53:57.883", "Id": "64699", "Score": "0", "body": "Not enough for an answer but you could/should use list comprehension in vectorr and the with keyword when you open your file (you forfot to close it)" } ]
[ { "body": "<p>There are two algorithmic aspects to your code which concern me. The most significant problem is that you read the entire file in to memory before you start processing the data:</p>\n\n<pre><code>filelist = a.readlines()\n</code></pre>\n\n<p>This is an inefficient way to do things with large input files.</p>\n\n<p>You should instead be reading the data 1 line at a time and processing each line as you get it. This allows you to have a much smaller memory 'footprint', and it allows you to discard data that you do not need.... instead of your while loop <code>while count &lt; leng</code> consider the approach:</p>\n\n<pre><code>for line in a:\n ....\n</code></pre>\n\n<p>This should reduce your memory significantly.</p>\n\n<p>(Asker updated question....)\n<strike>\nThe second issue you should consider changing is using numpy arrays for the <code>vectorr</code> method as well. This array is about the same size as the final array and you are incrementally allocating memory for it. Doing it with a single initializer (perhaps <code>vect = empty((I*J*K, 3))</code> ) would be worth considering.\n</strike></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T13:30:36.557", "Id": "64701", "Score": "0", "body": "I think I have uploaded the wrong version of the code (I am very sorry!!)-I going to edit it right now" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T13:22:09.903", "Id": "38747", "ParentId": "38745", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T12:44:42.477", "Id": "38745", "Score": "2", "Tags": [ "python" ], "Title": "Importing of big files:right approach?" }
38745
<p>I made Conway's Game of Life in JavaScript and was hoping someone could give me some pointers regarding my logic of checking adjacent cells. I know there must be a better way, but at the same time, it works.</p> <p><strong>JS:</strong> </p> <pre><code>var board = [["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""], ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]]; //boolean to tell if cell is alive var alive = new Boolean(null); //counter will be used to see how many cells are alive var counter; //number of initial alive cells var number = Math.floor((Math.random()*900)+5); //coordinates for alive cells var xcor; var ycor; //make table and assign ID to all cells var idAssign; document.write("&lt;table border='1px&gt;'"); for (var x = 0; x &lt; 30; x++ ) { document.write("&lt;tr&gt;"); for (var y = 0; y &lt; 30; y ++) { idAssign = x.toString() + y.toString(); document.write("&lt;td id='" + idAssign + "'&gt;oo&lt;/td&gt;"); } document.write("&lt;/tr&gt;"); } document.write("&lt;/table&gt;"); //generate coordinates for the cells that are alive for (var i=0; i &lt; number; i++) { xcor = Math.floor((Math.random()*29)+0); ycor = Math.floor((Math.random()*29)+0); board[xcor][ycor] = "x"; } function run(){ //loop to check all cells for (var x=0; x != 30; x++) { for (var y=29; y != -1; y--) { //reset counter and boolean after every iteration counter = 0; alive = null; //evaluation of cells var check; check = x.toString() + y.toString(); //check current cell if(board[x][y] == "x") { alive = true; } else{ alive = false; } //BOUNDS //Handle left bound if (y == 0) { if (board[x ][(y + 1)] == "x"){ counter ++; } //Left bottom corner if (x == 29) { if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y + 1)] == "x") { counter ++; } } //Left top corner else if (x == 0) { if (board[(x + 1)][y] == "x") { counter ++; } if (board[(x + 1)][(y + 1)] == "x") { counter ++; } } else{ if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y + 1)] == "x") { counter ++; } if (board[x][(y + 1)] == "x") { counter ++; } if (board[(x + 1)][y] == "x") { counter ++; } if (board[(x + 1)][(y + 1)] == "x") { counter ++; } } } //handle right bound else if (y == 29) { if (board[(x)][(y - 1)] == "x"){ counter ++; } //right bottom corner if (x == 29) { if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y - 1)] == "x") { counter ++; } } //right top corner else if (x == 0) { if (board[x + 1][y] == "x") { counter ++; } if (board[(x + 1)][(y - 1)] == "x") { counter ++; } } else{ if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y - 1)] == "x") { counter ++; } if (board[x][(y - 1)] == "x") { counter ++; } if (board[(x + 1)][y] == "x") { counter ++; } if (board[(x + 1)][(x - 1)] == "x") { counter ++; } } } else{ //Top bounds if (x == 0) { if (board[x][(y + 1)] == "x") { counter ++; } if (board[x][(y - 1)] == "x") { counter ++; } if (board[(x + 1)][y] == "x") { counter ++; } if (board[(x + 1)][y + 1] == "x") { counter ++; } if (board[(x + 1)][y - 1] == "x") { counter ++; } } //Bottom bounds else if (x == 29) { if (board[x][(y + 1)] == "x") { counter ++; } if (board[x][(y - 1)] == "x") { counter ++; } if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y + 1)] == "x") { counter ++; } if (board[(x - 1)][(y - 1)] == "x") { counter ++; } } else{ //center of board if (board[x][(y + 1)] == "x") { counter ++; } if (board[x][(y - 1)] == "x") { counter ++; } if (board[(x - 1)][y] == "x") { counter ++; } if (board[(x - 1)][(y + 1)] == "x") { counter ++; } if (board[(x - 1)][(y - 1)] == "x") { counter ++; } if (board[(x + 1)][(y + 1)] == "x") { counter ++; } if (board[(x + 1)][(y - 1)] == "x") { counter ++; } } } //end board checking //apply rules to cell if (alive == true) { if (counter &lt; 2) { board[x][y] = ""; } if (counter &gt; 3) { board[x][y] = ""; } } else if (alive == false) { if (counter == 3) { board[x][y] = "x"; } else if (counter != 3){ board[x][y] = ""; } } }//Inner FOR }// Outer FOR var IDcheck; for (var x= 0; x &lt; 30; x ++) { for (var y = 0; y &lt;30; y ++) { IDcheck = x.toString() + y.toString(); if (board[x][y] == "x" ) { document.getElementById(IDcheck).className = 'active'; } else{ document.getElementById(IDcheck).className = 'NotActive'; } } } }//WHILE </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;!-- Author: Justin Murphy &gt; &lt;--- Start Date: November 27, 2013 &gt; &lt;--- File: Display.html &gt; &lt;--- Supporting Files: Life.js --&gt; &lt;title&gt;Conway's Game Of Life&lt;/title&gt; &lt;link rel='stylesheet' type='text/css' href='style.css'&gt; &lt;script src='Life.js'&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onload='setInterval(function(){run();},100)'&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The reason I have all spaces set to the array manually is because, instead of randomly generating the starting plots for the bacteria, one could comment out that code and place them manually to see that sort of patterns they can make.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:58:58.143", "Id": "64737", "Score": "2", "body": "About a year ago I created a Game of Life in Javascript, as an excercise. I used html5 canvas to render, but you can see how I solved some things. http://jsfiddle.net/mgvd/a2tVe/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:44:11.790", "Id": "64739", "Score": "3", "body": "The jsfiddle link doesn't work in my browser, so I have no idea how you solved anything. You should post the details on this site, with a link solely for reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:55:31.847", "Id": "64766", "Score": "2", "body": "Thanks to all who answered. I am not going to lable a correct answer yet, but I do plan to. I just want to see give it a day or 2 to see if any one else can come with anything. Thanks for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:08:51.730", "Id": "64810", "Score": "0", "body": "Not worth a whole answer, but `function(){run();}` in your `setInterval` call can be more succinctly written `run` - since `run` is already a function taking no arguments, there's no reason I can think of to wrap it in an anonymous function with no arguments. Also, remember that `var` only scopes to the current function (including code written above the `var` declaration), not current `{}` pair; so `for (var x=0; x != 30; x++)` gives a misleading impression of the scope of `x`." } ]
[ { "body": "<p>There is a major bug/issue, and also stringing together three very different recommendations here.</p>\n\n<h2>Bug/issue</h2>\n\n<p>in the Game-Of-Life you are supposed to scan the entire board, and only then apply the changes. You are applying changes part-way through the process (as you check each cell, you change its state). So, if you change the cell in one location, when you check it's neighbour it will affect the results).</p>\n\n<p>You need to 'store' the counter for each cell until you have completed the scan, and then re-set each block in the board. Essentially you need the following:</p>\n\n<pre><code>var counter[];\n//loop to check all cells\nfor (var x=0; x &lt; DIMENSION; x++) {\n for (var y=0; y &lt; DIMENSION; y++) {\n counter[x][y] = 0;\n // check all cells and update counter[x][y]\n }\n}\n// loop to update board....\nfor (var x=0; x &lt; DIMENSION; x++) {\n for (var y=0; y &lt; DIMENSION; y++) {\n // check whether we are alive or dead....\n if (counter[x][y] == 2 || counter[x][y] == 3) {\n board[x][y] = \"x\";\n } else {\n board[x][y] = \"\";\n }\n }\n}\n</code></pre>\n\n<h2>Code style:</h2>\n\n<p>Seriously, you manually create the blank <code>board</code>? Wasn't that sore on the wrists? Lazy programmers are a good thing, consider the following:</p>\n\n<pre><code>var DIMENSION= 30;\nvar board = [];\nfor (var y = 0; y &lt; DIMENSION; y++) {\n for (var x = 0; x &lt; DIMENSION; x++) {\n board[y][x] = \"\";\n }\n}\n</code></pre>\n\n<p>Note, this declares the <strong>dimension</strong> for the game. This is a single constant. Your use of <code>30</code> and <code>29</code> in a lot of places is called <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">using <strong>Magic Numbers</strong></a>, and this is a bad thing... You need to replace those with a <code>dimension</code></p>\n\n<p>OK, that gets rid of the copy/paste <code>board</code> initializer.</p>\n\n<h2>Math.random()</h2>\n\n<p>To initialize the 'alive' cells you use: </p>\n\n<pre><code>xcor = Math.floor((Math.random()*29)+0);\nycor = Math.floor((Math.random()*29)+0);\n</code></pre>\n\n<p>This is never going to generate the value 29... It is a common mistake to make when using <code>Math.random()</code> which is to forget that <code>Math.random()</code> returns a value from <code>0.0</code> (inclusive) to <code>1.0</code> <strong>(EXCLUSIVE)</strong>. In other words, it will never generate <code>1.0</code> and you will thus never get the value <code>29</code>.</p>\n\n<p>The right approach is:</p>\n\n<pre><code>xcor = Math.floor(Math.random()*DIMENSION);\nycor = Math.floor(Math.random()*DIMENSION);\n</code></pre>\n\n<h2>Using Buddy-table</h2>\n\n<p>In the Game-of-life, each cell has a buddy. The buddy cells are:</p>\n\n<ul>\n<li>above me (or nothing if we are at the top) - to the left, immediate, and to the right</li>\n<li>left of me (or nothing if we are at the left)</li>\n<li>right of me (or nothing if we are at the right)</li>\n<li>below me (or nothing if we are at the bottom) - to the left, immediate and to the right.</li>\n</ul>\n\n<p>We can represent these buddies as:</p>\n\n<pre><code>var BUDDIES = [\n [-1, -1], [0, -1], [1, -1], // above\n [-1, 0], [1, 0], // our row\n [-1, 1], [0, 1], [1, 1]]; // below\n</code></pre>\n\n<p>Those arrays are what we have to add to our <code>(x,y)</code> co-ordinate to get the surrounding buddies.... but, the table does not help (yet) with cells at the margins.</p>\n\n<p><strike>\nBut, there is <a href=\"http://en.wikipedia.org/wiki/Modulo_operation\">a <strong>modulo</strong> trick</a> for that. Consider the function:</p>\n\n<pre><code>function buddy(dim, pos, direction) {\n return (pos + direction + dim) % dim;\n}\n</code></pre>\n\n<p></strike></p>\n\n<p>Since your version of the game does not 'wrap' at the margins, use this function instead:</p>\n\n<pre><code>function buddy(maxdim, pos, direction) {\n var newpos = pos + direction;\n if (newpos &gt;= maxdim) {\n newpos = -1;\n }\n return newpos;\n}\n</code></pre>\n\n<p>This function takes the dimension of the board, the position (in one dimension), and which way we want to look for our buddy. So, consider we want to find the position of our 'left' buddy:</p>\n\n<pre><code>var left = buddy(DIMENSION, x, -1);\n</code></pre>\n\n<p>If <code>x</code> is 5 for example, it will add the -1, and 5 together to get 4.</p>\n\n<p>If <code>x</code> is 0, it will return <code>-1</code></p>\n\n<p>If we want to find the <strong>right</strong> buddy at position 29, the math will be: 29 + 1, which is <code>30</code>, and that will be translated to -1.</p>\n\n<p>Now, all the 'duplicate' code you have for your neighbour checks can be reduced to a loop:</p>\n\n<pre><code># Using the buddies array above\nfor (var i = 0; i &lt; buddies.length; i++) {\n var budx = buddy(DIMENSION, x, BUDDIES[i][0]);\n var budy = buddy(DIMENSION, y, BUDDIES[i][1]);\n if (budx &gt;= 0 &amp;&amp; budy &gt;= 0 &amp;&amp; \"x\" == board[budx][budy]) {\n counter++;\n }\n} \n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Between these three (.5) suggestions (board initialization (and dimension magic number), Random, and Buddies) you should be able to reduce your code size massively.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:29:09.437", "Id": "64722", "Score": "0", "body": "You don't have to actually process the entire board before writing the values back; There's a way to do it where you store a row's values in an array and use that array to get the old values when computing the next row." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:31:16.070", "Id": "64723", "Score": "1", "body": "Also, why is there a `+0` in `Math.floor((Math.random()*dimension)+0);`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:32:37.633", "Id": "64725", "Score": "0", "body": "@AJMansfield - copy-paste from the OP's code. There is no other reason... will edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:34:17.753", "Id": "64726", "Score": "0", "body": "There are some typos in the buddy table, for example [0,-1] appears twice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:39:03.500", "Id": "64728", "Score": "0", "body": "@default.kramer - thanks, and I changed the formatting to make it 'obvious'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:54:32.577", "Id": "64765", "Score": "0", "body": "Thanks! this is by far the most helpful to date. The only reason I made the whole board is so that I could visualise my starting bacteria for the runs where I comment out the auto generate. I also realize that would never hit 29 in the random number generator. I figured that it wouldnt matter becausea full board would just revert to an empty board next turn. I really like the buddy idea! Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:19:07.680", "Id": "64774", "Score": "2", "body": "@DaveJarvis that is correct, and it is not supposed to. DIMENSION is 30, and since the array index is 0-based, the largest value we ever want is 29. We want to generate values from 0 to 29 inclusive, so `Math.floor(Math.random() * 30)` is what we want to do (Note DIMENSION is 30, and not 29 like you have in your JFiddle)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:41:09.470", "Id": "64792", "Score": "0", "body": "@rolfl: Ah! I misunderstood the implications of what you wrote. Thanks for the update. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:00:31.337", "Id": "64805", "Score": "0", "body": "You might be able to get away with using `const DIMENSION`, instead of `var`, but I'm not certain how widespread the support for it is yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:02:10.503", "Id": "64806", "Score": "1", "body": "@David, Google's Javascript style guide [recommends against it (not supported in IE)](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Constants)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:08:37.310", "Id": "64809", "Score": "0", "body": "@rolfl Ah, thanks, and thanks for the link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T01:31:14.167", "Id": "64815", "Score": "0", "body": "This is a very good answer which touches on several key thing in programming that beginners often end up learning the hard way (I know I did). It might be wroth mentioning that the trick with deferring updates is an example of double buffering, with the issue arising from use of only a single buffer (the buffer here is the array which stores the board). Also, personally I like to use the modulo trick, combined with an `if (within_bounds(x, y))` kind of conditional to handle edges and corners." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T13:52:36.663", "Id": "38749", "ParentId": "38746", "Score": "68" } }, { "body": "<p>In addition to @rolfl suggestion you could create a separate <code>LifeBoard</code> class and keep the array private and have a second count array. Then provide <code>get</code>, <code>set</code> and <code>remove</code> methods. Whenever square is set, increment it's neighbors in the count array, whenever one is removed, decrement them.</p>\n\n<p>That way it saves you always double counting squares as you move over the board.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:02:29.617", "Id": "64807", "Score": "0", "body": "Since this is JavaScript, there is no such thing as a \"class\". I guess what you mean is to have an *object*, or possibly a constructor for multiple similar objects, with the \"private\" data scoped to the constructor or an IIFE. The distinctions are worth keeping in mind, as I think a lot of JS code gets over-complex because people are trying to emulate OO as they know it from another language, rather than using the JS OO facilities to solve their actual problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:48:10.390", "Id": "64843", "Score": "0", "body": "Yea, my bad. I see everything in Java terms these days ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:27:47.830", "Id": "38750", "ParentId": "38746", "Score": "4" } }, { "body": "<p>To reduce memory usage and increase performance I recommend you consider a sparse matrix approach. Instead of having an entire array of mostly empty cells, you can just keep a list of cells that are live. As a cell changes state, you update the display for that cell and the list for the surrounding cells.</p>\n<hr />\n<p><strong>Edit:</strong> I will describe it in more detail as I have time.</p>\n<hr />\n<p>To do this, create a cell object that has attributes for x, y coordinates for each live cell you want to represent:</p>\n<pre><code>function cell(x, y) {\n this.x = x;\n this.y = y;\n}\n</code></pre>\n<p>Also create a grid object that is just an array of cells, and has the following methods:</p>\n<pre><code>grid.isLive(x,y) \\\\ return true if cell(x, y) is found in grid array.\ngrid.liveNeighbors(x,y) \\\\ returns number of live neighbors around any grid coordinate\n</code></pre>\n<p>To create the new grid state, test each <code>(x,y)</code> coordinate of the entire grid space with <code>grid.liveNeighbors(x,y)</code> and add live cells to the next grid object.</p>\n<p>This can be further optimized by using the existing grid to eliminate large dead areas from the test. For example, you could find out the min and max x and y values and only test that region.</p>\n<p>Or could add a <code>boolean live</code> and <code>int liveNeighbors</code> attribute to the cell object to keep track of the <code>liveNeighbors</code> value in nearby <code>dead</code> cells, then switch them live when the value is within the life threshold. This will allow you to only iterate through the grid list, not the entire grid space, providing much better performance in many cases.</p>\n<hr />\n<p><strong>Edit:</strong> I created a short, simple Python example version <a href=\"https://stackoverflow.com/questions/15297834/infinite-board-conways-game-of-life-python/21009663#21009663\">here</a>, converting to JavaScript will make it a little longer.</p>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:48:58.283", "Id": "64733", "Score": "8", "body": "That's a good idea, but you should give some more info on how to actually implement this in JS. It's not something that will be obvious to the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:52:01.333", "Id": "64763", "Score": "1", "body": "Could you provide a small scale example of this? you have peaked my interest" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:04:16.527", "Id": "64808", "Score": "4", "body": "'Piqued'. :) http://english.stackexchange.com/questions/101450/is-it-peek-peak-or-pique" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:11:54.337", "Id": "38765", "ParentId": "38746", "Score": "7" } }, { "body": "<p>I see several issues with the initialization, aside from the obvious gigantic literal array.</p>\n\n<ul>\n<li><strong>Ambiguous element IDs:</strong> You concatenate <code>x.toString() + y.toString()</code> for the element IDs. When you refer to ID 121, is that (12, 1) or (1, 21)?</li>\n<li><p><strong>Namespace pollution (global variables):</strong> <code>alive</code>, <code>counter</code>, <code>xcor</code>, <code>ycor</code>, and <code>idAssign</code> do not need to be in the global scope. The simple fix is to initialize the board using an Immediately Invoked Function Expression (IIFE):</p>\n\n<pre><code>var board = (function(dim, min) {\n var b = new Array(dim);\n // TODO: initialize b\n return b;\n})(30, 5);\n</code></pre>\n\n<p>I would go a step further and change it to a constructor (see below).</p></li>\n<li><p><strong>Underpopulation:</strong> You use the following code to generate the initial alive cells:</p>\n\n<pre><code>//number of initial alive cells\nvar number = Math.floor((Math.random()*900)+5);\n\n/* Some code here which should not have been placed\n in an intervening position */\n\n//generate coordinates for the cells that are alive\nfor (var i=0; i &lt; number; i++) {\n xcor = Math.floor((Math.random()*29)+0);\n ycor = Math.floor((Math.random()*29)+0);\n\n board[xcor][ycor] = \"x\";\n}\n</code></pre>\n\n<p>You'll be breathing life into some cells twice, so <code>number</code> is actually an upper bound, not an exact count, of the number of cells that are initially alive. Perhaps you don't care about the exact count, since it's random anyway, but at least the \"number of initial alive cells\" comment should be made more accurate.</p>\n\n<p>To get an exact count, populate the first <em>n</em> cells, then do a shuffle.</p></li>\n<li><strong><code>\"x\"</code> as a boolean:</strong> You use <code>\"x\"</code> to basically serve as a boolean value; <code>true</code> would be more conventional.</li>\n</ul>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>function Board(dim, min) {\n var b = new Array(dim);\n for (var i = 0; i &lt; b.length; i++) {\n b[i] = new Array(dim);\n }\n\n // Give life to a random number of cells\n var initPopulation = min + Math.floor((dim * dim + 1 - min) * Math.random());\n for (var i = 0; i &lt; initPopulation; i++) {\n b[i / dim &gt;&gt; 0][i % dim] = true;\n }\n // Two-dimensional Fisher-Yates shuffle\n for (var i = dim * dim - 1; i &gt; 0; i--) {\n var j = Math.floor((i + 1) * Math.random());\n var swap = b[i / dim &gt;&gt; 0][i % dim]; \n b[j / dim &gt;&gt; 0][j % dim] = b[i / dim &gt;&gt; 0][i % dim]; \n b[i / dim &gt;&gt; 0][i % dim] = swap; \n }\n this.array = b;\n}\n\nvar board = new Board(30, 5);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:11:59.400", "Id": "38792", "ParentId": "38746", "Score": "9" } } ]
{ "AcceptedAnswerId": "38749", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T13:01:22.673", "Id": "38746", "Score": "45", "Tags": [ "javascript", "html", "game-of-life" ], "Title": "Conway's Game of Life in JavaScript" }
38746
<p>I have created a small 'game' which basically asks the user for the row number and column number and then picks a random number and if that number is above 11, out of 15, the user wins. When the user wins that position in the array is replaced with a X or O to indicate a win or loss.</p> <p>The program works fine. As it is my first real program, I know that there is room for improvement. </p> <p>I'm looking for constructive feedback on program efficiency, possible performance improvements and just better ways to code a similar program (at a basic level).</p> <pre><code>#include &lt;stdafx.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdlib.h&gt; #include &lt;ctime&gt; using namespace std; void fill(char Array[10][10]); int xRan; int choicei = 12; int choicej = 12; int main() { char Array[10][10]; srand(time(0)); xRan = rand() % 15 + 1; while (choicei &gt; 10 || choicej &gt; 10) { cout &lt;&lt; "Enter The Row Number Less Than 10!" &lt;&lt; endl; cin &gt;&gt; choicei; cout &lt;&lt; endl; cout &lt;&lt; "Enter The Column Number Less Than 10!" &lt;&lt; endl; cin &gt;&gt; choicej; cout &lt;&lt; endl; } fill(Array); for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 10; j++) { cout &lt;&lt; Array[i][j] &lt;&lt; " "; } cout &lt;&lt; endl; } if (xRan &gt; 11) { cout &lt;&lt; "\nCongratulations! You Won!\n" &lt;&lt; endl; } else { cout &lt;&lt; "\nBetter Luck Next Time!\n" &lt;&lt; endl; } } void fill(char Array[10][10]) { for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 10; j++) { Array[i][j] = '*'; } } if (xRan &gt; 11) { for (int i = 0; i &lt; 1; i++) { for (int j = 0; j &lt; 10; j++) { Array[choicei - 1][choicej - 1] = 'X'; } } } else { for (int i = 0; i &lt; 1; i++) { for (int j = 0; j &lt; 10; j++) { Array[choicei - 1][choicej - 1] = 'O'; } } } } </code></pre>
[]
[ { "body": "<p>Think about what happens when you want to change your dimensions from 10x10 to 12x14.\nHow many locations in your code would require updating?</p>\n\n<p>You can look into using constants for the dimensions and the <code>.length</code> property of your arrays to bound your <code>for</code> loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:36:27.330", "Id": "64707", "Score": "0", "body": "Yes that is a good point. I could let the user define the dimensions of the 'playing board'. Thanks for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:22:12.907", "Id": "64759", "Score": "2", "body": "The tag says C++. Raw arrays have no properties/members." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:32:23.180", "Id": "38753", "ParentId": "38752", "Score": "5" } }, { "body": "<p>Also using the name 'Array' should be camelCase, but with small letter start, as it is a variable, and types should start with big letter CamelCase. So I'd suggest using 'array' instead. It will help you on bigger projects and other languages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:48:16.823", "Id": "38757", "ParentId": "38752", "Score": "2" } }, { "body": "<p>When reading and validating <em>choicei</em> and <em>choicej</em>, it would be better from the user's point of view to only re-supply the invalid entry, not both of them in case one of them is invalid. Code-wise, a do-while loop is more suitable since you need to run the loop at least once.</p>\n\n<p>Something along this line would certainly be an improvement</p>\n\n<pre><code>do {\n read choicei\n} while(choicei is invalid)\n\ndo {\n read choicej\n} while(choicej is invalid)\n</code></pre>\n\n<p>I also think that you should account for the user entering &lt;= 0, because indexing <em>Array</em> with a 0 (since you subtract 1 from the indices) or negative choicei/choicej will result in an out of bounds access. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:37:25.673", "Id": "64951", "Score": "0", "body": "Also check for bad input. If you user enters 'PLOP' the read will fail, the value of choice is not set correctly and your while loop infinitely." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:09:14.850", "Id": "38758", "ParentId": "38752", "Score": "5" } }, { "body": "<p>In Fill you're wasting resources running more loops than necessary:</p>\n\n<pre><code>void fill(char Array[10][10])\n{\n for (int i = 0; i &lt; 10; i++)\n {\n for (int j = 0; j &lt; 10; j++)\n {\n Array[i][j] = '*';\n }\n }\n\n if (xRan &gt; 11)\n Array[choicei - 1][choicej - 1] = 'X';\n else\n Array[choicei - 1][choicej - 1] = 'O';\n\n}\n</code></pre>\n\n<p>In this program it's probably not too big a deal, but I think it would make more sense to fill the array at the beginning and change the specific element when you get an answer. This way if you wanted to allow the user to play again, you can reset the array by changing the one element, instead of re doing the whole array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:33:11.190", "Id": "38760", "ParentId": "38752", "Score": "5" } }, { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p><code>&lt;stdlib.h&gt;</code> is a C library. Use <code>&lt;cstdlib&gt;</code> for C++.</p></li>\n<li><p>These shouldn't be global:</p>\n\n<pre><code>int xRan;\nint choicei = 12;\nint choicej = 12;\n</code></pre>\n\n<p>As you're using <code>xRan</code> in another function, initialize it in <code>main()</code> only:</p>\n\n<pre><code>int xRan = rand() % 15 + 1;\n</code></pre>\n\n<p>and pass it to that function as an argument.</p>\n\n<p>I also don't see why <code>choicei</code> and <code>choicej</code> are initialized to 12. If there's a reason for that, there should be a comment specifying that. Since it looks needless, just declare them in <code>main()</code> closely in scope with the input:</p>\n\n<pre><code>cout &lt;&lt; \"Enter The Row Number Less Than 10!\" &lt;&lt; endl;\nint choicei; // declare here\ncin &gt;&gt; choicei;\n</code></pre>\n\n<p></p>\n\n<pre><code>cout &lt;&lt; \"Enter The Column Number Less Than 10!\" &lt;&lt; endl;\nint choicej; // declare here\ncin &gt;&gt; choicej;\n</code></pre>\n\n<p>On another note, <code>choicei</code> and <code>choicej</code> are not good names. What are <code>i</code> and <code>j</code>? One would assume they have to do with simple loop counters, but this doesn't seem to be the case here. Consider something like <code>rowNumberChoice</code> and <code>colNumberChoice</code>.</p></li>\n<li><p>I don't know how high your compiler warnings are turned up, but your <code>std::srand()</code> <em>may</em> produce warnings corresponding to \"possible loss of data.\" This is usually remedied by casting the <code>std::time()</code> return to an <code>unsigned int</code>.</p>\n\n<p>If these warnings become present, call <code>std::srand()</code> like this:</p>\n\n<pre><code>// if you're using C++11, use nullptr instead of NULL\nstd::srand(static_cast&lt;unsigned int&gt;(std::time(NULL));\n</code></pre></li>\n<li><p>In C++, prefer to use standard containers over C-style arrays. You especially shouldn't pass one to a function as it would <em>decay into a pointer</em>. It's best to avoid this in C++.</p>\n\n<p>I recommend using <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a>, if you're using C++11. As 2D, it would be initialized like this:</p>\n\n<pre><code>std::array&lt;std::array&lt;char&gt;, 10&gt;, 10&gt; gameBoard;\n</code></pre>\n\n<p>As @nvuono mentioned, you could have row and column constants so that minimal updating is needed. You could then have this:</p>\n\n<pre><code>const unsigned int rows = 10;\nconst unsigned int cols = 12;\n\nstd::array&lt;std::array&lt;char&gt;, rows&gt;, cols&gt; gameBoard;\n</code></pre>\n\n<p>To pass this 2D array to functions:</p>\n\n<pre><code>// you may use a typedef to \"rename\" this type for less typing\n// name should be capitalized as it is a type\ntypedef std::array&lt;std::array&lt;char&gt;, rows&gt;, cols&gt; Board;\n\n// pass as const-ref as the board shouldn't be modified\nvoid displayBoard(Board const&amp; gameBoard) { }\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T22:27:55.720", "Id": "64965", "Score": "0", "body": "I have made choicei/j equal 12 as the program runs a loop until the user enters a choice under 10. Thanks for the feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:56:51.077", "Id": "38777", "ParentId": "38752", "Score": "10" } }, { "body": "<ol>\n<li><p>Remove these the inclusion of <code>&lt;stdlib.h&gt;</code> and <code>&lt;string&gt;</code>.<br>\nYou never use them.</p></li>\n<li><p>Use a consistent naming convention for variables.</p>\n\n<p>You have 3 different naming conventions being used:<br>\n<code>xRan</code><br>\n<code>choicei</code><br>\n<code>Array</code></p>\n\n<p>If you're working by yourself, pick one and stick to it. If you're working on a larger project, use the conventions already in use.</p></li>\n<li><p>Avoid global variables. In general, polluting the global namespace is a bad practice. </p></li>\n<li><p>Avoid magic numbers.<br>\nI normally don't recommend using macros. But in this case, it wouldn't hurt. You could do something like this:</p>\n\n<pre><code>#define MAX_ROWS 10 \n#define MAX_COLS 10\n#define MIN_WIN 11 // Random number must &gt;= MIN_WIN \n</code></pre></li>\n<li><p>Following @Erevis's advice, create a function to encapsulate the functionality of accepting user input. </p>\n\n<pre><code>int GetValue (const int min, const int max, const char *szWhat = \"row\") ;\n\n// ...\n\nint GetValue (const int min, const int max, const char *szWhat)\n{\n int n = 0 ;\n\n do {\n std::cout &lt;&lt; \"Enter a \" &lt;&lt; szWhat &lt;&lt; \" number between \" &lt;&lt; min &lt;&lt; \" and \" &lt;&lt; max &lt;&lt; \"!\" &lt;&lt; std::endl ;\n std::cout &lt;&lt; \"&gt; \" ;\n std::cin &gt;&gt; n ;\n std::cout &lt;&lt; std::endl ; \n\n if (std::cin.good () == false) {\n std::cin.clear () ;\n std::cin.ignore (std::numeric_limits &lt;std::streamsize&gt;::max (), '\\n') ;\n continue ;\n } \n\n } while (n &lt; min || n &gt; max) ;\n\n return n ;\n}\n</code></pre></li>\n<li><p>Based on @Tinstaafl's answer, create a function for printing the outcome.</p>\n\n<pre><code>void PrintOutcome (const int row, const int column, const bool has_won) ;\n\n// ...\n\nvoid PrintOutcome (const int row, const int column, const bool has_won)\n{\n char board [MAX_ROWS] [MAX_COLS] ;\n\n for (size_t i = 0; i &lt; MAX_ROWS; ++i) {\n for (size_t j = 0; j &lt; MAX_COLS; ++j) {\n board [i] [j] = '*' ;\n }\n }\n\n char c = (has_won == true) ? 'X' : 'O' ;\n board [row - 1] [column - 1] = c ;\n\n for (size_t i = 0; i &lt; MAX_ROWS; ++i) {\n for (size_t j = 0; j &lt; MAX_COLS; ++j) {\n std::cout &lt;&lt; board [i] [j] &lt;&lt; ' ' ;\n }\n\n std::cout &lt;&lt; std::endl ;\n }\n\n std::cout &lt;&lt; std::endl ;\n\n if (has_won == true) {\n std::cout &lt;&lt; \"Congratulations, you won!\" &lt;&lt; std::endl ;\n }\n\n else {\n std::cout &lt;&lt; \"Unfortunately, you lost!\" &lt;&lt; std::endl ;\n }\n}\n</code></pre></li>\n<li><p>Give the user a chance to continue playing the game.</p>\n\n<pre><code>bool ContinuePlaying () ;\n\n/...\n\nbool ContinuePlaying ()\n{\n char c ;\n std::cout &lt;&lt; \"Do you wish to continue playing? &lt;y/n&gt;\" &lt;&lt; std::endl ;\n std::cout &lt;&lt; \"&gt; \" ;\n\n std::cin &gt;&gt; c ;\n\n return (c == 'y') ;\n}\n</code></pre></li>\n<li><p>Your <code>main</code> function can then be simplified into:</p>\n\n<pre><code>int main (void)\n{\n srand (static_cast &lt;unsigned&gt; (time (NULL))) ;\n\n do {\n bool has_won = (rand () % 15 + 1) &gt;= MIN_WIN ;\n\n int row = GetValue (1, MAX_ROWS) ;\n int column = GetValue (1, MAX_COLS, \"column\") ;\n\n PrintOutcome (row, column, has_won) ;\n\n } while (ContinuePlaying () == true) ;\n\n return 0 ;\n}\n</code></pre></li>\n<li><p>@Jamal mentioned not to pass an array an as argument to your function. I want to give you an example of why you should not do that. Suppose you have a function like this: </p>\n\n<pre><code>void SomeFunc (int board [10] [10])\n{\n for (size_t i = 0; i &lt; 10; ++i) {\n for (size_t j = 0; j &lt; 10; ++j) {\n std::cout &lt;&lt; board [i] [j] &lt;&lt; \" \" ;\n }\n std::cout &lt;&lt; std::endl ;\n }\n}\n</code></pre>\n\n<p>From the compiler's point of view, this is the same as:</p>\n\n<pre><code>void SomeFunc (int *board [10])\n</code></pre>\n\n<p>So you could do something like this:</p>\n\n<pre><code>int main (void)\n{\n int b1 [10] [10] ;\n int b2 [5] [10] ;\n\n // ... Initialize b1 and b2 to valid values.\n\n SomeFunc (b1) ;\n SomeFunc (b2) ; // error\n\n return 0 ;\n}\n</code></pre>\n\n<p>This would compile, but cause undefined behavior and possibly crash your program (if you're lucky).</p></li>\n</ol>\n\n<p><strong>Comments</strong><br>\n<em>@LokiAstari</em> </p>\n\n<p>Unless I'm misunderstanding your fourth comment, here's a counter-example for it (compiled with VS2012): </p>\n\n<pre><code>void SomeFunc (int board [2] [3])\n{\n auto s1 = sizeof (board [0]) / sizeof (board [0] [0]) ; // s1 = 3\n}\n\nint main (void)\n{\n int b1 [2] [3] = \n {\n {1, 2, 3},\n {4, 5, 6}\n } ;\n\n int b2 [3] [2] =\n {\n {1, 2},\n {3, 4},\n {5, 6}\n } ;\n\n SomeFunc (b1) ;\n SomeFunc (b2) ; // Does not compile\n\n return 0 ;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:35:06.807", "Id": "64949", "Score": "0", "body": "Rather than macros use `const int`. This way your constants are also typed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:36:24.953", "Id": "64950", "Score": "1", "body": "In your read you should also check for bad input. Otherwise you will go into an infinite loop (you are assuming the user can enter bad values so you should really check for bad input)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:38:58.600", "Id": "64952", "Score": "0", "body": "If you are going to create a function for printing then use standard conventions and call it `operator<<`. You can also have `print()` that uses `operator<<`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:41:18.953", "Id": "64953", "Score": "1", "body": "From the compilers point of view its `void SomeFunc (int** board)` all arrays are collapsed to pointers across function boundaries. You should pass by reference to maintain validity of the array semantics. (ie sizeof() will not work as you expect based on function definition)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T15:37:13.637", "Id": "66135", "Score": "0", "body": "@LokiAstari 1) The macros are just numeric literals in a single translation unit. Could you explain how your suggestion would improve the code? 2) Good point. I actually did not know how to fix `std::cin` after bad input until I read your answer [here](http://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer). 3) How would that work? Wouldn't we have to wrap the 2D array into a struct? 4) Unless I'm misunderstanding your comment, this is not true. Please see the counter-example that I posted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T18:37:12.027", "Id": "66203", "Score": "0", "body": "1) It gives the literals a type. Types are very important in C++. It has none of the downsides of macros (which don't obey scope boundaries in the same way the language does). It has the same upside (takes zero space)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T18:38:31.220", "Id": "66204", "Score": "0", "body": "2) Good. Sorted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T18:39:39.253", "Id": "66205", "Score": "1", "body": "3) Yes. But that's encapsulation for you. It forces you to be nice and tidy and keep functions that work together in the same pace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T18:45:33.963", "Id": "66207", "Score": "1", "body": "4) Now try: `sizeof (board) / sizeof (board [0])`. Do you expect all combinations to work or just the ones you happen to remember are exceptions to the rule. Using this technique will lead to you making a mistake. Pass by reference to avoid the possibility of it going wrong (or preferably pass a standard container by reference)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T19:12:09.413", "Id": "66211", "Score": "0", "body": "@LokiAstari 1) Thinking about scope boundaries, wouldn't it be better for it to be `static const int` or using an anonymous namespace?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T19:13:16.153", "Id": "66212", "Score": "0", "body": "@LokiAstari 3) I agree that using a struct would be better, but I created my answer on the premise that a 2D array was required. I might go back later and change it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T19:16:28.060", "Id": "66213", "Score": "0", "body": "@LokiAstari 4) My point was that the compiler does not see it as the same as a `void SomeFunc (int** board)`. Aside from that, I agree with you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T21:36:49.883", "Id": "66232", "Score": "0", "body": "1) Static/anonymous would be great additions if you want to limit scope." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:19:09.657", "Id": "38778", "ParentId": "38752", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T14:29:54.933", "Id": "38752", "Score": "6", "Tags": [ "c++", "beginner", "game", "random", "number-guessing-game" ], "Title": "Random number game" }
38752
<p>I have a year or so of experience in developing in Java. I submitted <a href="https://github.com/kristjanr/energycalc" rel="nofollow">the solution</a> for <a href="http://blog.codeborne.com/2012/04/every-developer-wants-to-estimate-his.html" rel="nofollow">this task</a>, but never got the feedback that was promised. Since I still would like to get a feedback on my solution, I figured that here I will find skilled developers who wish to help me and others who may have similar questions.</p> <blockquote> <p>Compute electricity day- and night- consumption of a client. Given client's per-hour electricity consumption for some month. Goal is to compute total day- and night- consumption. Hours are enumerated from 1 starting from beginning of month. Day hours are 7-23 at working days (8-24 at daylight saving time or summer). All other hours are night hours. Example for January 2012:</p> <pre class="lang-none prettyprint-override"><code>1 - 2kW (hour #1 is January 1, Sunday, 00:00 - 01:00 - NIGHT) 2 - 3kW (hour #2 is January 1, Sunday, 01:00 - 02:00 - NIGHT) 26 - 3kW (hour #26 is January 2, Monday, 01:00 - 02:00 - NIGHT) 32 - 6kW (hour #32 is January 2, Monday, 07:00 - 08:00 - DAY) ... 744 - 0kW (hour #744 is January 31, 23:00 - 24:00) </code></pre> <p>In this case, night consumption is 8 = 2+3+3 and day consumption is 6.</p> </blockquote> <pre class="lang-java prettyprint-override"><code> /** * Used for calculating day and night tariff energy consumption for one month. Takes into account the start and end time changes of * the day and night tariff because of the day light saving time period. * This constructor uses Estonian time zone and 7-23 as day hours and 8-24 as day hours at daylight saving time. * * @param consumptionData One month's consumption data for each hour. Each hour - consumption pair has to be on a separate line. * Syntax: First the hour value, second, the separator: ' - ' and then the amount. * Hours have to be integers, and start from 1. Lines with non-integer hour values are disregarded. * Amount has to be a number value. Non-numbers are considered as zero value. * For example, if one line of data is '1 - 2.5kW', then the hour #1 is first day of a month at 00:00 - 01:00. * @param month Month (1-12) for which the data belongs to. * @param year Year for which the data belongs to. */ public MonthConsumption(final BufferedReader consumptionData, final int month, final int year) </code></pre> <p></p> <pre class="lang-java prettyprint-override"><code> /** * Used for calculating day and night tariff energy consumption for one month. Takes into account the start and end time changes of * the day and night tariff because of the day light saving time period. * * @param consumptionData One month's consumption data for each hour. Each hour has to be on a separate line. * First the hour value, then the separator ' - ' and then the amount. * Hours have to be integers, and start from 1. Lines with non-integer hour values are disregarded. * Amount can be double or integer value. * For example, if one line of data is '1 - 2kW', then the hour #1 is first day of a month at 00:00 - 01:00. * @param month Month (1-12) for which the data belongs to. * @param year Year for which the data belongs to. * @param timezone Timezone where the data was measured. Values for the timezones can be acquired * &lt;a href="http://joda-time.sourceforge.net/timezones.html"&gt;here&lt;/a&gt; * from the 'Canonical ID' column. This is needed to consider the daylight saving time changes. * @param dayTariffStartHour The hour of the day from which the day tariff is being measured during the standard, non-daylight saving time period. * @param dayTariffEndHour The hour of the day which is the last hour of day tariff during the standard, non-daylight saving time period. * @param dstDayTariffStartHour The hour of the day from which the day tariff is being measured during the daylight saving time period. * @param dstDayTariffEndHour The hour of the day which is the last hour of day tariff during the daylight saving time period. */ public MonthConsumption(final BufferedReader consumptionData, final int month, final int year, final String timezone, final int dayTariffStartHour, final int dayTariffEndHour, final int dstDayTariffStartHour, final int dstDayTariffEndHour) </code></pre> <p></p> <pre class="lang-java prettyprint-override"><code>/** * * @return Consumption amount that the day tariff applies to. */ public Double duringDayTariff() </code></pre> <p></p> <pre class="lang-java prettyprint-override"><code> /** * * @return Consumption amount that the night tariff applies to. */ public Double duringNightTariff() @Test public void nightConsumptionIsFromFirstHourToEighthHourWhenDST() throws Exception { BufferedReader reader = new BufferedReader(new StringReader("1 - 1" + "\n" + "8 - 1" + "\n" + "24 - 10" + "\n" + "9 - 10")); MonthConsumption monthConsumption = new MonthConsumption(reader, 4, 2013); assertEquals(2, monthConsumption.duringNightTariff(), 0); } </code></pre> <p></p> <pre class="lang-java prettyprint-override"><code>@Test public void testIncludedWithTheTask() throws Exception { BufferedReader reader = new BufferedReader(new StringReader("1 - 2" + "\n" + "2 - 3" + "\n" + "26 - 3" + "\n" + "32 - 6" + "\n" + "744 - 0")); MonthConsumption monthConsumption = new MonthConsumption(reader, 1, 2013); assertEquals(8, monthConsumption.duringNightTariff(), 0); assertEquals(6, monthConsumption.duringDayTariff(), 0); } </code></pre> <p></p> <pre class="lang-java prettyprint-override"><code>@Test public void daylightSavingStartsOnLastSundayOfMarchInEstoniaAt01UTC_March2013() throws FileNotFoundException { String fileName = "endOfMarch2013.csv"; String fileSeparator = System.getProperty("file.separator"); final String filePath = "src" + fileSeparator + "test" + fileSeparator + "resources" + fileSeparator + fileName; BufferedReader reader = new BufferedReader(new FileReader(filePath)); MonthConsumption monthConsumption = new MonthConsumption(reader, 3, 2013); /* The "endOfMarch2013.csv" file has 50 hours, each with consumed value of 1. The 723th hour is 2013 31th March 02:00-02:59. DST starts at 03:00 (UTC 01:00). This means that the time from 3:00-3:59 is skipped. 724th hour is 2013 31th March 04:00-05:59 Therefore, 744th hour is the beginning of the next month, which will not be added.*/ assertEquals(48, monthConsumption.duringNightTariff(), 0); assertEquals(1, monthConsumption.duringDayTariff(), 0); } </code></pre> <p>Questions:</p> <ol> <li>Is the public interface easy to use? Is there a better way instead of <code>BufferedReader</code> to pass data to <code>MonthConsumption</code>? Do the public methods of <code>MonthConsumption</code> have understandable documentation?</li> <li>Which tests are missing? Should I create tests for private methods as well? Have you come up with a test that would give some unwanted response?</li> <li>Is the design of unit tests using best practices? Do the unit tests serve as an explanation of what the program does? If no, then what should I change?</li> <li>Are there enough/not too many comments? Are there some private methods that need comments?</li> <li>Do the method and variable names help in understanding and reading the code?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:13:45.547", "Id": "65196", "Score": "2", "body": "Personally, I distinguish between comments and JavaDoc, the last is documentation which is non-negotiable. Can there be too many comments? Yes, absolutely. Can there be too many JavaDoc? If you do JavaDoc right, there can't be enough of it (and from reading through this, you're doing it awesome)!" } ]
[ { "body": "<p>the first thing that I noticed is that your functions do not describe an action, they are missing a verb. So when a reader comes to the function \"MonthConsumption()\" he has to read your comment to find out if the function calculates a mont consumption or .. or .. or consumes a month :-)</p>\n\n<p>I like that you name your methos quite explicit, for my taste they are a bit too long. Good thing: in case of the @Test you exactly know the conditions for this test. But i would suggest giving shorter names.</p>\n\n<p>Regarding to your comments: in \"Clean Code\" (by Robert C Martin) it is said that comments should not be neccessary to understand a code. However, I think comments are often neccesary to describe something in the real world.</p>\n\n<p>The second function has a lot of parameters. I would suggest going for a object-based concept to avoid too much function parameters.</p>\n\n<p>It is obvious that you worked and thought a lot on this example. Keep on, stay interested, a good progammer always learns :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:55:44.387", "Id": "65201", "Score": "0", "body": "I believe `MonthConsumption` is the name of the constructor, in which case the naming would be appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T10:17:49.700", "Id": "65313", "Score": "0", "body": "Yes, your're right! I didn't notice that the Method had no return value - so it must be the constructor. So we are missing a lot of Context / source code here in order to be able to review the code correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T11:29:17.577", "Id": "65317", "Score": "0", "body": "Full source code was provided in the link." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:41:07.697", "Id": "38769", "ParentId": "38762", "Score": "4" } }, { "body": "<h3>I/O and Exception Handling</h3>\n\n<p>Whenever you perform I/O, you will have a possibility of <code>IOException</code>s. The code in <code>MonthConsumption</code> is not in a position to decide what to do if that happens. You should have the constructors declare <code>throws IOException</code> — unless you like the idea of giving everyone free electricity whenever your server encounters a glitch. Otherwise, your only recourse would be to throw some (wrapped) <code>RuntimeException</code> instead, which would be ugly.</p>\n\n<p>Depending on how paranoid you are, you might also want to declare <code>throws MalformedDataException</code> as well.</p>\n\n<p>Given that you accept a <code>BufferedReader</code>, I would like to know, in what state will you leave the <code>BufferedReader</code> after the constructor completes? Will you <code>.close()</code> it? (I assume not.) Would there ever be the possibility that the stream contains data for more than one month, and if so, would <code>MonthConsumption</code> be smart enough to stop reading just before the start of the following month? (I hope so, but I wouldn't count on undocumented behaviour.) It would be nice if you clarified these issues in the JavaDoc.</p>\n\n<p>One kind of <code>IOException</code> of particular concern is end of file. What happens if the end of the stream is encountered after reading a complete row, but before the end of the month is reached? If we are running this code to generate a mid-month status update, that would be perfectly fine. That suggests that EOF should be treated as normal. On the other hand, if a stream prematurely terminates due to an I/O glitch while we are generating monthly invoices, a customer could get free electricity for the rest of the month. The caller should be able to distinguish between the two conditions, perhaps with a <code>.getCurrentDateTime()</code> method to check how far it has read.</p>\n\n<h3>Usability</h3>\n\n<p>I find <code>public Double duringDayTariff()</code> and <code>public Double duringNightTariff()</code> problematic.</p>\n\n<p>I think that the naming is a bit off. \"Tariff\" implies that money is involved, yet in this code you are only concerned about the time periods during which a rate applies. Furthermore, you're not fetching a tariff or tariff period, but the amount of electricity consumed during a tariff period.</p>\n\n<p>Avoid boxed types in interfaces. Returning a <code>double</code> would be more conventional. To be clear, it should be documented what the return value represents. Is it a monetary amount? An amount of electricity? In what units? Kilowatt-hours? Kilovolt-amps? Joules? Whatever unit was used in the data feed?</p>\n\n<p>My recommendation here would be:</p>\n\n<pre><code>/**\n * Totals the electricity consumed during the month during the daytime\n * tariff period, in kW*h.\n */\npublic double getDaytimeConsumption() { … }\n\n/**\n * Totals the electricity consumed during the month during the nighttime\n * tariff period, in kW*h.\n */\npublic double getNighttimeConsumption() { … }\n</code></pre>\n\n<h3>Orthogonality and Extensibility</h3>\n\n<p>One concern for me is the cluster of five arguments to the more complex constructor:</p>\n\n<pre><code>public MonthConsumption(…, String timezone,\n int dayTariffStartHour, int dayTariffEndHour,\n int dstDayTariffStartHour, int dstDayTariffEndHour)\n</code></pre>\n\n<p>This makes me uneasy for two reasons:</p>\n\n<ol>\n<li>You hard-code the idea of two tariff periods.</li>\n<li>Your code for parsing the stream and adding values is now committed to handling daylight saving time as well.</li>\n</ol>\n\n<p>I think it would be worthwhile to decompose the problem by introducing a <code>TariffPeriod</code> concept. Even if the business is committed to the idea of only two tariff periods, your code would benefit from better organization.</p>\n\n<pre><code>public interface TariffPeriod {\n public boolean isApplicable(DateTime dt);\n}\n\npublic class MonthConsumption {\n public MonthConsumption(…, String timezone, TariffPeriod... tariffPeriods) {\n …\n }\n\n /**\n * Totals the electricity consumed during the month during the specified\n * tariff period, in kW*h. The tariff period should be one of the\n * periods specified in the constructor. To get the consumption for\n * all times that fall outside any tariff period, use null for the\n * tariffPeriod.\n */\n public double getConsumption(TariffPeriod tariffPeriod) {\n …\n }\n}\n</code></pre>\n\n<p>Then you can implement a <code>TariffPeriod</code> that includes 7h–23h during standard time and 8h—24̱h during daylight saving time. The nighttime period could be considered the \"default\".</p>\n\n<h3>Implementation Notes</h3>\n\n<p>Whenever you have alternate constructors, the one with more defaults should chain to the one with more explicit parameters.</p>\n\n<p>Keeping a map of the hour-by-hour consumption data seems to be overkill, when all you care about are the totals for each tariff period. Just keep running totals for each tariff period as you parse.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:00:02.433", "Id": "38992", "ParentId": "38762", "Score": "4" } } ]
{ "AcceptedAnswerId": "38769", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:52:45.250", "Id": "38762", "Score": "6", "Tags": [ "java", "unit-testing", "api", "jodatime" ], "Title": "Computing the electricity consumption of a client" }
38762
<p>I based this implementation upon the implementation given in <a href="https://stackoverflow.com/a/16215688/1219414">this answer</a> and the book linked in it, but modified it to, instead of a constraint list and a substitution stack, generate a substitution tree in a single tree traversal operation. </p> <p>Each node in the substitution tree is a <code>VariableType</code>. Child nodes are in the <code>Types</code> array. Types with no children represent just variable types, types with one child represent type that have been replaced with the child, and types with two children represent function types. </p> <p>The <code>Deepest</code> method gets the current substitute given any type, since to replace, say, <code>a</code> with <code>b</code>, provided <code>a</code> is a leaf (has no children), you just set <code>b</code> to be the only child of <code>a</code>. This is what the <code>ReplaceWith</code> method does, which must take a leaf as the type to be replaced. </p> <p>The <code>Unify</code> method must always get deepest terms (terms with zero or two children).</p> <pre><code>public interface ILambdaTerm { } public interface IVariableTerm : ILambdaTerm { string Name { get; } } public interface IAbstractionTerm : ILambdaTerm { string ArgumentName { get; } ILambdaTerm Body { get; } } public interface IApplicationTerm : ILambdaTerm { ILambdaTerm Function { get; } ILambdaTerm[] Parameters { get; } } public class VariableType { public VariableType[] Types; public VariableType(VariableType argType, VariableType resType) { Types = new VariableType[] { argType, resType }; } public VariableType() { Types = new VariableType[0]; } private bool Contains(VariableType type) { if (Types.Length == 0) return this == type; else return Types.Any(subType =&gt; subType.Contains(type)); } public void ReplaceWith(VariableType type) { if (type.Contains(this)) throw new Exception("Circular type."); Types = new VariableType[] { type }; } public VariableType Deepest() { VariableType type = this; while (type.Types.Length == 1) type = type.Types[0]; return type; } } public class TypeChecking { private static void Unify(VariableType a, VariableType b) { if (a == b) return; if (a.Types.Length == 0) a.ReplaceWith(b); else { if (b.Types.Length == 0) b.ReplaceWith(a); else { Unify(a.Types[0].Deepest(), b.Types[0].Deepest()); Unify(a.Types[1].Deepest(), b.Types[1].Deepest()); } } } private static VariableType TypeOfTerm(ILambdaTerm term, IScope&lt;VariableType&gt; typeContext) { if (term is IVariableTerm) { var varTerm = (IVariableTerm)term; if (!typeContext.ContainsKey(varTerm.Name)) throw new Exception(string.Format("Undeclared variable '{0}'.", varTerm.Name)); return typeContext[varTerm.Name].Deepest(); } if (term is IAbstractionTerm) { var absTerm = (IAbstractionTerm)term; var argType = new VariableType(); var resType = TypeOfTerm(absTerm.Body, new InnerScope&lt;VariableType&gt;(typeContext, absTerm.ArgumentName, argType)); return new VariableType(argType, resType); } if (term is IApplicationTerm) { var appTerm = (IApplicationTerm)term; var resType = new VariableType(); var argType = TypeOfTerm(appTerm.Parameters[0], typeContext); var funType = TypeOfTerm(appTerm.Function, typeContext); Unify(funType, new VariableType(argType, resType)); return resType.Deepest(); } else throw new Exception(string.Format("Dunno what to do with a '{0}'.", term)); } public static VariableType TypeOfTerm(ILambdaTerm term) { return TypeOfTerm(term, new GlobalScope&lt;VariableType&gt;()); } } </code></pre> <p>I also have an extension method which returns a type as a string, that uses a <code>Dictionary&lt;VariableType, string&gt;</code> to automatically assign a name to each type, considering only deepest types (types with zero or two children). I'm not to worried about this method so I skipped it to keep the post short. </p> <p>I'm not too worried about performance as I'm about correctness of the code above.</p>
[]
[ { "body": "<p>I can't say much about the correctness but I have some comments about the design:</p>\n\n<ol>\n<li><p>Whenever you write code like this:</p>\n\n<pre><code>if (foo is SomeType)\n{\n // do something\n}\nelse if (foo is SomeOtherType)\n{\n // do something else\n}\n...\n</code></pre>\n\n<p>then this is an indicator that your abstraction is flawed. I'm not saying you should never ever do it but more often than not it indicates a design problem.</p></li>\n<li><p>Another point is the empty <code>ILambdaTerm</code> interface. An interface is like a contract - so what does an empty contract mean? Not much really.</p></li>\n<li><p>Don't throw generic <code>Exception</code>. In your case an <code>InvalidOperationException</code> or maybe your own defined <code>TermValidationException</code> would probably make more sense. This would give the user at least some way of catching specific exceptions.</p></li>\n</ol>\n\n<hr>\n\n<p>For the design here is what I would consider changing:</p>\n\n<ol>\n<li><p>Move <code>Unify</code> into <code>VariableType</code> and make it public. <code>Unify</code> only operates on <code>VariableType</code>s so it makes more sense to live on the <code>VariableType</code> class.</p></li>\n<li><p><code>Types</code> in <code>VariableType</code> can now become private as well which reduces unnecessary exposure of the internal data storage of the class.</p></li>\n<li><p>Add a method <code>VariableType GetVariableType(IScope&lt;VariableType&gt; typeContext)</code> to the <code>ILambdaTerm</code> interface and move the implementation of the logic from the <code>if (term is ...)</code> blocks into the <code>GetVariableType</code> implementation in each of the concrete classes for the terms, e.g.:</p>\n\n<pre><code>public interface VariableTerm : IVariableTerm \n{\n public string Name { get; private set; }\n\n public VariableTerm(string name)\n {\n Name = name;\n }\n\n public override VariableType GetVariableType(IScope&lt;VariableType&gt; typeContext)\n {\n if (!typeContext.ContainsKey(Name))\n throw new Exception(string.Format(\"Undeclared variable '{0}'.\", Name));\n return typeContext[Name].Deepest();\n }\n}\n</code></pre>\n\n<p>Now you can get the <code>VariableType</code> of a term simply by writing:</p>\n\n<pre><code>ILambdaTerm myTerm = ...\n...\n\nvar variableType = term.GetVariableType(new GlobalScope&lt;VariableType&gt;());\n</code></pre>\n\n<p>and your <code>TypeChecking</code> class can disappear.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T09:18:23.167", "Id": "38817", "ParentId": "38763", "Score": "2" } } ]
{ "AcceptedAnswerId": "38817", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:58:57.583", "Id": "38763", "Score": "5", "Tags": [ "c#" ], "Title": "Is this implementation of the Hindley-Milner algorithm correct?" }
38763
<p>I'm in a location with poor Internet access. In order to ensure that a call to an external service succeeds, I am wrapping the call in a pseudo-<code>do-while</code> in Python. Additionally, I am limiting the call to running a maximum of three times:</p> <pre><code>def post_safe(url, params): done = 0 max_tries = 3 messages = [] while done&lt;max_tries: try: response = requests.post(url, data=params) except Exception as e: messages.append(e) time.sleep(1) else: done = max_tries+1 done += 1 if done==max_tries: output = "%s\n" % (datetime.now().strftime('%Y-%m-%d %H:%M'),) output+= "requests() failed 3 times:\n" for m in messages: output+= m+"\n" print(output) return False return True </code></pre> <p>I personally am not satisfied with the 'Pythoness' of this code. It looks inelegant, and I would have preferred to use the type <code>bool</code> for <code>done</code> but that would require a second variable to count the iterations.</p> <p><strong>Is there a cleaner way to achieve a <code>do-while</code> in Python while limiting the amount of iterations?</strong></p>
[]
[ { "body": "<p>The <code>else</code> branch in your <code>try</code> is hackish (skipping over the <code>max_tries</code>) so I added <code>success</code> variable.<br>\n(Although you asked not to avoid it in the question, I think it's the better way, and I'll explain why.)</p>\n\n<p>It also nicely allowed me to </p>\n\n<ul>\n<li>replace <code>if done==max_tries</code> with <code>if not success</code>;</li>\n<li>remove <code>else</code> branch altogether;</li>\n<li>return <code>success</code> instead of having two <code>return</code> statements.</li>\n</ul>\n\n<p>I think it reads more easily now.</p>\n\n<pre><code>def post_safe(url, params):\n messages = []\n\n success = False\n max_retries = 3\n retries = 0\n\n while retries &lt; max_retries and not success:\n try:\n response = requests.post(url, data=params)\n success = True\n except Exception as e:\n messages.append(e)\n time.sleep(1)\n\n retries += 1\n\n if not success:\n output = \"%s\\n\" % (datetime.now().strftime('%Y-%m-%d %H:%M'),)\n output+= \"requests() failed 3 times:\\n\"\n for m in messages:\n output+= m+\"\\n\"\n print(output)\n\n return success\n</code></pre>\n\n<p>You <strong>can</strong> also get rid of <code>success</code> by returning <code>True</code> early in <code>try</code>:</p>\n\n<pre><code>def post_safe(url, params):\n messages = []\n\n retries = 0\n max_retries = 3\n\n while retries &lt; max_retries:\n try:\n response = requests.post(url, data=params)\n return True\n except Exception as e:\n messages.append(e)\n time.sleep(1)\n\n retries += 1\n\n output = \"%s\\n\" % (datetime.now().strftime('%Y-%m-%d %H:%M'),)\n output+= \"requests() failed 3 times:\\n\"\n for m in messages:\n output+= m+\"\\n\"\n print(output)\n\n return False\n</code></pre>\n\n<p>I <strong>don't</strong> like this approach. It wins us a variable and two lines but obfuscates the flow: </p>\n\n<ul>\n<li>In which case will the last block run? When we had an <code>if not success</code> condition, it was obvious, but now from a quick glance it <em>looks</em> like this block executes every time;</li>\n<li>What are function's <code>return</code> points? The first example had just one, and it was obvious what the return value represented.</li>\n</ul>\n\n<p>Let me quote <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">PEP 20</a>:</p>\n\n<ul>\n<li>Sparse is better than dense.</li>\n<li>Readability counts.</li>\n</ul>\n\n<p>Finally, <code>success</code> may be an “extra” variable from computer's point of view, but for a human, it's <em>the</em> expression that determines if the last block of code runs. It's good to <em>give it a name</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:37:45.540", "Id": "64727", "Score": "1", "body": "Thanks, Dan. Though just a tad more readable, I don't like the use of the extra variable (I mention that in the OP). I do think that the extra readability is due to the better-named variable (`done` was a terrible name). I'm hoping that a more 'Pythonic' answer comes along. I would almost expect this to be a common design pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:42:21.533", "Id": "64730", "Score": "0", "body": "@dotancohen I added a second example that doesn't need `success`, but personally I find it less obvious." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T12:39:14.997", "Id": "64866", "Score": "0", "body": "There were some terrific answers here. I choose this answer based on the readability. It _feels_ wasteful, but it is very readable and maintainable. Thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:33:12.367", "Id": "38768", "ParentId": "38766", "Score": "2" } }, { "body": "<p>One of the beauties of Python is that it can be made to read like English. With a very small amount of messing with your code, you can get to this, which I feel is much more readable:</p>\n\n<pre><code>def post_safe(url, params):\n\n done = False\n tries_left = 3\n messages = []\n\n while tries_left and not done:\n tries_left -= 1\n try:\n response = requests.post(url, data=params)\n done = True\n except Exception as e:\n messages.append(e)\n time.sleep(1)\n\n if not done:\n output = \"%s\\n\" % (datetime.now().strftime('%Y-%m-%d %H:%M'),)\n output+= \"requests() failed 3 times:\\n\"\n for m in messages:\n output+= m+\"\\n\"\n print(output)\n\n return done\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:08:28.113", "Id": "64740", "Score": "0", "body": "Great idea about decrementing the counter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:09:50.517", "Id": "64741", "Score": "2", "body": "That's what optimization freaks teach you to do in C: it seems that comparing to 0 is cheaper in some computer architectures..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:25:38.447", "Id": "64745", "Score": "0", "body": "Thank you, I also like the idea of decrementing the counter. I'll deliberate a bit before choosing one of the two excellent answers. Maybe a third will show up in the meantime!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:44:51.760", "Id": "64751", "Score": "0", "body": "nit-pick - sometimes I like `val += 1` instead of `val++` because it makes sense in that context, but, because `-` and `=` look more alike, I never recommend `val -= 1`. just use `val--`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:52:47.583", "Id": "64764", "Score": "0", "body": "@rolfl I see your point, but `val--` is not valid Python syntax..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:03:06.670", "Id": "64769", "Score": "3", "body": "@Jaime - I only open my mouth to swap feet. Appreciate that you didn't add 'idiot' to your comment ;-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:07:33.603", "Id": "38770", "ParentId": "38766", "Score": "3" } }, { "body": "<p>Python has a language feature just for that: <a href=\"http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\"><code>else</code> clauses on loops</a>.</p>\n\n<blockquote>\n <p>Loop statements may have an <code>else</code> clause; it is executed when the loop terminates through exhaustion of the list (with <code>for</code>) or when the condition becomes false (with <code>while</code>), but not when the loop is terminated by a <code>break</code> statement.</p>\n</blockquote>\n\n<pre><code>def post_safe(url, params):\n max_tries = 3\n messages = []\n\n for _ in range(max_tries):\n try:\n response = requests.post(url, data=params)\n return True\n except Exception as e:\n messages.append(e)\n time.sleep(1)\n\n else:\n print(datetime.now().strftime('%Y-%m-%d %H:%M'))\n print(\"requests() failed %d times:\" % (max_tries))\n for m in messages:\n print(m)\n return False\n</code></pre>\n\n<p>I'd also make the following changes:</p>\n\n<ul>\n<li>The <code>else</code> clause on the <code>try</code> block is unnecessary; it can be replaced with a <code>break</code> within the <code>try</code> block just after calling <code>.post()</code>. But in the end, you'll just end up returning <code>True</code>, so why not get out of there right away with <code>return True</code>? (For that matter, the <code>else</code> block that I just suggested is also unnecessary, as the <code>else</code> could be removed and its contents outdented by one level.)</li>\n<li>It seems easier to print each line separately than to build a multi-line string to print all at once. You might want to consider <a href=\"http://docs.python.org/2/library/logging.html\"><code>logging</code></a> instead.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:47:01.860", "Id": "64753", "Score": "0", "body": "huh ... lsned - learn something new every day." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:36:19.330", "Id": "64761", "Score": "1", "body": "Considering the `return True` in the `try` block, the `else` clause on the `for` loop is unnecessary too! But I must say, `for-else` is great and thank you for mentioning it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:37:00.967", "Id": "38773", "ParentId": "38766", "Score": "9" } }, { "body": "<p>Consider stripping the method down to the essential <code>requests.post()</code> call, and using the <a href=\"https://pypi.python.org/pypi/retrying\" rel=\"nofollow\"><code>@retry</code></a> decorator instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-06T19:55:41.627", "Id": "155164", "Score": "0", "body": "Thank you, I will try the `retrying` package. Note that I reverted your edit, as this question is about the general case of do-while in Python, not the specific HTTP request issue that is used as an example of why it is necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-06T21:00:52.410", "Id": "155176", "Score": "0", "body": "But a `do`-`while` differs from a `while` in exactly that aspect: A thing is done at least once and *maybe* again and again. There is at least a strong relation to the idea of a retry in that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-06T19:51:26.727", "Id": "86063", "ParentId": "38766", "Score": "1" } } ]
{ "AcceptedAnswerId": "38768", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:26:06.097", "Id": "38766", "Score": "6", "Tags": [ "python", "error-handling" ], "Title": "Do-While loop in Python, with limit on the amount of 'do's" }
38766
<p>I am trying to write clean code in Java for reading text of any size and printing the word count in ascending order without using Java collection framework.</p> <p>For example, given the following input text "What is the your name of the name?", it should print:</p> <pre><code>your 1 of 1 is 1 What 1 name 2 the 2 </code></pre> <p>I have written the below code, but I am not sure it is the right answer. Please evaluate it.</p> <pre><code>public class WordArrayList { private WordData[] words; public void setWords(WordData[] words) { this.words = words; } public WordData[] getWords() { return words; } private int size; public WordData getWord(int index) { return words[index]; } public int getSize() { return size; } private static final int DEFAULT_WORD_ARRAY_SIZE = 10; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public WordArrayList() { words = new WordData[DEFAULT_WORD_ARRAY_SIZE]; } public WordArrayList(int initialCapacity) { super(); if (initialCapacity &lt; 0) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); words = new WordData[initialCapacity]; } public int insertWord(final String word) { if (checkAndAddExistingWord(word)) { return 0; } checkAndIncreaseCapacity(); words[size] = new WordData(word); size++; return 1; } private boolean checkAndAddExistingWord(String word) { int position = 0; for (position = 0; position &lt; size; position++) { if (words[position].getWord().equals(word)) { words[position].incrementWordCount(); return true; } } return false; } private void checkAndIncreaseCapacity() { if (isWordArrayFull(size)) increaseCapacity(size); } private void increaseCapacity(int size) { int newCapacity = size * 2; if (newCapacity &gt; MAX_ARRAY_SIZE) { newCapacity = Integer.MAX_VALUE; } WordData[] newWords = new WordData[newCapacity]; System.arraycopy(words, 0, newWords, 0, size); } private boolean isWordArrayFull(int wordCount) { return (wordCount - words.length &gt; 0); } public void setWord(int i, WordData word) { words[i] = word; } public class TextAnalyzer { private static final String REG_SPLIT_EXP = "\\s+"; private String text; private String textSplitExp; private WordArrayList wordArrayList; public TextAnalyzer(String text, String textSplitExp) { this.textSplitExp = textSplitExp; this.text = text; wordArrayList = new WordArrayList(); } public TextAnalyzer(String text) { this.textSplitExp = REG_SPLIT_EXP; this.text = text; wordArrayList = new WordArrayList(); } private String[] convertToArray() { return text.split(textSplitExp); } public void generateWordArrayList() { String[] splitTextArray = convertToArray(); for (int i = 0; i &lt; splitTextArray.length; i++) { wordArrayList.insertWord(splitTextArray[i]); } } public void printWordArrayList() { for (int i = 0; i &lt; wordArrayList.getSize(); i++) { System.out.println("=" + wordArrayList.getWord(i).getWord() + "==" + wordArrayList.getWord(i).getWordCount()); } } public void sortWordArrayList() { TextAnalyzerUtil.sort(wordArrayList); } } public class WordData { public WordData(final String vWord) { this.word = vWord; this.wordCount=1; } private String word; public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public void setWord(String word) { this.word = word; } private int wordCount; private int position; public String getWord() { return word; } public void incrementWordCount() { this.wordCount++; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } } </code></pre> <p>For testing:</p> <pre><code>analyzer.generateWordArrayList(); analyzer.sortWordArrayList(); analyzer.printWordArrayList(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:41:47.030", "Id": "64729", "Score": "0", "body": "Could you include the `TextAnalyzerUtil.sort` method in your code? That way we could compile the code ourselves and therefore make a better review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:16:29.323", "Id": "64743", "Score": "1", "body": "Nevermind, sorting the word list isn't that important really :)" } ]
[ { "body": "<p>There are a couple of things you should think about or fix:</p>\n\n<ul>\n<li><p>Indentation. You're not really consistent in indenting your code. Please follow the Java conventions.</p></li>\n<li><p>No need to call <code>super()</code> inside your constructor, the default empty super constructor is automatically called.</p></li>\n<li><p>Use \"constructor chaining\" in <code>WordArrayList</code>, and <code>TextAnalyzer</code>. That is, call one constructor from another. For example,</p>\n\n<pre><code>public TextAnalyzer(String text) {\n this(text, REG_SPLIT_EXP);\n}\n</code></pre></li>\n<li><p>You have a whole lot of unnecessary methods: <code>setWords</code>, <code>getWords</code>, <code>setWordCount</code>, <code>setWord</code>. You don't use them and I really don't think that you need them.</p></li>\n<li><p>Use <code>private final</code> for fields that should be initialized once and then never change, such as <code>private final String word;</code> in the <code>WordData</code> class. Apply this wherever possible.</p></li>\n<li><p><code>private int position;</code> is not used in <code>WordData</code>, and I don't think you need to use it either. Select and press the <kbd>Delete</kbd> button on your keyboard</p></li>\n<li><p>I suggest naming the class <code>WordList</code> instead. The fact that it uses an array is not important. It is a List of words, how the internal list works is not needed for the user to know</p></li>\n<li><p>Calling <code>generateWordArrayList</code> multiple times would produce strange results.</p></li>\n<li><p><code>convertToArray</code> is private, contains one line, and is only called from one location: Does it really need to be it's own method?</p></li>\n<li><p>Use a \"for-each\" loop to improve readability when iterating:</p>\n\n<pre><code>for (String str : splitTextArray)\n</code></pre></li>\n<li><p>You can store the number of times each word occurs with a <code>HashMap&lt;String, Integer&gt;</code> instead. To initialize the HashMap, you can use this:</p>\n\n<pre><code>Map&lt;String, Integer&gt; words = new HashMap&lt;String, Integer&gt;();\nfor (String str : splitTextArray) {\n if (words.containsKey(str))\n words.put(str, words.get(str) + 1);\n else words.put(str, 1);\n}\n</code></pre>\n\n<p>Note that you can use <code>TreeMap</code> instead of <code>HashMap</code> to keep the keys in a sorted order, so that if you iterate over <code>words.entrySet()</code>, you will always iterate in sorted order. (You can also provide a custom <code>Comparator</code> to the TreeMap if you are not satisfied with the built-in sorting)</p></li>\n</ul>\n\n<p>Overall the current classes you have seems to do what they are supposed to do, and the result is correct. Good job.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:29:58.820", "Id": "64746", "Score": "0", "body": "thanks for your prompt response sorry for not adding sorting code but it was just quick sort. Can the above code be done in better way. I am asking in better design prospect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:33:03.743", "Id": "64747", "Score": "0", "body": "@Nitin Remove the `WordData` class, and replace the `WordArrayList` class with a `Map<String, Integer>`. That's the simplest and in my opinion best way to get the job done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:35:21.577", "Id": "64748", "Score": "0", "body": "Hi Simon, sorry i need to write code without collection so no hashmap" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:39:32.997", "Id": "64749", "Score": "0", "body": "@Nitin In that case, just clean up your code by following the other points I have pointed out for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:43:20.747", "Id": "64750", "Score": "0", "body": "thanks Simon, do u think I need to rename any class name,method name or variable name like WordList as u suggested? Any where i can improve exception handling?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:45:02.170", "Id": "64752", "Score": "0", "body": "@Nitin I personally don't see the need for any exceptions in your code. But you might want to ask your teacher/professor for tips, if he or she is not happy about your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:40:32.613", "Id": "64762", "Score": "3", "body": "When putting a count as a value in a map, I tend to use a mutable value (e.g. `AtomicInteger`) so updating the count can be done without doing a `put` every time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:26:25.917", "Id": "64776", "Score": "0", "body": "Just one doubt Can above code support million of word. Or I need to modify it?" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:15:45.280", "Id": "38771", "ParentId": "38767", "Score": "13" } }, { "body": "<h3>Bug</h3>\n\n<p>In <code>increaseCapacity()</code>, you create a new array and copy the old contents to it, but never replace the old array.</p>\n\n<h3>Efficiency</h3>\n\n<p>The running time will be O(<em>n</em><sup>2</sup>), where <em>n</em> is the number of words, since you could potentially run through the entire existing array when adding a new word. Using a <code>HashMap</code> would be O(<em>n</em>), and a <code>TreeMap</code> would be O(<em>n</em> log <em>n</em>). You are probably doing this the \"hard\" way for fun, so that's OK, as long as you are aware of the potential performance problem.</p>\n\n<h3>Interface</h3>\n\n<p>You should pare down the number of exposed methods, not just to reduce the amount of code, but to improve the interface. If you put getters and setters on all fields, your class would be too promiscuous. At that point, you might as well make all the fields <code>public</code>. (In fact, the way your current code exposes all its state, it is about as unmaintainable as code that uses global variables.) By choosing what methods to expose, you give the class a specific purpose and prevent it from being misused. Also, limiting the interface helps you reserve the capability to change the implementation, should you come up with a better idea later.</p>\n\n<p>For <code>WordArrayList</code>:</p>\n\n<ul>\n<li>You should rename it to <code>WordCounter</code>. <code>WordArrayList</code> sounds like a generic, passive data structure. <code>WordCounter</code> has a clear purpose.</li>\n<li><code>insertWord()</code> is a misnomer, it implies that it will always result in an additional entry, and that the caller has some control over the order of insertion. I think <code>addWord()</code> would be more appropriate.</li>\n<li>I would also offer <code>addWords(String[] words)</code>, since it's convenient for callers, and it might present opportunities for optimization if you add a whole batch of words at once.</li>\n<li>Instead of exposing the guts of the object, I suggest presenting a method to retrieve an <code>Enumeration</code> of the results, based on the general advice above. (When the Java Collections Framework was introduced in 1.2, <code>Enumeration</code> was semi-deprecated in favor of <code>Iterator</code>. I don't know if you consider <code>Iterator</code> to be off-limits as a result, so I chose the antiquated <code>Enumeration</code> interface instead.)</li>\n<li>I would consolidate your private helper methods a bit for simplicity.</li>\n<li>I've added a <code>reset()</code> method to clear all the counts, which is quite optional. It makes up for the removal of <code>WordCount.setWordCount()</code>.</li>\n</ul>\n\n<p>For <code>WordData</code>:</p>\n\n<ul>\n<li>I would expose just <code>getWord()</code> and <code>getWordCount()</code> (probably better renamed to <code>getCount()</code>).</li>\n<li>The position should not be stored part of <code>WordData</code>, and in fact you never use it.</li>\n<li>You made the constructor take a <code>final</code> argument. That's OK, but the better place to put the <code>final</code> keyword is in the <code>private final String word</code> declaration.</li>\n<li>I choose to make it an inner class of <code>WordCounter</code>, but that's just my preference.</li>\n</ul>\n\n<p>Note that with these changes, users of <code>WordCounter</code> have no way to muck with its internal state except through the approved interfaces. <code>WordCounter</code> can offer some guarantees of self consistency in a way that the original <code>WordArrayList</code> couldn't. If it's used in a more complex system, those guarantees make it possible for you to debug the code using reasoning.</p>\n\n<h3>Constructor chaining</h3>\n\n<p>Whenever you offer more than one constructor, you should chain them, such that the one with more default parameters calls the one with explicit parameters.</p>\n\n<h3>Code formatting</h3>\n\n<p>Your code formatting is all over the place, in terms of indentation. You should also leave a blank line between methods for readability.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.Enumeration;\nimport java.util.NoSuchElementException;\n\npublic class WordCounter {\n\n //////////////////////////////////////////////////////////////////////\n\n public static class WordData {\n private final String word;\n private int wordCount;\n\n WordData(String vWord) {\n this.word = vWord;\n this.wordCount = 1;\n }\n\n public String getWord() {\n return word;\n }\n\n public int getWordCount() {\n return wordCount;\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n private static class WordFrequencyComparator implements Comparator&lt;WordData&gt; {\n @Override\n public int compare(WordData a, WordData b) {\n int wcDiff = b.getWordCount() - a.getWordCount();\n return wcDiff != 0 ? wcDiff : a.getWord().compareTo(b.getWord());\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n private WordData[] words;\n private int size;\n private static final int DEFAULT_WORD_ARRAY_SIZE = 10;\n private static final Comparator&lt;WordData&gt; DESCENDING_WORD_FREQUENCY_COMPARATOR = new WordFrequencyComparator();\n\n public WordCounter() {\n this(DEFAULT_WORD_ARRAY_SIZE);\n }\n\n public WordCounter(int initialCapacity) {\n if (initialCapacity &lt; 0)\n throw new IllegalArgumentException(\"Illegal Capacity: \"\n + initialCapacity);\n words = new WordData[initialCapacity];\n }\n\n /**\n * Clears the word count.\n */\n public void reset() {\n for (int i = 0; i &lt; size; i++) {\n words[i] = null;\n }\n }\n\n /**\n * Adds word to the word count.\n *\n * @return 1 if the word was previously unseen, 0 otherwise.\n */\n public int addWord(String word) {\n checkAndIncreaseCapacity(size + 1);\n if (checkAndAddExistingWord(word)) {\n return 0;\n }\n words[size++] = new WordData(word);\n return 1;\n }\n\n /**\n * Adds words to the word count.\n *\n * @return the number of previously unseen words.\n */\n public int addWords(String[] words) {\n checkAndIncreaseCapacity(size + words.length);\n int newWordsAdded = 0;\n for (String w : words) {\n newWordsAdded += addWord(w);\n }\n return newWordsAdded;\n }\n\n /**\n * Returns an Enumeration of the WordData in descending order of word\n * frequency. Behavior is undefined if you add words or reset the\n * counter while enumerating.\n */\n public Enumeration&lt;WordData&gt; elements() {\n Arrays.sort(words, 0, size, DESCENDING_WORD_FREQUENCY_COMPARATOR);\n return new Enumeration&lt;WordData&gt;() {\n private int i = 0;\n\n @Override\n public boolean hasMoreElements() {\n return i &lt; size;\n }\n\n @Override\n public WordData nextElement() {\n try {\n return words[i++];\n } catch (ArrayIndexOutOfBoundsException e) {\n throw new NoSuchElementException();\n }\n }\n };\n }\n\n private boolean checkAndAddExistingWord(String word) {\n for (WordData wd : words) {\n if (wd.getWord().equals(word)) {\n wd.wordCount++;\n return true;\n }\n }\n return false;\n }\n\n private void checkAndIncreaseCapacity(int sizeHint) {\n if (size &gt;= words.length) {\n int newCapacity = size * 2;\n if (newCapacity &lt; sizeHint) {\n newCapacity = sizeHint;\n }\n if (newCapacity &lt; 0) {\n newCapacity = Integer.MAX_VALUE;\n }\n WordData[] newWords = new WordData[newCapacity];\n System.arraycopy(words, 0, newWords, 0, size);\n words = newWords;\n }\n }\n}\n</code></pre>\n\n<p>With the changes above, <code>TextAnalyzer</code> can become a lot simpler:</p>\n\n<pre><code>import java.util.Enumeration;\n\npublic class TextAnalyzer {\n\n private static final String REG_SPLIT_EXP = \"\\\\s+\";\n private WordCounter wordCounter;\n\n public TextAnalyzer(String text, String textSplitExp) {\n wordCounter = new WordCounter();\n wordCounter.addWords(text.split(textSplitExp));\n }\n\n public TextAnalyzer(String text) {\n this(text, REG_SPLIT_EXP);\n }\n\n public void printWords() {\n Enumeration&lt;WordCounter.WordData&gt; words = wordCounter.elements();\n while (words.hasMoreElements()) {\n WordCounter.WordData wordData = words.nextElement();\n System.out.println(\"=\" + wordData.getWord() + \"==\"\n + wordData.getWordCount());\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T07:04:32.377", "Id": "65004", "Score": "0", "body": "thanks @200_success. I have couple of doubts 1. Can we scale this application for large number of text e.g. 1 miilion words. 2. Arrays is part of collection framework and use legacy sort which in terns clone the whole can we use sort without using Arrays?." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:57:20.640", "Id": "65186", "Score": "1", "body": "1. See my remarks about efficiency in the review. 2. You're right on both counts. `Arrays` was introduced with Java Collections in Java 1.2, and `Arrays.sort(Object[])` uses mergesort, which does not operate in place. In place of `Arrays.sort()`, you could substitute whatever sorting method you were using before." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:48:58.830", "Id": "38785", "ParentId": "38767", "Score": "9" } } ]
{ "AcceptedAnswerId": "38771", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T16:30:24.427", "Id": "38767", "Score": "10", "Tags": [ "java", "strings", "array" ], "Title": "Word count program in Java" }
38767
<p>I have a function which sends an email via outlook when given text, a subject, and recipients shown below:</p> <pre><code>def __Emailer(text, subject, recipient, auto=True): import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) if type(recipient) == type([]): for name in recipient: mail.Recipients.Add(name) else: mail.To = recipients mail.Subject = subject mail.HtmlBody = text if auto: mail.send else: mail.Display(True) </code></pre> <p>Now, I know that type comparisons in Python are <em>strongly discouraged</em>, but I can't think of a better way to do this. I want it to send to multiple addresses if <code>recipient</code> is a list using the <code>mail.Recipients.Add(name)</code>, and <code>mail.To</code> if there is only one name (not given as a list). How can I accomplish this without using nasty type comparisons?</p>
[]
[ { "body": "<p>In Python, it is part of the mentality to check for behavior rather than for exact type. </p>\n\n<p>Your method doesn't even need <code>recipients</code> to be a list—it can be any iterable (e.g. a set) so it can be used in the <code>for</code> loop. Strings, however, are also iterable, so you need to tell <em>them</em> apart. </p>\n\n<p>One way to check if something is a string is to <a href=\"https://stackoverflow.com/a/1835259/458193\">look for a string-specific method, such as <code>strip</code></a>.</p>\n\n<pre><code>def __Emailer(text, subject, recipients, auto=True):\n import win32com.client as win32 \n\n outlook = win32.Dispatch('outlook.application')\n mail = outlook.CreateItem(0)\n\n if hasattr(recipients, 'strip'):\n recipients = [recipients]\n\n for recipient in recipients:\n mail.Recipients.Add(recipient)\n\n mail.Subject = subject\n mail.HtmlBody = text\n\n if auto:\n mail.send\n else:\n mail.Display(True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:00:37.367", "Id": "64767", "Score": "0", "body": "That's beautiful. I thought of doing something like this with ```try...except```, but I'd actually have to execute code to do that, this is much better!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:39:27.540", "Id": "64777", "Score": "1", "body": "`mail.Recipients.Add(recipient)` should fail if you try to add a list. If so, you could duck type off that behavior. This is more of design problem of the calling function or the function being called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:00:11.023", "Id": "64780", "Score": "0", "body": "@dansalmo But why would `recipient` be a list? It would only be the case if you passed a nested list to `recipients`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:05:44.250", "Id": "64781", "Score": "0", "body": "Yes, Just pass what is received, then if `mail.Recipients.Add(recipient)` is a list, it will fail, then you can iterate over it. I meant to comment on the original question above, where `recipient` might be a list or string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:08:39.640", "Id": "64782", "Score": "0", "body": "Ah, I got it! I'm not feeling sure about duck type something outside of Python's bounds though (`Add` is from Outlook COM API)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:46:39.413", "Id": "38780", "ParentId": "38776", "Score": "3" } }, { "body": "<p>Sometimes type checking makes for more readable code than duck typing, and this is probably one of those cases. What you shouldn't do is compare the types the way you are doing, it is better to use <code>isinstance</code> instead. You could check directly for the input being a string as:</p>\n\n<pre><code>if isinstance(recipient, str):\n mail.To = recipients\nelse:\n for name in recipient:\n mail.Recipients.Add(name)\n</code></pre>\n\n<p>You may also want to look at the <a href=\"http://docs.python.org/2/library/collections.html#collections-abstract-base-classes\" rel=\"nofollow\">ABCs (Abstract Base Classes) in the <code>collections</code> module</a>, which provide a convenient way to check for certain general attributes in an object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:10:50.360", "Id": "38783", "ParentId": "38776", "Score": "3" } } ]
{ "AcceptedAnswerId": "38780", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:52:18.913", "Id": "38776", "Score": "4", "Tags": [ "python", "python-2.x", "outlook" ], "Title": "Sending an email via Outlook" }
38776
<p>This morning, I wrote a quick-and-dirty table-revision generation script: (<a href="https://gist.github.com/chrisforrence/8303815" rel="nofollow">gist</a>). It is intended to be run in the command line. Here's the entirety of it (149 lines):</p> <p> <pre><code>/** * Creates a revision table for an already-existing table. * TODO: Better error checking/handling * TODO: Sanitize table name input * * Usage: * [user@host]$ php MySQLRevision.php * // Table name: &lt;enter table name&gt; * * The MIT License (MIT) * * Copyright (c) 2014 Chris Forrence * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ const DB_TYPE = 'mysql'; const DB_NAME = ''; const DB_HOST = ''; const DB_USER = ''; const DB_PASS = ''; try { $dbh = new PDO(DB_TYPE . ":dbname=" . DB_NAME . ";host=" . DB_HOST, DB_USER, DB_PASS, array(PDO::ATTR_PERSISTENT =&gt; true)); } catch(PDOException $e){ $dbh = null; } if($dbh == null) { echo 'Could not get connection to database. Exiting.' . PHP_EOL; exit(); } echo '// Table name: '; $tn = trim(fgets(STDIN)); if(strlen($tn) &gt; 0) { $toRet = array(); list($query, $columns) = generateRevisionTable($dbh, $tn); if(is_array($columns) &amp;&amp; count($columns) &gt; 0) { $toRet[] = 'DROP TRIGGER IF EXISTS `rev_' . $tn . '_trigger_i`;'; $toRet[] = 'DROP TRIGGER IF EXISTS `rev_' . $tn . '_trigger_u`;'; $toRet[] = 'DROP TRIGGER IF EXISTS `rev_' . $tn . '_trigger_d`;'; $toRet[] = 'DROP TABLE IF EXISTS `rev_' . $tn . '`;'; $toRet[] = $query; unset($query); $toRet[] = 'DELIMITER ;;'; $toRet[] = generateInsert($tn, $columns); $toRet[] = generateUpdate($tn, $columns); $toRet[] = generateDelete($tn, $columns); $toRet[] = 'DELIMITER ;'; } else { $toRet[] = '// Could not find columns'; } foreach($toRet as $q) { echo PHP_EOL . $q . PHP_EOL; } } $dbh = null; unset($dbh); function generateRevisionTable($dbh, $tn) { try { $q = $dbh-&gt;prepare("SHOW COLUMNS FROM $tn"); $q-&gt;execute(); $toRet = array(); $table_fields = $q-&gt;fetchAll(); $c = 'CREATE TABLE `rev_' . $tn . '` (' . PHP_EOL; $cl = array(); foreach($table_fields as $t) { $c .= ' `' . $t['Field'] . '` ' . ($t['Type'] == 'timestamp' ? 'datetime' : $t['Type']) . ',' . PHP_EOL; $cl[] = $t['Field']; } $c .= " `revision_action` ENUM('INSERT', 'UPDATE', 'DELETE') NOT NULL," . PHP_EOL; $c .= " `revision_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT," . PHP_EOL; $c .= " `revision_modification` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," . PHP_EOL; $c .= " PRIMARY KEY(`revision_id`)" . PHP_EOL . ");"; } catch(PDOException $e) { echo $e-&gt;getMessage() . PHP_EOL; $dbh = null; exit(); } return array($c, $cl); } function generateDelete($tn, $cl) { $c = "CREATE TRIGGER `rev_${tn}_trigger_d` BEFORE DELETE ON `${tn}`" . PHP_EOL; $c .= " FOR EACH ROW BEGIN INSERT INTO rev_${tn} ("; foreach($cl as $cls) { $c .= '`' . $cls . '`, '; } $c .= 'revision_action) VALUES ('; foreach($cl as $cls) { $c .= 'OLD.`' . $cls . '`, '; } $c .= "'DELETE'); END;;" . PHP_EOL; return $c; } function generateUpdate($tn, $cl) { $c = "CREATE TRIGGER `rev_${tn}_trigger_u` AFTER UPDATE ON `${tn}`" . PHP_EOL; $c .= " FOR EACH ROW BEGIN INSERT INTO rev_${tn} ("; foreach($cl as $cls) { $c .= '`' . $cls . '`, '; } $c .= 'revision_action) VALUES ('; foreach($cl as $cls) { $c .= 'NEW.`' . $cls . '`, '; } $c .= "'UPDATE'); END;;" . PHP_EOL; return $c; } function generateInsert($tn, $cl) { $c = "CREATE TRIGGER `rev_${tn}_trigger_i` AFTER INSERT ON `${tn}`" . PHP_EOL; $c .= " FOR EACH ROW BEGIN INSERT INTO rev_${tn} ("; foreach($cl as $cls) { $c .= $cls . ', '; } $c .= 'revision_action) VALUES ('; foreach($cl as $cls) { $c .= 'NEW.`' . $cls . '`, '; } $c .= "'INSERT'); END;;" . PHP_EOL; return $c; } </code></pre> <p>From this, I have a few questions:</p> <ol> <li>I know that I'm not handling my PDO object very well. For truly one-off scripts, is this acceptable, or should I create an internal PDO wrapper?</li> <li>It is currently very possible to inject code. Since this would (presumably) not be public-facing, is it something that I can ignore (and fix it as a low priority)?</li> <li>Am I missing anything in the script that would cause resource leaks, major problems, etc.?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:23:42.670", "Id": "64775", "Score": "0", "body": "The only real comment I have to add is, If you know you could do better then why not? For question 1 I would say its never acceptable to half do the job. 2) NEVER ignore a security threat. It is low risk, but there is still risk." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:40:12.000", "Id": "64785", "Score": "0", "body": "@SaggingRufus: Valid points; it comes down to time usage, and I think that as is, it is working code. Fixable? Certainly. Production code? Nope. For point 2, unfortunately, it looks like I'll have to use a blacklist to restrict characters (and then something to add an extra `\\`` to entered table names)." } ]
[ { "body": "<blockquote>\n <ol>\n <li>I know that I'm not handling my PDO object very well. For truly one-off scripts, is this acceptable, or should I create an internal PDO wrapper?</li>\n </ol>\n</blockquote>\n\n<p>It is generally discouraged to wrap PDO. Please see this <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class\">excellent post on the topic</a> which explains that better than I could.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>It is currently very possible to inject code. Since this would (presumably) not be public-facing, is it something that I can ignore (and fix it as a low priority)?</li>\n </ol>\n</blockquote>\n\n<p>Why do you feel that you are less likely to inject dangerous code than 'the public'? Would you paste anything in there that you got in an email? Not even next year? Not even by accident?</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>Am I missing anything in the script that would cause resource leaks, major problems, etc.?</li>\n </ol>\n</blockquote>\n\n<p>You should probably set <code>charset=utf8</code>, and make sure that <code>PDO::ATTR_PERSISTENT</code> does what you think it does. You might be more interested in <code>$q-&gt;errorInfo()</code> than <code>$e-&gt;getMessage()</code>. Also, I would rewrite this:</p>\n\n<pre><code>if(strlen($tn) &gt; 0) {\n ..lots of code here..\n}\n</code></pre>\n\n<p>As this:</p>\n\n<pre><code>if(strlen($tn) &gt; 0) {\n echo \"Please provide input blah blah\\n\";\n exit();\n}\n\n..lots of code here..\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:41:59.190", "Id": "38794", "ParentId": "38779", "Score": "1" } } ]
{ "AcceptedAnswerId": "38794", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:34:49.077", "Id": "38779", "Score": "0", "Tags": [ "php", "optimization", "pdo" ], "Title": "Generating revision-table to accompany existing table" }
38779
<p>I'm at loggerheads between performing operations one-by-one within a method, performing all of them at once (in one block) within the method, or breaking them up into four different methods.</p> <p>In terms of best-practice, which of the following three options seems most advantageous, and why would it be preferred over the other options?</p> <h2>1st Option</h2> <p>Call the code:</p> <pre><code>string filename = string.Empty; DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { filename = openFileDialog1.FileName; } else { MessageBox.Show("No file selected - exiting"); return; } SpacelessWordBreakAerator(filename); </code></pre> <p>Implementation of code:</p> <pre><code> private void SpacelessWordBreakAerator(string filename) { string soughtCombo = string.Empty; string desiredCombo = string.Empty; List&lt;string&gt; specialWordEndings = new List&lt;String&gt;(); specialWordEndings.Add("é"); specialWordEndings.Add("í"); specialWordEndings.Add("ñ"); specialWordEndings.Add("?"); specialWordEndings.Add("!"); specialWordEndings.Add(","); specialWordEndings.Add("."); specialWordEndings.Add(":"); specialWordEndings.Add(";"); specialWordEndings.Add("\""); specialWordEndings.Add("»"); specialWordEndings.Add("ß"); List&lt;string&gt; specialWordBeginnings = new List&lt;String&gt;(); specialWordBeginnings.Add("¿"); specialWordBeginnings.Add("¡"); specialWordBeginnings.Add("\""); specialWordBeginnings.Add("«"); // Aerate "special" combinations: Cursor.Current = Cursors.WaitCursor; try { using (DocX document = DocX.Load(filename)) { foreach (string endChar in specialWordEndings) { foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", endChar, beginChar); desiredCombo = string.Format("{0} {1}", endChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); // Save after each step } // Aerate "special" ending with "normal" beginning - create a new DocX object with each different logic block using (DocX document = DocX.Load(filename)) { foreach (string endChar in specialWordEndings) { for (int i = FIRST_CAP_POS; i &lt;= LAST_CAP_POS; i++) { char upperChar = (char)i; soughtCombo = string.Format("{0}{1}", endChar, upperChar); desiredCombo = string.Format("{0} {1}", endChar, upperChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); } // Aerate "normal" ending with "special" beginning using (DocX document = DocX.Load(filename)) { for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", lowerChar, beginChar); desiredCombo = string.Format("{0} {1}", lowerChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); } // Aerate "normal" combinations (this is the legacy "InsertSpaceBetweenLowercaseAndUppercaseChars" helper method) using (DocX document = DocX.Load(filename)) { for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; for (int j = FIRST_CAP_POS; j &lt;= LAST_CAP_POS; j++) { char upperChar = (char)j; string originalStr = string.Format("{0}{1}", lowerChar, upperChar); string newStr = string.Format("{0} {1}", lowerChar, upperChar); document.ReplaceText(originalStr, newStr); } } document.Save(); } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! Aintcha glad?!?"); } </code></pre> <h2>2nd Option</h2> <p>Call the code: (same as first option)</p> <p>Implementation of code:</p> <pre><code> private void SpacelessWordBreakAerator(string filename) { // same var and const declarations as in first option... Cursor.Current = Cursors.WaitCursor; try { // Keep using the DocX object until the end, and save it only after all operations have completed using (DocX document = DocX.Load(filename)) { // Aerate "special" combinations: foreach (string endChar in specialWordEndings) { foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", endChar, beginChar); desiredCombo = string.Format("{0} {1}", endChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } } // Aerate "special" ending with "normal" beginning foreach (string endChar in specialWordEndings) { for (int i = FIRST_CAP_POS; i &lt;= LAST_CAP_POS; i++) { char upperChar = (char)i; soughtCombo = string.Format("{0}{1}", endChar, upperChar); desiredCombo = string.Format("{0} {1}", endChar, upperChar); document.ReplaceText(soughtCombo, desiredCombo); } // Aerate "normal" ending with "special" beginning for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", lowerChar, beginChar); desiredCombo = string.Format("{0} {1}", lowerChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } // Aerate "normal" combinations (this is the legacy "InsertSpaceBetweenLowercaseAndUppercaseChars" helper method) for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; for (int j = FIRST_CAP_POS; j &lt;= LAST_CAP_POS; j++) { char upperChar = (char)j; string originalStr = string.Format("{0}{1}", lowerChar, upperChar); string newStr = string.Format("{0} {1}", lowerChar, upperChar); document.ReplaceText(originalStr, newStr); } } document.Save(); } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! Aintcha glad?!?"); } </code></pre> <h2>3rd Option</h2> <p>Call the code:</p> <pre><code>string filename = string.Empty; DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { filename = openFileDialog1.FileName; } else { MessageBox.Show("No file selected - exiting"); return; } // Break it up into four separate methods SpacelessWordBreakUnusualCombo(filename); SpacelessWordBreakUnusualEndNormalBegin(filename); SpacelessWordBreakNormalEndUnusualBegin(filename); SpacelessWordBreakNormalCombo(filename); </code></pre> <p>Implementation of code:</p> <pre><code> private void SpacelessWordBreakUnusualCombo(string filename) { string soughtCombo = string.Empty; string desiredCombo = string.Empty; List&lt;string&gt; specialWordEndings = new List&lt;String&gt;(); specialWordEndings.Add("é"); specialWordEndings.Add("í"); specialWordEndings.Add("ñ"); specialWordEndings.Add("?"); specialWordEndings.Add("!"); specialWordEndings.Add(","); specialWordEndings.Add("."); specialWordEndings.Add(":"); specialWordEndings.Add(";"); specialWordEndings.Add("\""); specialWordEndings.Add("»"); specialWordEndings.Add("ß"); List&lt;string&gt; specialWordBeginnings = new List&lt;String&gt;(); specialWordBeginnings.Add("¿"); specialWordBeginnings.Add("¡"); specialWordBeginnings.Add("\""); specialWordBeginnings.Add("«"); // Aerate "special" combinations: Cursor.Current = Cursors.WaitCursor; try { using (DocX document = DocX.Load(filename)) { foreach (string endChar in specialWordEndings) { foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", endChar, beginChar); desiredCombo = string.Format("{0} {1}", endChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); // Save after each step } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! What a relief!"); } private void SpacelessWordBreakNormalBeginUnusualEnd(filename) { string soughtCombo = string.Empty; string desiredCombo = string.Empty; List&lt;string&gt; specialWordEndings = new List&lt;String&gt;(); specialWordEndings.Add("é"); specialWordEndings.Add("í"); specialWordEndings.Add("ñ"); specialWordEndings.Add("?"); specialWordEndings.Add("!"); specialWordEndings.Add(","); specialWordEndings.Add("."); specialWordEndings.Add(":"); specialWordEndings.Add(";"); specialWordEndings.Add("\""); specialWordEndings.Add("»"); specialWordEndings.Add("ß"); // Aerate "special" combinations: Cursor.Current = Cursors.WaitCursor; try { // Aerate "special" ending with "normal" beginning using (DocX document = DocX.Load(filename)) { foreach (string endChar in specialWordEndings) { for (int i = FIRST_CAP_POS; i &lt;= LAST_CAP_POS; i++) { char upperChar = (char)i; soughtCombo = string.Format("{0}{1}", endChar, upperChar); desiredCombo = string.Format("{0} {1}", endChar, upperChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! Ah, the beauty of it all!"); } private void SpacelessWordBreakUnusualBeginNormalEnd(filename) { string soughtCombo = string.Empty; string desiredCombo = string.Empty; List&lt;string&gt; specialWordBeginnings = new List&lt;String&gt;(); specialWordBeginnings.Add("¿"); specialWordBeginnings.Add("¡"); specialWordBeginnings.Add("\""); specialWordBeginnings.Add("«"); Cursor.Current = Cursors.WaitCursor; try { using (DocX document = DocX.Load(filename)) { for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; foreach (string beginChar in specialWordBeginnings) { soughtCombo = string.Format("{0}{1}", lowerChar, beginChar); desiredCombo = string.Format("{0} {1}", lowerChar, beginChar); document.ReplaceText(soughtCombo, desiredCombo); } } document.Save(); } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! Oh, wonderful day!"); } private void SpacelessWordBreakNormalCombo(filename) { string soughtCombo = string.Empty; string desiredCombo = string.Empty; Cursor.Current = Cursors.WaitCursor; try { using (DocX document = DocX.Load(filename)) { for (int i = FIRST_LOWER_POS; i &lt;= LAST_LOWER_POS; i++) { char lowerChar = (char)i; for (int j = FIRST_CAP_POS; j &lt;= LAST_CAP_POS; j++) { char upperChar = (char)j; string originalStr = string.Format("{0}{1}", lowerChar, upperChar); string newStr = string.Format("{0} {1}", lowerChar, upperChar); document.ReplaceText(originalStr, newStr); } } document.Save(); } } finally { Cursor.Current = Cursors.Default; } MessageBox.Show("SpacelessWordBreakAerator() finished! Happy happy joy joy!"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:42:16.983", "Id": "64852", "Score": "2", "body": "Why do you call `.add()` so many times? Why not go `List<string> specialWordEndings = new List<String>(){\"a\",\"b\",\"c\"};`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:05:40.980", "Id": "64887", "Score": "0", "body": "Good point; that would be better form." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:07:24.007", "Id": "64896", "Score": "0", "body": "Have you looked at my answer? Your update suffers from the very same problems, which I gave you a complete solution for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:08:26.607", "Id": "64897", "Score": "0", "body": "Also, I wouldn't use names like `Popul8` and `DuckbilledPlatypus` in production code.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:16:44.670", "Id": "64898", "Score": "0", "body": "@DanAbramov: I always use \"Popul8\"; why not? As for the other, I work for a foundation for the preservation of Duckbilled Platypi, an endangered species in some parts of the word - thus, why wouldn't I use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:29:38.450", "Id": "64900", "Score": "0", "body": "I meant \"world,\" of course - not \"word.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:42:17.727", "Id": "64903", "Score": "0", "body": "I changed the real code to use the more terse form of adding strings to the generic string list; there's no pressing need to do it with all the code here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:32:07.640", "Id": "64926", "Score": "1", "body": "Ah, platypus makes sense then, sorry! Why write `Popul8` when you can write `Populate`? As for the rest—you asked for a review, and there are still issues in your code (namely, code repetition and useless `int` -> `char` conversions). I'm not sure why you don't want to fix those, especially if I gave you working code for that. Anyway, that's up to you of course." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T00:13:47.560", "Id": "64972", "Score": "0", "body": "As to not using \"Popul8\": I do not wear a tuxedo when I code!" } ]
[ { "body": "<p>I'd take the last option and then extract common functionality between</p>\n\n<ul>\n<li><code>SpacelessWordBreakUnusualCombo</code></li>\n<li><code>SpacelessWordBreakNormalBeginUnusualEnd</code></li>\n<li><code>SpacelessWordBreakUnusualBeginNormalEnd</code></li>\n</ul>\n\n<p>and other methods into a single method that accepts parameters.</p>\n\n<p>On the glance, they look <em>too</em> similar so it should be just one method.</p>\n\n<p>If I'm not mistaken, it should look like this:</p>\n\n<pre><code>private void ReplaceTextInFile(string filename, IDictionary&lt;string, string&gt; replacementMap)\n{\n Cursor.Current = Cursors.WaitCursor;\n\n try\n {\n using (DocX document = DocX.Load(filename))\n {\n foreach (var replacement in replacementMap)\n {\n document.ReplaceText(replacement.Key, replacement.Value);\n }\n\n document.Save();\n }\n }\n finally\n {\n Cursor.Current = Cursors.Default;\n }\n}\n</code></pre>\n\n<p>All your methods seem to be special cases of this method, with different <code>replacementMap</code> parameter.</p>\n\n<p>Then create a method to build a <code>Dictionary&lt;string, string&gt;</code> representing <strong>all</strong> replacements you'll ever need:</p>\n\n<pre><code> private static readonly List&lt;string&gt; SpecialWordBeginnings = new List&lt;string&gt; { \"¿\", \"¡\", \"\\\"\", \"«\" };\n private static readonly List&lt;string&gt; SpecialWordEndings = new List&lt;string&gt; { \"é\", \"í\", \"ñ\", \"?\", \"!\", \",\", \".\", \";\", \"\\\"\", \"»\", \"ß\" };\n\n private static readonly IDictionary&lt;string, string&gt; ReplacementMap = BuildReplacementMap();\n\n private static IDictionary&lt;string, string&gt; BuildReplacementMap()\n {\n var result = new Dictionary&lt;string, string&gt;();\n\n foreach (var ending in SpecialWordEndings)\n {\n foreach (var beginning in SpecialWordBeginnings)\n {\n result.Add(\n ending + beginning,\n ending + \" \" + beginning\n );\n }\n\n for (var uppercaseChar = 'A'; uppercaseChar &lt;= 'Z'; uppercaseChar++)\n {\n result.Add(\n ending + uppercaseChar,\n ending + \" \" + uppercaseChar\n );\n }\n }\n\n for (var lowercaseChar = 'a'; lowercaseChar &lt;= 'z'; lowercaseChar++)\n {\n foreach (var beginning in SpecialWordBeginnings)\n {\n result.Add(\n lowercaseChar + beginning,\n lowercaseChar + \" \" + beginning\n );\n }\n\n for (var uppercaseChar = 'A'; uppercaseChar &lt;= 'Z'; uppercaseChar++)\n {\n result.Add(\n string.Concat(lowercaseChar, uppercaseChar),\n lowercaseChar + \" \" + uppercaseChar\n );\n }\n }\n\n return result;\n }\n</code></pre>\n\n<p>Also note that you can do <code>for</code> on <code>char</code>s directly, no need to convert from <code>int</code>.</p>\n\n<p>Since the replacement map is always the same, it is better to compute it once and store in a static field (which I did).</p>\n\n<p>Finally, pass the map to our first method:</p>\n\n<pre><code>ReplaceTextInFile(filename, ReplacementMap);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T22:43:07.350", "Id": "64795", "Score": "0", "body": "I would move `specialWordEndings` and `specialWordBeginnings` to class static variables. This will save on memory and time when instantiating the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:47:24.287", "Id": "64842", "Score": "0", "body": "The map is data, and should probably be coming from a config file/database. Otherwise, spot on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:50:56.257", "Id": "64858", "Score": "0", "body": "@jmoreno: I stand by generating it though. If the map itself came from database, it would *not* be trivial to add one more word beginning or ending (or e.g. support Cyrillic characters). Generating it preserves the logic and shows the intent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:24:24.067", "Id": "64899", "Score": "0", "body": "@DanAbramov: I was referring to `SpecialWordBeginnings` and `SpecialWordEndings`. How much effort would be involved in adding \"@\" to `SpecialWordBeginnings`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:32:53.723", "Id": "64927", "Score": "0", "body": "@jmoreno: Got it, sorry!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:06:35.693", "Id": "38782", "ParentId": "38781", "Score": "7" } }, { "body": "<p>I would suggest a change to the top level logic to address the following issues.</p>\n\n<ul>\n<li>Don't read/write the file multiple times.</li>\n<li>Make it easy to add new DocX transformers.</li>\n<li>Make each transformer an explicit class.</li>\n</ul>\n\n<p>I would make a DocXTransformer class something like below.</p>\n\n<pre><code>public class DocXTransformer\n{\n private DocX document;\n\n public DocXTransformer(string filename)\n {\n document = DocX.Load(filename);\n }\n\n public void Transform(IEnumerable&lt;ITransformer&gt; transformers)\n {\n foreach( var transform in transformers)\n {\n document = transform.Execute(document);\n }\n document.Save();\n }\n}\n</code></pre>\n\n<p>Creating the DocXTransformer will load the file.\nCalling Transform, will execute a list of Transformer classes, which each implement the ITransform interface.</p>\n\n<pre><code>public interface ITransformer\n{\n DocX Execute(DocX document);\n}\n</code></pre>\n\n<p>I think this make the different logic parts separate and you will get cleaner code, where it's going to be easy to add a new transformer, while still paying some attention to performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:49:08.183", "Id": "64857", "Score": "0", "body": "It may be a good direction but until we know for sure there that are different kinds of transforms, this sounds like a premature generalization to me. Still, +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:18:18.893", "Id": "38814", "ParentId": "38781", "Score": "3" } } ]
{ "AcceptedAnswerId": "38782", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T18:53:05.167", "Id": "38781", "Score": "5", "Tags": [ "c#", "strings", "comparative-review" ], "Title": "Splitting words in a selected file" }
38781
<pre><code>bool loadFileContents(const std::string&amp; fileName, std::string &amp;out) { bool res = false; FILE* file = fopen(fileName.c_str(), "r"); char buf[128] = { 0 }; if (file) { while (fread(buf, 1, sizeof(buf), file)) out += std::string(buf); res = true; } fclose(file); return res; } </code></pre> <p>The rationale behind using <code>std::string</code> for the <code>out</code> parameter is that it handles the buffer underneath. However, I feel like it's a move from C-style, but not quite a C++ one.</p> <p>Should I consider using some kind of stream for the <code>out</code> param?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:27:03.637", "Id": "64783", "Score": "0", "body": "[Here's the same SO question, which also has an answer](http://stackoverflow.com/questions/20980801/what-would-be-a-correct-c-style-for-function-loading-file-contents)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:29:08.773", "Id": "64784", "Score": "0", "body": "This was the result of a bad migration, so please do not vote to close or migrate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:43:50.947", "Id": "64955", "Score": "0", "body": "Here is a question about copying a file. But the same rules apply. http://stackoverflow.com/q/10195343/14065" } ]
[ { "body": "<p>Here are some of the C-style features of your code:</p>\n\n<ul>\n<li><code>FILE</code> </li>\n<li><code>fopen</code> </li>\n<li><code>char buf [128]</code> </li>\n<li><code>fclose</code> </li>\n</ul>\n\n<p>I personally liked the answer that was given in @Jamal's link.</p>\n\n<pre><code>std::ifstream fin(fileName);\nstd::ostringstream oss;\n\noss &lt;&lt; fin.rdbuf();\nout = oss.str();\n</code></pre>\n\n<p>The only problem with this is that it doesn't work well with binary files.<br>\nYou could make <code>out</code> be a <code>std::vector &lt;char&gt;</code> instead.</p>\n\n<pre><code>std::vector &lt;char&gt; loadFileContents (const std::string &amp;filename)\n{\n std::ifstream ifile ;\n ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;\n\n std::vector &lt;char&gt; vecBuffer ;\n typedef std::vector &lt;char&gt;::size_type size_type ;\n\n try {\n ifile.open (filename) ;\n ifile.seekg (0, ifile.end) ;\n size_type size = static_cast &lt;size_type&gt; (ifile.tellg ()) ;\n ifile.seekg (0, ifile.beg) ;\n vecBuffer.resize (size) ;\n ifile.read (&amp;vecBuffer [0], size) ;\n }\n\n catch (std::ios_base::failure &amp;e) {\n std::cerr &lt;&lt; e.what () &lt;&lt; std::endl ;\n }\n\n return vecBuffer ;\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization\">NRVO</a> allows us not to worry about returning the <code>std::vector &lt;char&gt;</code> by value. </p>\n\n<p>If you have access to C++11, then you could do: </p>\n\n<pre><code>std::vector &lt;char&gt; loadFileContents (const std::string &amp;filename)\n{\n std::ifstream ifile ;\n ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;\n\n std::vector &lt;char&gt; vecBuffer ;\n\n try {\n ifile.open (filename) ;\n std::istreambuf_iterator &lt;char&gt; iter (ifile) ;\n std::istreambuf_iterator &lt;char&gt; eos ;\n vecBuffer = std::move (std::vector &lt;char&gt; (iter, eos)) ; \n }\n\n catch (std::ios_base::failure &amp;e) {\n std::cerr &lt;&lt; e.what () &lt;&lt; std::endl ;\n }\n\n return vecBuffer ;\n}\n</code></pre>\n\n<p>If you want to enter template territory, then you could try this:</p>\n\n<pre><code>template &lt;typename Container&gt;\nContainer loadFileContents (const std::string &amp;filename)\n{\n std::ifstream ifile ;\n ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;\n\n try {\n ifile.open (filename) ;\n std::istreambuf_iterator &lt;char&gt; iter (ifile) ;\n std::istreambuf_iterator &lt;char&gt; eos ;\n return Container (iter, eos) ; \n }\n\n catch (std::ios_base::failure &amp;e) {\n std::cerr &lt;&lt; e.what () &lt;&lt; std::endl ;\n }\n\n return Container () ;\n}\n</code></pre>\n\n<p>Then in your main, you could do:</p>\n\n<pre><code>int main (void)\n{\n std::string strData = loadFileContents &lt;std::string&gt; (FILENAME) ;\n std::vector &lt;char&gt; vecData = loadFileContents &lt;std::vector &lt;char&gt; &gt; (FILENAME) ;\n\n return 0 ;\n}\n</code></pre>\n\n<p>If we choose to not return the <code>Container</code>, then we could do:</p>\n\n<pre><code>template &lt;typename Container&gt;\nvoid loadFileContents (const std::string &amp;filename, Container &amp;container)\n{\n std::ifstream ifile ;\n ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;\n\n try {\n ifile.open (filename) ;\n std::istreambuf_iterator &lt;char&gt; iter (ifile) ;\n std::istreambuf_iterator &lt;char&gt; eos ;\n container = Container (iter, eos) ; \n }\n\n catch (std::ios_base::failure &amp;e) {\n std::cerr &lt;&lt; e.what () &lt;&lt; std::endl ;\n }\n}\n\nint main (void)\n{\n std::string strData ;\n std::vector &lt;char&gt; vecData ;\n\n loadFileContents (FILENAME, strData) ;\n loadFileContents (FILENAME, vecData) ;\n\n return 0 ;\n}\n</code></pre>\n\n<p>The benefit of this one is that we wouldn't have to supply template arguments in <code>main</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:52:54.877", "Id": "38796", "ParentId": "38784", "Score": "2" } } ]
{ "AcceptedAnswerId": "38796", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T19:45:50.930", "Id": "38784", "Score": "3", "Tags": [ "c++", "stream" ], "Title": "What would be a correct C++ style for function loading file contents?" }
38784
<p>These arrays are the result of Store Procedure. They are to build a Google Chart, therefore I need transform the array to a specific format. I also want to remove the <code>$col</code> and <code>$row</code> elements that have a Null value. These arrays are dynamic to their length variable, but a <code>$row</code> element array always has the same length as a <code>$cols</code> array. I achieve that by using <code>eval()</code> to build the <code>if</code> statement dynamically. </p> <p>Is there a better way to do this without using <code>eval()</code>? Are there any improvements that can be done?</p> <p>I'm using PHP 5.4.</p> <pre><code>$cols = Array ( 0 =&gt; 'Name', 1 =&gt; 'MCR', 2 =&gt; 'MCD', 3 =&gt; 'COM', 4 =&gt; 'INV', 5 =&gt; 'IDM', 6 =&gt; 'PPO', 7 =&gt; 'HKD', 8 =&gt; 'ALL', 9 =&gt; 'POS', 10 =&gt; 'MCD-SP', 11 =&gt; 'MCD-BH', 12 =&gt; 'MCD-CL', 13 =&gt; 'MCD-CO', 14 =&gt; 'MCR-SP', 15 =&gt; 'MCR-PO' ); $rows = Array( 0 =&gt; Array( 0 =&gt; 'Primero', 1 =&gt; 19683.43, 2 =&gt; NULL, 3 =&gt; 3757.38, 4 =&gt; NULL, 5 =&gt; NULL, 6 =&gt; NULL, 7 =&gt; NULL, 8 =&gt; NULL, 9 =&gt; NULL, 10 =&gt; NULL, 11 =&gt; NULL, 12 =&gt; NULL, 13 =&gt; NULL, 14 =&gt; NULL, 15 =&gt; NULL ), 1 =&gt; Array ( 0 =&gt; 'Segundo', 1 =&gt; 15340.5767, 2 =&gt; NULL, 3 =&gt; NULL, 4 =&gt; NULL, 5 =&gt; NULL, 6 =&gt; NULL, 7 =&gt; NULL, 8 =&gt; NULL, 9 =&gt; NULL, 10 =&gt; NULL, 11 =&gt; NULL, 12 =&gt; NULL, 13 =&gt; NULL, 14 =&gt; NULL, 15 =&gt; NULL ), 2 =&gt; Array ( 0 =&gt; 'Tercero', 1 =&gt; NULL, 2 =&gt; NULL, 3 =&gt; NULL, 4 =&gt; NULL, 5 =&gt; NULL, 6 =&gt; NULL, 7 =&gt; NULL, 8 =&gt; NULL, 9 =&gt; NULL, 10 =&gt; 4969.65, 11 =&gt; NULL, 12 =&gt; NULL, 13 =&gt; NULL, 14 =&gt; 23695.39, 15 =&gt; NULL ), 3 =&gt; Array ( 0 =&gt; 'Cuarto', 1 =&gt; NULL, 2 =&gt; NULL, 3 =&gt; NULL, 4 =&gt; NULL, 5 =&gt; NULL, 6 =&gt; NULL, 7 =&gt; NULL, 8 =&gt; NULL, 9 =&gt; NULL, 10 =&gt; NULL, 11 =&gt; 45974.86, 12 =&gt; NULL, 13 =&gt; NULL, 14 =&gt; NULL, 15 =&gt; NULL ), 4 =&gt; Array ( 0 =&gt; 'Quinto', 1 =&gt; NULL, 2 =&gt; NULL, 3 =&gt; NULL, 4 =&gt; NULL, 5 =&gt; NULL, 6 =&gt; NULL, 7 =&gt; NULL, 8 =&gt; NULL, 9 =&gt; NULL, 10 =&gt; 1405.8, 11 =&gt; 39244, 12 =&gt; NULL, 13 =&gt; NULL, 14 =&gt; NULL, 15 =&gt; NULL ) ); $qty_col = count($cols) - 1; $qty_rows = count($rows); //echo $qty_rows; $ifScript = ''; for ($a = 1; $a &lt;= $qty_col; $a++) { $unsetScript = 'unset('; $ifScript .='if('; for ($b = 0; $b &lt;= $qty_rows; $b++) { $ifScript .= 'empty($rows[' . $b . '][' . $a . '])'; $unsetScript .='$rows[' . $b . '][' . $a . ']'; if ($b == $qty_rows) { $ifScript .='){'; //$ifScript .='){&lt;br&gt;'; $unsetScript .=', $cols[' . $a . ']);'; } else { $ifScript .= ' &amp;&amp; '; $unsetScript .=', '; } } $ifScript .= $unsetScript . '}'; //$ifScript .= $unsetScript . '&lt;br&gt;}&lt;br&gt;'; } //echo $ifScript; eval($ifScript); $cols = array_values($cols); $rows = array_map('array_values', $rows); foreach ($cols as $key =&gt; $value) { $cols[$key] = array( 'id' =&gt; NULL, 'label' =&gt; $value ); $type = ($key == 0) ? 'string' : 'number'; $cols[$key]['type'] = $type; } foreach ($rows as $key1 =&gt; $value1) { foreach ($value1 as $key2 =&gt; $value2) { $val = (empty($value2)) ? '0.00' : $value2; $format = ($key2 == 0) ? strtoupper(trim($value2)) : '$' . number_format($value2, '2', '.', ','); $value1[$key2] = array( 'v' =&gt; $val, 'f' =&gt; $format ); } $rows[$key1] = array( 'c' =&gt; $value1 ); } $newArray = array( 'cols' =&gt; $cols, 'rows' =&gt; $rows ); echo '&lt;pre&gt;'; print_r($newArray); echo '&lt;/pre&gt;'; </code></pre> <p><strong>Output</strong></p> <pre><code>Array ( [cols] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; [label] =&gt; Name [type] =&gt; string ) [1] =&gt; Array ( [id] =&gt; [label] =&gt; MCR [type] =&gt; number ) [2] =&gt; Array ( [id] =&gt; [label] =&gt; COM [type] =&gt; number ) [3] =&gt; Array ( [id] =&gt; [label] =&gt; MCD-SP [type] =&gt; number ) [4] =&gt; Array ( [id] =&gt; [label] =&gt; MCD-BH [type] =&gt; number ) [5] =&gt; Array ( [id] =&gt; [label] =&gt; MCR-SP [type] =&gt; number ) ) [rows] =&gt; Array ( [0] =&gt; Array ( [c] =&gt; Array ( [0] =&gt; Array ( [v] =&gt; Primero [f] =&gt; PRIMERO ) [1] =&gt; Array ( [v] =&gt; 19683.43 [f] =&gt; $19,683.43 ) [2] =&gt; Array ( [v] =&gt; 3757.38 [f] =&gt; $3,757.38 ) [3] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [4] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [5] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) ) ) [1] =&gt; Array ( [c] =&gt; Array ( [0] =&gt; Array ( [v] =&gt; Segundo [f] =&gt; SEGUNDO ) [1] =&gt; Array ( [v] =&gt; 15340.5767 [f] =&gt; $15,340.58 ) [2] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [3] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [4] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [5] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) ) ) [2] =&gt; Array ( [c] =&gt; Array ( [0] =&gt; Array ( [v] =&gt; Tercero [f] =&gt; TERCERO ) [1] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [2] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [3] =&gt; Array ( [v] =&gt; 4969.65 [f] =&gt; $4,969.65 ) [4] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [5] =&gt; Array ( [v] =&gt; 23695.39 [f] =&gt; $23,695.39 ) ) ) [3] =&gt; Array ( [c] =&gt; Array ( [0] =&gt; Array ( [v] =&gt; Cuarto [f] =&gt; CUARTO ) [1] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [2] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [3] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [4] =&gt; Array ( [v] =&gt; 45974.86 [f] =&gt; $45,974.86 ) [5] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) ) ) [4] =&gt; Array ( [c] =&gt; Array ( [0] =&gt; Array ( [v] =&gt; Quinto [f] =&gt; QUINTO ) [1] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [2] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) [3] =&gt; Array ( [v] =&gt; 1405.8 [f] =&gt; $1,405.80 ) [4] =&gt; Array ( [v] =&gt; 39244 [f] =&gt; $39,244.00 ) [5] =&gt; Array ( [v] =&gt; 0.00 [f] =&gt; $0.00 ) ) ) ) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:58:45.467", "Id": "64812", "Score": "0", "body": "Every heard of `RecursiveFilterIterator` (part of the SPL)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T01:42:39.730", "Id": "64818", "Score": "3", "body": "[Iterator garden by hakre](https://github.com/hakre/Iterator-Garden). But please just search the web. That's how I came across it as well :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:13:50.580", "Id": "64831", "Score": "1", "body": "If you're using `eval` that much, the question isn't _\"is there a better way\"_, but _\"how many alternative ways are there, and how much better are they\"_ ;-P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:29:50.090", "Id": "64869", "Score": "1", "body": "I just erased two attempts at making this better as I didn't like my own results. When you do get this solved, please post the improved code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:11:35.773", "Id": "64882", "Score": "0", "body": "@dotancohen could you please share your idea in http://ideone.com/ ***two heads are better than one***" } ]
[ { "body": "<p>Why not do something like this?</p>\n\n<pre><code>$output = array();\n\nif((bool)$cols &amp;&amp; (bool)$rows) {\n foreach($rows as $row_index =&gt; $row) {\n foreach($cols as $column_index =&gt; $column_name) {\n $column_has_atleast_one_value = false;\n if(isset($row[$column_index]) &amp;&amp; (bool)$row[$column_index]){\n $output[\"cols\"][$column_index] = array(\n \"id\" =&gt; NULL,\n \"label\" =&gt; $column_name,\n \"type\" =&gt; ($column_index == 0) ? 'string' : 'number'\n );\n }\n }\n }\n}\n\nif((bool)$rows) {\n\n foreach($rows as $row_index =&gt; $columns) {\n foreach($columns as $column_index =&gt; $column_data){\n if(!isset($output[\"cols\"][$column_index])){\n continue;\n }\n $column_formatted = \"\";\n if($column_index == 0) {\n $column_formatted = strtoupper($column_data);\n } else {\n if(!(bool)$column_data) {\n $column_data = \"0.00\";\n }\n $column_formatted = '$' . number_format($column_data, '2', '.', ',');\n }\n $output[\"rows\"][$row_index][\"c\"][$column_index] = array(\n \"v\" =&gt; $column_data,\n \"f\" =&gt; $column_formatted\n );\n }\n }\n}\n\necho \"&lt;pre&gt;\";\nprint_r($output);\necho \"&lt;/pre&gt;\";\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>Array\n(\n [cols] =&gt; Array\n (\n [0] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; Name\n [type] =&gt; string\n )\n\n [1] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; MCR\n [type] =&gt; number\n )\n\n [3] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; COM\n [type] =&gt; number\n )\n\n [10] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; MCD-SP\n [type] =&gt; number\n )\n\n [14] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; MCR-SP\n [type] =&gt; number\n )\n\n [11] =&gt; Array\n (\n [id] =&gt; \n [label] =&gt; MCD-BH\n [type] =&gt; number\n )\n\n )\n\n [rows] =&gt; Array\n (\n [0] =&gt; Array\n (\n [c] =&gt; Array\n (\n [0] =&gt; Array\n (\n [v] =&gt; Primero\n [f] =&gt; PRIMERO\n )\n\n [1] =&gt; Array\n (\n [v] =&gt; 19683.43\n [f] =&gt; $19,683.43\n )\n\n [3] =&gt; Array\n (\n [v] =&gt; 3757.38\n [f] =&gt; $3,757.38\n )\n\n [10] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [11] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [14] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n )\n\n )\n\n [1] =&gt; Array\n (\n [c] =&gt; Array\n (\n [0] =&gt; Array\n (\n [v] =&gt; Segundo\n [f] =&gt; SEGUNDO\n )\n\n [1] =&gt; Array\n (\n [v] =&gt; 15340.5767\n [f] =&gt; $15,340.58\n )\n\n [3] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [10] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [11] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [14] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n )\n\n )\n\n [2] =&gt; Array\n (\n [c] =&gt; Array\n (\n [0] =&gt; Array\n (\n [v] =&gt; Tercero\n [f] =&gt; TERCERO\n )\n\n [1] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [3] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [10] =&gt; Array\n (\n [v] =&gt; 4969.65\n [f] =&gt; $4,969.65\n )\n\n [11] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [14] =&gt; Array\n (\n [v] =&gt; 23695.39\n [f] =&gt; $23,695.39\n )\n\n )\n\n )\n\n [3] =&gt; Array\n (\n [c] =&gt; Array\n (\n [0] =&gt; Array\n (\n [v] =&gt; Cuarto\n [f] =&gt; CUARTO\n )\n\n [1] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [3] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [10] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [11] =&gt; Array\n (\n [v] =&gt; 45974.86\n [f] =&gt; $45,974.86\n )\n\n [14] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n )\n\n )\n\n [4] =&gt; Array\n (\n [c] =&gt; Array\n (\n [0] =&gt; Array\n (\n [v] =&gt; Quinto\n [f] =&gt; QUINTO\n )\n\n [1] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [3] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n [10] =&gt; Array\n (\n [v] =&gt; 1405.8\n [f] =&gt; $1,405.80\n )\n\n [11] =&gt; Array\n (\n [v] =&gt; 39244\n [f] =&gt; $39,244.00\n )\n\n [14] =&gt; Array\n (\n [v] =&gt; 0.00\n [f] =&gt; $0.00\n )\n\n )\n\n )\n\n )\n\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:28:28.563", "Id": "65137", "Score": "0", "body": "thanks, but I have to remove the `$col` and `$row` elements that have a Null value... see my output it has only 6 elements for each col...that's the part I made with eval()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T22:27:24.237", "Id": "65141", "Score": "0", "body": "Hi, I updated my code to get rid of the columns that have null values. When you are dealing with array or databases, try your best to keep the index keys same across all datasets. Because one misleading number can throw the whole structure off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T22:53:41.717", "Id": "65142", "Score": "0", "body": "Thanks, Could we have a chat?, I see new things for me in your script that I want to learn if you can clarify. the `continue` and the `(bool)$cols`. Also I reset the array because google chart doesn't work if the array isn't reset" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T20:01:40.170", "Id": "38936", "ParentId": "38787", "Score": "1" } } ]
{ "AcceptedAnswerId": "38936", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:04:08.167", "Id": "38787", "Score": "0", "Tags": [ "php", "array" ], "Title": "how many alternative ways are there, and how much better are they to transform this array?" }
38787
<p>I recently read the book <em>Clean Code</em> and I also did some research on the SOLID principles. I'm looking for general feedback on if I was able to transpose the examples (written in Java) to Python while still maintaining a "Pythonic" program.</p> <p>I wrote a simple TicTacToe game in Python using Tkinter as the GUI and I tried to strike a balance between readable, clean code and avoiding code cluttering with useless functions (<code>get()</code>, <code>set()</code>, <code>isEmpty()</code> and other 1-liners)</p> <p>Having a generic BoardGUI class specializing in <code>TicTacToeBoardGUI</code> is my attempt at the open/close principle.</p> <p>The 3 modules (models, views, game) implement a minimalistic MVC design where GameApplication controls the flow and events.</p> <p>The part I don't know how to handle is using polymorphism to have different levels of AI (right now the AI only checks a random empty box)</p> <p><a href="http://www.filedropper.com/tictactoe" rel="nofollow">http://www.filedropper.com/tictactoe</a> (~200 lines total)</p> <p><strong>main.py</strong></p> <pre><code>#!/usr/bin/env import Tkinter as tk from game import GameApplication def convert_images(): """Returns a dictionary with the images converted into PhotoImages Tkinter can use""" img_dict = {} img_dict.update({'cross': tk.PhotoImage(file='images/cross.gif')}) img_dict.update({'circle': tk.PhotoImage(file='images/circle.gif')}) return img_dict def main(): root = tk.Tk() root.title('Tic-Tac-Toe v1.0') images = convert_images() GameApplication(root, images) root.mainloop() if __name__ == '__main__': main() </code></pre> <p><strong>models.py:</strong></p> <pre><code>#!/usr/bin/env from collections import namedtuple class TicTacToeBoard(): """ Keeps track of the status of the boxes of a standard 3x3 TicTacToe game I don't particularly like the victory, draw and _find_lines functions, any better solutions? """ ROWS = 3 COLUMNS = 3 EMPTY = 0 O = 1 X = 2 def __init__(self): self.boxes = {(column, row): namedtuple('box', 'value') \ for row in range(TicTacToeBoard.ROWS) \ for column in range(TicTacToeBoard.COLUMNS)} for __, items in self.boxes.items(): items.value = TicTacToeBoard.EMPTY self._lines = self._find_all_lines() def victory(self): for line in self._lines: if self.boxes[line[0]].value == self.boxes[line[1]].value == self.boxes[line[2]].value: if self.boxes[line[0]].value != TicTacToeBoard.EMPTY: return True return False def draw(self): for __, box in self.boxes.items(): if box.value == TicTacToeBoard.EMPTY: return False return True def _find_all_lines(self): lines = [] for x in range(3): lines.append(((0, x), (1, x), (2, x))) lines.append(((x, 0), (x, 1), (x, 2))) lines.append(((0, 0), (1, 1), (2, 2))) lines.append(((0, 2), (1, 1), (2, 0))) return lines </code></pre> <p><strong>views.py:</strong></p> <pre><code>#!/usr/bin/env import Tkinter as tk from math import ceil class BoardGUI(tk.LabelFrame): """ Questions: Does this class respects the open/close principle? Am I reinventing the wheel by transforming the coordinates to row and columns or Tkinter.canvas can do that already? A generic board game of arbitrary size, number of columns and number of rows. It can be inherited to serve as a point and click GUI for different board games. The mouse coordinates should be carried by an event passed in parameter to the functions Boxes are accessed with the tags kw from a Tkinter canvas They are nothing but drawings; actual rows and columns are computed based on mouse position and size Needs Tkinter compatible images to draw in boxes Coordinates for the boxes are either in form of (box_column, box_row) or (box_top_left_x, box_top_left_y) """ def __init__(self, root, rows, columns, width, height, **options): tk.LabelFrame.__init__(self, root, **options) self._rows = rows self._columns = columns self._width = width self._height = height self.canvas = tk.Canvas(self, width=self._width, height=self._height) self.canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.TRUE) self._draw_boxes() def get_box_coord(self, event): return self._convert_pixels_to_box_coord(event.x, event.y) def draw_image_on_box(self, coord, image): (x, y) = self._convert_box_coord_to_pixels(coord) self.canvas.create_image((x, y), image=image, anchor=tk.NW) def draw_message_in_center(self, message): self.canvas.create_text(self._find_board_center(), text=message, font=("Helvetica", 50, "bold")) def _draw_boxes(self): [self.canvas.create_rectangle(self._find_box_corners((column, row))) \ for row in range(self._rows) \ for column in range(self._columns)] def _find_box_corners(self, coord): boxWidth, boxHeight = self._find_box_dimensions() column, row = coord[0], coord[1] topLeftCorner = column * boxWidth topRightCorner = (column * boxWidth) + boxWidth bottomLeftCorner = row * boxHeight bottomRightCorner = (row * boxHeight) + boxWidth return (topLeftCorner, bottomLeftCorner, topRightCorner, bottomRightCorner) def _find_board_center(self): return ((self._width / 2), (self._height / 2)) def _find_box_dimensions(self): return ((self._width / self._columns), (self._height / self._rows)) def _convert_box_coord_to_pixels(self, coord): boxWidth, boxHeight = self._find_box_dimensions() return ((coord[0] * boxWidth), (coord[1] * boxHeight)) def _convert_pixels_to_box_coord(self, x, y): column = ceil(x / (self._height / self._columns)) row = ceil(y / (self._width / self._rows)) return (column, row) class TicTacToeBoardGUI(BoardGUI): """ Allows you to draw circles or crosses on a 3x3 square gaming board Tkinter needs to keep a reference of the images to loop. It's better to initiate them elsewhere and pass them in parameters even if they seem like they should be internal attributes. """ ROWS = 3 COLUMNS = 3 def __init__(self, root, width, height, images): BoardGUI.__init__(self, root, TicTacToeBoardGUI.ROWS, TicTacToeBoardGUI.COLUMNS, width, height) self.xSymbol = images['cross'] self.oSymbol = images['circle'] def draw_x_on_box(self, coord): self.draw_image_on_box(coord, self.xSymbol) def draw_o_on_box(self, coord): self.draw_image_on_box(coord, self.oSymbol) </code></pre> <p><strong>game.py:</strong></p> <pre><code>#!/usr/bin/env import Tkinter as tk from views import TicTacToeBoardGUI from models import TicTacToeBoard from random import shuffle class GameApplication(tk.Frame): """ Serves as a top level Tkinter frame to display the game and as a controller to connect the models and the views. I'm willingly giving this class 2 tasks because the controller as a single event to connect and the purpose of this exercise isn't the MVC pattern but the SOLID and clean code principles It simply instantiates the models and views necessary to play a TicTacToe game and interpret a left mouse click as a move from the Human player """ CANVAS_WIDTH = 300 CANVAS_HEIGHT = 300 def __init__(self, root, images, **options): tk.Frame.__init__(self, root, **options) self._boardModel = TicTacToeBoard() self._boardView = TicTacToeBoardGUI(root, GameApplication.CANVAS_WIDTH, GameApplication.CANVAS_HEIGHT, images) self._boardView.pack() self._connect_click_event() if self._ai_goes_first(): self._ai_plays() def _player_plays(self, event): coord = self._boardView.get_box_coord(event) if self._boardModel.boxes[coord].value != self._boardModel.EMPTY: return self._boardModel.boxes[coord].value = self._boardModel.X self._boardView.draw_x_on_box(coord) self._ai_plays() def _ai_plays(self): #Simply checks a random empty box on the board; #The minmax algorithm could be used to never lose but that's no fun for coord, box in self._boardModel.boxes.items(): if box.value == self._boardModel.EMPTY: self._boardModel.boxes[coord].value = self._boardModel.O self._boardView.draw_o_on_box(coord) break self._check_end_game_status() def _check_end_game_status(self): if self._boardModel.victory(): self._boardView.draw_message_in_center("Victory!") elif self._boardModel.draw(): self._boardView.draw_message_in_center("Draw!") def _ai_goes_first(self): result = [True, False] shuffle(result) return result[0] def _connect_click_event(self): self._boardView.canvas.bind("&lt;Button-1&gt;", self._player_plays) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:36:55.223", "Id": "64833", "Score": "1", "body": "Please check the indentation; it is off at least in `TicTacToeBoard.draw`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:12:22.077", "Id": "64867", "Score": "1", "body": "[`collections.namedtuple`](http://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) does not work like you think it does, please check docs." } ]
[ { "body": "<p>Looks to me that you want to have a box with various buttons that allows you to select, say, easy, medium, or hard. Return that and then say </p>\n\n<pre><code>if AIChoose == \"Easy\":\n getEasyAIMove()\nelif AIChoose == \"Medium\":\n GetMedAIMove()\nelif AIChoose == \"Hard\":\n GetHardAIMove()\n</code></pre>\n\n<p>Now, that's obviously the easy part, but a Tic-Tac-Toe AI is actually not at all hard:</p>\n\n<pre><code>def GetHardAIMove():\n # first check if you're about to win. If you are, move there\n # now check if your opponent is about to win. If he is, block him\n # check if any of the corners are free. If they are, go to a random one of them\n # check if the middle is free. If it is, go to it\n #otherwise, go to a random open spot\ndef GetMedAIMove():\n # here's where we cheat. generate a random number between 1 and 3. if its &lt;= 2, GetHardAIMove. otherwise, go easy.\ndef GetEasyAIMove():\n # If you're about to win, go there\n # If you're about to lose, go there\n # Otherwise, go to a random spot.\n</code></pre>\n\n<p>See? This is a quick and painless AI that can beat decent players who don't know how it's made about 50-60% of the time.</p>\n\n<p>EDIT: Since Tic-Tac-Toe can always be won or tied by the player that moves first, you may wish to add this into the AI by doing something like this:</p>\n\n<pre><code>def GetHardAIMove():\n # if you move first:\n # after making sure you or your opponent isn't about to win:\n # move to a corner\n # then move to the corner opposite that\n # then move to a random corner\n # at this point, you have either won or tied\n # first check if you're about to win. If you are, move there\n # now check if your opponent is about to win. If he is, block him\n # check if any of the corners are free. If they are, go to a random one of them\n # check if the middle is free. If it is, go to it\n #otherwise, go to a random open spot\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:47:05.820", "Id": "39706", "ParentId": "38789", "Score": "4" } } ]
{ "AcceptedAnswerId": "39706", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T20:46:23.113", "Id": "38789", "Score": "8", "Tags": [ "python", "game", "tkinter", "tic-tac-toe" ], "Title": "Clean code and SOLID principles for a simple Python TicTacToe game" }
38789
<p>I wrote <a href="https://github.com/RobertZenz/daemonize-win" rel="nofollow">a simple tool to allow to daemonize any process under Microsoft Windows</a>.</p> <p>The goal is to push <em>any</em> process into the background with no questions asked. That includes GUI applications, which means that the main window will not be created...or at least not shown. For console applications it will simply detach the process from the current console and <em>not</em> open another one. Usage is simple:</p> <pre><code>daemonize.exe PROGRAM [ARGUMENTS] </code></pre> <p>So let's cut to the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;windows.h&gt; // The important things to note and know: // // * Only works with ASCII paths and filenames. // * Quotes all arguments regardless of content. // * SW_HIDE in STARTUPINFO is needed for GUI applications // * DETACHED_PROCESS in CreateProcessA is needed for command line applications // int main(int argc, char *argv[]) { if (argc &lt;= 1) { printf("daemonize.exe COMMAND [ARGUMENTS]"); return 1; } char* command = argv[1]; char* arguments = NULL; if (argc &gt; 2) { // We only need to concatenate arguments if there // actually are arguments. int idx; // Calculate the length of all arguments size_t argLength = 0; for (idx = 1; idx &lt; argc; idx++) { argLength += strlen(argv[idx] + 2 + 1); // One for the space, two for the quotes. } argLength--; // Strip the last space. // Reserve some memory and NULL the new string. //The + 1 is the space for the last null character. arguments = (char*)malloc(sizeof(char) * (argLength + 1)); arguments[0] = 0; // Now concatenate the arguments. for (idx = 1; idx &lt; argc; idx++) { strcat(arguments, "\""); strcat(arguments, argv[idx]); strcat(arguments, "\""); if (idx &lt; argc - 1) { strcat(arguments, " "); } } } STARTUPINFO startInfo; PROCESS_INFORMATION process; ZeroMemory(&amp;startInfo, sizeof(startInfo)); ZeroMemory(&amp;process, sizeof(process)); startInfo.cb = sizeof(startInfo); // Tell the system to use/honor the ShowWindow flags. startInfo.dwFlags = STARTF_USESHOWWINDOW; // Tell the system that the main window of the process should be hidden. startInfo.wShowWindow = SW_HIDE; if (!CreateProcessA( command, // application name arguments, // command line arguments NULL, // process attributes NULL, // thread attributes FALSE, // inherit (file) handles // Detach the process from the current console. DETACHED_PROCESS, // creation flags NULL, // environment NULL, // current directory &amp;startInfo, // startup info &amp;process) // process information ) { printf("Creation of the process failed, trying to fetch error message...\n"); long lastError = GetLastError(); char* message = NULL; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // Flags NULL, // source lastError, // message identifier 0, // language id (LPSTR)&amp;message, // message buffer 0, // size of the message NULL // arguments ); printf(message); return 1; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T23:39:11.563", "Id": "64804", "Score": "0", "body": "The Windows analogue of a daemon is a [service](http://stackoverflow.com/q/7073557/1157100)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:14:06.480", "Id": "64841", "Score": "0", "body": "@200_success: The idea is/was that the process is bound against the session of the user. F.e. [redshift](http://jonls.dk/redshift/) which would always require an open cmd window if launched via an \"start all my applications on login\" script." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T22:54:26.310", "Id": "65359", "Score": "0", "body": "What's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T11:06:18.723", "Id": "65400", "Score": "0", "body": "@ChrisW: No direct question, I think I did everything to my best ability and I'm not sure if I could to anything else, I just want a code review to be sure, because this is one of the few pieces of C/C++ code that I ever wrote." } ]
[ { "body": "<p>It looks good: very good, assuming it works (i.e. has the run-time behaviour that you want: I don't know the effect of calling <code>CreateProcess</code> in that way).</p>\n\n<p>You don't <code>free(arguments)</code> but that doesn't matter because memory will be reclaimed by the O/S when the process exits. Similarly, in theory I'd expect an API call to release <code>message</code>.</p>\n\n<p>I don't see why you need the <code>(LPSTR)</code> cast. Using a cast can hide compiler warnings/errors, which should be fixed instead of their causing errors at run-time.</p>\n\n<p>Instead of <code>int idx;</code> it's better to not define a local variable until the moment at which you initialize it: instead you could say, <code>for (int idx = 1; idx &lt; argc; idx++)</code>.</p>\n\n<p>Also, shouldn't it be <code>for (int idx = 2; idx &lt; argc; idx++)</code>? Because, <code>idx=1</code> is the 'command' parameter, not the first 'argument' parameter.</p>\n\n<hr>\n\n<p>If when you say \"C/C++\" you mean \"C++\", then it's more conventional these days to use <code>std::string</code> instead of C-style strings (but this is an unusually short program; perhaps although I don't know why you want to avoid the hassle of linking to the STL, especially if you know enough to avoid the many pitfalls of C-style string manipulation, which you seem to have).</p>\n\n<p>For example, using <code>std::string</code> you could write the following, which is simpler than the string-manipulation code you have at the moment:</p>\n\n<pre><code>std::string s;\nfor (int idx = 1; idx &lt; argc; idx++)\n{\n s += \"\\\"\" + argv[idx] + \"\\\"\";\n if (idx &lt; argc - 1) {\n s += \" \";\n }\n}\nchar* arguments = strdup(s.c_str());\n</code></pre>\n\n<p>The reason for <code>strdup</code> in the above is that <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx\" rel=\"nofollow\">MSDN says</a> ...</p>\n\n<blockquote>\n <p>The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.</p>\n</blockquote>\n\n<p>... which helps to explain why arguments must be <code>char*</code> not <code>const char*</code>. Sometimes you can ignore these (the windows API sometimes doesn't say its parameters are <code>const</code> when in fact they are), but doing so may be unsafe bad practice (so I use <code>strdup</code> above -- note that <code>strdup</code>'ed memory should be <code>free</code>'ed).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T16:52:16.513", "Id": "65415", "Score": "1", "body": "The question is in C, not C++. C uses C-style strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T17:07:13.577", "Id": "65416", "Score": "0", "body": "The OP called it \"C/C++ code\" in a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T17:16:19.237", "Id": "65417", "Score": "1", "body": "You misinterpreted the comment. The OP is just saying that has little experience in either C or C++ (i.e. usually programs in Java). The question is still tagged [tag:c]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T17:21:57.273", "Id": "65418", "Score": "0", "body": "@200_success Whatever. The first (original) part of the answer is applicable to C. The 2nd part is an example/comparison with C++. C programmers used to use C++ compilers as \"a better C\": to compile their C code, only gradually adding C++-specific features as they learned them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T11:38:18.573", "Id": "39086", "ParentId": "38793", "Score": "2" } }, { "body": "<p>I know that saying this misses the point of the question, but I couldn't help myself from remarking this:</p>\n\n<p>Separating the string creation and allocation for arguments into it's own function shaves about thirty lines from your main function (it does, however <em>add</em>, rather than substract, from the final file size). It's mainly in the interests of readability. I append a proof-of-concept implementation.</p>\n\n<pre><code>char* quoteAndSerialize(int count, const char **vector)\n{\n/*\n Concatenate the first count elements of vector into a single string.\n\n The elements are quoted before concatenation, and each pair of consecutive\n elements is separated by a space character. The resulting string is\n zero-terminated. If the pointer to the resulting string is lost before\n deallocation, memory leaks will ocurr.\n*/\n int finalSize;\n char* string;\n\n finalSize = quoteAndSerialize_finalSize(count, vector);\n string = (char*) malloc(sizeof(char) * finalSize);\n string[0] = 0;\n\n for (int i = 0; i &lt; count; i++) {\n strcat(arguments, \"\\\"\");\n strcat(arguments, vector[i]);\n strcat(arguments, \"\\\"\");\n if (i &lt; count - 1) {\n strcat(arguments, \" \");\n }\n }\n return string;\n}\n\nint quoteAndSerialize_finalSize(int count, const char **vector)\n{\n int finalSize = 0;\n\n //add together the length of all arguments\n for (int i = 0; i &lt; count; i++)\n {\n finalSize += strlen(vector[i]);\n }\n\n // for every argument, there will be two \\\" characters surrounding it\n finalSize += 2 * count;\n\n // for every argument after the first, there will be a space separating\n // it from the previous one\n if (count != 0) finalSize += count - 1;\n\n // since strings are zero-terminated:\n finalSize += 1;\n\n return finalSize;\n}\n</code></pre>\n\n<p>This allows for something like:</p>\n\n<pre><code>(...)\n\n char* command = argv[1];\n char* arguments = NULL;\n\n // create a null-terminated string containing all arguments, each surrounded\n // by quotes, and separated by spaces\n arguments = quoteAndSerialize(argc - 2, argv + 2)\n\n STARTUPINFO startInfo;\n PROCESS_INFORMATION process;\n\n\n(...)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-25T23:24:59.597", "Id": "193622", "Score": "0", "body": "Welcome to Code Review! I recommend that you add more context to your post: while your post isn't *entirely* a code dump, all it is doing is saying that you've reduced the amount of lines in the code, and you even said that it \"misses the point of the question\". While you don't have to delete your answer, I recommend that you add more to it: why should the OP do what you have done, other than that it cuts down on some lines?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-25T23:41:31.893", "Id": "193624", "Score": "0", "body": "Thank you, SirPython, for your quick reply. My post *does* miss the point of the question: the question is whether the presented code is correct and it does what the OP says it does. The content of my reply was relevant to the style and readability of the code, not to it's pourpose or correctness; this is why I had qualms about posting. The reason I *did* post is because I spend a good five minutes looking at the code before I figured that the entire block after the first 'if' wasn't relevant to the problem, instead of the five seconds I could've." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-26T00:51:07.047", "Id": "193628", "Score": "0", "body": "Readability and style reviews are perfectly acceptable here. What @SirPython was saying is that you should state why you feel this would be better than the current version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-26T09:26:26.077", "Id": "193642", "Score": "0", "body": "It does, as a matter of fact, not miss the point of the question. Now in hindsight, I'm rather surprised that I *did not* do this, so yes, your answer is perfectly fine and on-topic. The processing of the arguments should be in it's own function." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-25T23:21:13.350", "Id": "105725", "ParentId": "38793", "Score": "1" } } ]
{ "AcceptedAnswerId": "39086", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:31:17.573", "Id": "38793", "Score": "3", "Tags": [ "c", "windows" ], "Title": "Daemonize a process under Microsoft Windows" }
38793
<p>Elsewhere, there was a question about finding an elegant solution to a particular problem, and the following solution was presented.</p> <p>I'm curious whether this solution is elegant <strong>from the perspective of easy to understand</strong> for a Ruby programmer (which I am no longer).</p> <pre><code>merged_file = File.open("merge_out.txt", "w") files = ARGV.map { |filename| File.open( filename, "r") } lines = files.map { |file| file.gets } while lines.any? next_line = lines.compact.min file_id = lines.index( next_line ) merged_file.print next_line lines[ file_id ] = files[ file_id ].gets end </code></pre> <p>The question is not whether it is efficient, but just "how long does it take a Ruby programmer to understand what this does?"</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:16:24.880", "Id": "175987", "Score": "0", "body": "The code does something, it's not _hypothetical_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:22:08.110", "Id": "175990", "Score": "0", "body": "Please stop changing the summary of this question. I have not debated its closure because it is not code that I own or maintain. However, the topic that I was asking about was nothing to do with \"Merging files\", it is to do with \"how clear is the code\". Placing the answer of what the code does in the title detracts from the point of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:29:27.780", "Id": "175998", "Score": "3", "body": "@GreenAsJade Titles are meant to describe **what the code does**, instead of what you want to ask. Currently, your title is poor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:33:34.260", "Id": "175999", "Score": "2", "body": "@GreenAsJade You should read the [help section, about \"Titling your question\"](http://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:36:10.427", "Id": "176000", "Score": "0", "body": "I have subsequent to posting this question been educated about this. Changing the title now on this _closed_ question doesn't help one bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:37:48.563", "Id": "176002", "Score": "0", "body": "Did someone vote to open it? I'm not aware of that. I already _supported_ the motion to close it, when it happened, due to the obvious breach of guidelines. The question explicitly acknowledges that it's not my code: it's not in any way pretending that it is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T10:39:38.830", "Id": "176003", "Score": "0", "body": "@GreenAsJade My apolegies. If you want, I can remove my comments." } ]
[ { "body": "<p>I had no trouble figuring it out what it does, but I'm not sure I'd call it \"easy to understand\". </p>\n\n<p>All the declarations are implicit and thus if you're familiar with all the in's and outs of Array and the map method, it's pretty straight forward what the code is attempting to do. Some of the logic takes a bit of thinking about,</p>\n\n<p>I did puzzle a bit over this line</p>\n\n<pre><code>file_id = lines.index( next_line)\n</code></pre>\n\n<p>I think the most puzzling part is the unstated requirement that the input files are already sorted. Otherwise this line doesn't work. Once I figured out that this line meant that the input files were sorted, the rest fell into place.</p>\n\n<p>The exit condition is also a bit tricky to figure out.</p>\n\n<p>The code really feels like a translation to ruby from a more explicitly functional language, it doesn't feel \"ruby-like\" at all. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T22:17:00.410", "Id": "38798", "ParentId": "38795", "Score": "11" } }, { "body": "<p>It took me about five minutes to figure out, then I found that I got it wrong. At first, I thought that it would take lines from each named file in turn. Then, I thought that it would take the first paragraph from each file, before realizing that an \"empty\" line still consists of a <code>\"\\n\"</code> and therefore wouldn't get compacted out. In the end, I decided that it's just concatenating all the files. Then I ran the code to discover that it does one round of mergesort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T01:41:50.270", "Id": "64817", "Score": "0", "body": "This is exactly how I read the code, except that I never ran it and discovered that it ran just one round of merge sort. The mental disconnect for me was seeing those file opens. I expected the code below to deal with the files in their entirety, not just part of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T03:49:55.597", "Id": "64821", "Score": "0", "body": "What does \"one round of mergesort\" mean? The code is supposed to deal with the files in their entirety... my understanding is that it does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T05:35:23.463", "Id": "64824", "Score": "1", "body": "I mean that if each of the files is already individually sorted, then the code in this question lists all of the lines in sorted order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T11:07:04.853", "Id": "64862", "Score": "0", "body": "Ah yes - that is what it indeed does... in their entirety." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T00:35:59.140", "Id": "64975", "Score": "1", "body": "That some of us were so confused about what it does is an indication that, at least for us, the code is too clever." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T00:38:06.273", "Id": "64976", "Score": "1", "body": "On the other hand, I'm not sure how to go about improving it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T01:59:57.877", "Id": "64978", "Score": "0", "body": "FWIW, I like it, once I realised how it works. I reckon the way to improve it is a couple of comments and it's elegance would shine. It's not my code. If you're interested, the original question was here: http://stackoverflow.com/questions/20969921/elegant-way-to-merge-2-text-files-alphabetically-line-by-line-in-ruby/20970171#20970171" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:53:16.630", "Id": "38804", "ParentId": "38795", "Score": "8" } }, { "body": "<ol>\n<li><p>Took around a 100 seconds to understand. Would be twice faster if I had a commentary: <code># this code merges two presorted files</code>.</p></li>\n<li><p>All is pretty ok, but what you forgot here is to close all opened files. And it is the only reason to have a first variable declared, otherwise I would mix both <code>map</code>s together.</p></li>\n<li><p>If you pass filenames via ARGV, there should be also the <code>merged_filename</code> as the first or last parameter. Or at any position and optional if you start to use some named options parsing.</p></li>\n</ol>\n\n<p>So we have this:</p>\n\n<pre><code>files_to_merge = ARGV.map &amp;File.method(:open)\nlines = files_to_merge.map &amp;:gets\nmerged_file = File.open \"merge_out.txt\", \"w\"\nwhile lines.any?\n merged_file.print(next_line = lines.compact.min)\n file_id = lines.index next_line\n lines[file_id] = files_to_merge[file_id].gets\nend\nmerged_file.close\nfiles_to_merge.each &amp;:close\n</code></pre>\n\n<hr>\n\n<p>But what if try to solve the problem of <em>mindblowing</em> <code>file_id = .index</code>?<br>\nYou could put file handler and current line together into an Array or Hash, but I don't feel like it makes code better:</p>\n\n<pre><code>files_and_lines = ARGV.map(&amp;File.method(:open)).map{ |file| {file:file, line:file.gets} }\n...\nloop do\n files_and_lines.select!{ |tuple| tuple[:line] }\n break if files_and_lines.empty?\n next_tuple = files_and_lines.min_by{ |tuple| tuple[:line] }\n merged_file.print next_tuple[:line]\n next_tuple[:line] = next_tuple[:file].gets\nend\n...\n</code></pre>\n\n<p>Trying to make it shorter didn't work for me: converting tuples into Hash pair <code>file-&gt;line</code> can't easily return file for line and <code>line-&gt;file</code> doesn't look better either because to edit a key you have to have some temporal <code>array</code> variable:</p>\n\n<pre><code>files_and_lines = Hash[ ARGV.map(&amp;File.method(:open)).map{ |file| [file.gets, file] } ]\n...\nloop do\n break if files_and_lines.keep_if{ |line, file| line }.empty?\n array = files_and_lines.to_a.sort_by &amp;:first\n merged_file.print array[0][0]\n array[0][0] = array[0][1].gets\n files_and_lines = Hash[array]\nend\n...\n</code></pre>\n\n<p>So just <s>leave Britney alone</s> don't touch it -- <code>.index</code> is ok.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T13:13:47.990", "Id": "169206", "Score": "1", "body": "[Use parentheses for non-system function calls](https://github.com/bbatsov/ruby-style-guide#no-dsl-parens), you don't do this practically anywhere in your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T14:01:43.060", "Id": "169216", "Score": "0", "body": "@DevonParsons, why should I do what some kid on github says?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T14:05:25.333", "Id": "169217", "Score": "3", "body": "It's not some kid, it's the community driven accepted style guide." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T14:58:21.413", "Id": "169225", "Score": "0", "body": "Really, because the rule I linked to tells you exactly what to do. You seem upset about this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T15:38:18.630", "Id": "169242", "Score": "0", "body": "The problem of modern coders is that they do not realise who is worth to listen to and who is not. And if you think code reviewing is about parentheses, you probably don't know what the good code actually is." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:50:16.073", "Id": "38873", "ParentId": "38795", "Score": "9" } }, { "body": "<p>I am a beginner and I don't understand what it does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-10T00:26:33.357", "Id": "169357", "Score": "2", "body": "I deleted this post when I saw it in the low-quality review queue. On further reflection, it is more relevant as an answer than I initially thought. Apologies for any confusion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-11T08:11:47.487", "Id": "169643", "Score": "0", "body": "@rolf I had the same thought and would have voted to close/delete if you didn't comment here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T11:04:18.050", "Id": "93081", "ParentId": "38795", "Score": "3" } } ]
{ "AcceptedAnswerId": "38798", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T21:49:03.193", "Id": "38795", "Score": "2", "Tags": [ "ruby" ], "Title": "How clear is this Ruby code?" }
38795
<p>A few months ago I wrote this module but, coming back to it, I find it a bit hard to read and reason about. I want to ask community's opinion on whether this needs to be refactored, and how I could approach this.</p> <pre><code>(function (q) { 'use strict'; var DELAY_BEFORE_RENDERING_NEXT_PAGE_VIEW = 3 * 1000; window.st.viewer.Helper.PageViewFactory = (function () { function promiseRenderView(page, token) { return page.fetchUnlessReady() .then(token.throwIfCanceled) .then(function () { var view = new window.st.viewer.View.PageView({ model: page }); view.render(); return view; }); } var scheduledPage, scheduledPromise; function scheduleRenderNextView(page, token) { // After some time passes, prefetch and prerender next page view // so if it is requested (very likely), we can re-use an existing promise. scheduledPage = null; scheduledPromise = null; q.delay(DELAY_BEFORE_RENDERING_NEXT_PAGE_VIEW) .then(token.throwIfCanceled) .then(function () { return page.promiseNext(); }) .then(token.throwIfCanceled) .then(function (nextPage) { if (nextPage) { scheduledPage = nextPage; scheduledPromise = promiseRenderView(nextPage, window.st.Helper.CancellationToken.getNone()); } else { scheduledPage = null; scheduledPromise = null; } }) .catch(token.catchItself) .done(); } function scheduleRenderView(page, token) { var promise = (page !== scheduledPage) ? promiseRenderView(page, token) : scheduledPromise; scheduleRenderNextView(page, token); return promise; } return { scheduleRenderView: scheduleRenderView }; })(); })(Q); </code></pre> <p>This module exports a single function called <code>scheduleRenderView</code>. Its purpose is, given a <code>page</code> model and a cancellation token, do the following steps asynchronously:</p> <ol> <li>Fully fetch <code>page</code> model (it may be loaded partially);</li> <li>Create and render (in memory) a <code>PageView</code> for it;</li> <li>Return this view to the caller;</li> <li><p>Additionally, after a 3 second delay:</p> <ul> <li>Request next <code>page</code> by calling <code>promiseNext</code>;</li> <li>Pre-render next page by repeating steps 1-3 for it and store the pre-rendered view <strong>in case it gets requested the next time</strong> <code>scheduleRenderView</code> is called (very likely)</li> </ul></li> </ol> <p>The user views pages one by one, and I wanted to anticipate the most likely scenario where she will request the next page.</p> <p>I also wanted to make this optimization invisible to the calling code.</p> <p>Is this code hard to comprehend? Are the simpler ways to achieve the same?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T23:16:01.420", "Id": "64800", "Score": "0", "body": "I must say, this sure looks like a complicated way to express what it is you're trying to do. If it were me, I'd back up to first principles and find a much easier way to express what I was trying to do. I don't understand enough about what you're trying to do to take a crack at it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T23:18:27.690", "Id": "64801", "Score": "0", "body": "@jfriend00: What is it that you don't understand? I'll happily clarify this." } ]
[ { "body": "<p>Is this code hard to comprehend? Yes.</p>\n\n<p>That is because there are a lot of unknown functions: <code>view.render</code>, <code>page.fetchUnlessReady</code>, <code>token.catchItself</code> ,<code>token.throwIfCanceled</code> or <code>window.st.Helper.CancellationToken.getNone()</code> etc. etc.</p>\n\n<p>In my mind, I would approach this more like : </p>\n\n<pre><code>function scheduleRenderView( page )\n{\n //Load and display the page\n var promise = model.loadPage( page ).then( function(){\n view.renderPage( model.getPage( page ) );\n });\n //Load the next page\n model.loadPage( page.next() );\n return promise;\n}\n</code></pre>\n\n<p><code>loadPage</code> would either return immediately if we retrieved already the data once ( from cache ) or download the page model.</p>\n\n<p><code>getPage</code> gets a page model from cache</p>\n\n<p><code>renderPage</code> would do the obvious</p>\n\n<p>This means I would forego the pre-rendering which really sounds like pre-mature optimization, how long could that take?</p>\n\n<p>2 other minor comments:</p>\n\n<ul>\n<li>Why access some variables through <code>window</code>, that does not seem to make sense</li>\n<li>In my mind, adding functions to the <code>window.st.viewer.Helper</code> is terrible global variable abuse, not to mention that you probably should add it to <code>Helper.prototype</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:46:23.800", "Id": "64855", "Score": "0", "body": "Pre-rendering is not an immature optimization, there was a real need for it. What do you suggest for namespacing instead of `window.st.viewer.*`? `Helper` is a namespace, not a class, why add something to its prototype? Again, `window.st` is just a root namespace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:48:11.577", "Id": "64856", "Score": "0", "body": "Do you think I should re-word the question to remove any methods specific to my code (`fetchUnlessReady`, etc, and only leave the “essence” of the code)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:54:28.110", "Id": "64861", "Score": "0", "body": "To make it clear: `CancellationToken` is a class, `getNone` is its static method. It's not just some global variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:23:30.907", "Id": "64888", "Score": "0", "body": "Your suggestion might make it easier indeed to review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:24:39.380", "Id": "64889", "Score": "0", "body": "Also, you could just use `st` for your namespace, there is no need for using `window`, I am sure you can avoid local variable clashes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:24:10.203", "Id": "65051", "Score": "1", "body": "In fact you were right. Rendering *was* a premature optimization. It renders view in DOM and begins to fetch images, fonts, etc, so it *looks* like a useful optimization. What I didn't realize, is that I'm scheduling it too early—before the *current* view's resources probably have loaded, so it *slowed down current view's rendering*. I cut this code completely, fixed a couple of problems, and seems to run more smoothly now. So you were right after all!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T03:03:09.463", "Id": "38806", "ParentId": "38800", "Score": "2" } }, { "body": "<p>Two more points to complement <a href=\"https://codereview.stackexchange.com/a/38806/2634\">konijn's answer</a> to my question:</p>\n\n<ul>\n<li>I'm moving from <code>window.st.*</code> madness to using <a href=\"http://requirejs.org\" rel=\"nofollow noreferrer\">require.js</a> with <a href=\"https://github.com/jrburke/almond\" rel=\"nofollow noreferrer\">Almond</a> (I wish I did this before);</li>\n<li>Instead of hand-rolled cancellation mechanism, I'm moving from Q to <a href=\"https://github.com/petkaantonov/bluebird\" rel=\"nofollow noreferrer\">bluebird</a> which already <a href=\"https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellation\" rel=\"nofollow noreferrer\">supports opt-in cancellation</a>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:09:55.233", "Id": "40063", "ParentId": "38800", "Score": "1" } } ]
{ "AcceptedAnswerId": "38806", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T22:52:21.867", "Id": "38800", "Score": "4", "Tags": [ "javascript", "mvc", "asynchronous", "promise" ], "Title": "Refactoring asynchronous JS pre-rendering code" }
38800
<p>I have the following factory class, wonder if this code can be implemented in better way. I saw few discussions about spring factory bean, but don't find good examples.</p> <pre><code>@service public CustomerSearchFactory{ @Autowired private CustomerSearchByID searchById; @Autowired private CustomerSearchByName searcyByName; @Autowired private CustomerSearchBySSN searchBySSN; public CustomerSearch getInstance(Request param){ if (StringUtils.isNotBlank(param.getID()){ return searchById; }else if (StringUtils.isNotBlank(param.getName()){ return searcyByName; }else if (StringUtils.isNotBlank(param.getSSN()){ return searchBySSN; } } } @service public CustomerSearchByID implements CustomerSearch{ @Autowired private Service1 service1; public Response search(Request request){ -- -- ReturnResponse rs = service1.performSearch(inputRequest); -- return response; } } @service public CustomerSearchBySSN implements CustomerSearch{ @Autowired private Service2 service2; public Response search(Request request){ -- -- ReturnResponse rs = service2.performSSNSearch(inputRequest); --enter code here` return response; } } </code></pre> <p>caller code:</p> <pre><code>CustomerSearch customerSearch= customerSearchFactory.getInstance(param) response = customerSearch.search(request); </code></pre> <p>I am using the spring 3.1 framework and want to know if this code can be optimized.</p>
[]
[ { "body": "<p>I would advise not to use a different <code>CustomerSearch</code> per search criteria.<br/>\nAs your functionality will evolve you could need a <code>CustomerSearch</code> that is using the country the <code>Customer</code> is from.<br/>\nBut what if you want to search on the <code>Country</code> in combination with part of the name?<br/>\nSoon you will be combining different search criteria together which will require one smart <code>CustomerSearch</code> bean.<br/></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:44:34.973", "Id": "64968", "Score": "0", "body": "Malachi, The reason for having different customer search is to invoke different services. I don't think we will have another search in the application and the search can be done only on one criteria. let know if you have any suggestion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:34:36.533", "Id": "38832", "ParentId": "38802", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T00:13:48.600", "Id": "38802", "Score": "3", "Tags": [ "java", "spring" ], "Title": "factory pattern in spring" }
38802
<p>I'm making a Windows service that watches a directory for new files to process them.</p> <p>I hit a race condition between the file copying going on and me trying to process it. Going by a SO answer I wrote the following wait-and-retry method to make sure I can work with the file:</p> <pre><code>public static void WaitForFile(string file, CancellationToken token, int retryIntervalMillis = 200) { while (!token.IsCancellationRequested) { try { using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None)) return; } catch { Thread.Sleep(retryIntervalMillis); } } throw new OperationCanceledException(token); } </code></pre> <p>My question is: would this be a correct way to make this waiting cancellable? The token is cancelled to shut down the service, the idea is to allow for a clean (-ish) shutdown even in a case a bug means the file in question is inadvertently kept open indefinitely.</p> <p>(Or if the reason the file can't be opened is some other, non-intermittent condition I haven't guarded against yet.)</p> <p>For instance, is it okay to use the token this way in my method, and also expect the same token to cancel a <code>BlockingCollection</code>'s consuming enumerator?</p> <p>My intent is to base the service around the expectation it can be hard-crashed at any time, so I'm fine with an exception taking out most of the call stack leading to it.</p> <h2>Edit:</h2> <p>These are changes that I have since made to the code</p> <pre><code>const int ErrorSharingViolation = -2147024864; public static FileStream WaitForFile(string file, CancellationToken token, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read, Action&lt;Stream&gt; action = null, int retryIntervalMillis = 200) { while (!token.IsCancellationRequested) { try { var stream = File.Open(file, mode, access, FileShare.None); if (action != null) { using (stream) { action(stream); } } return stream; } catch (IOException exception) { if (exception.HResult != ErrorSharingViolation) { throw; } else { Thread.Sleep(retryIntervalMillis); } } } throw new OperationCanceledException(token); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T06:08:02.433", "Id": "64825", "Score": "0", "body": "It seems to me that you're only closing a newly created connection to the file not an existing one. You might have to pass the stream instead so that it can be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T06:12:23.233", "Id": "64826", "Score": "0", "body": "@tinstaafl That's intentional. I want to wait until it's possible to create new connections to the file in the first place. The existing connection is made from Windows Explorer as it copies the file into the drop folder, not from my service." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:51:57.200", "Id": "64859", "Score": "0", "body": "What happens in the case of an exception, does the file become unusable until the program is closed? Also, in my opinion this usage of try/catch falls under \"expected behaviour\", is there not a way you can test the file without opening a stream? Wouldn't it be more common for an exception to occur than for it to not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:01:18.337", "Id": "64880", "Score": "0", "body": "Related: [Waiting for a file to be accessible with Thread.Sleep() and exception catching](http://codereview.stackexchange.com/questions/7210/waiting-for-a-file-to-be-accessible-with-thread-sleep-and-exception-catching)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:16:39.907", "Id": "64909", "Score": "0", "body": "@Sam That's why the `using` is there – the file is opened, then immediately closed again so the caller can open it. I've since changed it to actually invoke a callback instead to avoid the (in my use case unlikely) race condition where another process may open the file between `WaitForFile()` closing and the caller opening it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:35:07.670", "Id": "64913", "Score": "0", "body": "Oh right. Sorry, I didn't see that there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:56:56.857", "Id": "64919", "Score": "0", "body": "@Bobby That looks like a good approach if I knew enough about implementing my own async/await tasks. But as a rule I try not to use code snippets from the internet I don't understand. (Since the file is immediately passed to a 7-zip library that doesn't support async, it's really no benefit to me now.)" } ]
[ { "body": "<p>Your <code>catch</code> statement is catching <strong>any</strong> error <em>(<strong>EVERY ERROR</strong>)</em>, which is not a good thing. I assume there are several errors that you are anticipating, but you shouldn't catch them all. You will run into bugs and won't know what is going on because the errors will be bulked into your cancellation. </p>\n\n<p>I would catch only the exceptions that you know about and are ready for, meaning that you have a solution for that exception.</p>\n\n<hr>\n\n<p>You also might want to set it so that right before <code>WaitForFile</code> is exited, it closes the file no matter what happens inside the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:17:34.490", "Id": "64910", "Score": "0", "body": "I've changed that part in my code since yesterday, I'll edit that into my sample. It's a valid observation about the code as posted, but really the crux of my question was, specifically, implementing cancellation correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:18:28.353", "Id": "64911", "Score": "2", "body": "The `using` statement should take care of closing (by calling `Dispose()`) the file. As far as I can tell there's no code path that does not do so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:47:25.537", "Id": "64969", "Score": "0", "body": "I'm sorry you feel I was moving the goalposts with my edit, but I believe even as originally phrased it was clear what I'm asking about is how I implement cancellation, not the wait-and-retry mechanism itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T00:28:20.840", "Id": "64974", "Score": "0", "body": "on Code Review we Review what code you have. catching every error is bad practice, unless you are logging it. the new code looks better from what I have seen" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T03:50:05.883", "Id": "64988", "Score": "0", "body": "Sorry, but I call shenanigans. I find it hard to believe it's against the policy of CR for the OP to actually raise specific issues about their code; or that you're expected to consider a question accepted when someone answering finds *something*, however tangential to those issues. I will poke around meta though. (Remember: I'm not saying your answer is bad, you have my upvote. I just don't think it makes my question \"answered\" as you said in the comments reverting my edit.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T06:21:12.300", "Id": "65001", "Score": "0", "body": "I am not saying that I answered your questions, but I gave an *Answer* (or a \"Review\", or *suggestion*). I didn't say you couldn't raise specific issues about your code. I said you shouldn't change the question after someone has reviewed your code. it invalidates their answer (review)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T23:21:58.593", "Id": "65145", "Score": "2", "body": "Ah, I think I get it now. You weren't accusing me of moving the goalposts, but of messing up the context of your answer and making it seem like it's completely unrelated. Sorry for being argumentative there, I read the situation wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T23:24:45.907", "Id": "65146", "Score": "0", "body": "perfect analogy. you got it!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:20:34.683", "Id": "38829", "ParentId": "38807", "Score": "10" } } ]
{ "AcceptedAnswerId": "38829", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T04:08:44.373", "Id": "38807", "Score": "8", "Tags": [ "c#", "task-parallel-library" ], "Title": "Implementing a cancellable \"infinite\" loop" }
38807
<p>Markdown was developed by John Gruber, and described on his <a href="http://daringfireball.net/projects/markdown/" rel="nofollow noreferrer">website</a>. However, the grammar was not rigorously specified, leading to a number of variant implementations. In September 2014, a <a href="http://standardmarkdown.com" rel="nofollow noreferrer">Standard Markdown</a> specification was released to address these concerns.</p> <p>Some implementations of Markdown also offer non-standard extensions to the language. For example, Stack Exchange uses an enhanced version of Markdown to allow editing of Questions and Answers, and even this wiki text. For help on the Stack Exchange enhancements <a href="https://codereview.stackexchange.com/editing-help">check out the help pages</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T04:09:50.533", "Id": "38808", "Score": "0", "Tags": null, "Title": null }
38808
Markdown is a markup language which can allow for plain-text documents to be transformed into HTML and other formats.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T04:09:50.533", "Id": "38809", "Score": "0", "Tags": null, "Title": null }
38809
<p><a href="https://stackoverflow.com/questions/20969923/weird-behaviour-of-a-seconds-elapsed-function/20970030?noredirect=1#comment31504047_20970030">Background of the problem</a></p> <p>My Class level variables: </p> <pre><code> static int secondsInterval = 100000000; static long secondsSpecial=0; static Date dateSecondsReg; static Integer intValue; </code></pre> <p>I have a function which uses the standard Java Calendar:</p> <p>The function accepts a value in long(Which is seconds elapsed from a certain date till now) and a date(Start date) then based on this calculates seconds elapsed for sometime in future. The problem I was running into earlier was that the <code>cal.add(Calendar.HOUR,intValue);</code> would only accept int values as args and I used to add seconds earlier, now I changed it to Hours so that I dont get an Integer Overflow. </p> <pre><code>public static void secondsToNotify(long seconds, String d){ Date dt = Convert(d); System.out.println(""+dt); Calendar cal = Calendar.getInstance(); cal.setTime(dt); secondsSpecial = secondsInterval*(1+(seconds/secondsInterval)); System.out.println(""+(secondsSpecial)); long hour = (secondsSpecial /60)/60; System.out.println(""+hour); if(hour &gt;= Integer.MAX_VALUE){ }else{ intValue = (int) (long)hour; } cal.add(Calendar.HOUR,intValue); dateSecondsReg = cal.getTime(); System.out.println(""+dateSecondsReg); System.out.println(""+secondsSpecial); } </code></pre> <p>The code in:</p> <pre><code>secondsSpecial = secondsInterval*(1+(seconds/secondsInterval)); </code></pre> <p>is important for me to get an integer division to drop off the residue. </p> <p>Is this fine or there is something more behind the scenes? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:43:55.537", "Id": "64853", "Score": "1", "body": "What's your goal? To parse `d` as a date and add `seconds` to it, except that `seconds` is rounded up to the next 1157 days? May I ask why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:52:39.147", "Id": "64860", "Score": "0", "body": "I want to predict seconds in multiples of 100000000 in future, for the date d." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T11:29:03.850", "Id": "64863", "Score": "0", "body": "Why don't you use the [answer](http://stackoverflow.com/a/20970398/1157100) you got on Stack Overflow for avoiding overflow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:56:14.770", "Id": "64982", "Score": "0", "body": "I am done with the overflow, the point of posting here was to double check if I am going wrong anywhere. The overflow is not present in the above code." } ]
[ { "body": "<pre><code> static long secondsSpecial=0;\n</code></pre>\n\n<p>Static variables that get modified? Rethink your approach.</p>\n\n<p>If you have static variables, there's a good chance that either your design is wrong, or it should be an instance class. Always limit the scope of variables, methods and classes to the smallest one possible. A variable that is not used outside of the class should not be public, a function that only concerns the class it is defined in should not be public, a variable that is only used inside one function should not be declared in the class but in the function itself and so on.</p>\n\n<hr>\n\n<pre><code>public static void secondsToNotify(long seconds, String d){\n</code></pre>\n\n<p>What does <code>d</code> do? What is it for? Rename it according to what it role is, or provide <em>thorough</em> documentation on why it only is one letter.</p>\n\n<hr>\n\n<pre><code>System.out.println(\"\"+dt);\n</code></pre>\n\n<p>Are you coming from a VB6 background? I wish I could say that the last time I saw someone using the \"empty-string-concatenate-cast\" was somewhere in the nineties...unfortunately I did not code back then and I work with a VB6 coder...so...</p>\n\n<p>Why is that bad? It's some sort of, well, implicit type casting in the hope that it might work. That the Java compiler allows such thing is still a mystery to me.</p>\n\n<p>Easier readable alternatives:</p>\n\n<pre><code>System.out.println(dt.toString()); // Turns out this does the same in a better way.\nSystem.out.println(dt); // Calls the objects toString() method.\n</code></pre>\n\n<hr>\n\n<pre><code>secondsSpecial = secondsInterval*(1+(seconds/secondsInterval)); \n</code></pre>\n\n<p>By now I know that those variables do not have the ideal names they could have.</p>\n\n<hr>\n\n<pre><code>System.out.println(\"\"+(secondsSpecial));\n</code></pre>\n\n<p>Same here...are you aware that <code>System.out</code> has an overload of <code>println</code> that accepts <code>long</code>?</p>\n\n<pre><code>System.out.println(secondsSpecial);\n</code></pre>\n\n<hr>\n\n<pre><code>long hour = (secondsSpecial /60)/60; \n</code></pre>\n\n<p>I here for inform you that this static method is not threadsafe...well, that felt funny.</p>\n\n<p>If this static helper method is called from two different threads, it's possible that the first thread will set <code>secondsSpecial</code>, print something and while the first thread prints something the second will come along and also set <code>secondsSpecial</code>.</p>\n\n<pre><code>...\nThread1: Set secondsSpecial to 3\nThread2: Set the time of the calendar\nThread1: Print the value of secondsSpecial\nThread2: Set secondsSpecial to 25634\nThread1: Use secondsSpecial\n</code></pre>\n\n<p>And that's why static variables that get modified are bad. No one would expect a <em>static helper method</em> to be not threadsafe if not explicitly told about. Or would you think that <code>Arrays.asList()</code> is not threadsafe?</p>\n\n<hr>\n\n<pre><code>if(hour &gt;= Integer.MAX_VALUE){\n\n}else{\n</code></pre>\n\n<p>Silently failing is not acceptable, this would be a good moment to throw a <code>IllegalArgumentException</code> with a descriptive message.</p>\n\n<hr>\n\n<pre><code>intValue = (int) (long)hour; \n</code></pre>\n\n<p><code>hour</code> is already a long.</p>\n\n<hr>\n\n<pre><code>System.out.println(\"\"+dateSecondsReg);\nSystem.out.println(\"\"+secondsSpecial);\n</code></pre>\n\n<p>While we're at it, your function should not directly print to stdout. If you want to log something within a function, a Logger would be appropriate.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>secondsSpecial = secondsInterval*(1+(seconds/secondsInterval));\n</code></pre>\n \n <p>is important for me to get an integer division to drop off the residue. </p>\n</blockquote>\n\n<p>Please correct me, but isn't that what <code>seconds / 60</code> does?</p>\n\n<p>Java automatically performs an integer division if it is handed two integers/long. Anyway, this solution would be hacky at best, <code>(int)Math.floor(value)</code> would be better.</p>\n\n<hr>\n\n<p>All in all, it sounds more like you want to rewrite the function completely and instead only accept a calendar instance which you then add the long seconds to. Like this (pseudo code):</p>\n\n<pre><code>function addSecondsToCalendar(Calendar cal, long seconds) {\n long hours = seconds / 60\n if hours &gt;= Integer.MAX_VALUE throw IllegalArgumentException\n\n cal.add(hours)\n}\n</code></pre>\n\n<hr>\n\n<p>Which raises the question what you're doing that you need this functionality. Short comparison:</p>\n\n<pre><code>Integer.MAX_VALUE: 2147483647\nIn minutes: 35791394.116667\nIn hours: 596523.23527778\nIn days: 24855.134803241\nIn years: 68.096259734906\n</code></pre>\n\n<p>So if you only use <code>int</code> seconds, you can already schedule notifications (that's what your function does, right?) for the next ~68 years.</p>\n\n<p>If, on the other hand, you use \"historic\" dates as starting point, then it is understandable that you need a bigger range than ~68 years. Should be mentioned in the JavaDoc of the method, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:17:13.117", "Id": "64847", "Score": "0", "body": "This has been insightful, the part of static variables however was only due to the case that I somehow could not remove or forgot to remove it while posting it here. I had isolated the problem code form my main project and developed a new project just to check this function while the compiler was giving me warnings Cannot make a static reference to the non-static field secondsInterval. Also I accept that I am too bad at naming variables, where can I find a good naming convention guide? Thanks a ton :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:22:59.060", "Id": "64848", "Score": "0", "body": "If you haven't read it, I can only recommend [Effective Java](http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683). It has a short but very useful section on names. Also if you only use variables in a function, always declare them in that function. Start with the smallest scope, meaning declare variables where you need them and *only* make them more accessible/visible if you have the need for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:25:37.370", "Id": "64849", "Score": "0", "body": "Yes actually for keeping these variables Class level has a meaning in my code, the function in real code has two values of interest, so getters and setters and hence class level." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:26:53.993", "Id": "64850", "Score": "0", "body": "Then it should be an instance-class in my opinion." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:07:12.680", "Id": "38819", "ParentId": "38810", "Score": "2" } } ]
{ "AcceptedAnswerId": "38819", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T04:30:41.017", "Id": "38810", "Score": "2", "Tags": [ "java", "datetime", "integer" ], "Title": "Check robustness of function to add an interval to a date" }
38810
<p>As I understand it, blowfish (actually eksblowfish, as it's used one way) is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.</p> <pre><code>&lt;?php /* * Generate a secure hash for a given password. The cost is passed * to the blowfish algorithm. Check the PHP manual page for crypt to * find more information about this setting. Returns null on failure. */ function generate_hash($password, $cost=11){ /* To generate the salt, first generate enough random bytes. Because * base64 returns one character for each 6 bits, the we should generate * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first * 22 base64 characters */ $salt=substr(base64_encode(openssl_random_pseudo_bytes(17,$secure)),0,22); /* If the random generation was not secure enough, do not continue */ if(!$secure) return null; /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to * replace any '+' in the base64 string with '.'. We don't have to do * anything about the '=', as this only occurs when the b64 string is * padded, which is always after the first 22 characters. */ $salt=str_replace("+",".",$salt); /* Next, create a string that will be passed to crypt, containing all * of the settings, separated by dollar signs */ $param='$'.implode('$',array( "2y", //select the most secure version of blowfish (&gt;=PHP 5.3.7) str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits $salt //add the salt )); /* Now do the actual hashing */ $hash=crypt($password,$param); if(strlen($hash)!=60) return null; return $hash; } /* * Check the password against a hash generated by the generate_hash * function. */ function validate_pw($password, $hash){ /* Regenerating the with an available hash as the options parameter should * produce the same hash if the same password is passed. */ return crypt($password, $hash)===$hash; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:11:41.647", "Id": "64830", "Score": "3", "body": "Why bother reinventing the wheel? Time and energy best spent upgrading your PHP version to 5.5, which introduced the `password_hash` function, to be called like so: `password_hash($password, PASSWORD_BCRYPT, array('salt' => 'yourSalt', 'cost' => 15));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T10:46:18.460", "Id": "64854", "Score": "0", "body": "Or even use something like phpass http://www.openwall.com/phpass/ . I feel that it is better to use something tested than roll your own (which may include vulnerabilities)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T19:08:02.620", "Id": "72629", "Score": "1", "body": "If PHP 5.5 isn't available, ircmaxell has made a drop in PHP version that just requires PHP 5.3: https://github.com/ircmaxell/password_compat" } ]
[ { "body": "<p>I would have to agree with @EliasVanOotegem. Consider using <code>password_hash()</code> and <code>password_verify()</code>. All you've done is recreate something, which <a href=\"https://security.stackexchange.com/questions/25585/is-my-developers-home-brew-password-security-right-or-wrong-and-why\">we know shouldn't be done</a>.</p>\n\n<p>Documentation for the <a href=\"http://us2.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">former</a> and <a href=\"http://us2.php.net/manual/en/function.password-verify.php\" rel=\"nofollow noreferrer\">latter</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T18:54:36.447", "Id": "42184", "ParentId": "38812", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T06:08:39.363", "Id": "38812", "Score": "1", "Tags": [ "php", "security" ], "Title": "PHP secure hash generator" }
38812
<p>I tend to write quite explicit tests for my rails controllers exposing APIs with two seperate concerns:</p> <ul> <li>meeting the defined API-Response with headers headers and the response itself</li> <li>ensuring the right calls to underlaying methods/objects are made</li> </ul> <p>However when the calls are not simply executable in a test the controller tends to get bloated. This is due to the fact that when the calls are stubbed out the execution order of the two test concerns is reversed:</p> <ul> <li>for the api calls: <ul> <li>first stub the call method (since we don't want this to be run)</li> <li>make the request</li> <li>test the response</li> </ul></li> <li>for the method calls <ul> <li>define the receive-expectations</li> <li>make the request</li> </ul></li> </ul> <p>Example Code:</p> <pre><code>require 'spec_helper' describe ItemsController do render_views shared_examples :empty_success_response do it { expect(response.status).to eql(202) } it { expect(response.content_type).to eql('application/json')} it 'returns error message' do json = JSON.parse(response.body) expect(json).to be_blank end end context 'a single item' do subject { FactoryGirl.create(:item) } describe '#destroy' do let(:do_action) do delete :destroy, id: subject.id.to_s end describe 'response' do before do controller.stub!(:destroy_item) do_action end it_behaves_like :empty_success_response end it 'makes the call' do expect(controller).to receive(:destroy_item).once.times.with(subject.id.to_s) do_action end end # ... end end </code></pre> <p>Note: The destroy_item method is just a stand in, the actual method makes more sense ;)</p> <p>The code in the example works nicely, and is even fairly dry (mostly because the request is moved into a let), but feels still very chunky and bloated - especially if we consider this is just one simple actions, with a usual controller having quite a few more real logic to test.</p> <p>Does anyone have an idea how to make this code more readable?</p> <p>Or does it maybe make sense to split the 2 kinds of tests completely? This would however mean quite a bit of duplication since we have the same caller-code in 2 places.</p>
[]
[ { "body": "<p>shared examples share the <a href=\"https://stackoverflow.com/a/5557454\"><code>let</code> scope</a>, so you could further dry up your code (assuming you use <code>do_action</code> for every action) to this:</p>\n\n<pre><code>shared_examples :empty_success_response do\n\n before do\n do_action\n end\n\n ...\nend\n</code></pre>\n\n<p>Also, if you are using do_action, I also like to add to my scopes:</p>\n\n<pre><code>describe '#destroy' do\n let(:do_action) do\n delete :destroy, id: subject.id.to_s\n end\n\n after do\n do_action\n end\n\n ...\nend\n</code></pre>\n\n<p>This way, you don't have to call <code>do_action</code> if all you do in the test is set expectations. </p>\n\n<pre><code>it 'makes the call' do\n expect(controller).to receive(:destroy_item).once.times.with(subject.id.to_s)\nend\n</code></pre>\n\n<p>If in some tests you want <code>do_action</code> to run before the end of the test - that's no problem, since <code>let</code> runs the code only once - so it won't run again at the end of that specific test!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:05:08.683", "Id": "40859", "ParentId": "38813", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T07:07:47.757", "Id": "38813", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "How can this rails controller test be cleaner refactored?" }
38813
<p>I have two threads - one thread queues items another thread dequeues. <code>dequeue</code> is fast enough and so we can assume that queue is never contains more than 65536 items.</p> <p>C++ doesn't contain "ring-buffer." Boost has one, but it doesn't allow "reuse" of elements. So I wrote my own ring-buffer, which I think is very fast and requires no memory allocation. The code below has not been tested but it should show the general idea.</p> <p>Do you find my code fine? Can you suggest how I can improve it or if there's something I can use instead of it? #include #include #include </p> <pre><code>#include &lt;chrono&gt; #include &lt;thread&gt; template&lt;class T&gt; class ArrayPool { public: ArrayPool() { }; ~ArrayPool(void) { }; // reader thread bool IsEmpty() { return curReadNum == curWriteNum; } // reader thread T* TryGet() { if (curReadNum == curWriteNum) { return NULL; } T* result = &amp;storage[curReadNum &amp; MASK]; ++curReadNum; return result; } // writer thread T* Obtain() { return &amp;storage[curWriteNum &amp; MASK]; } // writer thread void Commit() { // Ensure storage is written before mask is incremented ? // insert memory barrier ? ++curWriteNum; if (curWriteNum - curReadNum &gt; length) { std::cout &lt;&lt; "ArrayPool curWriteNum - curReadNum &gt; length! " &lt;&lt; curWriteNum &lt;&lt; " - " &lt;&lt; curReadNum &lt;&lt; " &gt; " &lt;&lt; length &lt;&lt; std::endl; } } // writer thread void ObtainAndCommit(T* val) { memcpy(&amp;storage[curWriteNum &amp; MASK], val, sizeof(T)); // copy constructor will likely be slower cause every field is copied // storage[curWriteNum &amp; MASK] = *val; Commit(); } private: static const uint32_t length = 65536; static const uint32_t MASK = length - 1; T storage[length]; // curWriteNum must be volatile because access from both // reader and writer threads // curReadNum don't need to be volatile because accessed // only from one (reader) thread volatile uint32_t curWriteNum; uint32_t curReadNum; }; struct myStruct { int value; }; ArrayPool&lt;myStruct&gt; pool; void ReadThread() { myStruct* entry; while(true) { while ((entry = pool.TryGet()) != NULL) { std::cout &lt;&lt; entry-&gt;value &lt;&lt; std::endl; } } } void WriteThread(int id) { std::chrono::milliseconds dura(1000 * id); std::this_thread::sleep_for(dura); myStruct* storage = pool.Obtain(); storage-&gt;value = id; pool.Commit(); std::cout &lt;&lt; "Commited value! " &lt;&lt; id &lt;&lt; std::endl; } int main( void ) { boost::thread readThread = boost::thread(&amp;ReadThread); boost::thread writeThread; for (int i = 0; i &lt; 100; i++) { writeThread = boost::thread(&amp;WriteThread, i); } writeThread.join(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T21:39:50.517", "Id": "64960", "Score": "0", "body": "because of currWriteNum/curReadNum overflow you have a dependency on the ring size being a power of 2. You should write length in those terms or add a comment about the dependency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T14:13:24.693", "Id": "65506", "Score": "0", "body": "Should an answer assume that you don't want to detect buffer overruns, because they're \"impossible\" or \"undefined\" or \"not supported\", for example because of scheduling or data-flow constraints in the threads which use this class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T15:39:48.073", "Id": "65518", "Score": "0", "body": "@ChrisW of course. question is not about \"rare\" conditions. When someone will be wrong I can dig and fix. Question about \"general scenario\". Let's make this code working under \"normal, assumed\" conditions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T00:58:47.560", "Id": "94307", "Score": "0", "body": "I'd #include <cstdint> instead of stdint.h. Second, I'm not 100% sure about that one, but your c'tor and d'tor of ArrayPool are empty, and you don't define copy/move c'tors, so I think it's better practice to omit the c'tor/d'tor and just let the compiler generate the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-15T22:43:34.307", "Id": "177525", "Score": "2", "body": "I am appalled by the number of people telling you to \"just use locks.\" Yes, using a wait-free ringbuffer is overkill if your locks aren't contended or you don't need near-realtime performance. But if you're ever writing code that can't block--signal handlers and audio callbacks come to mind--then you need something like a ringbuffer. Telling you not to write one doesn't help at all with your understanding of *how* to write one." } ]
[ { "body": "<ul>\n<li><p>there is absolutely no thread safety constructs, this means that you'll see a lot of <em>interesting</em> race conditions and memory inconsistencies </p></li>\n<li><p>just assuming dequeues happen fast enough does not mean they will in production</p></li>\n<li><p>you return <code>T</code> by value in <code>Obtain()</code>, instead of by reference so you can't actually write into it</p></li>\n<li><p><code>Obtain</code> is a bad name, it sounds like it gets the next value like <code>TryGet</code> does</p></li>\n<li><p><code>memcpy</code> is a bad idea to use to store the values if there is ever a custom copy constructor and a destructor</p></li>\n<li><p>that said <code>Obtain</code>-><code>store</code>-><code>Commit</code> can be put into a single <code>Put(T*)</code> member function</p></li>\n<li><p>eventually <code>curReadNum</code> and <code>curWriteNum</code> will overflow, it's not a real problem here because your length is a power of 2 and they are unsigned</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:16:08.057", "Id": "64868", "Score": "0", "body": "Thanks. Yes, I think Obtain() must return T* so i can memcpy to internal storage. Note I store only \"simple\" things, simple structures. I don't need a code that works for any kind of data. I need maximum performance on my data. The question is if my code is good \"in general\" or if \"design and idea good in general\". Or you can suggest another approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:39:39.897", "Id": "64870", "Score": "0", "body": "@javapowered you should at least fix points 1 and 2, which deals with memory consistency (a.k.a. flush the written value out to the shared memory instead of the cache) and should dequeuing ever be delayed for whatever reason you must be able to handle that cleanly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:43:53.053", "Id": "64871", "Score": "1", "body": "\"flush the written value out to the shared memory instead of the cache\" how can I do that? can you give an example which demonstrates such kind of problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T01:30:40.967", "Id": "65461", "Score": "0", "body": "`Obtain->store->Commit can be put into a single Put(T*)` how? note I do not want to allocate memory at runtime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T01:35:17.533", "Id": "65462", "Score": "0", "body": "@javapowered the Put will then do exactly as your `Obtain` -> store -> `Commit` does now, and you just pass a pointer or reference into `Put`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T01:39:38.080", "Id": "65463", "Score": "0", "body": "I see, the problem is that sometimes I do not have a pointer to memcpy. I reconfigure values in different way. But `Put(T*)` can be added in addition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T07:43:38.417", "Id": "65474", "Score": "0", "body": "@javapowered then allocate one on the stack and pass a pointer to that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T08:30:08.407", "Id": "65480", "Score": "0", "body": "i don't want to reallocate memory - it's much faster to reuse memory" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T12:27:32.337", "Id": "38821", "ParentId": "38815", "Score": "11" } }, { "body": "<h1>Use assignment instead of memcpy</h1>\n\n<p>A better implementation of Obtain can return a non-const reference which you can assign to:</p>\n\n<pre><code>T&amp; Obtain() {\n return storage[curWriteNum &amp; MASK];\n}\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>void Processor::EnqueueFutOrderbook(orders* param)\n{\n orders&amp; storageItem = futOrdersUpdates.Obtain();\n storageItem = *param;\n futOrdersUpdates.Commit();\n}\n</code></pre>\n\n<p>That deals with the \"use the copy constructor instead of memcpy\" suggested by @ratchetfreak.</p>\n\n<p><em>If you use memcpy instead of assignment then your code is incorrect for all types of T which have a non-trivial (e.g. user-defined) copy constructor.</em></p>\n\n<blockquote>\n <p>Copy-construct will be slower than memcpy, isn't it?</p>\n</blockquote>\n\n<p>The reason for using assignment is if T has a non-trivial copy-constructor (more accurately, an 'assignment operator'): for example if T is a <code>std::auto_ptr&lt;&gt;</code> or if it contains a <code>std::string</code>: if T has a non-trivial user-defined assignment operator, memcpy avoids calling it: which, may be faster but is incorrect behaviour!</p>\n\n<p>In your example though your <code>T</code> is <code>myStruct</code>, which has a default (or non-existent) assignment operator. In that case the assignment is done by the compiler as an intrinsic, which is likely to be at least as fast as the run-time-library's <code>memcpy</code> function.</p>\n\n<p>Which of the following do you think is faster:</p>\n\n<pre><code>void test()\n{\n T source, target;\n // test the speed of `memcpy`\n for (int i = 0; i; i &lt; 100000)\n memcpy(&amp;target,&amp;source,sizeof(T));\n // test the speed of compiler-generated assignment with copy-constructor\n for (int i = 0; i; i &lt; 100000)\n target = source;\n}\n</code></pre>\n\n<h1>An implementation which locks each method could be safe</h1>\n\n<p>One ('atomic') <code>Store</code> function would be easier to use than separate <code>Obtain</code> and <code>Commit</code> methods:</p>\n\n<pre><code>void Store(const T&amp; newValue) {\n storage[curWriteNum &amp; MASK] = newValue;\n ++curWriteNum;\n if (curWriteNum - curReadNum &gt; length)\n {\n std::cout &lt;&lt;\n \"ArrayPool curWriteNum - curReadNum &gt; length! \" &lt;&lt;\n curWriteNum &lt;&lt; \" - \" &lt;&lt; curReadNum &lt;&lt; \" &gt; \" &lt;&lt; length &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>Instead of trying \"lock-free\" code, adding locks as follows would make it safe.</p>\n\n<pre><code>#pragma once\n\n#include &lt;stdint.h&gt;\n#include &lt;iostream&gt;\n#include &lt;mutex&gt;\n\ntemplate&lt;class T&gt; class ArrayPool\n{\npublic:\n bool IsEmpty() {\n std::lock_guard&lt;std::mutex&gt; lck (mtx);\n return curReadNum == curWriteNum;\n }\n\n bool TryGet(T&amp; output)\n {\n std::lock_guard&lt;std::mutex&gt; lck (mtx);\n if (curReadNum == curWriteNum)\n {\n return false;\n }\n output = storage[curReadNum++ &amp; MASK];\n return true;\n }\n\n void Store(const T&amp; newValue) {\n std::lock_guard&lt;std::mutex&gt; lck (mtx);\n if (((curWriteNum+1) &amp; MASK) == (curReadNum &amp; MASK))\n {\n std::cout &lt;&lt;\n \"ArrayPool curWriteNum - curReadNum &gt; length! \" &lt;&lt;\n curWriteNum &lt;&lt; \" - \" &lt;&lt; curReadNum &lt;&lt; \" &gt; \" &lt;&lt; length &lt;&lt; std::endl;\n throw std::exception();\n }\n storage[curWriteNum++ &amp; MASK] = newValue;\n }\n\nprivate:\n static const uint32_t length = 1 &lt;&lt; 4;\n static const uint32_t MASK = length - 1;\n T storage[length];\n uint32_t curWriteNum;\n uint32_t curReadNum;\n std::mutex mtx;\n};\n</code></pre>\n\n<p>Modify your client functions to call it like this:</p>\n\n<pre><code>void ReadThread() {\n myStruct entry;\n while(true) {\n if (pool.TryGet(entry)) {\n std::cout &lt;&lt; entry.value &lt;&lt; std::endl;\n }\n }\n}\n\nvoid WriteThread(int id) {\n std::chrono::milliseconds dura(1000 * id);\n std::this_thread::sleep_for(dura);\n\n myStruct storage;\n storage.value = id;\n pool.Store(storage);\n std::cout &lt;&lt; \"Commited value! \" &lt;&lt; id &lt;&lt; std::endl;\n}\n</code></pre>\n\n<blockquote>\n <p>My primary requirement is latency. That's why I don't want to use lock, only memory barrier if absolutely required. And you don't ansered main question - if reader is guaranteed to see latest value. Should I insert memory barrier somewhere or something?</p>\n</blockquote>\n\n<p>When I write code my primary requirement is always 'correctness' first. Usually the cost of a lock is:</p>\n\n<ul>\n<li>Trivial (unnoticeable) compared to whatever other processing the program is doing (for example, in your program, writing to <code>std::out</code>).</li>\n<li>Worth it for thread-safety.</li>\n</ul>\n\n<h1>Your buffer overrun detection is broken</h1>\n\n<p><em>I marked the following with <code>&lt;strike&gt;</code> because it is not relevent if you are not trying to detect a buffer overrun.</em></p>\n\n<p><strike>\nThis statement won't work after you store 2^32 items:</p>\n\n<pre><code>if (curWriteNum - curReadNum &gt; length) { ... }\n</code></pre>\n\n<p>Instead use something like this, <strong>before</strong> you write to storage and increment curWriteNum:</p>\n\n<pre><code>if (((curWriteNum+1) &amp; MASK) == (curReadNum &amp; MASK))\n{\n std::cout &lt;&lt;\n \"ArrayPool curWriteNum - curReadNum &gt; length! \" &lt;&lt;\n curWriteNum &lt;&lt; \" - \" &lt;&lt; curReadNum &lt;&lt; \" &gt; \" &lt;&lt; length &lt;&lt; std::endl;\n throw std::exception(); // or, return false;\n}\n</code></pre>\n\n<p>The following is very unsafe, because you return a pointer to memory which (because you've incremented ++curReadNum) you now think it is already safe to overwrite:</p>\n\n<pre><code>T* TryGet()\n{\n if (curReadNum == curWriteNum)\n {\n return NULL;\n }\n T* result = &amp;storage[curReadNum &amp; MASK];\n ++curReadNum;\n return result;\n}\n</code></pre>\n\n<p>Try something like this instead:</p>\n\n<pre><code>bool TryGet(T&amp; output)\n{\n if (curReadNum == curWriteNum)\n {\n return false;\n }\n output = storage[curReadNum++ &amp; MASK];\n return true;\n}\n</code></pre>\n\n<p></strike></p>\n\n<blockquote>\n <p>I not always have object which I can copy so I have to use Obtain.</p>\n</blockquote>\n\n<p>In that case you can modify TryGet to return a pointer<strike>, however in that case you should delay incrementing curReadNum until after you have finished using the pointer:</p>\n\n<pre><code> T* TryPeek()\n {\n std::lock_guard&lt;std::mutex&gt; lck (mtx);\n if (curReadNum == curWriteNum)\n {\n return NULL; // or 'return 0;'\n }\n return &amp;storage[curReadNum &amp; MASK];\n }\n\n // Call this after TryPeek() to discard most recently peeked\n void Pop()\n {\n std::lock_guard&lt;std::mutex&gt; lck (mtx);\n ++curReadNum;\n }\n</code></pre>\n\n<p>Which you can call like this:</p>\n\n<pre><code>void ReadThread() {\n myStruct* entry;\n while(true) {\n if (entry = pool.TryPeek()) {\n // Use the entry\n std::cout &lt;&lt; entry-&gt;value &lt;&lt; std::endl;\n // Discard the entry after finished using it\n pool.Pop();\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Thanks, I think no need to declare CurReadNum as volatile - buffer is never \"overflow\" so CurReadNum is actually read from one thread only.</p>\n</blockquote>\n\n<p>That's true if (only if) you don't care about detecting buffer overruns.</p>\n\n<blockquote>\n <p>So declaring CurReadNum as volatile is absolutely useless ...</p>\n</blockquote>\n\n<p>If you have code to detect buffer overruns (and you did write some such code in your OP) then it's not \"absolutely useless\": it may be <code>required</code>, to make that code work correctly. A problem with multi-threaded code is that testing cannot prove that it's correct: testing can only prove that it's incorrect. Correctness needs to built-in, by design and code inspection.</p>\n\n<blockquote>\n <p>... but will likely add some latency.</p>\n</blockquote>\n\n<p>I doubt whether you can devise a performance test which, in practice, can detect any difference in latency.\n</strike></p>\n\n<h1>Attempting a lock-free implementation</h1>\n\n<blockquote>\n <p>And main question still not answered - if declaring curWriteNum as volatile is enough on modern Intel Xeon processor? I'm using 2 phisical processors server BTW. Is volatile enough and mandatory? Or memory barrier must/can be better?</p>\n</blockquote>\n\n<p>If it were my code and I wanted it to be thread-safe, then I would use some kind of lock.</p>\n\n<blockquote>\n <p>I surely don't want to use lock as they are extremmely slow.</p>\n</blockquote>\n\n<p>I think it's sufficient to put a memory fence at the start and end of every method, to emulate the memory fences which are implied by the lock_guard statements.</p>\n\n<blockquote>\n <p>of course I can \"guard\" every method, but I want to find certain places where memory barrier is REQUIRED but not more? I do not want to use more barriers than required.</p>\n</blockquote>\n\n<p>I think the worry is that a compiler and CPU are allowed to reorder statements, and could theoretically write an incremented value to <code>curWriteNum</code> before writing to <code>storage</code>.</p>\n\n<p>If you remove the unwanted overrun-detection code from my <code>Store</code> method then, as you say, the only memory that's used by both threads are <code>curWriteNum</code> and <code>storage</code>; so:</p>\n\n<pre><code>#pragma once\n\n#include &lt;stdint.h&gt;\n#include &lt;iostream&gt;\n\ntemplate&lt;class T&gt; class ArrayPool\n{\npublic:\n bool IsEmpty() {\n // 'data dependency' memory barrier here\n // or not because we don't mind if this return 'false positive' because we'll check again later\n return curReadNum == curWriteNum;\n }\n\n bool TryGet(T&amp; output)\n {\n if (IsEmpty())\n {\n return false;\n }\n output = storage[curReadNum++ &amp; MASK];\n return true;\n }\n\n T* TryPeek() // Unlike TryGet this leaves the element in Storage\n {\n if (IsEmpty())\n {\n return 0;\n }\n return &amp;storage[curReadNum];\n }\n\n void Pop() // Call this after a successful TryPeek\n {\n ++curReadNum;\n }\n\n void Store(const T&amp; newValue) {\n storage[curWriteNum &amp; MASK] = newValue;\n // Ensure storage is written before mask is incremented\n _MemoryBarrier();\n ++curWriteNum;\n }\n\nprivate:\n static const uint32_t length = 1 &lt;&lt; 4;\n static const uint32_t MASK = length - 1;\n T storage[length];\n volatile uint32_t curWriteNum;\n uint32_t curReadNum;\n};\n</code></pre>\n\n<p>The reason why I also declared curWriteNum as volatile is that, for some compilers, volatile is is a hint that the variable should not be enregistered.</p>\n\n<p>For example, without volatile, a test like <code>while (curReadNum == curWriteNum)</code> might be translated to:</p>\n\n<pre><code>mov eax,[curReadNum] ; move memory value to a CPU register\nmov ebx,[curWriteNum] ; move other memory value to a different CPU register\nlabel_loop_top:\ncmp eax,ebc ; compare the two values-in-registers\nje label_loop_top ; loop while the in-register values are equal\n</code></pre>\n\n<p>This code (caused by not declaring that curWriteNum is volatile) will never detect a subsequent write to curWriteNum.</p>\n\n<p>With volatile, the same compiler might translate <code>while (curReadNum == curWriteNum)</code> to:</p>\n\n<pre><code>mov eax,[curReadNum] ; move memory value to a CPU register\nlabel_loop_top:\ncmp eax,[curWriteNum] ; compare with the in-memory value\nje label_loop_top ; loop while it matches the in-memory value\n</code></pre>\n\n<p>This code (caused by declaring that curWriteNum is volatile) should eventually detect a subsequent write to curWriteNum.</p>\n\n<p>If you don't trust that <code>volatile</code> is sufficient to do this job, then theoretically you should have a memory barrier in the IsEmpty function above (to ensure that it will read <code>curWriteNum</code> from memory and not from a register), as well as having one in Store (to ensure that <code>storage</code> is written before <code>curWriteNum</code>).</p>\n\n<p>If you don't have this second memory barrier then <em>theoretically</em> a compiler or machine (perhaps a smarter one than the one you're using now) will read <code>curWriteNum</code> from memory on its first loop through IsEmpty(), notice that your ReadThread() code never modifies <code>curWriteNum</code>, and therefore assume it can thereafter reuse its old, cached, enregistered value of <code>curWriteNum</code> instead of reading it from memory again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T06:26:25.097", "Id": "65473", "Score": "0", "body": "i not always have object which I can copy so I have to use `Obtain`. I can add method `Put(T*)` in addition. Copy-construct will be slower than memcpy, isn't it? My primary requirement is latency. That's why I don't want to use `lock`, only memory barrier if absolutely required. And you don't ansered main question - if reader is guaranteed to see latest value. Should I insert memory barrier somewhere or something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T10:56:09.893", "Id": "65491", "Score": "0", "body": "I edited my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T11:52:55.413", "Id": "65493", "Score": "0", "body": "Thanks, I think no need to declare CurReadNum as volatile - buffer is never \"overflow\" so CurReadNum is actually read from one thread only. So declaring `CurReadNum` as `volatile` is absolutely useless but will likely add some latency. I guess nothing can be faster than `memcpy` so I prefer to keep using it even loosing readability. And main question still not answered - if declaring `curWriteNum` as `volatile` is enough on modern Intel Xeon processor? I'm using 2 phisical processors server BTW. Is `volatile` enough and mandatory? Or memory barrier must/can be better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T13:38:57.630", "Id": "65501", "Score": "0", "body": "@javapowered And edited again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T13:46:38.183", "Id": "65502", "Score": "0", "body": "thanks. `compiler-generated assignment is probably faster than memcpy` - how is that possible?. I surely don't want to use `lock` as they are extremmely slow. Let's wait probably someone can suggest how to modify code to be lock-free and valid. I need as much synchronization as required, but not more. `lock` would be overkill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T13:54:09.237", "Id": "65503", "Score": "0", "body": "@javapowered For example, your myStruct contains one integer. So to assign one myStruct to another, the compiler only needs to assign one integer to another: using memcpy for that purpose is overkill. Also the compiler already knows `sizeof(T)` so it may be a waste of time for your code to load `sizeof(T)` as a memcpy parameter. IMO, at best the compiler might recognize memcpy as an 'intrinsic' function, and inline it, so that memcpy becomes as fast as the compiler assignment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T15:45:43.940", "Id": "65521", "Score": "0", "body": "thanks, agree about using default copy-constructor! Now the only question I have is - where and what syncrhonization must be added for the best latency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T16:01:24.500", "Id": "65524", "Score": "0", "body": "or! not sure \"The default copy constructor for a C++ type works by invoking the copy constructor on each field in the instance with the corresponding field in the object the copy is being created from\". So I'm afraid it might be slower than just once memcpy call!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T17:29:18.477", "Id": "65539", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12469/discussion-between-chrisw-and-javapowered)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:42:54.963", "Id": "65925", "Score": "0", "body": "`volatile` is not useful for thread safety (see e.g. http://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming). `volatile` is to be used for memory-mapped hardware I/O, not to improve thread safety." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:52:20.870", "Id": "65928", "Score": "0", "body": "@ruds That depends on the compiler and version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T16:54:39.670", "Id": "65941", "Score": "0", "body": "@ChrisW OK, let me put it another way. In standard C++, \"operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading\" (http://en.wikipedia.org/wiki/Volatile_variable). This is also true of standard C, and apparently of POSIX and Win32." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T17:00:08.773", "Id": "65944", "Score": "0", "body": "@ruds In some compilers, volatile is (or at least was) necessary to prevent the variable from being enregistered. I.e. 'while (foo==0)` might be translated to `mov eax,[foo];label: cmp eax,0; je label;` without the volatile switch (which never detects a subsequent write to foo), and `label: cmp [foo],0; je label;` with the volatile switch; without volatile the compiler might not expect another thread to change the memory at all. I'm not saying that volatile is sufficient: only that it may be necessary or desirable (with some compilers)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T19:53:05.640", "Id": "65985", "Score": "0", "body": "@javapowered How do you know that locking is too slow? Is this data structure a bottleneck in your program or are you just guessing? Locking and unlocking a mutex only takes about as long as a (uncached) main memory reference (aka ~100ns)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T00:39:27.133", "Id": "66022", "Score": "0", "body": "@ruds of course locking is too slow. yes this is intensively used structure and I have only several microseconds to do everything in my HFT application" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:36:07.353", "Id": "66030", "Score": "0", "body": "@javapowered Did you profile your code? Did you try a structure using locks and find that it was not fast enough? Don't roll your own lock-free queue and expect to get it right; this is very complicated code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:56:28.573", "Id": "66032", "Score": "0", "body": "@ruds when you write low latency code you don't need to profile to know that `lock` are expensive. I have NO `lock` in my entire application except several \"non-critical\" cases. Why do you suggest to use `lock` in place where they NOT mandatory? Definitely this can be implemented easily without lock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T06:13:31.637", "Id": "66050", "Score": "0", "body": "+200 for the effort, but it seems i really can just use boost spsc_queue" } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:33:13.593", "Id": "39114", "ParentId": "38815", "Score": "9" } }, { "body": "<p>just as an example of possible race conditions consider the function:</p>\n\n<pre><code>void WriteThread(int id) {\n std::chrono::milliseconds dura(1000 * id);\n std::this_thread::sleep_for(dura);\n\n myStruct* storage = pool.Obtain();\n storage-&gt;value = id;\n pool.Commit();\n std::cout &lt;&lt; \"Commited value! \" &lt;&lt; id &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>then inline all called functions (which the compiler is allowed to do) (note this is pseudo code roughly representing what could happen).</p>\n\n<pre><code>void WriteThread(int id) {\n std::chrono::milliseconds dura(1000 * id);\n std::this_thread::sleep_for(dura);\n\n myStruct* storage = pool.storage[pool.curWriteNum &amp; MASK];\n storage-&gt;value = id;\n ++pool.curWriteNum; //ignoring the if and output because it is not relevant for this evample\n std::cout &lt;&lt; \"Commited value! \" &lt;&lt; id &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>now remember that volatile is not a fence but only stops the compiler from reordering with regard to other volatiles. The compiler is also allowed to store variables in temperaries whenever needed (as long as the \"as if\" rule stands for a single threadded program). So this reordering is leagal:</p>\n\n<pre><code>void WriteThread(int id) {\n std::chrono::milliseconds dura(1000 * id);\n std::this_thread::sleep_for(dura);\n\n auto temp = pool.curWriteNum &amp; MASK;\n ++pool.curWriteNum; \n //starting here the other thread can start reading causing a race condition\n myStruct* storage = pool.storage[temp];\n storage-&gt;value = id;\n std::cout &lt;&lt; \"Commited value! \" &lt;&lt; id &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>It should also be noted that volatile does not stop load and store reordering on hardware that supports this so even if the optimizer doesn't shoot you in the foot the hardware still may. It is also important to understand that what reordering happens where is very hard to predict so it is best to expect the worst. It may not be reordered the first time you look at the assembler but then you change something somewhere months later, maybe even in a completely different header which does not even use and you can't imagine the optimizer will change its behavior but it does and its allowed to and your code breaks, not on your machine but on your most important customers. Honestly you can't tell me with a straight face that you want to inspect every single spot these functions get inlined with -O3 optimization in assembler every time you recompile your project.</p>\n\n<p>I would suggest using c++11 std::atomic variables for curWriteNum and curReadNum. This would at least solve the stated race condition. </p>\n\n<p>It is also not a good idea to not handle an overflow. No matter how fast the consumer thread is it is next to impossible to prove that it will never have to wait for a lock for too long. As soon as it allocates memory (through new or otherwise) or even uses a function which could throw an exception derived from std::exception (which almost all exceptions are) then there is chance chance it will wait for the heap lock which literally take minutes in a worst case scenario where RAM has been swapped to an old, slow HD. Bottom line is that it probably will never happen on your machine but it probably will to some of your customers and they will then likely not remain your customers after that. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T14:28:53.847", "Id": "65907", "Score": "0", "body": "+1 That's an example why it's better (i.e. \"more correct\" even if not \"proven necessary via testing\") to have a fence after writing to `storage` and before incrementing `curWriteNum`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:05:28.803", "Id": "65918", "Score": "0", "body": "If this may happen then it would be very interesting to reproduce it. I believe you, but if this issue is so hard to reproduce probably it just will never happen? Also it would be nice to see \"proposed fix\". Should I have memory barrier AND volatile variable or it's enough to have just volatile variable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:13:15.023", "Id": "65919", "Score": "0", "body": "also MSDN states that C# \"MemoryBarrier is required only on multiprocessor systems with weak memory ordering (for example, a system employing multiple Intel Itanium processors).\". So if C# MemoryBarrier and C++ MemoryBarrier are similar, then C++ MemoryBarrier is useless on Intel Xeon?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T17:05:21.593", "Id": "65946", "Score": "0", "body": "@javapowered to be honest my memory barrier experience with production code comes from embedded ARM hardware so I'm not so sure about Intel. I would strongly suggest never ever using code in production which theoretically has a bug but is hard to reproduce in practice, it will bite you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T17:38:55.817", "Id": "65953", "Score": "0", "body": "The one time you could 'prove' there will be no overrun is when the system/protocol is throttled somehow, e.g. if the producer never creates more than 'n' unprocessed/outstanding requests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T19:04:13.793", "Id": "65973", "Score": "0", "body": "yes but if you have that then why not just build it into the quque ?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T14:19:48.193", "Id": "39387", "ParentId": "38815", "Score": "6" } }, { "body": "<p>As a general rule, if you don't have a strong grasp of the content in [intro.multithread] of the C++ standard, it's a bad idea to write or maintain lock-free code. In nearly all cases, the costs due to more difficult maintenance, data corruption, etc of lock-free code will exceed the small additional CPU cost of just using locks.</p>\n\n<hr>\n\n<p>Thus, my preferred implementation is this:</p>\n\n<pre><code>template &lt;typename T&gt; class ArrayPool {\n public:\n ArrayPool() = default;\n bool IsEmpty() const {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n return IsEmptyLocked();\n }\n T* TryGet() {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n if (IsEmptyLocked()) return nullptr;\n return GetLocked();\n }\n // Waits until this ArrayPool contains entries, then\n // returns an entry.\n T* WaitAndGet() {\n std::unique_lock&lt;std::mutex&gt; lock(mu);\n nonempty.wait(lock, std::bind(&amp;ArrayPool::IsNonEmpty, this));\n return GetLocked();\n }\n T* Obtain() {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n return ObtainLocked();\n }\n void Commit() {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n ++curWriteNum;\n }\n void ObtainAndCommit(T&amp;&amp; t) {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n *ObtainLocked() = std::move(t);\n ++curWriteNum;\n }\n void ObtainAndCommit(const T&amp; t) {\n std::lock_guard&lt;std::mutex&gt; lock(mu);\n // Using the copy constructor is always correct, and for PODs\n // should be just as fast as memcpy.\n *ObtainLocked() = t;\n ++curWriteNum;\n }\n\n private:\n // Precondition: mu is held\n bool IsEmptyLocked() const {\n return (curWriteNum &amp; MASK) == (curReadNum &amp; MASK);\n }\n // Preconditions: mu is held, !IsEmptyLocked()\n T* GetLocked() {\n return &amp;storage[curReadNum++ &amp; MASK];\n }\n // Precondition: mu is held\n T* ObtainLocked() {\n // optional but recommended error checking\n if (((curWriteNum + 1) &amp; MASK) == (curReadNum &amp; MASK)) {\n // The producer has outrun the consumer\n throw std::runtime_error(\"Queue full\");\n }\n return &amp;storage[curWriteNum &amp; MASK];\n }\n\n static const std::size_t length = 1ul &lt;&lt; 16;\n static const std::size_t MASK = length - 1;\n\n T storage[length];\n\n mutable std::mutex mu;\n // All members declared below are mu-guarded.\n std::condition_variable nonempty;\n std::size_t curReadNum;\n std::size_t curWriteNum;\n};\n</code></pre>\n\n<p>Note <code>WaitAndGet</code>; you should modify <code>ReadThread</code> to call that and avoid busy-waiting:</p>\n\n<pre><code>void ReadThread() {\n while (true) {\n auto* entry = pool.WaitAndGet();\n std::cout &lt;&lt; entry-&gt;value() &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>It appears that you'll be unable to do better than locking in this situation. You need to be sure of two things:</p>\n\n<ol>\n<li>Modifications to <code>curReadNum</code> and <code>curWriteNum</code> are immediately visible to the reader and writer thread (both threads observe both variables).</li>\n<li>Modifications to <code>storage[i]</code> made by the writer thread are visible to the reader thread before reading.</li>\n</ol>\n\n<p>Because writes to <code>curWriteNum</code> don't depend on <code>storage[i]</code>, this requires release-acquire semantics (for example, see the discussion of happens-before at <a href=\"http://en.cppreference.com/w/cpp/atomic/memory_order\" rel=\"nofollow\">http://en.cppreference.com/w/cpp/atomic/memory_order</a>). That is essentially what <code>mutex</code>'s lock/unlock give you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T00:41:57.360", "Id": "66025", "Score": "0", "body": "`locking` is very expensive. so far it seems this code works withoug locking (i'm using it). is it so diffucult to make it lock-free? I have just one thread that write (and never read) and one thread that read (and never write). This is simple thing!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:28:04.640", "Id": "66029", "Score": "0", "body": "You're spending money with the output of this thing and you're cool with opening yourself up to memory corruption due to data races? If you're only using one reader and one writer, why not just use one thread for the whole process?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T20:34:30.130", "Id": "39414", "ParentId": "38815", "Score": "1" } }, { "body": "<p><a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/boost/lockfree/spsc_queue.html\" rel=\"nofollow noreferrer\">The Boost Single-Producer Single-Consumer Queue</a> should meet your needs. If you're trying to use this for production code and you don't understand why your completely unsynchronized code is a bad idea, don't try to roll your own based on advice from well-meaning passersby.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:58:33.860", "Id": "66033", "Score": "1", "body": "spsc_queue doesn't allow to reuse elements. I believe my implementation is VERY simple so at least for education it would be interesting to make it CORRECT." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T02:01:14.420", "Id": "66034", "Score": "0", "body": "i will check `spsc_queue` but i'm afraid it's a little bit slow too. it's using `copy-constructor` which must be slower than just one call to `memcpy`. But probably i can live with this. Another problem is that it doesn't allow to \"reconfigure\" elements. I like my `Obtain` `Commit` semantic because it allows me to put element even if I don't have anything to put." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T02:07:31.020", "Id": "66035", "Score": "0", "body": "also probably I can learn http://www.boost.org/doc/libs/1_53_0/boost/lockfree/spsc_queue.hpp and copy \"synchronization\" code from `spsc_queue` to my `queue`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T02:11:34.757", "Id": "66036", "Score": "0", "body": "also I don't like how `next_index` is implemented. I think it must be faster to apply \"&\" than `while (unlikely(ret >= max_size)) ret -= max_size;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T02:18:16.530", "Id": "66037", "Score": "0", "body": "but in terms of synchronization I like `spsc_queue`, thanks, probably will use it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T02:43:11.743", "Id": "66039", "Score": "1", "body": "Almost certainly `next_index` as implemented is better. The `unlikely` macro is used to give a hint to the branch prediction circuits in the processor (http://stackoverflow.com/questions/109710/likely-unlikely-macros-in-the-linux-kernel). So you get one missed branch prediction every (in this case) 65k pushes/pops, and in return you're saving at least two instructions (and possibly a memory load for MASK) on every push/pop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T08:18:39.300", "Id": "66062", "Score": "1", "body": "copy constructor turns into a call to memcpy if the class is a pod type on most optimizers unless there is a faster way (which is the case with small classes)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:41:40.437", "Id": "39436", "ParentId": "38815", "Score": "4" } } ]
{ "AcceptedAnswerId": "39436", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:15:24.953", "Id": "38815", "Score": "13", "Tags": [ "c++", "multithreading", "circular-list" ], "Title": "One reader / one writer no-memory-allocation lock-free ring-buffer" }
38815
<p>Is it possible to create dynamic TR and TD elements in an HTML table? Something similar but better than this:</p> <pre><code>jQuery(document).ready(function() { $('button[name="new-title"]').on('click', function(){ var table = $('table[name="errortitle"]'); var tr = $('&lt;tr /&gt;'); var td = $('&lt;td /&gt;'); var input = $('&lt;input /&gt;').attr({'class' : 'form-control'}) var button = $('&lt;button /&gt;').attr({'class' : 'btn'}); var checkbox = input.clone().attr({'type' : 'checkbox', 'name' : 'check'}); var tdId = td.clone().html('-'); var tdTitle = td.clone().append(input.addClass('formInput').attr({'type': 'text'})); var tdCheckBox = td.clone().append(checkbox); var tdAction = td.clone().html(button.addClass('btn-danger').html('Usuń')); tr.append(tdCheckBox); tr.append(tdId); tr.append(tdTitle); tr.append(tdAction); table.append(tr); }); }); </code></pre> <p>Is it possible to make this code nicer or more efficient?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:34:47.357", "Id": "65128", "Score": "0", "body": "An alternative way should be AngularJS. You can define a default HTML and ride a repeater into this code. For more information: [AngularJS:ngRepeat](http://docs.angularjs.org/api/ng.directive:ngRepeat)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T19:47:18.720", "Id": "391987", "Score": "0", "body": "You can use `insertRow` and `insertCell`; very easy for `tr` and `td`." } ]
[ { "body": "<p>You could create a function that will add a row to the table based on the number of elements of data you pass to it (which will become columns):</p>\n\n<pre><code>function newRow($table,cols){\n $row = $('&lt;tr/&gt;');\n for(i=0; i&lt;cols.length; i++){\n $col = $('&lt;td/&gt;').append(cols[i]);\n $row.append($col);\n }\n $table.append($row);\n}\n</code></pre>\n\n<p>You can then call this function for every new row you want to make. <code>$table</code> expects a jQuery object, <code>cols</code> expects an array of elements (DOM or jQuery) to append to the row. I've also tidied up the jQuery that creates your elements. Did you know you can use the second parameter in the jQuery function to set element properties?:</p>\n\n<pre><code>jQuery(document).ready(function() {\n $('button[name=\"new-title\"]').on('click', function(){\n var table = $('table[name=\"errortitle\"]');\n\n var tdId = '-';\n var tdTitle = $('&lt;input /&gt;', {'class' : 'form-control formInput', 'type': 'text'});\n var tdCheckBox = $('&lt;input /&gt;', {'class' : 'form-control', 'type' : 'checkbox', 'name' : 'check'});\n var tdAction = $('&lt;button /&gt;', {'class' : 'btn btn-danger', html:'Usuń'});\n\n newRow(table,[tdCheckBox,tdId,tdTitle,tdAction]);\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/oGeez/bgfUR/\" rel=\"nofollow\"><kbd>JSFiddle</kbd></a></p>\n\n<p>Try it with any amount of column data:</p>\n\n<pre><code>newRow(table,[tdCheckBox,tdId,tdTitle,tdAction,'another col','and another','a final col']);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/oGeez/bgfUR/1/\" rel=\"nofollow\"><kbd>JSFiddle</kbd></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T09:38:35.923", "Id": "38818", "ParentId": "38816", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T08:28:50.897", "Id": "38816", "Score": "7", "Tags": [ "javascript", "jquery", "html" ], "Title": "jQuery dynamic elements like TR and TD, add to HTML table" }
38816
<p>I am getting data from JSON and then create rows of it:</p> <pre><code> $.each(data.GetwebMethodResult, function (index, item) { $("#TableABC").append(FunABC(item.aID, item.b, item.c, item.d, item.e, item.f)); }); function FunABC(a, b, c, d, e, f) { var row = "&lt;tr class='Row' onclick=\"AnotherUnrelatedFunction('" + a + "' , '" + b + "', '" + c + "', '" + d + "', '" + e + "', '" + f + "')\"&gt;" + " &lt;div class='mr'&gt;" + " &lt;td class='mc mci'&gt;" + " &lt;div class='mcit'&gt;" + a + "&lt;/div&gt;" + " &lt;/td&gt;" + " &lt;/div&gt;" + "&lt;/tr&gt;"; return row; } </code></pre> <p>Is there any better way of doing it?</p>
[]
[ { "body": "<p>Not really. It hard to optimize something with little logic. You could do this instead:</p>\n\n<pre><code>var row =\n \"&lt;tr class='Row' onclick=\\\"AnotherUnrelatedFunction('\" + a + \"' , '\" + b + \"', '\" + c + \"', '\" + d + \"', '\" + e + \"', '\" + f + \"')\\&gt; \\\n &lt;div class='mr'&gt; \\\n &lt;td class='mc mci'&gt; \\\n &lt;div class='mcit'&gt;\" + a + \"&lt;/div&gt; \\\n &lt;/td&gt; \\\n &lt;/div&gt; \\\n &lt;/tr&gt;\";\n</code></pre>\n\n<p>But aside from that looks good!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:59:37.743", "Id": "64873", "Score": "0", "body": "http://stackoverflow.com/questions/227552/common-sources-of-unterminated-string-literal just add the continuation character as I did sorry that was an over sight on my part" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:08:26.670", "Id": "64875", "Score": "0", "body": "also that TR should all be on the same line. I cant get it to work in that code block" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:04:08.480", "Id": "38823", "ParentId": "38822", "Score": "3" } }, { "body": "<p>I would think so;</p>\n\n<ul>\n<li>encoding listeners through HTML <code>onclick</code> is old skool</li>\n<li>variable names a,b,c,d,e,f earn an award for 2014 worst variable names</li>\n<li>instead of sending just the <code>item</code>, you are sending every property you need.</li>\n<li>you are setting content and listeners in one place ( mixing view and controller )</li>\n<li>You have a div between tr and td, which should not even work</li>\n</ul>\n\n<p>I would counter-propose something like</p>\n\n<pre><code>$.each(data.GetwebMethodResult, function (index, item)\n{\n $(\"#TableABC\").append( $(generateRow(a)).click( function(){ \n anotherUnrelatedFunction( item );\n }));\n});\n\nfunction generateRow(a) \n{\n return '&lt;tr class=\"Row mr\"&gt;' + \n '&lt;td class=\"mc mci\"&gt;' + \n '&lt;div class=\"mcit\"&gt;' +\n a + \n '&lt;/div&gt;' +\n '&lt;/td&gt;' + \n '&lt;/tr&gt;';\n}\n</code></pre>\n\n<p>This basically keeps the HTML stringing separate from the onClick handler assignment. Through closure it passes the entire item object to <code>anotherUnrelatedFunction</code> which means the signature becomes more concise (you would have to adjust <code>anotherUnrelatedFunction</code> obviously).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:23:33.843", "Id": "64878", "Score": "0", "body": "this will only work if the item stops at f and not z" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:32:35.460", "Id": "64879", "Score": "0", "body": "I do not understand your comment, what do you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:10:38.260", "Id": "64881", "Score": "0", "body": "since he chose it as answer it much not be the case. But if there were more entires in item you would not be able to pull the whole thing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:34:42.827", "Id": "64893", "Score": "0", "body": "@SaggingRufus I either still misunderstand or you are mistaken. `item` could have hundreds of properties and this would still work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:53:04.273", "Id": "64895", "Score": "0", "body": "yes but if not all of them were supposed to be transfer. For example: if item contain a-z but only a-f were required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:16:36.250", "Id": "64908", "Score": "0", "body": "That does not matter much, since you only transfer a pointer to an object. That is, if you trust the called function." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:13:24.027", "Id": "38828", "ParentId": "38822", "Score": "1" } }, { "body": "<p>Since you didn't specifically state you didn't want to use a third party library, I am going to recommend you look at underscore and it's template function. There are other template engines (mustache.js also comes to mind). These excel at doing exactly what you are trying to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:59:19.813", "Id": "38834", "ParentId": "38822", "Score": "0" } } ]
{ "AcceptedAnswerId": "38828", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T12:47:53.897", "Id": "38822", "Score": "3", "Tags": [ "javascript", "json" ], "Title": "Creating rows from JSON data" }
38822
<p>I have a class foo that needs to get input from different sources, namely input streams, arrays and iterators. The code that actually does the work in the end takes iterators as input, and all the other methods end up calling it behind the scenes:</p> <pre><code>void from_stream(std::istream&amp; in); // Read from stream and insert at end void from_stream(std::istream&amp; in, iterator it); // Read from stream and insert at it template&lt;typename T&gt; void from_buffer(T* buffer, size_t len); // Read from a buffer and insert at end template&lt;typename T&gt; void from_buffer(T* buffer, size_t len, iterator it); // Read from a buffer and insert at it // The work is done here template&lt;typename InputIterator&gt; void decode(InputIterator first, InputIterator last); // Decode range and insert at end template&lt;typename InputIterator&gt; void decode(InputIterator first, InputIterator last, iterator it); // Decode range and insert at it </code></pre> <p>I want users to be able to make calls like these (assume foo class is initially empty):</p> <pre><code>Foo foo; foo.from_stream(my_stream, foo.begin()); // or without foo.begin() foo.from_buffer(my_buffer, buflen, foo.begin() + 4); // same... </code></pre> <p>and internally the code will call specialized std::inserter, std::front_inserter or std::back_inserter functions as appropriate and pass them to foo::decode. I could just use std::inserter all the time, but I would think it is more efficient to use std::back_inserter when foo.end() is passed and so on.</p> <p>I could change the iterator argument to a template parameter and let the user decide what kind of iterator to use similar to the STL (which is actually what I am trying to aim for). This would also allow the user to pass a foo::iterator and overwrite content instead of inserting data. This would change the calls above to:</p> <pre><code>foo.from_stream(my_stream, std::back_inserter(foo)); foo.from_buffer(my_buffer, buflen, std::inserter(foo, foo.begin() + 4)); </code></pre> <p>I could use some design advice about what approach, or another one entirely, is "best".</p>
[]
[ { "body": "<p>Why not just <code>insert()</code> and <code>iterator</code> like most containers in the STL.</p>\n\n<pre><code> std::vector&lt;int&gt; data;\n std::ifstream file(\"Plop\");\n\n data.insert(data.end(), std::istream_iterator&lt;int&gt;(file),\n std::istream_iterator&lt;int&gt;());\n\n char buffer[] = \"1 2 3 4 5 6 6 7 8 9 10 11 12 13 14 15 16 17 18 19\";\n std::stringstream bufferStream(buffer);\n\n data.insert(data.end(), std::istream_iterator&lt;int&gt;(bufferStream), \n std::istream_iterator&lt;int&gt;());\n\n\n std::vector&lt;int&gt; anotherBuffer = LoadBuffer();\n data.insert(data.end(), std::begin(anotherBuffer), std::end(anotherBuffer));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:24:07.577", "Id": "65204", "Score": "0", "body": "I was too focused on my own interface to realize this. It is so much simpler and preferably STL-like, thanks! However, when passing data.end(), I would still need to create a std::back/front- or inserter to actually insert the data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T21:47:38.590", "Id": "38857", "ParentId": "38824", "Score": "3" } } ]
{ "AcceptedAnswerId": "38857", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:07:25.510", "Id": "38824", "Score": "3", "Tags": [ "c++" ], "Title": "Design for C++ class methods taking input from different sources" }
38824
<p>I'm wondering about the following code:</p> <pre><code>def ValidateGoto(placeToGo): conditions = {} conditions["not placeToGo"] = "Enter a positive integer in the text box" conditions[ "int(placeToGo) &lt;= 0"] = "I need a positive integer in the text box please" conditions[ "not DataStore.DBFILENAME"] = "There is no data available in the table" for condition, errormessage in conditions.iteritems(): try: if eval(condition): print errormessage return False except ValueError: return False return True </code></pre> <ol> <li><p>Should the <code>eval</code> statement be avoided? </p></li> <li><p>Is this approach justified to reduce the number of <code>if</code> statements?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:37:15.930", "Id": "64894", "Score": "1", "body": "This code does not work: the indentation is wrong and there is a missing double quote. Can you fix, please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:31:35.793", "Id": "65056", "Score": "1", "body": "Since I commented on it below, I figured I should point out the indentation of the first `return False` is still probably wrong. Inside the `try/except`, this code will always `return False`, or not catch the exception. It will never hit `return True` unless there had been no `conditions`." } ]
[ { "body": "<p>You have the right basic idea - pass a list of conditions - but the implementation is wrong.</p>\n\n<p>Yes, you should avoid <code>eval</code>; it is a dangerous source of potential error (and performs poorly as a non-bonus). You might put <em>anything</em> in there. You might not even notice a typo which caused nasty side effects, since Python has a very tolerant definition of truth and will be happy as long as the expression evaluates to <em>something</em>. Instead, why not pass a list of <a href=\"http://docs.python.org/3.3/reference/expressions.html#lambda\">lambda functions</a>? Then you just call each function in turn. Much safer.</p>\n\n<p>For example, you could build a list of tuples (condition, error message) like this:</p>\n\n<pre><code>conditions = [(lambda: not placeToGo, \"Enter a positive integer in the text box\"),\n(lambda: int(placeToGo) &lt;= 0, \"I need a positive integer in the text box please\"),\n(lambda: not DataStore.DBFILENAME, \"There is no data available in the table\")]\n</code></pre>\n\n<p>And then iterate through the list, calling each function in turn.</p>\n\n<p>If you are not familiar with functional programming (in Python or any other language), take a look at this <a href=\"https://thenewcircle.com/bookshelf/python_fundamentals_tutorial/functional_programming.html\">short tutorial</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:03:58.553", "Id": "64874", "Score": "0", "body": "Thank you very much :) The use of lambads makes it much better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:39:30.750", "Id": "64967", "Score": "0", "body": "Happy to be of help. The impulse behind your question was a good one :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:32:55.667", "Id": "38826", "ParentId": "38825", "Score": "7" } }, { "body": "<p>A safe eval aproach (not sure though if this helps but i would definitily recommend it if you must use it) is by using the <a href=\"https://docs.python.org/2/library/ast.html#ast.literal_eval\" rel=\"nofollow noreferrer\">ast module's literal eval</a></p>\n\n<pre><code>import ast\nast.literal_eval(data)\n</code></pre>\n\n<p>for more information you can take a look <a href=\"https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval\">here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:19:56.757", "Id": "38836", "ParentId": "38825", "Score": "0" } }, { "body": "<p>While I agree 100% that you should avoid <code>eval</code> for this, if all the cases come from within your code (i.e. not from user provided strings) it's more likely to be a performance problem than a security problem. If you do accept user-provided validations, <code>lambda</code>s aren't inherently safer.</p>\n\n<p>Finally, unless you're accumulating these in some fashion other than described, I think it's more readable to keep your logic together in the same function. Other approaches reduce the number of if statements, but not the number of executed if statements. As a trade-off you have more complex code. I'd suggest keeping it simple, perhaps introducing an exception so that everything can be a single line:</p>\n\n<pre><code>def ValidateGoto(placeGoto):\n if not placeGoto:\n raise ValidationError(\"Enter a positive integer in the text box\")\n if placeGoto &lt;= 0:\n raise ValidationError(\"I need a positive integer in the text box please\")\n if not DataStore.DBFILENAME:\n raise ValidationError(\"There is no data available in the table\")\n # optionally return placeGoto, or True, or whatever.\n</code></pre>\n\n<p>You'd use this with calling code like this:</p>\n\n<pre><code>try:\n ValidateGoto(goto)\nexcept ValidationError, err\n print err # then possibly return\nelse: # passed-validation case (can omit else if there's a return in the except)\n ...\n</code></pre>\n\n<p>If you are looking to make it easier to add named validations, you could take an approach similar to that used by unit tests. Choose a naming convention and write code that looks for the methods that follow that name. Here's a very simple skeleton to illustrate the idea:</p>\n\n<pre><code>class ValidateGoto:\n def __init__(self, placeGoto):\n for validation in dir(self):\n if validation.startswith(\"validate_\"):\n getattr(self)(placeGoto)\n\n def validate_provided(self, placeGoto):\n if not placeGoto:\n raise ValidationError(\"Enter a positive integer in the text box\")\n\n def validate_positive(self, placeGoto):\n if placeGoto &lt;= 0:\n raise ValidationError(\"I need a positive integer in the text box please\")\n\n def validate_table(self, placeGoto):\n if not DataStore.DBFILENAME:\n raise ValidationError(\"There is no data available in the table\")\n</code></pre>\n\n<p>This variant added a lot of complexity, yet it does allow you to use other tools (such as inheritance) to manage lists of validation functions. For the case as shown I would definitely <em>not</em> use this, but if your actual case has enough complexity to benefit from this, it could be a viable approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:04:11.633", "Id": "65008", "Score": "0", "body": "That is thumpingly plodding imperative code. A *list* of checks is being applied; treating them as a list is more accurate, flexible and extensible (you can have a list of named functions, there is no need for them to be lambdas). The checks in a list can be applied in any order, you can stop at the first error or do all the checks or filter the list. All of this is lost in your versions. In addition, you're duplicating the same logic again and again. The basic logic is \"make a check, report an error with a message if it fails\". You repeat that logic in each function..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:20:11.680", "Id": "65012", "Score": "1", "body": "... when it should only have to be written once. That's a particularly egregious sin in your last example, which adopts an OO style. Your OO example adds complexity to no benefit - why isn't it implementing the shared behaviour once, in a way that could be extended for all checks if desired? If you're going to do OO, make the error-reporting class implement the behaviour - once - and have the checks be a class that contains the salient properties (the check to be applied and the message to report). The OP's original code is actually better style than any of your examples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:28:43.830", "Id": "65053", "Score": "0", "body": "@itsbruce I think we'll have to disagree here. When the repeated code is `if` and `raise ValidationError`, I find the mechanics necessary to avoid repeating it are worse than the repetition. If the repeated raise is troublesome, the message could be stored, and raised if not empty (but that's more mental overhead, and not as flexible in terms of exception thrown). In short, I agree it's imperative. But the first way is also extremely easy to read, so it doesn't distract from the real work. *Did you notice the OP's version doesn't even check the second condition (as of rev 3's early return)?*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:23:28.540", "Id": "65222", "Score": "0", "body": "I think that the code provided above is plain and boring. I like the idea with the multiple functions in a list and going through them. Unfortunately, the answer above is simpler, that's why I am going for it. Its creativity against simplicity where I would always personally prefer creativity but I know that simplicity would be much more appreciated." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T01:57:49.040", "Id": "38869", "ParentId": "38825", "Score": "3" } } ]
{ "AcceptedAnswerId": "38869", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:09:50.790", "Id": "38825", "Score": "4", "Tags": [ "python", "python-2.x" ], "Title": "if statements or eval?" }
38825
<p>I created a JS widget library for distribution purpose on external websites and would like your thoughts on it.</p> <p><strong>What widget does:</strong> It adds an always visible text on the screen. When user clicks on text, an external page gets loaded in iFrame in a lightbox. Internally, widgets loads jQuery library and some external JS and CSS files.</p> <p><strong>What I need to be reviewed:</strong></p> <ol> <li>Check if prototype being used the right way and work across all browsers?</li> <li>If jQuery is correctly loaded and resolved correctly (even if the page hosting the script have same/different version of jQuery already running on the page)</li> <li>I used 'window.addEventListener' method to check if jQuery is loaded or not. Is it correct and the way ideally it should be?</li> <li>Is there any efficient way of loading the colorbox.js file</li> <li>Can the code be optimised further for improved performance?</li> <li>Is the code production ready?</li> </ol> <p><strong>HTML Code</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="http://yahoo.com"&gt;Anchor - by user code&lt;/a&gt; &lt;div style="height:1500px;"&gt;&lt;/div&gt; &lt;a href="http://yahoo.com"&gt;Another Anchor - by user code&lt;/a&gt; &lt;!-- Widget Script: Starts --&gt; &lt;script type="text/javascript" src="widget.js" &gt;&lt;/script&gt; &lt;Script type="text/javascript"&gt; var customWidget = new MyWidget(); customWidget.Render({ anchorText:'wikipedia', link: 'http://www.wikipedia.com/' }); &lt;/script&gt; &lt;!-- Widget Script: Ends --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>JS Code - widget.js</strong></p> <pre><code>var MyWidget = function () { // Loading CSS in Async var fileref = document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", 'widget.css'); document.getElementsByTagName("head")[0].appendChild(fileref); fileref = document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", 'http://www.jacklmoore.com/colorbox/example4/colorbox.css'); document.getElementsByTagName("head")[0].appendChild(fileref); // Localize jQuery variable var jQuery; // Load jQuery if not present if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.10.2') { var script_tag = document.createElement('script'); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"); if (script_tag.readyState) { script_tag.onreadystatechange = function () { // For old versions of IE if (this.readyState == 'complete' || this.readyState == 'loaded') { this.ResolveJqueryAndLoadAdditionalJsAndCss(); } }; } else { script_tag.onload = this.ResolveJqueryAndLoadAdditionalJsAndCss; } // Try to find the head, otherwise default to the documentElement (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); } else { // The jQuery version on the window is the one we want to use jQuery = window.jQuery; this.ResolveJqueryAndLoadAdditionalJsAndCss(); } }; MyWidget.prototype.ResolveJqueryAndLoadAdditionalJsAndCss = function () { // Restore $ and window.jQuery to their previous values and store the // new jQuery in our local jQuery variable jQuery = window.jQuery.noConflict(true); }; MyWidget.prototype.Render = function (data) { window.addEventListener("load", function () { jQuery(document).ready(function ($) { $.when( $.getScript("http://www.jacklmoore.com/colorbox/jquery.colorbox.js"), $.Deferred(function (deferred) { $(deferred.resolve); }) ).done(function () { console.log('colorbox loaded'); $('&lt;a href="' + data.link + '" class="cleanslate custom widgetExternalPage" style="position: fixed;right:0px; top:50%; z-index:1000000000;-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-o-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);"&gt;' + data.anchorText + '&lt;/a&gt;').appendTo('body'); $(".widgetExternalPage").colorbox({ iframe: true, width: "80%", height: "80%" }); }); }); }, true); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:51:12.937", "Id": "64916", "Score": "0", "body": "some of your questions imply that you have not tested the code and that you don't know if the code works or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:57:26.997", "Id": "64997", "Score": "0", "body": "I have verified and its working for modern browsers, however, I still need to check for old versions of IE. As I'm not an expert on JS and couldn't find an example suitable suitable to my needs, that's why I posted." } ]
[ { "body": "<h1>Focus on your widget</h1>\n\n<p><strong>Do not</strong> load its dependencies. Instead, have the user of the widget to load them for you. </p>\n\n<p>Real world scenario: </p>\n\n<ul>\n<li>Bootstrap requires jQuery for it to work. Do you see Bootstrap load jQuery for itself? <strong>No, you don't.</strong></li>\n<li>Do you see jQuery plugins load jQuery for themselves? <strong>No, you don't.</strong></li>\n</ul>\n\n<p>In simple scenarios, you should keep things simple. Don't overcomplicate.</p>\n\n<h1>Flexibility and minimalism</h1>\n\n<p>Give the user a bit of flexibility as to where they want to place the link. Also, do it with as least code to the user as possible. You can do it jQuery style like so:</p>\n\n<pre><code>$('body').alwaysVisibleLink({\n text : 'Wikipedia',\n href : 'http://wikipedia.org/'\n});\n</code></pre>\n\n<h1>With everything out of the way...</h1>\n\n<p>Assuming lightbox and jQuery are loaded beforehand, you can have an implementation as little as this:</p>\n\n<pre><code>$.fn.alwaysVisibleLink = function (config) {\n return this.each(function () {\n $('&lt;a/&gt;', {\n href: config.href,\n class: 'cleanslate custom widgetExternalPage'\n })\n .text(config.text)\n .appendTo(this)\n .css({\n 'position': 'fixed',\n 'right': '0px',\n 'top': '50%',\n 'z-index': 1000000000,\n '-webkit-transform': 'rotate(270deg)',\n '-moz-transform': 'rotate(270deg)',\n '-o-transform': 'rotate(270deg)',\n '-ms-transform': 'rotate(270deg)',\n 'transform': 'rotate(270deg)',\n 'filter': 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'\n })\n .colorbox({\n iframe: true,\n width: '80%',\n height: '80%'\n });\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:26:26.723", "Id": "64883", "Score": "2", "body": "If you refer to Google JS Map API(https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false), it assume user to put just couple of lines before closing <body> tag and then dynamically load all additional scripts files.\n\nI can't ask user to manually add dependency scripts as its a paid service (Feedback widget.)\n\nOther players like WebEngage also provide script where user just need to put couple of lines and script takes care of loading all the dependencies - Check out - http://blog.webengage.com/2012/04/28/introducing-webengage-javascript-api-and-new-version-of-the-integration-code/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:29:27.183", "Id": "64884", "Score": "0", "body": "@user3133397 The code you gave is not as big as Google API (And yes, I know how Google loads their scripts). You only mentioned *\"What widget does: It adds an always visible text on the screen.\"* and that's about it. What you give is what you get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:40:20.913", "Id": "64885", "Score": "0", "body": "Yes, I agree that its no where as big as Google Map API, but ain't it the review section? I believe (and correct me if I'm wrong) whole purpose of having this section is to get the code reviewed by peers and follow best practice. All I want is someone to comment on points that I mentioned in initial post and comment if anything can be done a better way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:49:56.800", "Id": "64886", "Score": "0", "body": "@user3133397 Not all best practices apply to all cases. And in your case, keeping it small and simple is a better way." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T15:12:07.160", "Id": "38833", "ParentId": "38830", "Score": "2" } }, { "body": "<p>Some observations:</p>\n\n<ul>\n<li><code>ResolveJqueryAndLoadAdditionalJsAndCss</code> is too long a function name</li>\n<li><code>ResolveJquery</code><strong><code>AndLoadAdditionalJsAndCss</code></strong> lies about what it does</li>\n<li>jQuery version <code>'1.10.2'</code> seems awfully restrictive, are you sure ?</li>\n<li>You copy pasted the code to load a css file, use a function</li>\n<li><code>console.log</code> in production code is bad</li>\n<li>functions in the <code>prototype</code> and variables should follow lowerCamelCasing.</li>\n</ul>\n\n<p>For your questions</p>\n\n<ol>\n<li>Check if prototype being used the right way and work across all browsers? </li>\n<li><p>If jQuery is correctly loaded and resolved correctly (even if the page hosting the script have same/different version of jQuery already running on the page)</p>\n\n<blockquote>\n <p>The only way to be sure is to test on all browser within pages using\n different versions of jQuery.</p>\n</blockquote></li>\n<li><p>I used 'window.addEventListener' method to check if jQuery is loaded or not. Is it correct and the way ideally it should be?</p>\n\n<blockquote>\n <p>That seems brittle to me, what if something else loaded first ? Also,\n do you re-render every single time something gets loaded ?</p>\n</blockquote></li>\n</ol>\n\n<hr>\n\n<ol>\n<li>Is there any efficient way of loading the colorbox.js file</li>\n<li><p>Can the code be optimised further for improved performance?</p>\n\n<blockquote>\n <p>Looks fine to me, not sure</p>\n</blockquote></li>\n</ol>\n\n\n\n<p>6 Is the code production ready? </p>\n\n<blockquote>\n <p>I think not yet, but close.</p>\n</blockquote>\n\n<p><strong>Update</strong></p>\n\n<p>Thoughts on making the jQuery requirements less brittle. Too start I would check whether jQuery was loaded or not before executing the rest. Maybe have a variable called <code>renderingRequested</code> and <code>renderData</code> and extract the actual rendering into a function called <code>render</code> and call your current <code>render</code> -> <code>requestRender</code>.</p>\n\n<p>then <code>requestRender</code> would be something like : </p>\n\n<pre><code>MyWidget.prototype.requestRender = function (data) \n{\n if( jQuery ){\n render( data );\n }\n else {\n renderingRequested = true;\n renderData = data;\n }\n}\n</code></pre>\n\n<p>then, a renamed <code>ResolveJqueryAndLoadAdditionalJsAndCss</code> would do this</p>\n\n<pre><code>MyWidget.prototype.jqLoaded = function () {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n if( renderingRequested ){\n render( renderData );\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:09:11.217", "Id": "64905", "Score": "0", "body": "/ Malachi - Thanks. I'll make the changes as per your observation. Regarding 'window.addEventListener' can you recommend any other possible/ideal way? I can't use jQuery's document.ready() [only alternative I'm aware of] as I am using 'window.addEventListener' only to ensure that jQuery is already loaded. Any thoughts..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:22:29.373", "Id": "38837", "ParentId": "38830", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:21:02.100", "Id": "38830", "Score": "2", "Tags": [ "javascript", "jquery", "jquery-ui" ], "Title": "Is this JS Widget written correctly and production-ready?" }
38830
<p>I have a process, let's call it Proc1. It is installed in two different directories and one instance of each is running:</p> <ul> <li>C:\DirA\Proc1.exe </li> <li>C:\DirB\Proc1.exe</li> </ul> <p>When iterating through all currently running processes, I need to be able to differentiate one from the other. I do this by looking at the full path to the process.</p> <p>Unfortunately, a little piece of documentation from MSDN has forced me to make this code pretty ugly:</p> <p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682489%28v=vs.85%29.aspx" rel="nofollow">MSDN</a></p> <blockquote> <p>If the function fails with ERROR_BAD_LENGTH when called with TH32CS_SNAPMODULE or TH32CS_SNAPMODULE32, call the function again until it succeeds.</p> </blockquote> <p>Please assume that C++11 is not available for this project.</p> <pre><code>bool MyClass::IsCorrectPath (const DWORD dwPid, const std::string &amp;strPath) const { DWORD dwError = 0 ; NormalHandle hModSnap ; // RAII wrapper for HANDLE do { hModSnap = ::CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, dwPid) ; if (hModSnap == INVALID_HANDLE_VALUE) { dwError == ::GetLastError () ; if (dwError == ERROR_PARTIAL_COPY) { // This occurs when trying to read a 64 bit process from a 32 bit process. return false ; } else if (dwError == ERROR_BAD_LENGTH) { // We have to repeatedly call ::CreateToolhelp32Snapshot () if we get this error continue ; } else { ThrowFunctionFailure ("MyClass::IsCorrectPath ()", "::CreateToolhelp32Snapshot ()", ::GetLastError ()) ; } } } while ((hModSnap == INVALID_HANDLE_VALUE) &amp;&amp; (dwError == ERROR_BAD_LENGTH)) ; MODULEENTRY32 me ; me.dwSize = sizeof (me) ; if (::Module32First (hModSnap.Get (), &amp;me) == FALSE) { ThrowFunctionFailure ("MyClass::IsCorrectPath ()", "::Module32First ()", ::GetLastError ()) ; } return (::_stricmp (strPath.data (), me.szExePath) == 0) ; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:13:51.463", "Id": "64979", "Score": "1", "body": "Since you say you want the full path to the process, I would pay more attention to this note: *Note that you can use the [QueryFullProcessImageName](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684919.aspx) function to retrieve the full name of an executable image ...* (though it does require Vista/2008 or later systems.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:57:00.197", "Id": "65084", "Score": "0", "body": "@Michael Urman: Since I only have the PID, I would have to call `OpenProcess` to get a `HANDLE` and then call that function. That actually seems like a great idea. Unfortunately, I have to support Windows Server 2003 =(." } ]
[ { "body": "<p>I think you don't need to check for errors twice, and that will make your code cleaner.</p>\n\n<pre><code>bool MyClass::IsCorrectPath (const DWORD dwPid, const std::string &amp;strPath) const\n{\n DWORD dwError = 0 ;\n NormalHandle hModSnap ; // RAII wrapper for HANDLE\n ::SetLastError (0) ;\n\n do { \n // repeat while the expected error occurs\n hModSnap = ::CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, dwPid) ;\n dwError == ::GetLastError () ;\n } while ((hModSnap == INVALID_HANDLE_VALUE) &amp;&amp; (dwError == ERROR_BAD_LENGTH)) ;\n\n if (dwError == ERROR_PARTIAL_COPY) {\n // This occurs when trying to read a 64 bit process from a 32 bit process.\n return false ;\n }\n\n if (hModSnap == INVALID_HANDLE_VALUE) {\n ThrowFunctionFailure (\"MyClass::IsCorrectPath ()\", \n \"::CreateToolhelp32Snapshot ()\", ::GetLastError ()) ;\n }\n\n MODULEENTRY32 me ;\n me.dwSize = sizeof (me) ;\n if (::Module32First (hModSnap.Get (), &amp;me) == FALSE) {\n ThrowFunctionFailure (\"MyClass::IsCorrectPath ()\", \"::Module32First ()\", ::GetLastError ()) ;\n }\n\n return (::_stricmp (strPath.data (), me.szExePath) == 0) ;\n}\n</code></pre>\n\n<p>So, instead of checking for all errors in every step of the loop, only check for the expected error. </p>\n\n<p>Once you're out of the loop, it means you received a different error or you have a valid handle. Check if success and continue.</p>\n\n<p>Does that make sense to you?</p>\n\n<p>edit: Changed dwError == ERROR_SUCCESS to dModSnap == INVALID_HANDLE_VALUE.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:12:38.060", "Id": "64906", "Score": "0", "body": "I like this, but I think there is a bug. Let's say the loop runs twice. Then wouldn't `dwError` still equal `ERROR_BAD_LENGTH`? This would cause us to throw an exception because the statement `if (dwError != ERROR_SUCCESS)` would still be true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:14:29.170", "Id": "64907", "Score": "0", "body": "If the loop runs twice, dwError should update to the last error, and given that we expect this second time to be a success hModSnap will be a handle and dwError is ERROR_SUCCESS, and everything works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:56:24.607", "Id": "64918", "Score": "0", "body": "I just checked. A successful call to a Windows function does not guarantee that `GetLastError ()` will be cleared. I've included a counter-example in my question. I could probably just change `dwError != ERROR_SUCCESS` to `hModSnap == INVALID_HANDLE_VALUE` to fix this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:06:53.397", "Id": "64922", "Score": "0", "body": "My bad, most of the API change last error when an error occurs, so, the right will be to check return value and last error to be sure." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:43:09.427", "Id": "38845", "ParentId": "38839", "Score": "2" } } ]
{ "AcceptedAnswerId": "38845", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T16:51:02.950", "Id": "38839", "Score": "3", "Tags": [ "c++", "windows", "winapi" ], "Title": "Using ::CreateToolhelp32Snapshot" }
38839
<p><strong>Background</strong></p> <p>This is my first experience with functional programming and totally self-study. I just have 2-3 days' worth experience in Haskell. Now let's continue with actual code.</p> <hr> <p>For <a href="http://www.haskell.org/haskellwiki/99_questions/1_to_10" rel="nofollow">Problem 2</a> of 99 haskell problems I wrote this function</p> <pre><code>module Functions ( lastButOne ) where lastButOne :: [a] -&gt; a lastButOne [a, b] = a lastButOne (_:xs) = lastButOne xs lastButOne a = error "Not Supported" </code></pre> <p>Is this code ok from functional programming perspective? I am open to criticism from any perspective. </p> <p><strong>EDIT 1</strong></p> <p>Code after @Pedro Rodrigues suggestions</p> <pre><code>lastButOne :: [a] -&gt; a lastButOne [a, _] = a lastButOne (_:xs) = lastButOne xs lastButOne _ = error "lastButOne requires a list with at least 2 members" </code></pre>
[]
[ { "body": "<p>You have the right idea, I just want to make a few remarks:</p>\n\n<ol>\n<li>You could have used <code>_</code> in the first and the last clause of your function in place of the ignored arguments. It might help readability to know right away that an argument is being ignored.</li>\n<li>You're explicitly throwing an error on invalid input which is fine. A good error message could be more helpful to the caller than just getting a pattern match fail. However it wouldn't have shocked me if you had omitted that last line. An even safer solution is having the function return <code>Just a</code> when the input is valid and <code>Nothing</code> when it's not, but for performance/convenience's sake many partial functions out there don't do that.</li>\n</ol>\n\n<p><strong>EDIT:</strong> To elaborate more on the safer solution point I mentioned earlier: <code>lastButOne</code> has type <code>lastButOne :: [a] -&gt; a</code>. However this type fails to convey that <code>lastButOne</code> is a partial function, and therefore may fail on certain inputs. It's very easy for a caller to overlook that he needs to watch out for invalid inputs. However, had you defined <code>lastButOne</code> as <code>lastButOne :: [a] -&gt; Maybe a</code> instead, then the fact that it might not produce a result for some inputs, is directly encoded in the type of the function, thus making it type safer. Any caller of <code>lastButOne</code> couldn't possibly overlook that he needs to handle failure.</p>\n\n<p>In case you haven't heard of <code>Maybe</code> yet, it's a data structure that is used to elegantly express a computation that may fail. Examples:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>my_div :: Integer -&gt; Integer -&gt; Maybe Integer\nmy_div _ 0 = Nothing\nmy_div a b = Just (div a b)\n</code></pre>\n\n<pre class=\"lang-js prettyprint-override\"><code>lastButOne :: [a] -&gt; Maybe a\nlastButOne [a, _] = Just a\nlastButOne (_:xs) = lastButOne xs\nlastButOne _ = Nothing\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T03:38:46.217", "Id": "64987", "Score": "0", "body": "Starting from `An even safer`... I didn't get anything. Can you give an example what do you mean. Also how is this a variant of Problem 2? I added an edited code. Is this what you meant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T11:56:03.723", "Id": "65028", "Score": "0", "body": "@AseemBansal Forget what I said about being a variant. Don't know what I was thinking... sorry for the confusion. I've already fixed my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:26:28.483", "Id": "65090", "Score": "0", "body": "The idea of `Maybe` is good but getting error every time `Couldn't match expected type 'a' with actual type Maybe 'a'` in `In an equation for 'lastButOne': lastButOne [a, _] = a`. Any ideas why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:16:46.110", "Id": "65136", "Score": "0", "body": "@AseemBansal I've added an example implementation to my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:43:24.520", "Id": "38864", "ParentId": "38840", "Score": "3" } } ]
{ "AcceptedAnswerId": "38864", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:17:20.850", "Id": "38840", "Score": "4", "Tags": [ "beginner", "haskell" ], "Title": "99 Haskell Problems - Problem 2" }
38840
<p>I'm looking for advice how to improve the code. It's a mess, but I don't know how to improve it. There are some mathematical errors, projectile movements are behaving strangely, code is messy in general, unit positions are off, etc.</p> <pre><code>var canvas = document.createElement("canvas"); canvas.id = "canvas"; var ctx = canvas.getContext("2d"); canvas.width = 1480; canvas.height = 900; document.body.appendChild(canvas); var units = []; var bgReady = false; var bgImage = new Image(); bgImage.onload = function () { bgReady = true; }; bgImage.src = "images/background.bmp"; camera = new Object(); camera.x = -50; camera.y = -50; camera.zoom = 1; mouse = new Object(); mouse.x=0; mouse.y=0; select = new Object(); select.x1=0; select.y1=0; select.x2=0; select.y2=0; selected = []; var change = 0; var x1=0; var x2=0; var y1=0; var y2=0; var explosions=[]; var projectiles=[]; var count = 0; var debug = 0; function unit(name,health,letter,team,x,y,speed,accel,range,rate,type,damage,speed2,shield) { this.name = name; this.letter = letter; this.x = x; this.y = y; this.viewx = 0; this.viewy = 0; this.team = team; this.isselected = 0; this.state = ""; //idle this.maxspeed = speed; this.speed = 0; this.accel = accel; this.movex = 0; this.movey = 0; this.health = health; this.maxhealth = health; this.prange = range; this.pdamage = damage; this.prate = rate; this.ptype = type; this.pspeed = speed2; this.ang = 0; this.size = 5; this.shield = shield; this.maxshield = shield; } function explosion(x,y,size,power,fade) { this.x = x; this.y = y; this.viewx = 0; this.viewy = 0; this.size = size; this.power = power; this.timer = 100; this.fade = fade; } function projectile(type,damage,x,y,targetx,targety,speed) { this.type = type; this.damage = damage; this.x = x; this.y = y; this.viewx = 0; this.viewy = 0; this.movex = targetx; this.movey = targety; this.speed = speed; this.timer = calcDist(x,y,targetx,targety)/speed; this.ang = Math.atan2((targety - y),(targetx - x)) * (180 / Math.PI); this.radius = 20; } function explode(x,y) { explosions.push(Object.create(new explosion(x,y,1,0.25,1))); } for(var i=0;i&lt;40;i++) { units.push(Object.create(new unit("tank",100,"T","player2",150+Math.random()*200,150+Math.random()*200,0.2,0.002,175,4,"bullet",10,2,0))); } for(var i=0;i&lt;15;i++) { units.push(Object.create(new unit("mech",125,"M","player1",400+Math.random()*200,200+Math.random()*200,0.2,0.002,225,1,"bullet",4,2,100))); } function calcDist(x1,y1,x2,y2) { var a = x2-x1; var b = y2-y1; return Math.sqrt((a*a)+(b*b)); } document.onkeydown = checkKey; function checkKey(e) { e = e || window.event; if (e.keyCode == '38'&amp;&amp;camera.y&gt;(-100*camera.zoom*1)) { // up arrow camera.y-=50; } if (e.keyCode == '40'&amp;&amp;camera.y&lt;(0+(bgImage.height*(camera.zoom-1)))) { // down arrow camera.y+=50; } if (e.keyCode == '39'&amp;&amp;camera.x&lt;(bgImage.width*0.7)*camera.zoom) { // right arrow camera.x+=50; } if (e.keyCode == '37'&amp;&amp;camera.x&gt;(-100*camera.zoom)) { // left arrow camera.x-=50; } } this.canvas.onmousewheel = function(ev) { //perform your own Event dispatching here if(ev.wheelDelta&gt;0) { if(camera.zoom&lt;6) { camera.x+=bgImage.width*0.2; camera.y+=bgImage.height*0.2; camera.zoom+=0.6; } } else { if(camera.zoom&gt;1) { camera.x-=bgImage.width*0.2; camera.y-=bgImage.height*0.2; camera.zoom-=0.6; } } return false; }; function getSelection() { if(select.x2&gt;select.x1) { var x1 = select.x1; var x2 = select.x2; } else { var x1 = select.x2; var x2 = select.x1; } if(select.y2&gt;select.y1) { var y1 = select.y1; var y2 = select.y2; } else { var y1 = select.y2; var y2 = select.y1; } if(change==1) { ctx.fillRect(x1-8,y1-8,x2-x1,y2-y1); ctx.beginPath(); //ctx.stroke(); ctx.closePath(); ctx.fill(); } } function moveUnit(unit,x,y) { unit.movex = x-50; unit.movey = y-50; unit.state = "moving"; } this.canvas.onmouseup = function(ev) { if(select.x2&gt;select.x1) { var x1 = select.x1; var x2 = select.x2; } else { var x1 = select.x2; var x2 = select.x1; } if(select.y2&gt;select.y1) { var y1 = select.y1; var y2 = select.y2; } else { var y1 = select.y2; var y2 = select.y1; } for(var i=0;i&lt;units.length;i++) { if (units[i].viewx&gt;x1 &amp;&amp;units[i].viewx&lt;x2 &amp;&amp;units[i].viewy&gt;y1 &amp;&amp;units[i].viewy&lt;y2 &amp;&amp;units[i].team=="player1"){ selected.push(units[i]); } } change = 0; } this.canvas.onmousedown = function(ev) { if(selected.length&gt;0) { for(var i=0;i&lt;selected.length;i++) { moveUnit(selected[i],mouse.x+((i%(selected.length/3))*40)-((selected.length/3)*20),mouse.y+((i/selected.length)*40)-40); } } selected.length = 0; select.x1 = ev.clientX; select.y1 = ev.clientY; change = 1; } window.onmousemove = function(ev) { select.x2 = ev.clientX; select.y2 = ev.clientY; mouse.x = ev.clientX; mouse.y = ev.clientY; } function paard() { drawUnits(); if(change==0) { for(var i=0;i&lt;selected.length;i++) { ctx.beginPath(); ctx.arc(selected[i].viewx+(camera.zoom*7*0.5),selected[i].viewy+(camera.zoom*9*0.5),25*camera.zoom,0,2*Math.PI); ctx.strokeStyle = "rgba(0, 255, 0, 25)"; ctx.lineWidth = 5; ctx.closePath(); ctx.stroke(); } } getSelection(); drawExplosions(); drawProjectiles(); } function drawUnits() { // ctx.fillStyle = "rgb(25, 25, 25)"; ctx.font = 12*camera.zoom+"px Helvetica"; ctx.textAlign = "left"; ctx.textBaseline = "top"; //top ctx.clearRect(-500,-500,2000,2000); ctx.drawImage(bgImage,-camera.x,-camera.y,bgImage.width*camera.zoom,bgImage.height*camera.zoom); for(var i=0;i&lt;units.length;i++) { if(units[i].team=="player1") { ctx.fillStyle = "rgb(25, 25, 255)"; } else { ctx.fillStyle = "rgb(255, 25, 25)"; } if(units[i].health&lt;=0) { for(var z=0;z&lt;5;z++) { explode(units[i].x+Math.random()*15,units[i].y+Math.random()*15); } units.splice(i,1); break; return; } if(units[i].state=="moving") { if(units[i].x&lt;units[i].movex+1 &amp;&amp;units[i].x&gt;units[i].movex-1 &amp;&amp;units[i].y&lt;units[i].movey+1 &amp;&amp;units[i].y&gt;units[i].movey-1) { units[i].state=""; units[i].speed=0; } else { var a = units[i].movex-units[i].x; var b = units[i].movey-units[i].y; var angleDeg = Math.atan2((units[i].movey - units[i].y),(units[i].movex - units[i].x)) * (180 / Math.PI); units[i].ang = angleDeg; if(Math.sqrt((a*a)+(b*b))&gt;30) { if(units[i].speed&lt;units[i].maxspeed) { units[i].speed+=units[i].accel; } } else { if(units[i].speed&gt;0.1) { units[i].speed-=units[i].accel*4; } } units[i].x+=Math.sin(angleDeg)*units[i].speed; units[i].y-=Math.cos(angleDeg)*units[i].speed; } } units[i].viewx = (units[i].x*camera.zoom)-camera.x; units[i].viewy = (units[i].y*camera.zoom)-camera.y; ctx.fillText(units[i].letter,units[i].viewx,units[i].viewy); if(units[i].shield&lt;units[i].maxshield) { units[i].shield+=0.03*(units[i].maxshield/100); } } } function drawExplosions() { for(var i=0;i&lt;explosions.length;i++) { ctx.strokeStyle = "rgba(255, "+explosions[i].timer*2.5+", 0, "+explosions[i].timer/100+")"; if(explosions[i].timer&gt;0) { explosions[i].size+=explosions[i].power; explosions[i].timer-=explosions[i].fade; explosions[i].viewx = (explosions[i].x*camera.zoom)-camera.x; explosions[i].viewy = (explosions[i].y*camera.zoom)-camera.y; ctx.beginPath(); ctx.strokeStyle = "rgba(255, "+explosions[i].timer*2.5+", 0, "+explosions[i].timer/100+")"; ctx.arc(explosions[i].viewx,explosions[i].viewy,explosions[i].size*camera.zoom,0,2*Math.PI); ctx.lineWidth = (explosions[i].size/3)*camera.zoom; ctx.closePath(); ctx.stroke(); } else { explosions.splice(i,1); } } } function drawProjectiles() { ctx.fillStyle = "rgb(255, 255, 25)"; for(var i=0;i&lt;projectiles.length;i++) { //var ang = Math.atan2((projectiles[i].movey - projectiles[i].y),(projectiles[i].movex - projectiles[i].x)) * (180 / Math.PI); projectiles[i].ang = Math.atan2((projectiles[i].movey - projectiles[i].y),(projectiles[i].movex - projectiles[i].x)) * (180 / Math.PI); projectiles[i].x += Math.sin(projectiles[i].ang)*projectiles[i].speed; projectiles[i].y -= Math.cos(projectiles[i].ang)*projectiles[i].speed; projectiles[i].viewx = (projectiles[i].x*camera.zoom)-camera.x; projectiles[i].viewy = (projectiles[i].y*camera.zoom)-camera.y; projectiles[i].timer -= 1; ctx.fillText(".",projectiles[i].viewx,projectiles[i].viewy-(10*camera.zoom)); if(projectiles[i].timer &lt;= 0) { if(projectiles[i].type=="bullet") { for(var u=0;u&lt;units.length;u++) { if(units[u].x&lt;projectiles[i].x+units[u].size &amp;&amp;units[u].x&gt;projectiles[i].x-units[u].size &amp;&amp;units[u].y&lt;projectiles[i].y+units[u].size &amp;&amp;units[u].y&gt;projectiles[i].y-units[u].size) { if(projectiles[i].damage&lt;units[u].shield) { units[u].shield-=projectiles[i].damage; } else { units[u].health-=projectiles[i].damage; } break; } } } if(projectiles[i].type=="explosive") { for(var u=0;u&lt;units.length;u++) { if(units[u].x&lt;projectiles[i].x+projectiles[i].radius &amp;&amp;units[u].x&gt;projectiles[i].x-projectiles[i].radius &amp;&amp;units[u].y&lt;projectiles[i].y+projectiles[i].radius &amp;&amp;units[u].y&gt;projectiles[i].y-projectiles[i].radius) { if(projectiles[i].damage&lt;units[u].shield) { units[u].shield-=projectiles[i].damage; } else { units[u].health-=projectiles[i].damage; } } } } projectiles.splice(i,1); } } } function attack() { // count++; for(var i=0;i&lt;units.length;i++) { if(count%units[i].prate==0) { for(var u=0;u&lt;units.length;u++) { if(units[i].team!=units[u].team&amp;&amp;calcDist(units[i].x,units[i].y,units[u].x,units[u].y)&lt;units[i].prange&amp;&amp;Math.random()&lt;1.5) { var d = calcDist(units[i].x,units[i].y,units[u].x,units[u].y); var sx = Math.sin(units[u].ang)*units[u].speed*(d/units[i].pspeed); var sy = Math.cos(units[u].ang)*units[u].speed*(d/units[i].pspeed); projectiles.push(Object.create(new projectile(units[i].ptype,units[i].pdamage,units[i].x,units[i].y,units[u].x+sx,units[u].y-sy,units[i].pspeed))); break; //return; } } } } } setInterval(paard,25); setInterval(attack,1000); </code></pre> <p><a href="https://dl.dropboxusercontent.com/u/75625262/supcom.rar">Here's the download link for the game</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:34:53.980", "Id": "64901", "Score": "1", "body": "Do you have prior experience with *object oriented programming*? Is this your first larger programming project? Knowing this could help to write a more useful code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:36:31.527", "Id": "64914", "Score": "4", "body": "Your lack of confidence in your code is concerning. CodeReview is for reviewing working code. It does not sound like your code works. Does it work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:52:05.553", "Id": "64957", "Score": "4", "body": "@rolfl I think it should be possible to provide tips for improving the code without necessarily fixing whatever bugs might be present." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T21:23:45.367", "Id": "64958", "Score": "3", "body": "@rolfl : prior work is here : http://codereview.stackexchange.com/questions/37672/javascript-rpg-advice" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T11:54:33.387", "Id": "65027", "Score": "0", "body": "Does it work? Apparently you did not even consider reading the whole post..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T11:56:39.863", "Id": "65029", "Score": "0", "body": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript As far as I can tell, I am using object oriented programming." } ]
[ { "body": "<p><strong>Object Literal Notation</strong></p>\n\n<p>There are number of objects that would be easier to create</p>\n\n<pre><code>camera = new Object();\ncamera.x = -50;\ncamera.y = -50;\ncamera.zoom = 1;\nmouse = new Object();\nmouse.x=0;\nmouse.y=0;\nselect = new Object();\nselect.x1=0;\nselect.y1=0;\nselect.x2=0;\nselect.y2=0;\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>var camera = { x : -50 , y : -50 },\n mouse = { x : 0 , y : 0 },\n select = { x1 : 0 , y1 : 0 , x2 : 0 , y2 : 0 };\n</code></pre>\n\n<p>if you create a Point constructor you could even do</p>\n\n<pre><code>function Point( x, y ){\n this.x = x;\n this.y = y;\n}\n\nvar camera = new Point( -50, -50),\n mouse = new Point( 0, 0 ),\n select = { from : new Point( 0, 0 ) , to : new Point( 0, 0 ) }\n</code></pre>\n\n<p>You would still repeat ( 0, 0 ) a lot, it seems you just want to initialize the x/y variable and you would still use <code>new</code> a lot, that could be helped with this approach:</p>\n\n<pre><code>function Point( x, y ){\n if ( !(this instanceof Point) )\n return new Point(x,y);\n this.x = x || 0;\n this.y = y || 0;\n}\n\nvar camera = Point( -50, -50),\n mouse = Point(),\n select = { from : Point() , to : Point() };\n</code></pre>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li><p>Constructors should start with an upper case so <code>unit</code> -> <code>Unit</code> , <code>explosion</code> -> <code>Explosion</code>.</p></li>\n<li><p><code>paard</code>: like <code>kaas</code>; we all like Dutch words, but code should only have names based on English.</p></li>\n<li><p>You are a bit too Spartan with <code>d</code>, <code>sx</code> and <code>sy</code>.</p></li>\n</ul>\n\n<p><strong>Magical constants</strong></p>\n\n<ul>\n<li>Team colors should be properly named constants, frankly I would have liked to see <code>ctx.fillStyle = team[i].color;</code></li>\n<li>There are too many constants to list them all, I think you get the picture</li>\n</ul>\n\n<p><strong>Extracting code into functions</strong></p>\n\n<ul>\n<li>The drawing code in <code>paard</code> could use it's own function</li>\n<li>The shooting code in <code>attack()</code> could use it's own function</li>\n</ul>\n\n<p><strong>DRY</strong></p>\n\n<ul>\n<li>The code for dealing with <code>explosive</code> and <code>bullet</code> is mostly copy pasted, consolidate that</li>\n</ul>\n\n<p><strong>Gameplay</strong></p>\n\n<pre><code>if(projectiles[i].damage&lt;units[u].shield)\n units[u].shield-=projectiles[i].damage;\nelse\n units[u].health-=projectiles[i].damage;\n</code></pre>\n\n<p>Are you sure that large damages completely bypass shield and are not at all absorbed by the shield ?</p>\n\n<p>Finally, I downloaded your game. Even though limited it was fun to kill all the baddies. There is more to review in your code but you should take care of these items first.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T20:40:35.880", "Id": "38937", "ParentId": "38842", "Score": "3" } }, { "body": "<p>When I make games in canvas, I use a grid system if it is applicable to said game. I think it could be applicable to your RTS.</p>\n\n<p>A coordinate on my grid looks like this: <code>\"10x15\"</code> (X = 10, Y =15).</p>\n\n<p>The grid itself, once generated, looks something like this: </p>\n\n<pre><code>var grid = [\"0x0\",\"0x1\",\"0x2\",\"0x3\"\n \"1x0\",\"1x1\",\"1x2\",\"1x3\"\n \"2x0\",\"2x1\",\"2x2\",\"2x3\"];\n</code></pre>\n\n<p>When tracking a unit or units, you can use an array of objects like this:</p>\n\n<pre><code>var units = [\n {\n \"type\": \"Infantry\",\n \"unitId\": 32,\n \"x\": 10,\n \"y\": 15,\n \"coords\": \"10x15\"\n },\n {\n \"type\": \"Artillery\",\n \"unitId\": 45\n \"x\": 15,\n \"y\": 15,\n \"coords\": \"15x15\"\n }\n];\n</code></pre>\n\n<p>By using an object that contains an x, y, and a combination of those points that forms a coordinate, it is much easier to move objects around and track their location for things like collision.</p>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-28T15:54:48.307", "Id": "133306", "ParentId": "38842", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:26:12.363", "Id": "38842", "Score": "6", "Tags": [ "javascript", "game" ], "Title": "RTS game improvement" }
38842
<p>Since I am new to MVC and the Entity Framework, I have been struggling to grasp the concept of creating useful Data and Service layers. I have come across a scenario where I believe my code has become very redundant: </p> <p><strong>Data Access Layer:</strong></p> <pre><code>public static class DeploymentOrderDataLayer { public static usr_OrderFulfillment GetScannedItem(string orderNumber, string itemNumber) { using (TPGContext context = new TPGContext()) { return context.usr_OrderFulfillment.FirstOrDefault(x =&gt; x.SOPNUMBE == orderNumber &amp;&amp; x.ItemNumber == itemNumber); } } public static void UpdateScannedItem(string orderNumber, string itemNumber, string user, string serialNumber) { using (TPGContext context = new TPGContext()) { var result = context.usr_OrderFulfillment.FirstOrDefault(x =&gt; x.SOPNUMBE == orderNumber &amp;&amp; x.ItemNumber == itemNumber); result.IsFulfilled = true; result.FulfilledBy = user; result.DateFulfilled = DateTime.Now; if (!string.IsNullOrEmpty(serialNumber)) { result.SerialNumber = serialNumber; } context.SaveChanges(); } } } </code></pre> <p>I call all of my Data Layers through a BusinessLayer, which handles my business logic:</p> <pre><code>public class DeploymentOrderBusinessLayer { public static void UpdateScannedItem(string orderNumber, string itemNumber, string user, string serialNumber = "") { var itemInfo = DeploymentOrderDataLayer.GetScannedItem(orderNumber, itemNumber); if (itemInfo == null) throw new BusinessException("Item number not found."); if (itemInfo.IsFulfilled) throw new BusinessException(string.Format("Item already fulfilled by {0}", itemInfo.FulfilledBy)); DeploymentOrderDataLayer.UpdateScannedItem(orderNumber, itemNumber, user, serialNumber); } } </code></pre> <p>The BusinessLayer then gets called from my DeploymentOrder Controller:</p> <pre><code> try { DeploymentOrderBusinessLayer.UpdateScannedItem(orderNumber, itemNumber, User.Identity.Name); } catch (BusinessException ex) { ViewBag.AlertMessage = ex.Message; } </code></pre> <p>A couple things that bug me:</p> <ol> <li><p>I'm calling GetScannedItem in my business layer so that I can do my validation first, before anything gets updated. When I'm ready to update, I have to re-query the database again, so that I can update my context. This extra hit to the database seems unnecessary to me, but I'm not sure how to fix it. </p></li> <li><p>The DeploymentOrderDataLayer is fine for my DeploymentOrderController, but useless for any other controllers that might need to access similar data. I would like my Data Layers to be more dynamic. </p></li> </ol> <p>Any suggestions are appreciated. </p>
[]
[ { "body": "<p>This is going to be just a partial review, I don't have much time but I can't help it, I have to say something.</p>\n\n<ul>\n<li><p><code>usr_OrderFulfillment</code> might be how the table is called in your database, and <code>SOPNUMBE</code> might be how a column is called in that table. <strong>It doesn't mean your <em>entities</em> have to be as painful</strong>. Entity Framework is an object/relational <em>mapper</em>; this implies a <em>mapping</em> - you can easily map <em>table</em> <code>usr_OrderFulfillment</code> to <em>entity</em> <code>OrderFulfillment</code> and <em>column</em> <code>SOPNUMBE</code> to <em>property</em> <code>OrderNumber</code>.</p></li>\n<li><p>Your <code>DeploymentOrderDataLayer</code> class (I wouldn't call a <em>class</em> a <em>layer</em> - call it a <em>service</em> if you will, but a <em>layer</em> is more for an <em>assembly</em> than for a <em>type</em>), is tightly coupled to <code>TPGContext</code>, and each new method requires a new instance of your context - even if 20 calls are made in the same request. You should <em>inject</em> the instance through the class' constructor and use a single instance per request. There's really no need to <code>new</code> it up and dispose it in every method. The class being <code>static</code> isn't helping either (it does explain the non-existing constructor though). Always prefer instances over static helpers.</p></li>\n<li><p>This architecture feels like stored procedures written in C# code. It's bloated, over-engineered and makes you almost as good as me in shredding KISS into tiny little pieces. Have you tried using the EF <code>DbContext</code> directly in your controller to get the job done, <em>and then</em> refactor into a more structured approach?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T21:49:22.500", "Id": "64962", "Score": "0", "body": "How do I \"inject\" the instance through the class' constructor? I don't think I have done anything like that before. I agree the architecture is over engineered, but I don't want my DBContext code to be in my controller. Maybe I could put that code in the BusinessLayer along with the validation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T00:05:46.147", "Id": "64971", "Score": "0", "body": "I'll edit with more details when I have a few minutes; sorry I'm speaking DI lingo - *constructor injection* is when you pass a class' *dependencies* as constructor arguments - the db context in this case. It moves the newing up to the caller, taking the concern of creating the context out of that class. You can then assign a `private readonly` field and use that instead of recreating it in every method :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:17:00.913", "Id": "38849", "ParentId": "38843", "Score": "5" } }, { "body": "<p>I have done this several different ways in several MVC projects for my work. I don't think there is a specific \"right way\" to do this and it really depends on the project. The size and scope of your project has a real bearing on how this is done. If it is small (one or two controllers tops, maybe 3 tables in the database), then the way shown in most MVC tutorials is probably just fine. However, as your project gets larger, maintainability becomes an issue and one must consider the repetitiveness of the code and the \"ripple effect\" small-ish changes have.</p>\n\n<p>Your code has the right idea, but I think your creation and disposal of entity framework context objects causes you problems. It is unnecessary IMHO and could slow down your application. In addition, you are losing that most beautiful ability of entity framework to track changes to entities and such. As for your separation of duties (having a separate object working with the entity context, having the controller use this object only to get and manipulate data, etc), I agree with how you have done it.</p>\n\n<p>I have found the using the following constraints has helped the code to be more maintainable for me. These change often as my code is critiqued at work and as I have to do maintenance on code I have long since forgotten how it worked:</p>\n\n<ul>\n<li>Entity Framework entities are allowed to be passed around between the model/data layer, but they are never passed into views. Entities don't serialize well and \"feels wrong\" to have a razor page be allowed to inadvertently perform database operations such as loading a child entity.</li>\n<li>There is only one Entity Framework context per request. This helps keep connection count down and allows you to pass entities around in your code. I often isolate this context from my controller code so that it is never touched by a controller (more on how I do this later).</li>\n<li>I have a separate Model project. This is mainly by personal preference since I often have several components to an application (the web front end, a service that runs in the background, a bootstrap console application, etc) and I often find it useful to share the same logic. However, I have occasionally got myself into DLL and dependency issues using this, so at times I skip this completely.</li>\n</ul>\n\n<p>Lately, I have implemented the following:</p>\n\n<ul>\n<li>A central object which handles my queries and \"hides\" the database context from everything else. If the database and such are in a separate project, I make the context \"internal\" rather than public so that the database context can only be instantiated from this central object. I believe this is called the \"repository pattern\", but I am not sure since one could say that the EF context is a repository on its own.</li>\n<li>The central object is <code>IDisposable</code> and when instantiated creates a single EF context and when disposed disposes the EF context.</li>\n<li>The central object returns entities and has a <code>SaveChanges</code> method that is just a wrapper to the context's SaveChanges.</li>\n<li>I often have several sub-objects that are only created by the central object which organize the various methods. For example, if I have a users table, an items table, and a purchases table, I would create separate objects for each set of operations that happens on each table. The <code>Users</code> object would have methods for finding and creating users, the <code>Items</code> object would have methods for finding and creating items, and the <code>Purchases</code> object would have methods for finding purchases. For operations that cross the boundaries (such as creating a purchase for a user with several items), I either just do it via the entity relationships or, if it is more complicated, I place the operation into the sub-object for the table that is most affected (in this example, the purchases object would get this particular operation since a purchase was created).</li>\n<li>In the <code>Application_BeginRequest</code> method, an instance of the central object is instantiated and attached to the <code>HttpContext.Current.Items</code> dictionary. In the <code>Application_EndRequest</code> method, the central object is disposed. No other central object is created during the request so that all entities used during the request are attached to the same context. This makes it easy to do things like have both an <code>IPrincipal</code>-style user (accessed via the controller's <code>User</code> property) and a database user which could be stored somewhere like <code>HttpContext.Current.Items</code>.</li>\n<li>In the event that an entity needs to leave the application, I use the DTO pattern (Data Transfer Object). These are serializable classes that I usually decorate with <code>DataContract</code> and <code>DataMember</code> attributes. As their constructor arguments, they take in one or more entities. In terms of logic, they are super super simple and have nothing more than a bunch of properties. The point of these is to mitigate entity serialization issues and also give a measure of control over what exactly is transmitted over the wire. These are what are placed into the <code>ViewBag</code> and set as the <code>Model</code> object for views. They are also the objects I pass out of WebAPI endpoints.</li>\n</ul>\n\n<p>I often create a static helper class which extracts and casts the various objects stored in <code>HttpContext.Current.Items</code> to their appropriate types. I also have lately been having these methods actually instantiate the objects rather than having <code>Application_BeginRequest</code> do it. <code>Application_EndRequest</code> is then modified to only dispose the objects if they are actually found in <code>HttpContext.Current.Items</code>.</p>\n\n<p>A small example of this is here (no central object separation of duties, no DTOs, and no static helper class): <a href=\"https://gist.github.com/kcuzner/8306451\" rel=\"nofollow\">https://gist.github.com/kcuzner/8306451</a></p>\n\n<p>Pretend that in the example the <code>DbQueries</code> class is your <code>DeploymentOrderDataLayer</code> class. I made that gist for another question and I would not have named that object in real life the way I have it in the gist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:26:29.413", "Id": "38851", "ParentId": "38843", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T17:36:26.617", "Id": "38843", "Score": "6", "Tags": [ "c#", "asp.net-mvc-4", "asp.net-mvc" ], "Title": "Building a better Data Access Layer Class" }
38843
<p>I am doing a little in-between semester reading in my C++ book, and I came up with the wonderful idea to try to make Yahtzee in C++. So far the code generates 5 random numbers and then calls the function that I made to display a rendering of the die. I cannot figure out how to allow the users to hold the dice that they want to keep for scoring, and I haven't developed a scoring system yet. I have essentially figured out how to roll some dice.</p> <p>I know somebody is going to get on me for using <code>using namespace std;</code>. But basically I am looking for some direction on what to do next for re-rolling and keeping score.</p> <pre><code>// dice.cpp : // #include "stdafx.h" #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; void diceRoll(); void dice1(); void dice2(); void dice3(); void dice4(); void dice5(); void dice6(); using namespace std; int getNum(); int main() { srand(static_cast&lt;int&gt;(time(0))); diceRoll(); cout&lt;&lt;"Thanks for rollin my dice"&lt;&lt;endl; system("pause"); return 0; } void diceRoll() { int roll1=0; int roll2=0; int roll3=0; int roll4=0; int roll5=0; char selection='y'; bool re1=' '; bool re2=' '; bool re3=' '; bool re4=' '; bool re5=' '; char choice1=' '; char choice2=' '; char choice3=' '; char choice4=' '; char choice5=' '; do{ cout&lt;&lt;"roll dice"&lt;&lt;endl; roll1=getNum(); roll2=getNum(); roll3=getNum(); roll4=getNum(); roll5=getNum(); switch(roll1) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch switch(roll2) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch switch(roll3) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch switch(roll4) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch switch(roll5) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch cout&lt;&lt;"would you like to re-roll die 1 (y/n)"&lt;&lt;endl; cin&gt;&gt;choice1; if(choice1=='y') { re1=true; } if(re1=true) { roll1=getNum(); switch(roll1) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch }//endif if(choice1=='n') { cout&lt;&lt;roll1; } cout&lt;&lt;"would you like to re-roll die 2 (y/n)"&lt;&lt;endl; cin&gt;&gt;choice2; if(choice2=='y') { re2=true; } if(re2=true) { roll2=getNum(); switch(roll2) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch }//endif cout&lt;&lt;"would you like to re-roll die 3 (y/n)"&lt;&lt;endl; cin&gt;&gt;choice3; if(choice3=='y') { re3=true; } if(re3=true) { roll3=getNum(); switch(roll3) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch }//endif cout&lt;&lt;"would you like to re-roll die 4 (y/n)"&lt;&lt;endl; cin&gt;&gt;choice4; if(choice4=='y') { re4=true; } if(re4=true) { roll4=getNum(); switch(roll4) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch }//endif cout&lt;&lt;"would you like to re-roll die 5 (y/n)"&lt;&lt;endl; cin&gt;&gt;choice5; if(choice5=='y') { re5=true; } if(re5=true) { roll5=getNum(); switch(roll5) { case 1: dice1(); break; case 2: dice2(); break; case 3: dice3(); break; case 4: dice4(); break; case 5: dice5(); break; case 6: dice6(); break; }//endSwitch }//endif cin&gt;&gt;selection; system("cls"); }while(selection=='y'); } int getNum() { int randNumber=0; randNumber = 1+ rand() % (6-1+1); return randNumber; } void dice1() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if(row==0||row==4) { cout&lt;&lt;"*"; } if(row==1||row==3) { if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } else cout&lt;&lt;" "; } if (row==2) { if(spacer==1||spacer==2||spacer==3||spacer==5||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==4) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } } }//endfor cout&lt;&lt;endl; } } void dice2() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if(row==0||row==4) { cout&lt;&lt;"*"; } if (row==1||row==3) { if(spacer==1||spacer==2||spacer==3||spacer==5||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==4) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } } if(row==2) { if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } else cout&lt;&lt;" "; } }//endfor cout&lt;&lt;endl; } } void dice3() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if(row==0||row==4) { cout&lt;&lt;"*"; } if (row==1||row==2||row==3) { if(spacer==1||spacer==2||spacer==3||spacer==5||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==4) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } } }//endfor cout&lt;&lt;endl; } } void dice4() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if(row==0||row==4) { cout&lt;&lt;"*"; } if (row==2) { if(spacer==1||spacer==2||spacer==3||spacer==4||spacer==5||spacer==6) { cout&lt;&lt;" "; } if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } } if (row==1||row==3) { if(spacer==1||spacer==3||spacer==4||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==2||spacer==5) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } }//endif }//endfor cout&lt;&lt;endl; } } void dice5() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if(row==0||row==4) { cout&lt;&lt;"*"; } if (row==2) { if(spacer==1||spacer==2||spacer==3||spacer==5||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==4) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } } if (row==1||row==3) { if(spacer==1||spacer==3||spacer==4||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==2||spacer==5) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } }//endif }//endfor cout&lt;&lt;endl; } } void dice6() { for(int row=0;row&lt;5;row++) { for(int spacer=0;spacer&lt;8;spacer++) { if (row==1||row==2||row==3) { if(spacer==1||spacer==3||spacer==4||spacer==6) { cout&lt;&lt;" "; }//endif if(spacer==2||spacer==5) { cout&lt;&lt;"x"; }//endif if(spacer==0||spacer==7) { cout&lt;&lt;"*"; } }//endif else { cout&lt;&lt;"*"; } }//endfor cout&lt;&lt;endl; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:32:07.810", "Id": "64912", "Score": "0", "body": "Your best bet is to copy the code into visual studio and try it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:35:15.800", "Id": "64928", "Score": "1", "body": "\"What to do next\" is off-topic for Code Review. We give suggestions for improving existing code, not how to write new code. But I am still upvoting this because I really think that your code is in desperate need of improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:01:05.783", "Id": "64938", "Score": "2", "body": "I haven't fully studied this yet, but it seems to me that much of this can be condensed by creating a new `Die` structure, perhaps as a class. I can't quite determine the purpose of each dice function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:06:24.520", "Id": "64941", "Score": "0", "body": "Take a look at [this](http://codereview.stackexchange.com/questions/31571/review-of-dice-class) implementation of a die I've done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:42:25.340", "Id": "64954", "Score": "0", "body": "@Jamal it looks like the dice functions exist to display an ascii art representation of a die to cout.\ncalling dice1() will display a die showing the face with 1 pip, calling dice6() will alternatively display a die showing 6 pips." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T20:44:38.783", "Id": "64956", "Score": "0", "body": "@YoungJohn: Okay. In that case, the functions should be given much better names." } ]
[ { "body": "<p>You might consider not generating the dice displays every time, but rather storing them as strings, for example:</p>\n\n<p>To display a dice value of 1 you could use the string:</p>\n\n<pre><code>std::string displayValue1 = \"\\n***\\n*x*\\n***\\n\\n\";\n</code></pre>\n\n<p>Then you could store your strings in an std::array or an std::vector which you index instead of using your switch statements.</p>\n\n<pre><code>std::vector&lt;std::string&gt; vectorOfDisplays\n{\n displayValue1,\n displayValue2,\n displayValue3,\n displayValue4,\n displayValue5,\n displayValue6\n};\n</code></pre>\n\n<p>For example instead of:</p>\n\n<pre><code>switch(roll1)\n{\ncase 1:\n dice1();\nbreak;\n\ncase 2:\n dice2();\nbreak;\n\ncase 3:\n dice3();\nbreak;\n\ncase 4:\n dice4();\nbreak;\n\ncase 5:\n dice5();\nbreak;\n\ncase 6:\n dice6();\nbreak;\n\n}//endSwitch\n</code></pre>\n\n<p>You could then do:</p>\n\n<pre><code>cout &lt;&lt; vectorOfDisplays.at(roll1);\n</code></pre>\n\n<p>Alright... not quite, you might need to have roll1-1 so that it is an index into a container (0-5) instead of (1-6).</p>\n\n<p>Doing so would probably reduce some of the complexity of your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:47:12.593", "Id": "38853", "ParentId": "38847", "Score": "2" } }, { "body": "<p>Here's how you can improve your code:</p>\n\n<ul>\n<li>Declaring function prototypes and function definitions in the same file just doesn't make sense. Just declare and define them before their use.</li>\n<li>Don't use <code>using namespace std;</code>: you are basically defeating the purpose of namespace. Get used to the <code>std::</code> prefix instead.</li>\n<li>Don't use <code>srand</code> or <code>rand</code> for uniform distributions: use <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow\"><code>std::uniform_int_distribution&lt;int&gt;</code></a> instead.</li>\n<li>When you are using variables postfixed with incrementing numbers (like <code>roll1</code>, <code>roll2</code>, <code>roll3</code>...), it's probably a good idea to use an <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow\"><code>std::array</code></a> or <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow\"><code>std::vector</code></a> instead.</li>\n<li>When you are duplicating a lot of code (like all those identical <code>switch</code> statements), it's usually the sign that you either need a loop or a function.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T21:07:58.450", "Id": "38856", "ParentId": "38847", "Score": "4" } }, { "body": "<p>Code Review is for reviewing existing code and not to discuss what additional features to add so I'm going to focus on reviewing what is there. This should reduce the amount of existing code somewhat and make it less daunting to add new functionality.</p>\n\n<ol>\n<li><p>Your functions and variables not always very well named. The name of a variable or function should convey its purpose in a concise manner so that when reading the code it is immediately obvious what the intended purpose is. So for example:</p>\n\n<ul>\n<li><code>getNum</code> should probably be named <code>getRandomDieRoll</code></li>\n<li>The <code>diceX</code> methods should be named <code>drawDieX</code></li>\n</ul></li>\n<li><p>You have tremendous amounts of code repetition. Programming is about efficiently solving a problem in an automated way and you should also try to apply this to the code your write. One of the most important principles is: <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY - Don't Repeat Yourself</a>.</p></li>\n</ol>\n\n<p>Now let's see how we can start refactoring things</p>\n\n<p>First of all the <code>switch</code> blocks all have the same code so we can easily extract those into a function:</p>\n\n<pre><code>void drawDieForRoll(int roll)\n{\n switch (roll)\n {\n case 1: drawDie1(); break;\n case 2: drawDie2(); break;\n case 3: drawDie3(); break;\n case 4: drawDie4(); break;\n case 5: drawDie5(); break;\n case 6: drawDie6(); break;\n }\n}\n</code></pre>\n\n<p>Now we can simplify <code>diceRoll</code> to:</p>\n\n<pre><code>void diceRoll()\n{\nint roll1=0;\nint roll2=0;\nint roll3=0;\nint roll4=0;\nint roll5=0;\nchar selection='y';\nbool re1=' ';\nbool re2=' ';\nbool re3=' ';\nbool re4=' ';\nbool re5=' ';\nchar choice1=' ';\nchar choice2=' ';\nchar choice3=' ';\nchar choice4=' ';\nchar choice5=' ';\ndo{\ncout&lt;&lt;\"roll dice\"&lt;&lt;endl;\nroll1=getNum();\nroll2=getNum();\nroll3=getNum();\nroll4=getNum();\nroll5=getNum();\n\ndrawDieForRoll(roll1);\ndrawDieForRoll(roll2);\ndrawDieForRoll(roll3);\ndrawDieForRoll(roll4);\ndrawDieForRoll(roll5);\n\n cout&lt;&lt;\"would you like to re-roll die 1 (y/n)\"&lt;&lt;endl;\n cin&gt;&gt;choice1;\n if(choice1=='y')\n {\n re1=true;\n }\n if(re1=true)\n {\n roll1=getNum(); \n }//endif\n if(choice1=='n')\n {\n cout&lt;&lt;roll1;\n }\n\n\ncout&lt;&lt;\"would you like to re-roll die 2 (y/n)\"&lt;&lt;endl;\ncin&gt;&gt;choice2;\nif(choice2=='y')\n{\n re2=true;\n}\n if(re2=true)\n {\n roll2=getNum();\n drawDieForRoll(roll2);\n }//endif\n\ncout&lt;&lt;\"would you like to re-roll die 3 (y/n)\"&lt;&lt;endl;\ncin&gt;&gt;choice3;\nif(choice3=='y')\n{\n re3=true;\n}\n if(re3=true)\n {\n roll3=getNum();\n drawDieForRoll(roll3);\n }//endif\n\ncout&lt;&lt;\"would you like to re-roll die 4 (y/n)\"&lt;&lt;endl;\ncin&gt;&gt;choice4;\nif(choice4=='y')\n{\n re4=true;\n}\n if(re4=true)\n {\n roll4=getNum();\n drawDieForRoll(roll4);\n }//endif\n\ncout&lt;&lt;\"would you like to re-roll die 5 (y/n)\"&lt;&lt;endl;\ncin&gt;&gt;choice5;\nif(choice5=='y')\n{\n re5=true;\n}\n if(re5=true)\n {\n roll5=getNum();\n\n drawDieForRoll(roll5);\n }//endif\n\ncin&gt;&gt;selection;\nsystem(\"cls\");\n}while(selection=='y');\n\n}\n</code></pre>\n\n<p>This reduced the function from 365 lines down to 100 lines, not bad.</p>\n\n<p>Now we can see that the block asking to re-roll die X are basically also all the same except for the die number.</p>\n\n<p>Now let's store the value of the rolls in an array which holds one entry per die. And because this is C++ we are going to use a <code>std::vector&lt;int&gt;</code></p>\n\n<pre><code>const int NumberOfDice = 5;\n\nstd::vector&lt;int&gt; rolls(NumberOfDice);\n</code></pre>\n\n<p>Now you can use a nice loop to roll your dice and <code>diceRoll</code> can be further simplified into:</p>\n\n<pre><code>void diceRoll()\n{\n char selection='y';\n\n const int NumberOfDice = 5;\n std::vector&lt;int&gt; rolls(NumberOfDice);\n\n do {\n cout &lt;&lt; \"roll dice\" &lt;&lt; endl;\n\n for (int dieIndex = 0; dieIndex &lt; NumberOfDice; ++dieIndex)\n {\n int currentRoll = getRandomDieRoll();\n rolls[dieIndex] = currentRoll;\n\n drawDieForRoll(currentRoll);\n }\n\n for (int dieIndex = 0; dieIndex &lt; NumberOfDice; ++dieIndex)\n {\n char choice = ' ';\n cout &lt;&lt; \"would you like to re-roll die \" &lt;&lt; (dieIndex + 1) &lt;&lt; \" (y/n)\"&lt;&lt;endl;\n cin &gt;&gt; choice;\n if (choice == 'y')\n {\n int currentRoll = getRandomDieRoll();\n rolls[dieIndex] = currentRoll;\n drawDieForRoll(currentRoll);\n }\n }\n\n cin &gt;&gt; selection;\n system(\"cls\");\n } while (selection == 'y'); \n}\n</code></pre>\n\n<p>We just got rid of another 65 lines of code so we have removed 90% of all code from that function retaining the same functionality.</p>\n\n<p>The next step is to simplify your drawing functions. If you want to draw ASCII art then well, just draw it:</p>\n\n<pre><code>void drawDie1()\n{\n cout &lt;&lt; \"*********\\n\"\n &lt;&lt; \"* *\\n\"\n &lt;&lt; \"* X *\\n\"\n &lt;&lt; \"* *\\n\"\n &lt;&lt; \"*********\\n\";\n}\n\nvoid drawDie2()\n{\n cout &lt;&lt; *********\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; * *\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; *********\\n\";\n}\n\nvoid drawDie3()\n{\n cout &lt;&lt; *********\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; *********\\n\";\n}\n\nvoid drawDie4()\n{\n cout &lt;&lt; *********\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; * *\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; *********\\n\";\n}\n\nvoid drawDie5()\n{\n cout &lt;&lt; *********\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; * X *\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; *********\\n\";\n}\n\nvoid drawDie6()\n{\n cout &lt;&lt; *********\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; * X X *\\n\"\n &lt;&lt; *********\\n\";\n}\n</code></pre>\n\n<p>These changes will be removing another 130 lines of code and make it much nicer to read as well.</p>\n\n<p>Will all of the above the code is now about 80-90% shorter than before and it should be much easier to handle and add new functionality.</p>\n\n<p>Disclaimer: I haven't compiled it so there might be the one or other typo hidden but hopefully you should be able to get it to work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T03:15:05.747", "Id": "38874", "ParentId": "38847", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:31:24.527", "Id": "38847", "Score": "4", "Tags": [ "c++", "game", "dice" ], "Title": "Yahtzee game in C++" }
38847
<p>This thing kills me: </p> <pre><code> def report_subtitle case params[:kind] when 'position' then h("for Position: #{@current_company.positions.find_by_id(params[:id])}") when 'grade' then h("for Grade: #{params[:id]}") when 'location' then h("for Location: #{Location.find_by_id(params[:id])}") when 'department' then h("for Deparment: #{@current_company.departments.find_by_id(params[:id])}") when 'supervisor' then h("Employees who report to #{@employees.first.supervisor.full_name}") when 'eeoc' then h("for EEOC Code: #{params[:id]}") end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T22:40:30.913", "Id": "64966", "Score": "2", "body": "What does your view template look like? If the report subtitle has this many cases, I'd expect that this is just the tip of the iceberg." } ]
[ { "body": "<p>There are a few issues with this method:</p>\n\n<ul>\n<li>The parameter <code>kind</code> is not descriptive enough. Is this a kind of report? Is it <code>report_type</code>?</li>\n<li>You seem to be looking up a <code>Location</code>, <code>Position</code> and <code>Department</code> using the same id. I'm not sure this is possible, but if it is, you should rather use the relations rather than id-lookups.</li>\n<li>This method is trying to generate a report's subtitle, presumably in the controller. The conditional of the <code>case</code> statements should be replaced by polymorphism. Something like separate classes which all respond to the same method.</li>\n</ul>\n\n<p>I don't quite understand the context of your code, but aim for something like</p>\n\n<pre><code>class PositionReport\n # ...\n def subtitle\n end\nend\n\nclass GradeReport\n # ...\n def subtitle\n end\nend\n</code></pre>\n\n<p>Then you are reasoning about different report types, each of which handles it's own subtitles (and other logic).</p>\n\n<p>Just my two cents.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T07:51:03.070", "Id": "41858", "ParentId": "38858", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T22:11:18.063", "Id": "38858", "Score": "2", "Tags": [ "ruby-on-rails", "helper" ], "Title": "Horrible case statement for displaying a title" }
38858
<p>I'v written this code snippet that's part of a code competition. </p> <p>I want to do the trick without the for-loop, or simply find a way to optimize this code for speed. </p> <pre><code>for ( i=1; i&lt;=N; i++ ) </code></pre> <p>How is it possible, if it is? What do I need to modify to speed up this code considering a very large input file?</p> <p>Here is the competition summary:</p> <blockquote> <p>Players generally sit in a circle. The player designated to go first says the number "1", and each player thenceforth counts one number in turn. However, any number divisible by 'A' e.g. three is replaced by the word fizz and any divisible by 'B' e.g. five by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates or makes a mistake is either eliminated. </p> <p>Write a program that prints out the the pattern generated by such a scenario given the values of 'A'/'B' and 'N' which are read from an input text file. The input text file contains three space delimited numbers i.e. A, B, N. The program should then print out the final series of numbers using 'F' for fizz, 'B' for 'buzz' and 'FB' for fizz buzz.</p> <p>Print out the series 1 through N replacing numbers divisible by 'A' by F, numbers divisible by 'B' by B and numbers divisible by both as 'FB'. Since the input file contains multiple sets of values, your output will print out one line per set. Ensure that there are no trailing empty spaces on each line you print.</p> </blockquote> <p>Input file:</p> <pre><code>3 5 10 2 7 15 </code></pre> <p>Output:</p> <pre><code>1 2 F 4 B F 7 8 F B 1 F 3 F 5 F B F 9 F 11 F 13 FB 15 </code></pre> <p>Here my code:</p> <pre><code>int main(int argc, const char * argv[]) { NSString* filename = [NSString stringWithCString:argv[1] encoding:NSASCIIStringEncoding]; NSString* content = [NSString stringWithContentsOfFile:filename encoding:NSASCIIStringEncoding error:nil]; NSScanner* scanner = [NSScanner scannerWithString:content]; while ( ![scanner isAtEnd] ) { NSString* line; [scanner scanUpToString:@"\n" intoString:&amp;line]; NSArray *nums = [ line componentsSeparatedByString:@" " ]; int A = [[nums objectAtIndex:0] intValue]; int B = [[nums objectAtIndex:1] intValue]; int N = [[nums objectAtIndex:2] intValue]; int i=0; for ( i=1; i&lt;=N; i++ ) { NSString *str = [ NSString stringWithFormat:@"%d", i ]; if ( i%A == 0 ) str = @"F"; if ( i%B == 0 ) str = @"B"; if ( i%A == 0 &amp;&amp; i%B == 0 ) str = @"FB"; printf( "%s ", [str UTF8String] ); } printf("\n"); } return 0; } </code></pre>
[]
[ { "body": "<p>A compiler might unroll the loop for you. Try inspecting the assembly output when it is compiled at different optimization levels.</p>\n\n<p>As for the body of the loop, I'd keep the string manipulation to a minimum.</p>\n\n<pre><code>int AB = A * B;\nfor ( int i=1; i&lt;=N; i++ )\n{\n if ( i % AB == 0 ) printf(\"FB \");\n else if ( i % A == 0 ) printf(\"F \");\n else if ( i % B == 0 ) printf(\"B \");\n else printf(\"%d \", i);\n}\n</code></pre>\n\n<p>Also consider concatenating the output to be printed at once. It's likely that I/O is the bottleneck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:00:41.007", "Id": "64991", "Score": "1", "body": "`N` is not const value, so it is not possible for compiler to unroll the loop" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T01:13:36.677", "Id": "38867", "ParentId": "38859", "Score": "3" } }, { "body": "<p>The title of your post puts a lot of stress on removing the <code>for</code> loop. Can it be removed?</p>\n\n<p>No, it cannot. You need at least one loop to solve the fizz-buzz...</p>\n\n<p>Additionally, the 'print' statements are by far the largest bulk of your performance problem.</p>\n\n<p>I don't really believe that this code suffers from a problematic performance issue, but, if you want it to go faster, your best bet would be to accumulate all your String values and only print the line once:</p>\n\n<pre><code>NSMutableString* result;\n....\n\nfor (...) {\n .....\n [result appendString:@\"FB \"];\n .....\n [result appendFormat:@\"%d \", i];\n\n}\nprintf(result);\nprintf(\"\\n\");\n</code></pre>\n\n<p>This saves a fair number of unnecessary print statements, and your performance will improve as a result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T12:36:49.213", "Id": "40839", "ParentId": "38859", "Score": "5" } } ]
{ "AcceptedAnswerId": "38867", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T22:40:30.897", "Id": "38859", "Score": "0", "Tags": [ "optimization", "performance", "objective-c", "fizzbuzz" ], "Title": "How can I remove this for-loop in this competitive FizzBuzz code?" }
38859
<p>From <a href="https://codereview.stackexchange.com/questions/38371/avoiding-duplicate-boilerplate-code-in-wcf-service?noredirect=1#comment63990_38371">a previous question</a>, I got the idea of moving boilerplate code structures into a helper function and passing in a lambda function to it.</p> <p>I then applied the idea to a data access class (code below). I'm not sure how to handle the result of my <code>ProcessDatabaseCall</code> helper function; it seems irrelevant to my pattern of use-cases. In this example I'm returning an <code>IEnumerable</code>; in other cases I'm returning <code>int</code>, <code>School</code>, etc.</p> <pre><code> public IEnumerable&lt;School&gt; SchoolsList(string searchChars) { DataSet ds = new DataSet(); List&lt;School&gt; schools = new List&lt;School&gt;(); bool cool = ProcessDatabaseCall("dbo.usp_esrvs_API_SchoolList", cmd =&gt; { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars)); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return true; }); //Foreach row in the data set add a json array object foreach (DataRow row in ds.Tables[0].Rows) { schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString())); } return schools; } private bool ProcessDatabaseCall(string procedureName, Func&lt;SqlCommand,bool&gt; processor) { using (SqlConnection Mackin1Conn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(procedureName, Mackin1Conn)) { return processor(cmd); } } } </code></pre> <p>The function used to look like this:</p> <pre><code>public IEnumerable&lt;School&gt; SchoolsList(string searchChars) { DataSet ds = new DataSet(); List&lt;School&gt; schools = new List&lt;School&gt;(); using (SqlConnection Mackin1Conn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("dbo.usp_esrvs_API_SchoolList", Mackin1Conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars)); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } } foreach (DataRow row in ds.Tables[0].Rows) { schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString())); } return schools; } </code></pre>
[]
[ { "body": "<p>I'd say the best course of action is to make your <code>ProcessDatabaseCall</code> generic:</p>\n\n<pre><code>private T ProcessDatabaseCall&lt;T&gt;(string procedureName, Func&lt;SqlCommand, T&gt; processor)\n{\n using (SqlConnection Mackin1Conn = new SqlConnection(connectionString))\n {\n using (SqlCommand cmd = new SqlCommand(procedureName, Mackin1Conn))\n {\n return processor(cmd);\n }\n }\n}\n</code></pre>\n\n<p>Your <code>SchoolList</code> call then turns into:</p>\n\n<pre><code>public IEnumerable&lt;School&gt; SchoolsList(string searchChars)\n{ \n return ProcessDatabaseCall(\"dbo.usp_esrvs_API_SchoolList\", cmd =&gt; {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(new SqlParameter(\"@SearchValue\", searchChars));\n\n SqlDataAdapter da = new SqlDataAdapter(cmd);\n DataSet ds = new DataSet();\n da.Fill(ds);\n\n var schools = new List&lt;School&gt;();\n //Foreach row in the data set add a json array object\n foreach (DataRow row in ds.Tables[0].Rows)\n {\n schools.Add(new School((int) row[\"esrvs_Account_ID\"], row[\"SchoolName\"].ToString()));\n }\n return schools;\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T07:34:03.357", "Id": "38880", "ParentId": "38860", "Score": "2" } }, { "body": "<p>Just replace <code>Func</code> delegate with <code>Action</code> delegate if you don't want return value:</p>\n\n<pre><code>private void ExecuteCommand(string commandText, Action&lt;SqlCommand&gt; action)\n{\n using (var conn = new SqlConnection(connectionString)) \n using (var cmd = new SqlCommand(commandText, conn))\n action(cmd);\n}\n</code></pre>\n\n<p>Then getting schools will look like (with help of LINQ you can get rid of local list of schools):</p>\n\n<pre><code>public IEnumerable&lt;School&gt; GetSchools(string searchChars)\n{\n DataSet ds = new DataSet();\n\n ExecuteCommand(\"dbo.usp_esrvs_API_SchoolList\", cmd =&gt; {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(new SqlParameter(\"@SearchValue\", searchChars));\n SqlDataAdapter da = new SqlDataAdapter(cmd);\n da.Fill(ds);\n });\n\n return from row in ds.Tables[0].AsEnumerable()\n select new School(row.Field&lt;int&gt;(\"esrvs_Account_ID\"),\n row.Field&lt;string&gt;(\"SchoolName\"));\n}\n</code></pre>\n\n<p>NOTE: Consider to use <a href=\"http://code.google.com/p/dapper-dot-net/\" rel=\"nofollow\">Dapper</a> both methods above are equivalent to:</p>\n\n<pre><code>private IEnumerable&lt;School&gt; GetSchools(string searchChars)\n{\n using (var conn = new SqlConnection(connectionString)) \n return conn.Query&lt;School&gt;(\"dbo.usp_esrvs_API_SchoolList\",\n new { SearchValue = searchChars },\n commandType: CommandType.StoredProcedure);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T20:06:02.370", "Id": "65709", "Score": "1", "body": "I hadn't heard of the `Action` delegate before -- thanks for pointing it out!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T08:38:07.543", "Id": "38883", "ParentId": "38860", "Score": "4" } } ]
{ "AcceptedAnswerId": "38883", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T22:54:50.157", "Id": "38860", "Score": "2", "Tags": [ "c#", "lambda" ], "Title": "Unwanted return values in lambda functions?" }
38860
<p>Which style of printing strings from the SI registry in NASM is more correct?</p> <p>I'm learning assembly and x86 architecture, but I'm rather new in it, so I've prepared two styles (in NASM) of printing a string, which is held in the <code>SI</code> register.</p> <p>For a clear text, the samples are at the bottom of the question content. I also want you to provide me with some information about the correctness of the code style in ASM. The most significant place in both code for me is the loop for printing a char from the whole string, so I want you to tell me which variant is more correct (or maybe both variants are bad and you can provide me a much better sample).</p> <p>Both samples don't need an OS and could be run as *.img (floopy image) in virtual machine or with the <code>mkisofs</code> (or similar software) be prepared as *.iso (CD image). In these code samples - I'm working with the BIOS to print the string. </p> <p>Also, about code style. I don't know which style is more correct in ASM, for e.g. in the 1<sup>st</sup> variant I'm using the name of the functions like: <code>print_string</code>, but as for the 2<sup>nd</sup> variant, I'm using the style, which is closer to C# name style <code>PrintCharacter</code>, so which variant of naming is more suitable in ASM language?</p> <p>To compile in NASM, just use this syntax:</p> <pre><code>nasm -f bin -o file.img file.asm </code></pre> <p>The first one (<a href="http://pastebin.com/32mDPump" rel="nofollow">http://pastebin.com/32mDPump</a>):</p> <pre><code>[BITS 16] start: mov ax, 07C0h add ax, 288 mov ss, ax mov sp, 4096 mov ax, 07C0h mov ds, ax mov si, text_string call print_string jmp $ text_string db 'Hello World!', 0 print_string: mov ah, 0Eh .repeat: lodsb cmp al, 0 je .done int 10h jmp .repeat .done: ret times 510-($-$$) db 0 dw 0xAA55 </code></pre> <p>The second one (<a href="http://pastebin.com/FnP0NGTY" rel="nofollow">http://pastebin.com/FnP0NGTY</a>):</p> <pre><code>[BITS 16] mov si, HelloString call PrintString jmp $ PrintCharacter: mov ah, 0x0E mov bh, 0x00 mov bl, 0x07 int 0x10 ret PrintString: next_character: mov al, [si] inc si or al, al jz exit_function call PrintCharacter jmp next_character exit_function: ret HelloString db 'Hello World', 0 times 510-($-$$) db 0 dw 0xAA55 </code></pre>
[]
[ { "body": "<p>The two samples don't quite do the same thing. The first sample starts by setting the location of the stack and data segments to some 'magic' location in memory:</p>\n\n<pre><code>mov ax, 07C0h\nadd ax, 288\nmov ss, ax\nmov sp, 4096\nmov ax, 07C0h\nmov ds, ax\n</code></pre>\n\n<p>The second sample doesn't (so it will use the SS and DS locations which are left in those registers by the O/S which loaded the program). I don't understand what 07C0h is and why there is that difference between the two programs.</p>\n\n<p>Also the styles of assembly are different, for example one uses <code>0Eh</code> and the other uses <code>0x0E</code>. Are they both supported by NASM?</p>\n\n<hr>\n\n<p>The first sample ends with <code>jmp $</code> which I don't understand: does it mean \"jump to here\" i.e. \"infinite loop\"? The <code>.done: ret</code> label seems to be unreachable.</p>\n\n<p>The second sample ends with <code>exit_function: ret</code> which I guess returns to the O/S.</p>\n\n<hr>\n\n<blockquote>\n <p>The most significant place in both code for me is the loop for printing a char from the whole string, so I want you to tell me which variant is more correct (or maybe both variants are bad and you can provide me a much better sample).</p>\n</blockquote>\n\n<p>Your using BIOS int 10h which <a href=\"http://en.wikipedia.org/wiki/INT_10H\" rel=\"noreferrer\">Wikipedia says</a> is:</p>\n\n<pre><code>Teletype output AH=0Eh AL = Character, BH = Page Number, BL = Color (only in graphic mode)\n</code></pre>\n\n<p>The first sample doesn't initialize the BX register (so it may may contain a semi-random value), the second does. BX may or may not have an effect (in fact this whole \"BIOS Teletype output\" API may or may not work) depending on current the video mode.</p>\n\n<p>If you're interested in speed then the following algorithm can be much faster than using the BIOS interrupt:</p>\n\n<ul>\n<li>Set the right video mode</li>\n<li>Set registers (for example, es:di) to point to the main memory location which is shared with the video card (<a href=\"http://en.wikipedia.org/wiki/Conventional_memory\" rel=\"noreferrer\">perhaps 0xB0000</a> if I recall correctly)</li>\n<li>Write the character into video memory</li>\n</ul>\n\n<p>Or instead of writing characters the the BIOS one at a time, there's a BIOS API which lets you write an entire string. I copied the following from <a href=\"http://www.computing.dcu.ie/~ray/teaching/CA296/notes/8086_bios_and_dos_interrupts.html#int10h_13h\" rel=\"noreferrer\">8086 BIOS and DOS interrupts (IBM PC)</a>:</p>\n\n<pre><code>INT 10h / AH = 13h - write string.\n\ninput:\nAL = write mode:\n bit 0: update cursor after writing;\n bit 1: string contains attributes.\nBH = page number.\nBL = attribute if string contains only characters (bit 1 of AL is zero).\nCX = number of characters in string (attributes are not counted).\nDL,DH = column, row at which to start writing.\nES:BP points to string to be printed.\nexample:\nmov al, 1\nmov bh, 0\nmov bl, 0011_1011b\nmov cx, msg1end - offset msg1 ; calculate message size. \nmov dl, 10\nmov dh, 7\npush cs\npop es\nmov bp, offset msg1\nmov ah, 13h\nint 10h\njmp msg1end\nmsg1 db \" hello, world! \"\nmsg1end:\n</code></pre>\n\n<p>As for your print loops:</p>\n\n<pre><code>print_string:\n mov ah, 0Eh\n\n.repeat:\n lodsb\n cmp al, 0\n je .done\n int 10h \n jmp .repeat\n</code></pre>\n\n<p>The first one (above) looks tight: i.e. it's good and short, with the <code>mov ah, 0Eh</code> performed once outside the loop. <code>lodsb</code> doesn't affect flags, so the separate <code>cmp</code> is necessary. There may be a faster way to compare <code>al</code> with 0, perhaps something like <code>or al,al</code>.</p>\n\n<p>I don't have a BIOS reference manual, but one thing it's lacking is a check of the 'return code' to see whether the output might have failed. <a href=\"http://wiki.osdev.org/BIOS#ASM_notes\" rel=\"noreferrer\">This</a> suggests that if the call fails it might leave a return code in <code>ah</code>. You want your <code>ah</code> preserved, so you might want to check that at least the first one didn't fail, and then have a loop which assumes that subsequent won't fail.</p>\n\n<p>If your string weren't null-terminated, if instead you knew the length of it ...</p>\n\n<pre><code>HelloString:\ndw 0bh\ndb 'Hello World'\n</code></pre>\n\n<p>... then you could load the length into <code>cx</code> and use the <code>loop</code> instruction, something like:</p>\n\n<pre><code>mov si, HelloString\nlodsw\nmov cx,ax\nmov ah,0eh\n.repeat:\nlodsb\nint 10h \nloop .repeat\n; .done:\nret\n</code></pre>\n\n<p>Beware that the above may not be the fastest way to loop, anymore. I once read that the more complicated opcodes (like <code>loop</code>) perform more slowly on modern CPUs than using several primitive instructions (e.g. <code>dec cx</code> and <code>jnz</code>). The reason for that is that a developer (or compiler) will choose and place those more primitive opcodes in such as way as to <a href=\"http://en.wikipedia.org/wiki/Instruction_pipeline#Hazards\" rel=\"noreferrer\">use both pipelines and not cause a stall</a>. Writing assembly which keeps both pipelines busy is an advanced art (which, they try to build-in to compilers). If I look at the output from a compiler, I hardly recognize it any more! Because, it often uses several instructions instead of one or two. Nevertheless I think that the loop above is compact and idiomatic (if you're writing code for another programmer to read, not writing code in order use every last CPU cycle).</p>\n\n<p>The second one doesn't seem to be optimized for size or speed:</p>\n\n<pre><code>PrintCharacter:\n mov ah, 0x0E\n mov bh, 0x00\n mov bl, 0x07\n int 0x10\n ret\n\nPrintString:\n next_character:\n mov al, [si]\n inc si\n or al, al\n jz exit_function\n call PrintCharacter\n jmp next_character\n exit_function:\n ret\n</code></pre>\n\n<ul>\n<li>Why not use <code>lodsb</code> instead of <code>mov al, [si]</code> and <code>inc si</code>?</li>\n<li>Why set <code>bl</code> and <code>bh</code> instead of setting <code>bx</code>?</li>\n<li>Why not set <code>bx</code> and <code>ah</code> before the loop begins (I think that a call to <code>int 10h</code> should preserve the contents of the <code>bx</code> register?</li>\n<li>Why make <code>PrintCharacter</code> a subroutine to be called, instead of including those instructions inline?</li>\n</ul>\n\n<blockquote>\n <p>Also, about code style. I don't know which style is more correct in ASM, for e.g. in the 1st variant I'm using the name of the functions like: print_string, but as for the 2nd variant, I'm using the style, which is closer to C# name style PrintCharacter, so which variant of naming is more suitable in ASM language?</p>\n</blockquote>\n\n<p>The NASM manual seems to use naming conventions more like <code>print_string</code>. <a href=\"http://www.nasm.us/doc/nasmdoc9.html#section-9.1.1\" rel=\"noreferrer\">Chapter 9</a> talks about writing assembly called from high-level languages. Names of HLL functions are subject to <a href=\"http://en.wikipedia.org/wiki/Name_mangling\" rel=\"noreferrer\">name mangling</a> so if you want to write the C <code>printf</code> function in assembly you might need to call it <code>_printf</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-27T16:51:04.703", "Id": "398163", "Score": "0", "body": "Quick note: I don't know enough about assembly to know whether it's always a bug, but the `push cs` in the `AH = 13h` example should be `push ss` when you're calling assembly from C. With Open Watcom C/C++, it'll work when building a `.com`, but output garbage when you build a `.exe` with a memory model where `cs=ss` is not longer true. (`cs` = \"code segment\" and `ss` = \"stack segment\", for people who are unaware.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T01:43:28.267", "Id": "39626", "ParentId": "38861", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:23:40.740", "Id": "38861", "Score": "9", "Tags": [ "strings", "beginner", "assembly" ], "Title": "Iterating string characters and passing them to a BIOS API" }
38861
<p>I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?</p> <p>Example:</p> <blockquote> <p>str = "happy" substr = "app"</p> <p>index = 1</p> </blockquote> <p>My code:</p> <pre><code>public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen &lt; 1) { return index; } else { for (int i = 0; i &lt; strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:14:02.980", "Id": "64980", "Score": "0", "body": "You can simplify that a great deal by not reassigning index at each step" } ]
[ { "body": "<p>Just checking that you intend to be <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged &#39;reinventing-the-wheel&#39;\" rel=\"tag\">reinventing-the-wheel</a>, you can do:</p>\n\n<pre><code>System.out.println(\"happy\".indexOf(\"app\"));\n</code></pre>\n\n<p>You did know that, right?</p>\n\n<p>Or, if you want to reformat the 'signature' to match yours, it is:</p>\n\n<pre><code>public static int subStringIndex(String str, String substr) {\n return str.indexOf(substr);\n}\n</code></pre>\n\n<p>There are a number of helper methods on String which will help:</p>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String%29\" rel=\"noreferrer\">String.indexOf(substr)</a> - return the index of the first occurrence of substr</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String,%20int%29\" rel=\"noreferrer\">String.indexOf(substr, start)</a> - return the index of the first occurrence of substr on or after the start position.</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String%29\" rel=\"noreferrer\">String.lastIndexOf(substr)</a> - return the index of the last occurrence of substr</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String,%20int%29\" rel=\"noreferrer\">String.lastIndexOf(substr, start)</a> - return the index of the last occurrence of substr starting <strong>before</strong> the start position.</li>\n - \n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T03:30:08.230", "Id": "64985", "Score": "0", "body": "I know there is a built in function but I wanted to solve the problem without it but thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:14:09.183", "Id": "38871", "ParentId": "38870", "Score": "7" } }, { "body": "<p>You can get away without the <code>index</code> variable as you're reassigning it at each step of your loop anyway.</p>\n\n<pre><code>public static int subStringIndex(String str, String substr) {\n int substrlen = substr.length();\n int strlen = str.length();\n int j = 0;\n\n if (substrlen &gt;= 1) {\n for (int i = 0; i &lt; strlen; i++) { // iterate through main string\n if (str.charAt(i) == substr.charAt(j)) { // check substring\n j++; // iterate\n if (j == substrlen) { // when to stop\n return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen\n }\n }\n else {\n j = 0;\n }\n }\n }\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T03:31:48.600", "Id": "64986", "Score": "0", "body": "Thanks! did not see this! much appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T02:15:28.017", "Id": "38872", "ParentId": "38870", "Score": "4" } }, { "body": "<p>Actually there is a bug. Consider <code>str=\"aaS\"</code> and <code>substr=\"aS\"</code>.\nAt first iteration <code>a</code> and <code>a</code> are equal.\nAt second iteration <code>a</code> and <code>S</code> are not equal, and it will skip it, however <code>substr</code>'s first character is equal to it.</p>\n\n<p>So it should be:</p>\n\n<pre><code>public static int subStringIndex(String str, String substr) {\n int substrlen = substr.length();\n int strlen = str.length();\n int j = 0;\n\n if (substrlen &gt;= 1) {\n for (int i = 0; i &lt; strlen; i++) { // iterate through main string\n if (str.charAt(i) == substr.charAt(j)) { // check substring\n j++; // iterate\n if (j == substrlen) { // when to stop\n return i - (substrlen - 1); //found substring. As i is currently at the end of our substr so sub substrlen\n }\n }\n else {\n i -= j;\n j = 0;\n }\n }\n }\n return -1;\n}\n</code></pre>\n\n<p><strong>Edit update:</strong></p>\n\n<p>Needed to subtract 1 from the String's length in order to pass the right answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-16T13:32:39.950", "Id": "163460", "ParentId": "38870", "Score": "1" } }, { "body": "<p>Here is another version: </p>\n\n<pre><code>public static int indexOf(String original, String find) {\n\n if (find.length() &lt; 1)\n return -1;\n\n boolean flag = false;\n for (int i = 0, k = 0; i &lt; original.length(); i++) {\n if (original.charAt(i) == find.charAt(k)) {\n k++;\n flag = true;\n if (k == find.length())\n return i - k + 1;\n } else {\n k = 0;\n if (flag) {\n i--;\n flag = false;\n }\n }\n }\n\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-02T19:34:39.177", "Id": "356071", "Score": "0", "body": "This is called a \"code dump\" some explanation of your changes would improve this answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-02T17:27:58.367", "Id": "186622", "ParentId": "38870", "Score": "0" } }, { "body": "<p>My re-writing: clear and clean, yet efficient. There is no innovation in the algorithm. Just the way of the coding in more structural re-arrangement, trying to make the thought and steps easy to read and understand (comments are welcome):</p>\n\n<pre><code>static int subStringIndex( String str, String substring) {\n if (substring.length() &lt; 1 )\n return -1;\n\n int L = str.length();\n int l = substring.length();\n int index = -1;\n\n for (int i = 0, j; i &lt;= L-l; i++) {\n // if the remaining (L-i) is smaller than l, \n // there won't be no enough length to contain the substring.\n for (j = 0; j &lt; l; j++) {\n if (substring.charAt(j) != str.charAt(i+j) ) {\n break;\n } \n }\n // has it reached the end of the shorter string? \n // if so, it means no non-equals encountered.\n if (j == l) {\n index = i;\n break;\n }\n }\n\n return index;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T06:06:39.920", "Id": "366636", "Score": "2", "body": "Welcome. Please if this is a different version as you say, then edit your answer to explain why it is better than the OP's one" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T05:48:02.007", "Id": "191043", "ParentId": "38870", "Score": "-2" } } ]
{ "AcceptedAnswerId": "38872", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T01:58:48.963", "Id": "38870", "Score": "6", "Tags": [ "java", "performance", "strings", "reinventing-the-wheel" ], "Title": "Finding index of first substring" }
38870
<p>I'm looking for a review paying special attention as to whether the code can be optimized in the form of number of variables used, especially for the <code>delete()</code> method.</p> <pre><code>public class circularLL { Node start; Node last; circularLL() { start=null; last=null; } class Node { int data; Node next; Node(int datanew) { data=datanew; } public void setNext(Node n) { next=n; } public Node getNext() { return next; } public void setData(int datanew) { data=datanew; } public int getData() { return data; } } public void insert(int datanew) { Node p=new Node(datanew); if(start==null) { start=p; last=p; p.setNext(p); } else { last.setNext(p); last=last.getNext(); last.setNext(start); } } public void delete(int datanew) { Node temp=start; Node temp1=start; Node previous=null; Node previous1=null; if(last.getData()==datanew) { while(temp1.getData()!=datanew) { previous1=temp1; temp1=temp1.getNext(); } previous1.setNext(temp.getNext()); last=previous1; } while(temp.getData()!=datanew) { previous=temp; temp=temp.getNext(); } previous.setNext(temp.getNext()); } public void display() { int count = 0; if(start == null) { System.out.println("\n List is empty !!"); } else { Node temp = start; while(temp.getNext() != last) { System.out.println("count("+count+") , node value="+temp.getData()); count++; temp = temp.getNext(); } System.out.println("count("+count+") , node value="+temp.getData()); } } public static void main(String args[]) { circularLL ll=new circularLL(); ll.insert(40); ll.insert(20); ll.insert(22); ll.insert(15); ll.insert(16); ll.insert(35); ll.insert(40); ll.insert(38); ll.delete(22); ll.display(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T15:37:17.383", "Id": "137009", "Score": "0", "body": "You would get more reviews if you provide more information about this piece of code." } ]
[ { "body": "<p>I'm not a big algorithms/data structures guy, but the only thing that caught my attention was the <code>delete</code> function. Is there a reason that <code>delete</code> uses data to identify the node, as opposed to just taking in the <code>Node</code> object you want to delete? It seems like that could get hairy if two nodes have the same data (which happens in <code>main</code>).</p>\n\n<p>Besides that, there are a few comments I have in general about the code. Most of the following is fairly standard code format type stuff, but I think it's worth saying it as many times as possible.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>It's fairly minor, it helps to make sure there's an empty line between methods.</p>\n\n<p>Also, I know some feel differently, but my preference about operators is that they have spaces on either side. <code>data=datanew</code> vs <code>data = datanew</code>.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>In Java, the convention is that class names start with a capital letter, so <code>circularLL</code> should be <code>CircularLL</code>. Even better, it should really be something more descriptive like <code>CircularLinkedList</code>.</p>\n\n<p>Besides that, names of methods, members, variables, etc should follow lowerCamelCase. So, <code>datanew</code> becomes <code>dataNew</code>, but I would personally call it <code>newData</code>.</p>\n\n<p>In <code>delete</code>, avoid variable names like <code>temp1</code> and <code>previous1</code>. With the number of variables and how they're named, you're starting to enter mental-juggling territory. What I mean by that is that as I read through the code, I have to keep reading back through the code to remember what a variable does because its name isn't descriptive enough.</p>\n\n<p><strong>Etc</strong></p>\n\n<p>I don't have too much else to say, but I would consider breaking this code out into two or three files. I would make a new class with <code>main</code> to separate the linked list from what's using it, and I might put <code>Node</code> in its own class.</p>\n\n<p>Sorry I couldn't help out more with the efficiency/number of variables issue, but you don't seem to be doing anything too crazy, and like I said before, data structures and algorithms aren't my strong suit. Just thought I'd throw in my two cents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:34:55.403", "Id": "64994", "Score": "0", "body": "Oh, just saw that you indented it, I'll take that out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T19:31:24.250", "Id": "103084", "Score": "0", "body": "+1 for formatting. The code looks closer to C code instead of java. While old, the code conventions from Sun is pretty widely accepted: http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:34:37.697", "Id": "38878", "ParentId": "38876", "Score": "11" } }, { "body": "<p>Generics would be quite useful here, because your <code>List</code> only works with <code>integers</code>, so your classes could be reworked to take type parameters </p>\n\n<pre><code> public class CircularLL&lt;T&gt;{\n\n Node&lt;T&gt; start;\n Node&lt;T&gt; last;\n\n class Node&lt;T&gt;{\n T data;\n public void setData(T datanew)\n {\n data= datanew;\n }\n public T getData()\n {\n return data;\n }\n ....\n }\n\n}\n</code></pre>\n\n<p>and now you create Lists of different types.</p>\n\n<pre><code> CircularLL&lt;Integer&gt; list = new CircularLL&lt;Integer&gt;();\n CircularLL&lt;String&gt; list = new CircularLL&lt;String&gt;();\n</code></pre>\n\n<p>in Java 7 you got type <code>inference</code> </p>\n\n<pre><code> CircularLL&lt;Integer&gt; list = new CircularLL&lt;&gt;();\n</code></pre>\n\n<p>Please note, that CircularLL is not the best name for this class, I would call it <code>CircularLinkedList</code> instead.</p>\n\n<p>One more thing, initialising instance variables to <code>null</code> is useless because it's done by default. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T18:20:22.480", "Id": "57598", "ParentId": "38876", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:05:36.207", "Id": "38876", "Score": "5", "Tags": [ "java", "optimization", "linked-list", "circular-list" ], "Title": "Circular linked list of integers" }
38876
<p>I have a text file that contains <code>name</code>, <code>age</code>, <code>salary</code>, <code>hoursWorked</code>, <code>randomText</code> and are filled with different delimiters.</p> <p>Text file:</p> <pre><code>susan:25-2600,28[asd] mary:21-2200,38[asd] john:23-3400,46[asd] </code></pre> <p>Instead of breaking them into individual strings using the code shown below:</p> <pre><code>string name,age,salary,hoursWorked,randomText; ifstream readFile("textfile.txt"); while(getline(readFile,line)) { stringstream iss(line); getline(iss, name, ':'); getline(iss, age, '-'); getline(iss, salary, ','); getline(iss, hoursWorked, '['); getline(iss, randomText, ']'); } readFile.close(); </code></pre> <p>What are some better strategies other than coding it this way?</p> <p><strong>Side note</strong> </p> <p>I declared all the variables to strings because of the <code>getline()</code> method. </p>
[]
[ { "body": "<p>I would create a class and define an input operator:</p>\n\n<pre><code>struct Person\n{\n std::string name;\n std::string age;\n std::string salary;\n std::string hoursWorked;\n std::string randomText;\n\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; str, Person&amp; data)\n {\n std::string line;\n Person tmp;\n if (std::getline(str,line))\n {\n std::stringstream iss(line);\n if ( std::getline(iss, tmp.name, ':') &amp;&amp; \n std::getline(iss, tmp.age, '-') &amp;&amp;\n std::getline(iss, tmp.salary, ',') &amp;&amp;\n std::getline(iss, tmp.hoursWorked, '[') &amp;&amp;\n std::getline(iss, tmp.randomText, ']'))\n {\n /* OK: All read operations worked */\n data.swap(tmp); // C++03 as this answer was written a long time ago.\n }\n else\n {\n // One operation failed.\n // So set the state on the main stream\n // to indicate failure.\n str.setstate(std::ios::failbit);\n }\n }\n return str;\n }\n void swap(Person&amp; other) throws() // C++03 as this answer was written a long time ago.\n {\n swap(name, other.name);\n swap(age, other.age);\n swap(salary, other.salary);\n swap(hoursWorked, other.hoursWorked);\n swap(randomText, other.randomText)\n }\n};\n</code></pre>\n\n<p>Now your code looks like this:</p>\n\n<pre><code>Person data;\nwhile(readFile &gt;&gt; data)\n{\n // Do Stuff\n}\n</code></pre>\n\n<p>PS. I noticed you were using <code>string</code> and <code>ifstream</code> without the <code>std::</code>. This suggests you have <code>using namespace std;</code> in your code. Please don't do that. see <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n\n<p>Don't explictly <code>close()</code> a file unless you are going to check that it worked (or are going the re-open). Prefer to let the destructor do the closing (that way it is exception safe). See: <a href=\"https://codereview.stackexchange.com/q/540/507\">My C++ code involving an fstream failed review</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:37:54.063", "Id": "79158", "Score": "0", "body": "In the operator>> definition I needed to add the class before the member variables (e.g. data.name, data.age) in the getline calls for this to compile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T14:45:39.123", "Id": "79172", "Score": "0", "body": "@user39469: Sorry. Fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:01:51.983", "Id": "79174", "Score": "0", "body": "Nice. The only thing I would change: I would use a local `Person tmp;` instance, and in the `if` code block (the \"OK: All read operations worked\" part) I would write `data = std::move(tmp);` (or `std::swap(data, tmp);`).. This way, you avoid the case when the stream doesn't actually contain a valid person (in that case, if one of the getline calls fails, `data` will not be partially filled with garbage)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T00:31:11.947", "Id": "38954", "ParentId": "38879", "Score": "15" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T05:58:40.180", "Id": "38879", "Score": "12", "Tags": [ "c++", "parsing" ], "Title": "Parsing text file in C++" }
38879
<p>To catch errors, I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node.</p> <pre><code> async.waterfall([ function(callback){ fnOne.GetOne(req, res,function(err,result) { if(err){ console.error("Controller : fnOne",err); callback(err,null); } else{ var fnOne = result; callback(null, fnOne); } }) }, function(fnOne, callback){ fnTwo.two(fnOne,function(err,result) { if(err) { console.error(err); callback(err,null); } else{ callback(null, context); } }) } ], function (err, result) { if(err){ console.error("Controller waterfall Error" , err); res.send("Error in serving request."); } }); </code></pre>
[]
[ { "body": "<p>Check out <a href=\"http://www.html5rocks.com/en/tutorials/es6/promises/\" rel=\"nofollow\">promises</a>. They are not (yet) available natively in Node.js, but you can use <a href=\"https://github.com/kriskowal/q\" rel=\"nofollow\">Q library</a>.</p>\n\n<p>Promises allow you to make your control flow explicit with methods like <code>catch</code> and <code>finally</code> instead of hiding it in callbacks.</p>\n\n<p>Also you won't need <code>async</code> with promises.</p>\n\n<p>Q provides a convenience method to “convert” a function that accepts a callback to a promise-returning function.</p>\n\n<p>I don't understand what <code>fnOne</code> or <code>fnTwo</code> is your code (seemingly objects and not functions), so I can't really translate your example, but it would look similar to this:</p>\n\n<pre><code>var Q = require('q');\n\n// Convert our functions to promise-returning functions\nvar getOne = Q.nbind(fnOne.GetOne, fnOne),\n getTwo = Q.nbind(fnTwo.two, fnTwo) ;\n\ngetOne(req, res)\n .then(function (result) {\n return getTwo(result);\n })\n .then(function (result) {\n // do something useful with final result\n })\n .catch(function (err) {\n console.error(\"Three was an error\", err); \n res.send(\"Error in serving request.\");\n })\n .done();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:32:28.060", "Id": "38905", "ParentId": "38884", "Score": "2" } } ]
{ "AcceptedAnswerId": "38905", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T08:52:53.343", "Id": "38884", "Score": "1", "Tags": [ "javascript", "node.js", "asynchronous" ], "Title": "Best way to handle the error in async node" }
38884
<p>I am thinking about passing a private variable of one class into another class, for some belonging case like 'company --> department --> employee'. As an employee can tell some information of his company, there's some private variables I'd like to pass.</p> <p>I think this relationship is not as same as common class and supClass. As an employee is not a type of department and a department is not a type of company (if I am wrong, please tell me more).</p> <p>So in a case like this, is it a good idea to use nested constructor functions?</p> <p>For example: <a href="http://jsfiddle.net/JsJJ9/" rel="nofollow">http://jsfiddle.net/JsJJ9/</a></p> <pre><code>function TeamClass(name){ var pass = "privateVariable" var slot = 1; this.members = []; // I have a list of members this.name = name; this.add = function(){ //add member into this team var m = new MemberClass(slot++); this.members.push(m) } function MemberClass(id){ //here comes the Nested class var id = id; this.report = function(){ alert('#'+id+' : Hello, i got some '+pass+'! ') //So, this member can tell some private data of his team. } } } class01 = new TeamClass('Team A'); class01.add(); class01.add(); class01.members[0].report(); class01.members[1].report(); </code></pre> <p>Also, I have tried to let the nested class can call the upper level's public variable. I have a function like this:</p> <pre><code>//at upper level class m.setBelonging(this) </code></pre> <p>and</p> <pre><code>//at belonging class var team = '' this.setBelonging = function(theOdj){ team = theOdj; } </code></pre> <p>(or see it at <a href="http://jsfiddle.net/JsJJ9/1/" rel="nofollow">http://jsfiddle.net/JsJJ9/1/</a>)</p> <p>Any comment about this approach?</p> <hr> <p>Added at 2014-01-11 :</p> <p>Actually, I am trying to ask how can I pass some variable that can't change outside the class (which in my understand, a private variable) to another class. And i found out may be i can do this by nested class. But I don't know is there any defects or there's some better approach.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:01:44.173", "Id": "65085", "Score": "0", "body": "This works well, you might get fed up with `this.` after a while, at that point you can look into IIFEs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:35:21.653", "Id": "65098", "Score": "1", "body": "`var pass = \"privateVariable\"` appears to be a placeholder. Could you put the real code in the question so that we can better understand your intention? It's hard to give advice for hypothetical situations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T08:26:51.777", "Id": "65310", "Score": "0", "body": "I am just new to OOP and I just meet the question while I am studying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T08:37:52.760", "Id": "65311", "Score": "0", "body": "Actually, I am trying to ask how can I pass some variable that can't change outside the class (which in my understand, a private variable) to another class. And i found out may be i can do this by nested class. But I don't know is there any defects or there's some better approach." } ]
[ { "body": "<p>Ideally, how you choose to represent the members inside <code>TeamClass</code> shouldn't matter to the outside world. Your solution is fine, but I think I'd get tired of accessing the members like this:</p>\n\n<pre><code>class01.members[0].report();\n</code></pre>\n\n<p>It's a bit cumbersome. Plus, why should I care that the members are in some array held by <code>TeamClass</code>? In fact, do I need to care about <code>MemberClass</code> at all? Why not further abstract it:</p>\n\n<pre><code>function TeamClass(name) {\n var pass = \"privateVariable\"\n var slot = 1;\n var members = [];\n this.name = name;\n\n this.add = function() {\n var m = new MemberClass(slot++);\n members.push(m)\n }\n\n this.memberReport = function(i) {\n if (i &gt;= members.length) {\n throw \"Invalid member index\";\n }\n members[i].report();\n }\n\n function MemberClass(id) { \n var id = id;\n this.report = function() {\n console.log('#' + id + ' : Hello, i got some ' + pass + '! ')\n }\n }\n}\n\nclass01 = new TeamClass('Team A');\nclass01.add();\nclass01.add();\nclass01.memberReport(0);\nclass01.memberReport(1);\n</code></pre>\n\n<p>Of course, it's hard to tell out of context if this is really the best solution to <em>your</em> problem, but it's something to consider.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T08:20:12.077", "Id": "65309", "Score": "0", "body": "I am new to OOP, and i am quiet confused. I'd like to know is it a better practice to put all the function related to \"member\" into MemberClass ?\nBecause in this example is only 2-levels nested, what if a have a ArmyClass to warp TeamClass ?\nAlso, It's so hard to find information about 'Passing private variable' of javascript , It is a unusual solution that I should avoid ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:07:42.707", "Id": "38921", "ParentId": "38885", "Score": "1" } }, { "body": "<p>Teams have members, so it almost seems natural to put the <code>Member</code> class into the <code>Team</code> class. But projects also have members. How are you going to implement that? You can't nest <code>Member</code> in both classes. Another problem with nested classes is that you have to traverse through Company -> Department -> Team -> Employee hierarchy just to get everyone's name or email.</p>\n\n<p>Answering your question, how can you pass some variable that can't change outside of the class. Create a getter method:</p>\n\n<pre><code>function Team() {\n var teamId = 4; // not changeable from outside\n this.getId = function() {\n return teamId;\n }\n}\n</code></pre>\n\n<p>Now you can access <code>teamId</code> from outside of the class, but can't change it.</p>\n\n<p>Or instead of creating truly private properties and functions, you can simply prefix them with an underscore to denote they are private and should never be accessed from outside. While nothing really stops you from accessing them, nothing also stops you from redefining the <code>Team</code> class and accessing anything you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T17:56:51.583", "Id": "39056", "ParentId": "38885", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T08:59:17.410", "Id": "38885", "Score": "1", "Tags": [ "javascript", "classes" ], "Title": "Passing private variable in JavaScript nested class?" }
38885
<p>I currently have a basic application that has a database backing it. I originally connected to the database with Entity Framework, but my tutor has requested from me to recreate the functionality with ADO.NET SQL. This has gone well so far using the <code>SqlDataReader</code>, however I have come across a problem.</p> <p>My database stores a list of animals, the animals are <code>Dog</code>, <code>Cat</code> and <code>Mouse</code>, they all inherit from the <code>Animal</code> class. With entity framework when I wanted to get an animal from the database, it used the discriminator column automatically and I didn't have to worry about any logic to detect what type of animal the animal was. However so far the only way I can think of doing this with SQL is to manually check the discriminator column.</p> <p>This works well for the moment but if I start adding say a hundred animals, it will become an impossible task to keep it working efficiently. My question is, is there another way to do this which is more elegant and will scale appropriately? The code for how I currently do the task is below:</p> <pre><code>if (reader.HasRows) { while (reader.Read()) { if (reader.GetString(3) == "Dog") { list.Add( new Dog() { AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")), Name = (string)reader.GetString(reader.GetOrdinal("Name")), Age = (int)reader.GetInt32(reader.GetOrdinal("Age")), }); } if (reader.GetString(3) == "Cat") { list.Add( new Cat() { AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")), Name = (string)reader.GetString(reader.GetOrdinal("Name")), Age = (int)reader.GetInt32(reader.GetOrdinal("Age")), }); } if (reader.GetString(3) == "Mouse") { list.Add( new Mouse() { AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")), Name = (string)reader.GetString(reader.GetOrdinal("Name")), Age = (int)reader.GetInt32(reader.GetOrdinal("Age")), }); } } } else { //no rows } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:12:31.150", "Id": "65010", "Score": "1", "body": "Could animals have properties, that extend base class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:13:38.420", "Id": "65011", "Score": "0", "body": "No, the only real difference is the name." } ]
[ { "body": "<p>Here is your code refactored - since all animals have id, name and age, you can remove duplication (reading and setting these properties for each type of animal):</p>\n\n<pre><code>if (reader.HasRows)\n{\n while (reader.Read())\n {\n string animalType = reader.GetString(3);\n\n Animal animal = CreateAnimal(animalType);\n animal.AnimalID = (int)reader[\"AnimalID\"];\n animal.Name = (string)reader[\"Name\"];\n animal.Age = (int)reader[\"Age\"]; \n list.Add(animal); \n }\n}\n</code></pre>\n\n<p>Animal creation (if you are using type name as discriminator you can even use <a href=\"http://msdn.microsoft.com/en-us/library/system.activator%28v=vs.110%29.aspx\">Activator.CreateInstance</a> instead of this switch to create an instance of class):</p>\n\n<pre><code>private Animal CreateAnimal(string animalType)\n{\n switch(animalType)\n {\n case \"Dog\": return new Dog();\n case \"Cat\": return new Cat(); \n case \"Mouse\": return new Mouse(); \n default:\n throw new ArgumentException();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:11:01.767", "Id": "38887", "ParentId": "38886", "Score": "5" } } ]
{ "AcceptedAnswerId": "38887", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:07:25.423", "Id": "38886", "Score": "5", "Tags": [ "c#", "homework", "ado.net" ], "Title": "Build object from database without a discriminator column?" }
38886
<p>I am pretty new to Python and just wanted to make sure I am going in the right direction with my coding style.</p> <p>After reading <a href="http://dirtsimple.org/2004/12/python-is-not-java.html" rel="nofollow">this</a>, I'm not so sure.</p> <p>The following is a convenience class that has operations used a lot in my main code.</p> <pre><code>import requests try: import simplejson as json except ImportError: import json """ Basic operations involving users """ #The URL of the API api_root = "http://api.stuff.com/v1/core"; class UserOperations(object): def __init__(self, headers): self.headers = headers def move_user(self,source_account,destination_account, user_id): user_id = str(user_id) #Get user user = self.get_user(source_account, user_id) if user is not None: #Remove user from source account self.remove_user(source_account, user_id) #Add user to destination account self.add_user(destination_account, user) def get_user(self, account_id, user_id): #Get user user = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers) #Throw exception if non-200 response user.raise_for_status() print "\nGet User " + user_id + ": " + user.text #Check user exists if user.json()['Data'] is None: return None #Return user return user.json()['Data'] def remove_user(self,account_id, user_id): #Delete a user result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers) #Throw exception if non-200 response result.raise_for_status() #Result of delete operation print "\nDelete Result " + result.text def add_user(self,account_id, user): #Add user to new account result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers) #Throw exception if non-200 response result.raise_for_status() #Result of add operation print "\nAdd User: " + result.text </code></pre> <p>Does this seem on the right track or are there any Python mantra's I'm missing out on.</p> <p><strong>Edit</strong></p> <p>Function to replace below code duplication</p> <pre><code>variable = requests.get(api_root + "/accounts/"....) variable.raise_for_status() </code></pre> <p>Function:</p> <pre><code>def request(self, request, account_id, user): if request is 'get': #Get user result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers) elif request is 'post': #Add user to new account result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers) elif request is 'delete': #Delete user from account result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers) #Throw exception if non-200 response result.raise_for_status() return result </code></pre> <p><strong>Edit</strong> Function attempt 2:</p> <pre><code>def request(self, request, account_id, user): function_dict = {} function_dict['get'] = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers) function_dict['post'] = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers) function_dict['delete'] = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers) result = function_dict.get(request) #Throw exception if non-200 response result.raise_for_status() return result </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:40:20.763", "Id": "65057", "Score": "0", "body": "Ugh, if..elif..elif That's a bad smell. Use a dictionary to map the request verb to the appropriate function. Raise an exception if there is no key in the dictionary to match the request method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:52:53.650", "Id": "65062", "Score": "0", "body": "Updated question, is this any cleaner?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:00:12.253", "Id": "65064", "Score": "0", "body": "Some. But now look at those three lines where you define the functions to go in the dictionary; see how much duplication there is. You shouldn't be retyping almost the same thing again and again. The OO solution (you being an alleged Java geek) would be to create a request object that knows how to construct a basic request and uri, and specialisations thereof which can fill in the blanks for a particular verb. Those objects could go into a dictionary and their methods called as necessary. I'm sure there are more idiomatic alternatives that also avoid the duplication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:32:02.250", "Id": "65097", "Score": "0", "body": "Right I tried a couple of things but keep ending up with my second example, any chance you could shed some light on this mysterious enigma?" } ]
[ { "body": "<ol>\n<li><p>Unlike in Java, not everything in Python needs to be a class. In Python we tend to reserve classes for representing <em>things</em> with individual state and common behaviour. If you just want to group some functions together, you can put them in a <em>module</em>.</p></li>\n<li><p>You have no documentation. What do these functions do and how am I supposed to call them? In Python you should give every public class, function and method a <em>docstring</em>.</p></li>\n<li><p>Why do you try importing <a href=\"https://pypi.python.org/pypi/simplejson/\" rel=\"nofollow\"><code>simplejson</code></a>? This is just the externally maintained version of the built-in <a href=\"http://docs.python.org/2/library/json.html\" rel=\"nofollow\"><code>json</code></a> module. You don't seem to use any <code>simplejson</code>-specific feature, so what's the point?</p></li>\n<li><p>Your code is not portable to Python 3, but this would be easy to fix by putting parentheses around the arguments to <code>print</code>.</p></li>\n<li><p>This code:</p>\n\n<pre><code>#Check user exists\nif user.json()['Data'] is None:\n return None\n\n#Return user\nreturn user.json()['Data']\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>return user.json()['Data']\n</code></pre></li>\n<li><p>You have code like this:</p>\n\n<pre><code>VARIABLE = requests.METHOD(api_root + '/accounts/' + account_id + STUFF, headers=self.headers)\nVARIABLE.raise_for_status()\n</code></pre>\n\n<p>in three places. You should make this a function.</p></li>\n<li><p>It's not clear what the point of this line is:</p>\n\n<pre><code>user_id = str(user_id)\n</code></pre>\n\n<p>All you ever do with <code>user_id</code> is add it to strings, where it will be converted to a string in any case.</p></li>\n<li><p>I prefer to use <a href=\"http://docs.python.org/2/library/stdtypes.html#str.format\" rel=\"nofollow\"><code>str.format</code></a> to build up strings, rather than <code>+</code>: the former tends to result in clearer code. For example:</p>\n\n<pre><code>api_root + \"/accounts/\" + account_id + \"/users/\" + user_id\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>'{}/accounts/{}/users/{}'.format(api_root, account_id, user_id)\n</code></pre></li>\n</ol>\n\n<h3>Comment on updated question</h3>\n\n<p>You have failed to avoid the duplicated code: you have just moved it around.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:16:13.597", "Id": "65048", "Score": "0", "body": "Thanks for the advice! Just a couple of questions, 1) To turn this piece of code into a module, would I just remove the class definition? 2)Each of those functions require a variable called `headers`, would it be better to pass them in when calling the function?\n\n3)How does the function look for removing the duplicate code? (Updated question)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:41:13.087", "Id": "65058", "Score": "0", "body": "I'm afraid I can't spot how to remove the code duplication, how can I make a generic function and differentiate between different types of requests?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:15:28.670", "Id": "65065", "Score": "0", "body": "@Tomcelic You really need to go back and re-read that page you linked to. I just read it and I can see one issue (if..elif) to which the author gives the same solution I did - so since you read that page before coming here, why didn't you take his advice. There is more advice on his page which would also help." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T12:10:56.207", "Id": "38900", "ParentId": "38890", "Score": "6" } }, { "body": "<p>Agreeing with Gareth, here are my additions:</p>\n\n<ol>\n<li><p>Don't use compound statements; better formatting (as recommended by <a href=\"http://www.python.org/dev/peps/pep-0008/#id19\" rel=\"nofollow\">PEP 8</a>):</p>\n\n<pre><code>try:\n import simplejson as json\nexcept ImportError:\n import json\n</code></pre></li>\n<li><p>I don't add strings either, when I can avoid it; my preferred solution would be (very suitable for i18n, by the way):</p>\n\n<pre><code>'%(api_root)s/accounts/%(account_id)s/users/%(user_id)s' % locals()\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:42:19.077", "Id": "38913", "ParentId": "38890", "Score": "1" } } ]
{ "AcceptedAnswerId": "38900", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:45:49.990", "Id": "38890", "Score": "4", "Tags": [ "python", "design-patterns", "python-2.x" ], "Title": "Python coding style from Java background" }
38890
<p>I am not new to html however would like to know about best practices. I need to develop a layout like this:</p> <p><img src="https://i.stack.imgur.com/5P2JW.png" alt="enter image description here"></p> <p>This is what I have proposed:</p> <pre><code>&lt;div id="body"&gt; &lt;div id="body-main"&gt; &lt;div id="body-main-upper"&gt; &lt;div id="body-main-upper-image"&gt; &lt;image&gt;&lt;/image&gt; &lt;/div&gt; &lt;div id="body-main-upper-image2"&gt; Text goes here &lt;image&gt;&lt;/image&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="body-main-bottom"&gt; &lt;Table&gt;&lt;tr /&gt;&lt;td /&gt;&lt;/Table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="sidebar"&gt; &lt;div id="sidebar-upper"&gt; &lt;image&gt;&lt;/image&gt; &lt;/div&gt; &lt;div id="sidebar-bottom"&gt; &lt;image&gt;&lt;/image&gt; &lt;div id="sidebar-bottom-table"&gt; &lt;/div&gt; Text goes here &lt;image&gt;&lt;/image&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/gdWM5/" rel="nofollow noreferrer">http://jsfiddle.net/gdWM5/</a></p> <p>Can this be improved in any way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T10:13:46.233", "Id": "65015", "Score": "0", "body": "Seems pretty solid to me. Depending on what you are trying to achieve you could possible remove a few `<div>s` here and there such as `div#body-main-upper-image`and target the images in CSS with `div#body-main-upper img`. Same with `div#body-main-bottom`, if there is only a table in that div then it could be seen as superfluous." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:08:16.733", "Id": "67689", "Score": "1", "body": "If you have CSS for this, can you add it please?" } ]
[ { "body": "<p>You might consider adding classes. You have many broadly similar elements on that page; adding classes to them would give you more flexibility in your CSS. As things stand, you can only apply style to elements based on their id, their parent elements or their type (and hey, they're all DIVs).</p>\n\n<p>I would use an identifier other than <strong>body</strong>, for clarity and to avoid any possibility of error/confusion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T10:17:38.733", "Id": "38894", "ParentId": "38891", "Score": "1" } }, { "body": "<p>your Table is not declared correctly in the markup. </p>\n\n<p><strong>This:</strong></p>\n\n<pre><code>&lt;div id=\"body-main-bottom\"&gt;\n &lt;Table&gt;&lt;tr /&gt;&lt;td /&gt;&lt;/Table&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Should look like this</strong></p>\n\n<pre><code>&lt;div id=\"body-main-bottom\"&gt;\n &lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>your self closing tag <code>&lt;tr /&gt;</code> means that the row is now closed, you shouldn't have a <code>&lt;td&gt;</code> outside of a row, it is bad structure and won't show correctly in browsers.</p>\n\n<hr>\n\n<p>HTML is not made up of <code>&lt;div&gt;</code>'s alone. you should include other elements as well, even when you are only figuring out your structure.</p>\n\n<p>Image tags are not <code>&lt;image&gt;</code> they are <code>&lt;img /&gt;</code> and as long as you have everything you need inside the attributes, they are self closing tags.</p>\n\n<p>from the looks of the Graphic, you may not need a table, you probably want a list instead of a table. If I were you I would look into an unordered list (you can format how you like with CSS)</p>\n\n<hr>\n\n<p>Element tags do not have Capital letters in them at all, they are Lowercase.</p>\n\n<hr>\n\n<p>More Descriptive ID names. If you have something that is going to be styled the same as something else give them class names and declare the style once. if you have one thing that is going to be different, create a class that will style <em>it</em> and the surrounding items the the same and add another class to <em>it</em> and declare it after the other class.</p>\n\n<hr>\n\n<h2>In Closing</h2>\n\n<p>I would say that you should figure out your CSS and then post a new question as well (with the CSS)</p>\n\n<p>this is not a finished structure, it looks like something you threw together in about a half an hour. probably took you longer to draw the picture than write the HTML</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:07:45.777", "Id": "82951", "Score": "1", "body": "Nitpick: HTML element names are in fact case insensitive (you frequently see all-uppercase names in older sites). However, XML is case sensitive. In XHTML, only the lowercase element names are legal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:12:14.187", "Id": "82953", "Score": "0", "body": "I know that in HTML it is case insensitive, but to be more standards compliant you should always name your tags in lowercase. it also makes it easier if you switch between HTML, XML, XHTML and other MLs, I believe the standard for XML is all lowercase as well. I agree with your comment @amon it's just not pretty in Caps. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:35:46.403", "Id": "38910", "ParentId": "38891", "Score": "8" } }, { "body": "<p>I am going to assume your table rows are for a real <em>table</em>, i.e. they're full of data itemized to present to the user. If this is not the case, do not use tables. Only use tables for layout if you are a real cretin that wants to exclude visually impaired persons with screen readers from using your product.</p>\n\n<p>I would look over all of your <code>div</code>s and see if there's a more sound tag for them. <code>div</code> implies a logical division with no semantic significance, so if you're using them just to divide your page visually, there is probably a better element to represent the content that can be visually blocked the way you want with CSS. The reason I suspect this to be the case is that your HTML contains only <code>div</code>, <code>image</code>, and table-related elements. Unless the web app is truly something the HTML standards committee has just never thought of, either the tables, <code>div</code>s, or both are being used inappropriately for layout.</p>\n\n<p>Previous reviewers have mentioned replacing some of your IDs with classes and/or changing the names that include \"body\", as well as unwrapping some more meaningful elements from their enclosing <code>div</code>s. These are all good ideas. I'm not certain that the rationale has been stated, though. </p>\n\n<p><code>id</code> attributes are a good idea in the broadest semantic sense when the element serves a role that is logically necessarily unique among all elements. They are additionally necessary to target anchors and <code>label</code> elements. Long long ago, they were the most logical way to make an element accessible from JS, but preemptively <code>id</code>ing almost every element in case it's needed in JS creates a maintenance hazard that can now be avoided. If it's conceivable that there could be more than one <code>sidebar</code> (there <em>are</em> two sides after all) in some future revision, for example, adding it will involve more work and possible catastrophic name collisions if you're identifying everything with IDs. You'll basically start defining what a sidebar is and should look like from scratch in the page's CSS and JS. Then you have to maintain <em>that</em> code, too. The <code>class</code> attribute allows you to assign similar styles and behaviors to the elements that share them. If two elements share <em>any</em> stylistic or functional aspect, they should share a <code>class</code>.</p>\n\n<p>Unwrapping elements from their parent <code>div</code> is an extension of using more appropriate tags and abandoning the \"everything needs an id\" approach because there are many <code>div</code>s which do literally nothing but possess an <code>id</code> and contain a more meaningful element. If the element inside needs to be identified, give it an <code>id</code> or <code>class</code> attribute as appropriate. The <code>div</code> wrapping it just makes it harder to revise or transplant without breaking CSS rules and layout.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:16:15.783", "Id": "38917", "ParentId": "38891", "Score": "1" } }, { "body": "<p>I have three main remarks:</p>\n\n<ol>\n<li>The markup is very heavily tied to the layout, in terms of naming. You will be able to write better CSS if you name elements for their purpose rather than their position. That is, avoid positioning terms such as \"upper\" and \"bottom\" when naming your element IDs, and prefer terms that describe the content, such as \"header\" and \"featured-news\".</li>\n<li>Consider introducing HTML5 elements, such as <a href=\"http://www.whatwg.org/specs/web-apps/current-work/#the-nav-element\" rel=\"nofollow\"><code>&lt;nav&gt;</code></a> for your sidebar, if appropriate.</li>\n<li>You may have a hard time implementing the CSS to put the <code>#sidebar</code> to the right of the <code>#body-main</code>, and it may be easier if you switch the order in which they appear in the HTML.</li>\n</ol>\n\n<p>Paul O'Brien has a useful <a href=\"http://www.pmob.co.uk/temp/3colfixedtest_4.htm\" rel=\"nofollow\">all-purpose template</a> for creating a page with a header, footer, and left and right sidebars. Most pages are just a special case of that generic solution; you want just the right sidebar. Here is how you can apply the technique…</p>\n\n<h3>HTML</h3>\n\n<pre><code>&lt;div id=\"body\"&gt;\n &lt;nav id=\"sidebar\"&gt;\n &lt;div id=\"sidebar-upper\"&gt;\n &lt;img src=\"https://cdn.sstatic.net/stackexchange/img/logos/se/se-logo.png\" width=\"125\" height=\"37\"&gt;\n &lt;/div&gt;\n &lt;div id=\"sidebar-bottom\"&gt;\n &lt;Table border=\"1\"&gt;\n &lt;tr&gt;&lt;th&gt;Table row&lt;/th&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Table row&lt;/td&gt;&lt;/tr&gt;\n &lt;/Table&gt;\n\n &lt;div id=\"sidebar-bottom-table\"&gt;\n &lt;/div&gt;\n Text goes here\n &lt;img src=\"https://cdn.sstatic.net/stackexchange/img/logos/se/se-icon.png\" width=\"40\" height=\"40\"&gt;\n &lt;/div&gt;\n &lt;/nav&gt;\n &lt;div id=\"body-main\"&gt;\n &lt;div id=\"body-main-upper-image2\"&gt;\n Body upper image 2\n &lt;img src=\"https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png\" width=\"40\" height=\"40\"&gt;\n &lt;/div&gt;\n &lt;div id=\"body-main-upper\"&gt;\n &lt;div id=\"body-main-upper-image\"&gt;\n &lt;img src=\"https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png\" width=\"125\" height=\"38\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"body-main-bottom\"&gt;\n &lt;Table border=\"1\"&gt;\n &lt;tr&gt;&lt;th&gt;Table row&lt;/th&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Table row&lt;/td&gt;&lt;/tr&gt;\n &lt;/Table&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>#body-main {\n border: 1px solid red;\n margin-right: 30%;\n}\n#body-main-upper {\n border: 1px solid pink;\n}\n#body-main-upper {\n border: 1px solid brown;\n}\n#sidebar {\n border: 1px solid blue;\n position: relative;\n float: right;\n width: 30%;\n}\n#sidebar-upper {\n border: 1px solid lightblue;\n}\n#sidebar-bottom {\n border: 1px solid navy;\n}\n#body-main-upper-image2 {\n float: right;\n width: 50%;\n}\n</code></pre>\n\n<h3>Implementation Notes</h3>\n\n<p>As I noted, the <code>#sidebar</code> comes before <code>#body-main</code>; the sidebar lives in the void created by the right margin of the main div. You may also have noticed that the <code>#body-main-upper-image2</code> comes before <code>#body-main-upper</code>; the former is <code>float</code>ed to the right in CSS. I encourage you to experiment with the <a href=\"http://jsfiddle.net/bU6xj/\" rel=\"nofollow\">jsFiddle</a> to see how that works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:38:06.607", "Id": "38978", "ParentId": "38891", "Score": "4" } } ]
{ "AcceptedAnswerId": "38910", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T09:56:19.323", "Id": "38891", "Score": "4", "Tags": [ "html", "layout" ], "Title": "Improve HTML structure?" }
38891
<p>Refactor this code so that I don't have to insert the parameters any time I need to use one of the functions.</p> <p>I have a class, say <code>julian</code>, for calculating Julian dates of today, a date I insert and the difference between these two Julian dates. </p> <pre><code> int julian::calc_julianToday() { time_t t = time(0); struct tm *now = localtime( &amp;t ); todDay = now-&gt;tm_mday; todMonth = now-&gt;tm_mon+1; todYear = now-&gt;tm_year+1900; int at = (14 - todMonth) / 12; int yt = todYear + 4800 - at; int mt = todMonth + 12 * at - 3; if (todYear &gt; 1582 || (todYear == 1582 &amp;&amp; todMonth &gt; 10) || (todYear == 1582 &amp;&amp; todMonth == 10 &amp;&amp; todDay &gt;= 15)) return julToday = todDay + (153 * mt + 2) / 5 + 365 * yt + yt / 4 - yt / 100 + yt / 400 - 32045; else return julToday = todDay + (153 * mt + 2) / 5 + 365 * yt + yt / 4 - 32083; } int julian::calc_juliandate(int day, int month, int year) { int a = (14 - month) / 12; int y = year + 4800 - a; int m = month + 12 * a - 3; if (year &gt; 1582 || (year == 1582 &amp;&amp; month &gt; 10) || (year == 1582 &amp;&amp; month == 10 &amp;&amp; day &gt;= 15)) return julStart = day + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045; else return julStart = day + (153 * m + 2) / 5 + 365 * y + y / 4 - 32083; } int julian::dates_diff(int day, int month, int year) { int start = calcJulStartDate(day, month, year); int today = calcJulTodayDate(); differ = today-start; return differ; } </code></pre> <p>Please note that all the variable types are declared in a header file. What I would like to do in <code>main()</code> is to be able to use <code>calc_juliandate()</code> without having to call it and pass its attributes each and every time I need it in another function, as in <code>dates_diff()</code>. Any suggestions about coding style or implementing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T10:36:04.063", "Id": "65020", "Score": "0", "body": "I'm seriously at a loss as to what exactly you are trying to achieve. Can you post some code showing how you would like to be able to use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T10:59:16.897", "Id": "65022", "Score": "0", "body": "I would like to use the result of calc_julianToday() as a variable accessible by other functions without having to create a new variable inside dates_diff() and re-insert the same attributes only to caclulate calc_julianToday(). Ideally calc_julianToday() should be calculated once. \nMaybe create a new object of the class julian? I don't know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:51:13.557", "Id": "65060", "Score": "5", "body": "Just use a normal date/time class and convert when needed. Do not try to rebuilt the whole date library in Julian, you will spend alot of time fixing all the bugs you will have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:49:50.833", "Id": "65111", "Score": "2", "body": "[Meta discussion](http://meta.codereview.stackexchange.com/q/1410/9357) about voting to close this question" } ]
[ { "body": "<p>Welcome to Code Review,</p>\n\n<p>I do not know how to solve your problem, however, your code could use polishing.</p>\n\n<ul>\n<li>Magical constants; your code is littered with them, use constants instead</li>\n<li>Undocumented magical constants, I can guess what <code>365</code> or <code>12</code> is used for, other constants like <code>32083</code> could use a comment or could show the calculation of how you got there</li>\n<li>Naming; <code>todDay</code>, <code>todMonth</code> and <code>todYear</code> are terrible names</li>\n<li>Naming; <code>at</code>, <code>ty</code> and <code>mt</code> are even worse</li>\n<li>Casing; be consistent, you mix underscores with casing and even your casing is not consistent ( <code>calc_julianToday</code> &lt;> <code>calc_juliandate</code> )</li>\n<li>Indenting! Your indenting is all over the place and distracts the reader</li>\n<li>Repeating / DRY;</li>\n</ul>\n\n<p>I do not write C++ but can you not write <code>calc_julianToday()</code> as</p>\n\n<pre><code>int julian::calc_julianToday()\n{\n time_t t = time(0);\n struct tm *now = localtime( &amp;t );\n return julToday = calc_juliandate( now-&gt;tm_mday, now-&gt;tm_mon+1, now-&gt;tm_year+1900 ) ; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:27:05.647", "Id": "65078", "Score": "0", "body": "Thank you Tomdemuy. All of your suggestions are very useful and will be taken into consideration." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:30:43.320", "Id": "38908", "ParentId": "38893", "Score": "6" } }, { "body": "<p>In <code>dates_diff</code>, you use a variable named <code>differ</code>. Is that an instance variable? It should be local, because it makes no sense to make it part of the object's state. Better yet, just <code>return</code> the difference directly.</p>\n\n<pre><code>int julian::dates_diff(int day, int month, int year)\n{\n int start = calcJulStartDate(day, month, year);\n int today = calcJulTodayDate();\n return today - start;\n}\n</code></pre>\n\n<p>However, the more fundamental question is, what does your <code>julian</code> class look like? Is it just a collection of <code>static</code> methods? I think we could do better than that in C++.</p>\n\n<pre><code>#include &lt;ctime&gt;\n\nclass Julian {\n /* Default constructor: today's date */\n Julian() {\n // TODO\n } \n\n Julian(int year, int month, int day) {\n // TODO\n }\n\n explicit operator long() const {\n return this-&gt;date;\n }\n\n long operator-(const Julian &amp;other) const {\n return this-&gt;date - other.date;\n }\n\n Julian operator-(long days) const {\n return Julian();\n }\n\n private:\n long date;\n};\n</code></pre>\n\n<p>Then you can use the code more naturally:</p>\n\n<pre><code>int main() {\n Julian today, newYear(2014, 1, 1);\n std::cout &lt;&lt; (today - newYear) &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:12:00.703", "Id": "38928", "ParentId": "38893", "Score": "4" } } ]
{ "AcceptedAnswerId": "38928", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T10:06:37.897", "Id": "38893", "Score": "3", "Tags": [ "c++", "classes", "datetime" ], "Title": "Calculating Julian dates" }
38893
<p>I have written a wrapper for Soap based 3rd party web service.</p> <p><a href="https://gist.github.com/veganista/bd940750d9e240e63b89" rel="nofollow">https://gist.github.com/veganista/bd940750d9e240e63b89</a></p> <p>I'm pretty happy with it so far (I think, anyway). It's only a small sub-set of what the full API offers but will suffice for my needs at the moment.</p> <p>I'm looking for some criticism from some other developers on my implementation.</p> <p>Edit: I'd also like some tips on how to make this easily testable. I currently haven't written any automated tests for the class. I'd use PHP Unit for testing. </p> <pre><code>&lt;?php namespace KashFlow; class KashFlow { /** * Contains the username used for authenticating with KashFlow * * @var string $username */ protected $username; /** * Contains the password used for authenticating with KashFlow * * @var string $password */ protected $password; /** * Holds a reference to the SoapClient used by the wrapper * * @var SoapClient $client */ protected $client; /** * Constructor method * * @param string $username Username used for authentication * @param string $password Password used for authentication * @return KashFlow Returns it's self */ public function __construct($username, $password){ $this-&gt;client = new \SoapClient('https://securedwebapp.com/api/service.asmx?WSDL', array('trace' =&gt; 1, 'soap_version' =&gt; SOAP_1_2)); $this-&gt;username = $username; $this-&gt;password = $password; return $this; } /** * Makes a request to kashflow. * * Used internally to for all requests but can also be used to make requests to kashflow * for methods without a wrapper. * * @param string $method The method to be called * @param array $arguments Any arguments that should be sent with the request */ public function request($method, $arguments = array()){ $arguments = array_merge(array('UserName' =&gt; $this-&gt;username, 'Password' =&gt; $this-&gt;password), $arguments); $result = $this-&gt;client-&gt;$method($arguments); if($result-&gt;Status == 'NO'){ throw new \Exception($result-&gt;StatusDetail); } return $result; } /** * This method returns all currencies that have been setup in the users account. * * @link http://www.kashflow.com/developers/soap-api/GetCurrencies/ * * @return array An array of objects of type Currencies */ public function getCurrencies(){ $result = $this-&gt;request('GetCurrencies'); return $result-&gt;GetCurrenciesResult; } /** * Gets the default currency for the account * * @return mixed Returns */ public function getDefaultCurrency(){ $currencies = $this-&gt;getCurrencies(); foreach($currencies as $currency){ if($currency-&gt;isDefault){ return $currency; } } return false; } /** * This method returns an array of all payments method available for use as the PayMethod * * @link http://www.kashflow.com/developers/soap-api/GetInvPayMethods/ * @return An array of objects of type PaymentMethod */ public function getInvoicePaymentMethods(){ $result = $this-&gt;request('GetInvPayMethods'); return $result-&gt;GetInvPayMethodsResult-&gt;PaymentMethod; } /** * This method will create an invoice and return the new invoice number. * * InvoiceLines are automatically added to the invoice array * * @param $data array Invoice data array * @param $lines array InvoiceLine data array * @return int An integer represeting the new Invoice number */ public function insertInvoice($data, $lines = array()){ $invoiceDefault = array( 'InvoiceDBID' =&gt; '', 'Paid' =&gt; 0, 'SuppressTotal' =&gt; 0, 'ProjectID' =&gt; '', 'NetAmount' =&gt; 0, 'VATAmount' =&gt; 0, 'AmountPaid' =&gt; 0, ); $lineDefault = array( 'LineID' =&gt; 0, 'Quantity' =&gt; 0, 'Description' =&gt; '', 'Rate' =&gt; 0, 'ChargeType' =&gt; 0, 'VatAmount' =&gt; 0, 'VatRate' =&gt; 0, 'Sort' =&gt; 0, 'ProductID' =&gt; 0, 'ProjID' =&gt; 0, ); $data = array_merge($invoiceDefault, $data, array('Lines' =&gt; array())); foreach($lines as $line){ $line = array_merge($lineDefault, $line); $data['Lines'][] = new \SoapVar($line, 0, 'InvoiceLine', 'KashFlow'); } $result = $this-&gt;request('InsertInvoice', array('Inv' =&gt; $data)); return $result-&gt;InsertInvoiceResult; } /** * This method allows you to add a payment to an invoice. * * @link http://www.kashflow.com/developers/soap-api/InsertInvoicePayment/ * @param $invoiceId int ID of the invoice number to enter payment for * @param $data array Invoice payment data array * @return int An integer representing the new payment number */ public function insertInvoicePayment($invoiceId, $data = array()){ $default = array( 'PayID' =&gt; '', 'PayDate' =&gt; date('Y-m-d'), 'PayNote' =&gt; '', 'PayMethod' =&gt; '', 'PayAccount' =&gt; '', 'PayAmount' =&gt; 0, ); $data = array_merge($default, $data, array('PayInvoice' =&gt; $invoiceId)); $result = $this-&gt;request('InsertInvoicePayment', array('InvoicePayment' =&gt; $data)); return $result-&gt;InsertInvoicePaymentResult; } /** * Ths method returns a customer based on their email address * * @link http://www.kashflow.com/developers/soap-api/getcustomerbyemail/ * @param string $email Email address of the customer * @return mixed Returns an object of type Customer on success of false if not found */ public function getCustomerByEmail($email){ try{ $result = $this-&gt;request('GetCustomerByEmail', array('CustomerEmail' =&gt; $email)); return $result-&gt;GetCustomerByEmailResult; }catch(\Exception $e){ return false; } } /** * This method lets you create a new Customer. * * @link http://www.kashflow.com/developers/soap-api/InsertCustomer/ * @param array An array containing cutomer data * @return int An integer containing the newly generated ID number for the customer */ public function insertCustomer($data){ $default = array( 'CustomerID' =&gt; '', 'Name' =&gt; '', 'Contact' =&gt; '', 'Telephone' =&gt; '', 'Mobile' =&gt; '', 'Email' =&gt; '', 'Address1' =&gt; '', 'Address2' =&gt; '', 'Postcode' =&gt; '', 'EC' =&gt; 0, 'OutsideEC' =&gt; 0, 'Source' =&gt; '', 'Discount' =&gt; 0, 'ShowDiscount' =&gt; false, 'PaymentTerms' =&gt; '', 'CheckBox1' =&gt; 0, 'CheckBox2' =&gt; 0, 'CheckBox3' =&gt; 0, 'CheckBox4' =&gt; 0, 'CheckBox5' =&gt; 0, 'CheckBox6' =&gt; 0, 'CheckBox7' =&gt; 0, 'CheckBox8' =&gt; 0, 'CheckBox9' =&gt; 0, 'CheckBox10' =&gt; 0, 'CheckBox11' =&gt; 0, 'CheckBox12' =&gt; 0, 'CheckBox13' =&gt; 0, 'CheckBox14' =&gt; 0, 'CheckBox15' =&gt; 0, 'CheckBox16' =&gt; 0, 'CheckBox17' =&gt; 0, 'CheckBox18' =&gt; 0, 'CheckBox19' =&gt; 0, 'CheckBox20' =&gt; 0, 'Created' =&gt; date('Y-m-d'), 'Updated' =&gt; date('Y-m-d'), ); $data = array_merge($default, $data); if(!isset($data['CurrencyID'])){ $defaultCurrency = $this-&gt;getDefaultCurrency(); $data['CurrencyID'] = $defaultCurrency-&gt;CurrencyId; } $result = $this-&gt;request('InsertCustomer', array('custr' =&gt; $data)); return $result-&gt;InsertCustomerResult; } /** * Gets a niceley formatted version of the last soap request * * @return string The last soap request */ public function getLastRequest(){ $request = $this-&gt;client-&gt;__getLastRequest(); $dom = new DOMDocument(); $dom-&gt;formatOutput = true; $dom-&gt;preserveWhitespace = false; $dom-&gt;loadXml($request); return '&lt;pre&gt;' . htmlspecialchars($dom-&gt;saveXml()) . '&lt;/pre&gt;'; } } </code></pre>
[]
[ { "body": "<p>Here are some tips for your class:</p>\n\n<p>For the lines like the following, I suggest applying different formatting (to make it more readable). Please see below:</p>\n\n<pre><code>$arguments = array_merge(array('UserName' =&gt; $this-&gt;username, 'Password' =&gt; $this-&gt;password), $arguments);\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>$arguments = array_merge(\n array(\n 'UserName' =&gt; $this-&gt;username, \n 'Password' =&gt; $this-&gt;password\n ), $arguments\n);\n</code></pre>\n\n<p>You could just use <code>Exception</code> rather then <code>\\Exception</code> is you define the class use in the beginning of your class like this:</p>\n\n<pre><code>use \\Exception;\n</code></pre>\n\n<p>I really enjoyed your <code>getLastRequest()</code> function implementation and a trace in XML.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-18T11:39:16.227", "Id": "66285", "Score": "1", "body": "Yes, better readability would be an improvement there. There's nothing gained by putting it all on one line really.\n\nI think adding the `use \\Exception` and `use \\SoapClient` are a good idea as it gives a bit of an overview of what the class uses." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T18:15:51.480", "Id": "39499", "ParentId": "38896", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T11:29:08.493", "Id": "38896", "Score": "1", "Tags": [ "php", "object-oriented", "classes", "php5", "web-services" ], "Title": "Review of my PHP Wrapper around Third Party Soap API" }
38896
<p>Continuation of this question: <a href="https://codereview.stackexchange.com/questions/36561/unit-of-work-with-generic-repository-pattern-mvvm-vol-2">https://codereview.stackexchange.com/questions/36561/unit-of-work-with-generic-repository-pattern-mvvm-vol-2</a></p> <p>I have made some modifications:</p> <ul> <li>Implement <em>lazy-loading</em> (hope so)</li> <li><code>Add()</code> and <code>Update()</code> returns <code>T</code> instead of <code>void</code></li> <li>Add <code>IFeedItemRepository</code>, <code>FeedItemRepository</code>, <code>IBaseRepository&lt;T&gt;</code></li> </ul> <p><strong>IBaseRepositry</strong></p> <pre><code>public interface IBaseRepository&lt;T&gt; where T : class { int Count { get; } T Add(T entity); T GetById(int id); T Update(T entity); IEnumerable&lt;T&gt; GetAll(); void Remove(T entity); void RemoveById(int id); } </code></pre> <p><strong>IBaseFeed</strong></p> <pre><code>public interface IBaseFeed { int Id { get; set; } string Title { get; set; } DateTime PubDate { get; set; } Uri Link { get; set; } string Misc { get; set; } } </code></pre> <p><strong>IFeedRepository</strong></p> <pre><code>internal interface IFeedRepository&lt;T&gt; : IBaseRepository&lt;T&gt; where T : class, IBaseFeed { int GetFeedIdByLink(string feedLink); int GetFeedIdByLink(Uri feedLink); T GetByLink(string feedLink); T GetByLink(Uri feedLink); } </code></pre> <p><strong>FeedRepository</strong></p> <pre><code>internal class FeedRepository&lt;T&gt; : IFeedRepository&lt;T&gt;, IDisposable where T : class, IBaseFeed, new() { private readonly SQLiteConnection _db; private Lazy&lt;IList&lt;T&gt;&gt; _feeds; private bool _isDisposed = false; public int Count { get { return _feeds.Value.Count; } } public FeedRepository(SQLiteConnection db) { this._db = db; this._feeds = new Lazy&lt;IList&lt;T&gt;&gt;(() =&gt; _db.Table&lt;T&gt;().ToList()); } public T Add(T feed) { this._db.Insert(feed); return feed; } public IEnumerable&lt;T&gt; GetAll() { return this._feeds.Value; } public T GetById(int id) { return this._feeds.Value.Where(feed =&gt; int.Equals(feed.Id, id)).Single(); } public T GetByLink(string feedLink) { return this.GetByLink(new Uri(feedLink)); } public T GetByLink(Uri feedLink) { return this._feeds.Value.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Single(); } public int GetFeedIdByLink(string feedLink) { return this.GetFeedIdByLink(new Uri(feedLink)); } public int GetFeedIdByLink(Uri feedLink) { return this._feeds.Value.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Select(feed =&gt; feed.Id).Single(); } public void Remove(T feed) { this._db.Delete(feed); } public void RemoveById(int id) { this.Remove(this.GetById(id)); } public T Update(T feed) { this._db.Update(feed); return feed; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._db != null) { this._db.Dispose(); } } this._isDisposed = true; } } </code></pre> <p><strong>IFeedItemRepository</strong></p> <pre><code>internal interface IFeedItemRepository : IFeedRepository&lt;FeedItem&gt; { IEnumerable&lt;FeedItem&gt; GetFeedItemsByFeedDataId(int feedDataId); } </code></pre> <p><strong>FeedItemRepository</strong></p> <pre><code>internal sealed class FeedItemRepository : FeedRepository&lt;FeedItem&gt;, IFeedItemRepository { public FeedItemRepository(SQLiteConnection db) : base(db) { } public IEnumerable&lt;FeedItem&gt; GetFeedItemsByFeedDataId(int feedDataId) { return base.GetAll().Where(feed =&gt; int.Equals(feed.FeedDataId, feedDataId)); } } </code></pre> <p><strong>IUnitOfWork</strong></p> <pre><code>internal interface IUnitOfWork { void Commit(); void Rollback(); } </code></pre> <p><strong>UnitOfWork</strong></p> <pre><code>public class UnitOfWork : IUnitOfWork, IDisposable { private readonly SQLiteConnection _db; private IFeedRepository&lt;FeedData&gt; _feedDataRepository; private IFeedItemRepository _feedItemRepository; private bool _isDisposed = false; public IFeedRepository&lt;FeedData&gt; FeedDataRepository { get { return _feedDataRepository; } set { _feedDataRepository = value; } } public IFeedItemRepository FeedItemRepository { get { return _feedItemRepository; } set { _feedItemRepository = value; } } public UnitOfWork(SQLiteConnection db) { this._db = db; this._feedDataRepository = new FeedRepository&lt;FeedData&gt;(this._db); this._feedItemRepository = new FeedItemRepository(this._db); this._db.BeginTransaction(); } public void Commit() { this._db.Commit(); } public void Rollback() { this._db.Rollback(); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._feedDataRepository != null) { ((FeedRepository&lt;FeedData&gt;)this._feedDataRepository).Dispose(); } if (this._feedItemRepository != null) { ((FeedItemRepository)this._feedItemRepository).Dispose(); } if (this._db != null) { this._db.Dispose(); } } this._isDisposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } </code></pre> <p>Has the implementation of <em>lazy-loading</em> been done correctly?</p> <p>What about this (UoW):</p> <pre><code> private IFeedRepository&lt;FeedData&gt; _feedDataRepository; private IFeedItemRepository _feedItemRepository; </code></pre> <p>Is it correct?</p> <p>Is the constructor in <code>FeedItemRepository</code> done properly?</p>
[]
[ { "body": "<p>Few tiny items:</p>\n\n<ol>\n<li><p><strike>Can you use an <code>IDbConnection</code> interface (or worst case, <code>DbConnection</code> class) instead of <code>SQLiteConnection</code> for your constructor parameter/class member? This would allow for more generic operation, easier unit testing and easier swap-out of database providers in the future. This is in both the <code>UnitOfWork</code> class and the <code>FeedRepository&lt;T&gt;</code> class.</strike> Upon further reflection, the way that particular SQLite client library is used, this is unfeasible at this time. Still, I'd recommend a different SQLite client if at all possible which conforms to <code>IDbConnection</code>, etc.</p></li>\n<li><p>I would advise against <code>Dispose()</code>ing of the <code>_db</code> in the <code>UnitOfWork</code> class' <code>Dispose()</code> method since the class doesn't create it - the caller does. Let the caller <code>Dispose()</code> of it. Same goes for the <code>FeedRepository&lt;T&gt;</code> class.</p></li>\n<li><p>Do the <code>FeedDataRepository</code> and <code>FeedItemRepository</code> properties in the <code>UnitOfWork</code> class really need setters? It seems dangerous to create them in the constructor and then <code>Dispose()</code> them in the <code>Dispose()</code> method when someone could come along and change either to something else entirely. You could lose the original references altogether. I'd wager these should be invariant once constructed.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:04:12.603", "Id": "65114", "Score": "0", "body": "AFAIK there ISN't different SQLite client for WinRT, am I right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:17:03.703", "Id": "65118", "Score": "0", "body": "Got me on that front. No idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:19:58.737", "Id": "65119", "Score": "0", "body": "Never mind ;)\nI deleted `Dispose()` from Respoitory and UoW should I do anything with setter(3)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:21:54.957", "Id": "65120", "Score": "1", "body": "This was a you-tell-me sort of thing. Do you need the setters? They seemed smelly to me considering the backing fields are created in the class. Are you assigning to them somewhere in client code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:28:50.233", "Id": "65122", "Score": "0", "body": "Grr!!! So stupid mistake! I meant a private set! Is it correct now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:35:05.147", "Id": "65123", "Score": "1", "body": "Same question applies - are you going to set via the property from within the class? Currently, it's not being done. Assignment is only to the backing member variable in the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:37:17.997", "Id": "65124", "Score": "0", "body": "I want only constructor can assignment value to `FeedDataRepository` and `FeedItemRepository`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:37:54.487", "Id": "65125", "Score": "1", "body": "Then remove the setters and mark the fields as `readonly`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:40:31.837", "Id": "65127", "Score": "0", "body": "http://pastebin.com/K70jq7Wq\nCorrect?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:43:36.293", "Id": "38914", "ParentId": "38901", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T12:24:44.217", "Id": "38901", "Score": "2", "Tags": [ "c#", "sqlite", "mvvm" ], "Title": "Unit of Work with Generic Repository Pattern MVVM, vol. 3" }
38901
<p>Here's a problem that I tried solving: </p> <blockquote> <p>Lakshagraha was a house built of lacquer, made by the Kauravas to kill the Pandavas. The Kauravas wanted to burn the house down when the Pandavas were asleep at night. But poor Kauravas – once again they underestimated their cousins. Having been warned of the nefarious plan, the Pandavas had had an underground set of passages built for escape.</p> <p>The underground rooms and passages were in the form of a n*m grid where every cell is either free or blocked by a pillar. The Pandavas start at a free cell and they need to reach a destination cell(which can be free or blocked).</p> <p>The following are the allowed valid moves:</p> <p>Move from an empty cell to another adjacent empty cell. (Cells sharing a common side are considered adjacent).</p> <p>If an adjacent cell is blocked, then set the edge of the blocked cell on fire.</p> <p>If two or more (distinct) edges of a blocked cell are set on fire, then the blocking pillar burns down and clears the cell. After the fire, the cell becomes empty.</p> <p>Initially no edge of any blocked cell is set on fire. Help the Pandavas find whether it is possible to reach the destination (target cell), because they are the good guys.</p> <p><strong>Input:</strong> The first line contains T, the number of test cases. The description of T Test cases follow. The first line of each test case consists of 2 space separated integers n and m, denoting the dimensions of the grid (n x m grid). Each of the following n lines contain m characters each, where the jth character of the ith line denotes the state of the cell located at the jth column of the ith row of the grid. Each cell can either be blocked (denoted by ‘*’), or free (denoted by ‘.’). The next line of each test case consists of 4 space separated integers sx, sy, ex, ey, where (sx, sy) denotes the cell where you are initially located at, and (ex, ey) denotes the destination cell (1 based indices).</p> <p><strong>Output:</strong> For each test case, output a single line containing <code>YES</code> or <code>NO</code>, denoting whether it is possible to reach the destination cell from the given starting cell by making valid moves as described above.</p> <p><strong>Constraints:</strong></p> <ul> <li>\$T ≤ 20\$</li> <li>\$1 ≤ n\$</li> <li>\$m ≤ 500\$</li> <li>\$1 ≤ sx\$, \$ex ≤ n\$</li> <li>\$1 ≤ sy\$, \$ey ≤ m\$</li> <li>The starting cell is always empty.</li> </ul> <h3>Sample Input</h3> <pre><code>3 2 3 .*. ... 1 1 1 3 3 3 ..* ..* .*. 2 1 3 3 2 3 .*. **. 2 3 1 2 </code></pre> <h3>Sample Output</h3> <pre><code>YES YES NO </code></pre> <p><strong>Time Limit:</strong> 2 sec</p> <p><strong>Memory Limit:</strong> 256 MB</p> </blockquote> <p>Initially, I used a backtracking approach to solve the problem. Obviously, that was slow and resulted in TLE. Later, I was told that a simple BFS would do. Hence, I just did a simple BFS, starting at the specified point. Whenever I encounter a pillar, I increase its count and see if its more than 1 (The pillar has been visited twice). If so, I push it into the queue and continue the BFS. Still, the code results in TLE. I really don't know how I can optimize this code more!</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; using namespace std; class data { public: int count; int x; int y; int flag; char value; }ob; int main() { // your code goes here int test; scanf("%d",&amp;test); int n,m; char temp; while(test--) { scanf("%d%d",&amp;n,&amp;m); //printf("%d %d",n,m); data ar[n][m]; for(int i=0;i&lt;n;i++) { for(int j=0;j&lt;m;j++) { scanf(" %c",&amp;temp); ob.count=0; ob.x = i; ob.y = j; ob.value = temp; ar[i][j] = ob; } } int sx,sy,ex,ey; scanf("%d%d%d%d",&amp;sx,&amp;sy,&amp;ex,&amp;ey); vector&lt;data&gt; v; sx-=1; sy-=1; ex-=1; ey-=1; v.push_back(ar[sx][sy]); int x,y; while(true) { if(v.size()==0) { printf("NO\n"); break; } else { ob = v[0]; v.erase(v.begin()); x = ob.x; y = ob.y; //cout&lt;&lt;"Current : "&lt;&lt;x&lt;&lt; " "&lt;&lt;y&lt;&lt;endl; ar[x][y].flag=1; if(x+1&lt;n) { if(ar[x+1][y].flag!=1) { if(ar[x+1][y].value == '.') { if(x+1 == ex &amp;&amp; y == ey) { printf("YES\n"); break; } else v.push_back(ar[x+1][y]); } else { ar[x+1][y].count+=1; if(ar[x+1][y].count&gt;1) { if(x+1 == ex &amp;&amp; y == ey) { printf("YES\n"); break; } else v.push_back(ar[x+1][y]); } } } } if(x-1&gt;=0) { if(ar[x-1][y].flag!=1) { if(ar[x-1][y].value == '.') { if(x-1 == ex &amp;&amp; y == ey) { printf("YES\n"); break; } else v.push_back(ar[x-1][y]); } else { ar[x-1][y].count+=1; if(ar[x-1][y].count&gt;1) { if(x-1 == ex &amp;&amp; y == ey) { printf("YES\n"); break; } else v.push_back(ar[x-1][y]); } } } } if(y+1&lt;m) { if(ar[x][y+1].flag!=1) { if(ar[x][y+1].value == '.') { if(x == ex &amp;&amp; y+1 == ey) { printf("YES\n"); break; } else v.push_back(ar[x][y+1]); } else { ar[x][y+1].count+=1; if(ar[x][y+1].count&gt;1) { if(x == ex &amp;&amp; y+1 == ey) { printf("YES\n"); break; } else v.push_back(ar[x][y+1]); } } } } if(y-1&gt;=0) { if(ar[x][y-1].flag!=1) { if(ar[x][y-1].value == '.') { if(x == ex &amp;&amp; y-1 == ey) { printf("YES\n"); break; } else v.push_back(ar[x][y-1]); } else { ar[x][y-1].count+=1; if(ar[x][y-1].count&gt;1) { if(x == ex &amp;&amp; y-1 == ey) { printf("YES\n"); break; } else v.push_back(ar[x][y-1]); } } } } } } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:22:22.260", "Id": "65089", "Score": "0", "body": "Before it can be optimized for speed, it really needs to be refactored. That should make optimization much easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:30:18.613", "Id": "65091", "Score": "0", "body": "@Jamal, I've always had trouble in that! What would you suggest as a good tutorial (or such kind) to properly structure the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:34:18.247", "Id": "65092", "Score": "0", "body": "I do not have anything in mind, but this code can still be reviewed to address code clarity and such. Optimization may still be mentioned, but it depends on what the reviewer wants to say." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:15:17.590", "Id": "86165", "Score": "0", "body": "I've seen it only in one place, but the mantra goes: Prefer `begin(v)` to `v.begin()`. A text search on [Sutter](http://herbsutter.com/elements-of-modern-c-style/) for \"Nonmember begin and end\" explains why: The basic rationale is that nonmember `begin`/`end` are more extensible." } ]
[ { "body": "<p>Before I get started, I'm writing C++11. If you're using GCC, you'll need to compile with <code>-std=c++11</code> (consult your compiler documentation otherwise; if you have to use C++98/03, you'll need to modify some of the code). The code I'm giving you is also untested -- you may need to debug it.</p>\n\n<p>OK, as Jamal mentioned, your first priority is to refactor. If your code isn't organized well, you will have a hard time optimizing it. One way to organize code like this is to write down a set of steps, and then write a function for each step. So let's start with <code>main</code>, and work from there. From a high level, you want to do the following things in your program:</p>\n\n<ol>\n<li>Read in the list of mazes from the input.</li>\n<li>Determine whether each maze can be solved.</li>\n<li>Output the answers.</li>\n</ol>\n\n<p>Note that I've separated the I/O from the meat of the program. This is good programming practice; it's an example of something called <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a>.</p>\n\n<p>This separation will require a good data structure to represent the mazes; we may need to modify the data structure later in order to handle our requirements, but for now let's start with this:</p>\n\n<pre><code>class Maze {\n public:\n struct Point {\n const int row, col;\n Point(int row, int col) : row(row), col(col) {}\n };\n\n Maze(int num_rows, int num_cols)\n : num_rows(num_rows), num_cols(num_cols),\n starting_point{0, 0}, target{0, 0},\n points(num_rows, std::vector&lt;bool&gt;(num_cols, true)) {\n }\n\n // The two versions are for convenience.\n bool is_free(int row, int col) const {\n return points[row - 1][col - 1]; // 1-based points, 0-based indices\n }\n bool is_free(const Point&amp; p) const { return is_free(p.row, p.col); }\n\n int num_rows() const { return num_rows; }\n int num_cols() const { return num_cols; }\n const Point&amp; starting_point() const { return starting_point; }\n const Point&amp; target() const { return target; }\n\n void set_is_free(int row, int col, bool is_free) {\n points[row - 1][col - 1] = is_free;\n }\n void set_starting_point(const Point&amp; p) {\n starting_point = p;\n }\n void set_target(const Point&amp; p) {\n target = p;\n }\n\n private:\n const int num_rows, num_cols;\n const Point starting_point, target;\n // points[row][col] is true iff the space in that row and column is free\n std::vector&lt;std::vector&lt;bool&gt;&gt; points;\n};\n</code></pre>\n\n<p>This class should allow us to do what we know we'll need to: construct a maze from input, then later retrieve the parameters of the problem (width, height, starting point, target) and check whether each cell in the maze is free.</p>\n\n<p>You may notice that I spelled it <code>std::vector</code>, not <code>vector</code>; that is because <a href=\"https://stackoverflow.com/questions/1265039/using-std-namespace\"><code>using namespace std;</code> is a bad idea</a>.</p>\n\n<p>OK, so now the main function:</p>\n\n<pre><code>int main() {\n const std::vector&lt;Maze&gt; mazes = read_test_cases();\n for (const auto&amp; maze : mazes) {\n if (solve_maze(maze)) {\n std::printf(\"YES\\n\");\n } else {\n std::printf(\"NO\\n\");\n }\n }\n}\n</code></pre>\n\n<p>Very simple, no? Now we must write the two functions <code>main</code> requires. First, <code>read_test_cases</code>. Now, you used a lot of <code>scanf</code>s; I won't change that, but consider learning how to use C++'s <code>iostream</code> library. However, I will change the names and structure of the code in order to improve readability.</p>\n\n<pre><code>std::vector&lt;Maze&gt; read_test_cases() {\n std::vector mazes;\n int num_tests;\n std::scanf(\"%d\", &amp;num_tests);\n mazes.reserve(num_tests);\n for (int i = 0; i &lt; num_tests; ++i) {\n int num_rows, num_cols;\n std::scanf(\"%d%d\", &amp;num_rows, &amp;num_cols);\n Maze maze(num_rows, num_cols);\n for (int row = 1; i &lt;= num_rows; ++row) {\n for (int col = 1; j &lt;= num_cols; ++col) {\n char space;\n std::scanf(\" %c\", &amp;space);\n maze.set_is_free(row, col, space == '.');\n }\n }\n Maze::Point start, target;\n std::scanf(\"%d%d%d%d\", &amp;start.row, &amp;start.col, &amp;target.row, &amp;target.col);\n maze.set_starting_point(start);\n maze.set_target(target);\n mazes.push_back(maze);\n }\n return mazes;\n}\n</code></pre>\n\n<p>OK, now let's get your search algorithm into <code>solve_maze</code>.</p>\n\n<pre><code>bool solve_maze(const Maze&amp; maze) {\n // A bunch of stuff that you had in struct data is now stored in maze.\n struct cell_search_state {\n int num_reachable_walls = 0;\n bool already_visited = false;\n };\n // The array ar that you declared is not standard-compliant C++;\n // arrays must have constant dimensions.\n std::vector&lt;std::vector&lt;cell_search_state&gt;&gt; cell_search_state(\n maze.num_rows(), std::vector&lt;cell_search_state&gt;(maze.num_cols()));\n // You're removing elements from the front of your search queue\n // and adding them to the end; this is inefficient with std::vector.\n // You want to use a queue for your data structure instead.\n //\n // Changing v from a vector to a queue will probably get you a decent\n // speedup by itself.\n std::deque&lt;Maze::Point&gt; search_queue = { maze.get_starting_point() };\n while (!search_queue.empty()) {\n const Maze::Point p = search_queue.front();\n search_queue.pop_front();\n search_state[p.row][p.col].already_visited = true;\n // By using get_neighbors, we can prevent the repetition\n // of code your function had.\n for (const auto&amp; neighbor : get_neighbors(p, maze)) {\n cell_search_state&amp; neighbor_state =\n search_state[neighbor.row][neighbor.col];\n if (neighbor_state.already_visited) continue;\n if (neighbor.is_free()\n || ++neighbor_state.num_reachable_walls &gt; 1) {\n if (neighbor == maze.get_target())\n return true;\n search_queue.push_back(neighbor);\n }\n }\n }\n return false;\n}\n</code></pre>\n\n<p>We used the following helpers in that function:</p>\n\n<pre><code>bool operator==(const Maze::Point&amp; l, const Maze::Point&amp; r) {\n return l.col == r.col &amp;&amp; l.row == r.row;\n}\n\nstd::vector&lt;Maze::Point&gt; get_neighbors(const Maze::Point&amp; p, const Maze&amp; m) {\n std::vector neighbors;\n if (p.col &lt; m.num_cols())\n neighbors.emplace_back(p.row, p.col + 1);\n if (1 &lt; p.col)\n neighbors.emplace_back(p.row, p.col - 1);\n if (p.row &lt; m.num_rows())\n neighbors.emplace_back(p.row + 1, p.col);\n if (1 &lt; p.row)\n neighbors.emplace_back(p.row - 1, p.col);\n return neighbors;\n}\n</code></pre>\n\n<p>I think this version of your code will be significantly faster. <code>v.erase(v.begin())</code> is pretty slow: it requires that you copy the entire contents of the vector (except for the first element, of course). The elements of the search queue <em>and</em> the search_state vector are also smaller -- they have disjoint data now, instead of redundant copies of the data (for instance, each element of <code>v</code> in your code contained a copy of <code>count</code>, <code>flag</code>, and <code>value</code>, even though you only used <code>x</code> and <code>y</code>, and each element of <code>ar</code> contained a copy of <code>x</code> and <code>y</code>, even though they were redundant with the indices.</p>\n\n<p>The bigger benefit, though, is it's much easier for someone to read this code and figure out what's going on! Some of the variables you had (e.g. <code>flag</code>, <code>count</code>) were difficult for me to rename -- until I had rearranged the code as I have it above! And if you hadn't told me you were doing breadth-first search <em>and</em> given me the problem statement, I would have had no idea what all your <code>if (x+1&lt;n)</code> etc. meant. Now a reader can come along and see that we're looking at the neighbors of a point in a maze.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:48:28.640", "Id": "65138", "Score": "0", "body": "Excellent, except that you took the refactoring one step too far. Each maze is an independent problem; you read it, solve it, and print the `YES` or `NO` result immediately. Repeat that _T_ times. There's no advantage to building a vector of all _T_ mazes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:57:51.607", "Id": "65139", "Score": "0", "body": "The small advantage is that all information about the input format is limited to `read_test_cases`. Your approach would require reading in the number of test cases, then calling `read_test_case` `N` times, which isn't terrible but is unnecessary. Since the number of test cases is guaranteed not to exceed 20 and the size of each `Maze` object will be well under 10kB (the exact size depends on the implementation of `std::vector<bool>`), this use of memory is unimportant and I judge the clarity gained by separation of concerns is worth the cost." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:13:54.253", "Id": "38938", "ParentId": "38904", "Score": "2" } }, { "body": "<p>Breadth-first searches are typically implemented using a queue. In fact, that's how you use it: you only ever do <code>v.push_back(…)</code> and <code>v.erase(v.begin())</code>. Therefore, the code would be clearer if you used a <code>std::queue</code> instead of a <code>std::vector</code>. Naming the vector (or queue) <code>v</code> is not helpful; <code>frontier</code> would be a more descriptive term.</p>\n\n<p><code>while(true)</code> should be avoided if practical, and in this case, it is absolutely practical to do so in the following code:</p>\n\n<pre><code> while(true)\n {\n if(v.size()==0)\n {\n printf(\"NO\\n\");\n break;\n }\n else\n {\n …\n }\n }\n</code></pre>\n\n<p>What you mean is</p>\n\n<pre><code> bool path_exists()\n {\n …\n while (frontier.size())\n {\n …\n if (…) return TRUE;\n }\n return FALSE;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T01:33:27.737", "Id": "65154", "Score": "0", "body": "I did use a queue initially. But the Online Judge generated a segmentation fault for no reason when I used it. But when I replaced it with vector, it worked." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T23:26:00.050", "Id": "38949", "ParentId": "38904", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T13:03:45.557", "Id": "38904", "Score": "4", "Tags": [ "c++", "algorithm", "pathfinding", "breadth-first-search", "time-limit-exceeded" ], "Title": "Time Limit Exceeded in BFS maze solver" }
38904
<p>I want to create a class <code>ClientSocket</code> with PHP, which is an adapter of the <code>fsockopen</code>, <code>fread</code>, and <code>fwrite</code>.</p> <pre><code>Class ClientSocket extends SenderAdapterAbstract { private $s = null; public function __construct($host, $port) { $this-&gt;s = fsockopen($host, $port); } // Abstract method concrete implementation public function send($message) { fwrite($this-&gt;s, $message); $result = fgets($this-&gt;s); fclose($this-&gt;s); } } </code></pre> <p>Should I test this class? A unit test is not really one if it talks to the network.</p> <p>Here is some rules about unit testing (I totally agree with them):</p> <p>A test is not a unit test if:</p> <ul> <li>It talks to the database</li> <li>It communicates across the network</li> <li>It touches the file system</li> <li>It can't run at the same time as any of your other unit tests</li> <li>You have to do special things to your environment (such as editing config files) to run it.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T13:44:55.003", "Id": "198442", "Score": "0", "body": "As explained here: http://stackoverflow.com/questions/21021916/how-to-really-unit-test-an-adapter I don't have to UNIT TEST these kind of adapter pattern... Maybe \"integration tests\" but not in the same test suite" } ]
[ { "body": "<p><code>a unit test is not really one if it talks to the network...</code></p>\n\n<p>I am not so sure what you meant by that. It seems like you are trying to follow exactly what someone may have said in a book or a talk. Unit testing is all about testing a 'Model'. And the assumptions are that the Model is isolated from any other models in the overall project.</p>\n\n<p>In your case the Unit Test for the ClientSocket would be called ClientSocketTest.</p>\n\n<pre><code>Class ClientSocketTest extends PHPUnit_Testcase\n{\n private $s = null;\n\n public function testSend()\n {\n $cs = new ClientSocket();\n $cs-&gt;send(\"My Message\");\n $result = $cs-&gt;result;\n $this-&gt;assert(\"Everything's Good\", $result);\n }\n}\n</code></pre>\n\n<p>I noticed that your send method has the variable $result. For Unit Testing to be successful a method should return something. The purpose of Unit Testing is to see whether the given input gives you the expected output. Don't overcomplicate it!</p>\n\n<p>Start with PHPUnit... and stick to it! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:15:58.843", "Id": "65455", "Score": "1", "body": "I think what he is saying is that when the unit test runs, it will try to open the socket to some host with a dependency on a network of some sort. If, while running the test, the network is unavailable, the test will fail" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:37:56.323", "Id": "65458", "Score": "0", "body": "Hmm... in that case it might be useful to create a local server or a hostname to simulate the request. This will at least tell you whether your method is doing what it was designed to do. But if you need an input from the host you are connecting to then if the test fails, it will bring it to your attention that something went wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:49:51.717", "Id": "65459", "Score": "0", "body": "That could work if the unit test set up the local server in setUp() or something. What's important is that the test controls the responses from the service or whatever he is connecting to. See my post where I show using dependency injection and mocks to solve the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T09:35:34.443", "Id": "65486", "Score": "0", "body": "A good unit tests suite should :\n\nallow parallel execution of the test suite, be independant of the environment, always execute the same way (if no code is added/changed/deleted ...)\n\nAdding a new local server is against all these requirements.\n\nIt seems this code is simply NOT unit testable... but maybe another kind of test would be needed here (integration test?)\n\nAny idea?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:37:49.717", "Id": "38932", "ParentId": "38906", "Score": "3" } }, { "body": "<p>I think that what you are getting at is that given the way the class is currently written, you've got a dependency and no way to replace it with a stand in for testing. If you don't replace it, 1) you would need to figure out what a suitable host name would be for the test, 2) if the network failed during the test, the test would fail, and 3) no way to test failures. </p>\n\n<p>To solve this problem, you would need to inject the dependency. In order to do that, you'd have to use some oop wrapper for the php fsock functions.</p>\n\n<p>Sometimes, I do go through the extra effort of creating injectable dependent wrappers and sometimes I do not.</p>\n\n<p>Here is an example of your modified class:</p>\n\n<pre><code>class SenderSocketAdapter extends SenderAdapterAbstract\n{\n public function __construct(Socket $socket)\n {\n $this-&gt;socket = $socket;\n }\n\n public function send($message)\n {\n $this-&gt;socket-&gt;fwrite($message);\n //as other poster said, you should probably \n //return a status or something here.\n //I'll assume that the parent function send is said to\n //return true on success and false on error. And I'll\n //assume that the called service returns \"0\" or \"-1\"\n return ($this-&gt;socket-&gt;fgets() === \"0\");\n }\n}\n</code></pre>\n\n<p>For the unit test:</p>\n\n<pre><code>class SenderSocketAdapterTest extends PHPUnit_TestCase\n{\n public function testSendSuccess()\n {\n $socket = $this-&gt;getMock('Socket');\n $sender = new SenderSocketAdapter($socket);\n\n $message = \"the message\";\n $socket-&gt;expects($this-&gt;once())\n -&gt;method('write')\n -&gt;with($this-&gt;equalTo($message))\n -&gt;will($this-&gt;returnValue(\"0\");\n $result = $sender-&gt;send($message);\n $this-&gt;assertTrue($result);\n }\n\n public function testSendFailure()\n {\n $socket = $this-&gt;getMock('Socket');\n $sender = new SenderSocketAdapter($socket);\n\n $message = \"the message\";\n $socket-&gt;expects($this-&gt;once())\n -&gt;method('write')\n -&gt;with($this-&gt;equalTo($message))\n -&gt;will($this-&gt;returnValue(\"-1\");\n $result = $sender-&gt;send($message);\n $this-&gt;assertFalse($result);\n }\n}\n</code></pre>\n\n<p>In the tests above, we are ensuring that the message being passed into the send method is being properly passed to the socket. And, we check to make sure that we return the correct boolean when the Socket operation is successful and when it fails. We do these things by directly controlling the \"Socket\" for the test conditions.</p>\n\n<p>Your calling code would then look something like:</p>\n\n<pre><code>$socket = new Socket($host, $port);\n$sender = new SenderSocketAdapter($socket);\nif ($sender-&gt;send('hello') === true) {\n echo \"success!\";\n} else {\n echo \"failure!\";\n}\n</code></pre>\n\n<p>You might want to look at <a href=\"https://github.com/clue/socket-raw\" rel=\"nofollow\">this socket wrapper</a> as a tool to use for your injected dependency.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T09:33:40.167", "Id": "65485", "Score": "0", "body": "Thx for your suggestion but, the original class ClientSocket wich extends SenderAdapterAbstract is already an adapter pattern, it will be injected to other classes. So I don't understand why should I add another Socket adapter since this is already done! And with your new Socket adapter, I would have the same problem: how to unit test this adapter" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:46:37.467", "Id": "39116", "ParentId": "38906", "Score": "1" } }, { "body": "<p>By definition adapters implement an interface defined by you, in order to prevent strong coupling between dependencies like frameworks, drivers, etc... and the other part of the code. The adapter is strong coupled to those dependencies, but the other part of the code, which uses the adapter, is strong coupled only to the interface the adapter is implementing... </p>\n\n<p>Unit testing means mocking out all the dependencies of a class and testing only the code the class contains, but that assumes that the class is loose coupled to its dependencies. By adapter pattern this is not the case, so you wont write unit tests for adapters. You can write integrations tests, which means you test if the adapter works well with its dependencies. Making integration tests is similar to unit tests except of mocking out all the dependencies. You can set up a scenario and define assertions. That's all. Be aware that integration tests are much slower than unit tests, so they are not for frequent usage.</p>\n\n<p>Your code is confusing, you set value of a <code>result</code> variable, but you don't return it, so I don't know what to test. If you want to test file write, you have to read the file you wrote in. If you want to test file read, you can read the content of a manually created file and compare the result what you wrote in the file by hand. If you want to check persistence, you have to clear your storage, save some content in it, read the content of your storage and compare with what you just saved. So writing integration tests is not hard, you can learn it in 10 minutes...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T09:17:17.917", "Id": "78889", "Score": "0", "body": "Yep I know integration testing. But It wasn't clear for me while practicing TDD and adding an adapter" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:10:09.267", "Id": "45267", "ParentId": "38906", "Score": "3" } } ]
{ "AcceptedAnswerId": "45267", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:15:31.593", "Id": "38906", "Score": "3", "Tags": [ "php", "unit-testing" ], "Title": "Unit-testing an adapter" }
38906
<p>A job application of mine has been declined because the test project I submitted was not coded in a clean and straightforward way.</p> <p>Fine, but that's all the feedback I got. Since I like to continuously improve my coding skills, are there people here who want to check out this project at Github? It's not complicated of course and it would be really helpful for me.</p> <p>The README contains the assignment specifics.</p> <p><a href="https://github.com/MatVre/iOS-MVC-Example" rel="nofollow">GitHub</a></p> <p>Crux of the requirements:</p> <blockquote> <h3>Functionality</h3> <p>The main should define and run 3 requests SIMULTANEOUSLY, each request is defined below:</p> <ol> <li><p><code>10thLetterRequest</code>:</p> <p>Grab a website’s content from the web Hold the web page content as a String and make it accessible from the Main Process the web page content: Find the 10th letter in the web page text and report it back to the Main program via a callback.</p></li> <li><p><code>Every10thLetterRequest</code>:</p> <p>Grab a website’s content from the web Hold the web page content as a String and make it accessible from the Main Process the web page content: Find every 10th letter(i.e: 10th, 20th, 30th etc.) in the web page text and report it back to the Main program via a callback. This callback should bring an appropriate data structure.</p></li> <li><p><code>WordCounterRequest</code>:</p> <p>Grab a website’s content from the web Hold the web page content as a String and make it accessible from the Main Process the web page content: Split the text into words by using whitespace characters (i.e: space, linefeed etc.) and write a simple algorithm to count every word in the document and report it back to the Main program via a callback. You can disregard html/javascript etc. and treat every word equally. The callback should bring an appropriate data structure of words and counts. So the main program should be able to ask how many times a certain word appears in the website.</p></li> </ol> </blockquote> <p>Core code: </p> <pre><code>// // dataRequest.m // assignment // // Created by Mathijs on 2013-12-19. // Copyright (c) 2013 Mathijs Vreeman. All rights reserved. // #import "dataRequest.h" @implementation dataRequest @synthesize urlString, occurrencesOfWordOutput, tenthLetterOutput, everyTenthOutput; - (void)getStringFrom:(NSURL *)url done:(void(^)())done { NSLog(@"URL is loaded only once"); // get contents of the URL NSError *error; urlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&amp;error]; if (error) { NSLog(@"%@", error); } // callback that URL is loaded done(); } - (void)getTenthLetterAndWhenComplete:(void(^)())completionCallback { NSLog(@"getTenthLetter called"); // strip white space to make sure to return a letter NSString *urlStringWithoutWhiteSpace = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""]; urlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@"\n" withString:@""]; urlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@"\t" withString:@""]; urlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@"\r" withString:@""]; // locate tenth letter and set output NSString *tenthLetter = [urlStringWithoutWhiteSpace substringWithRange:NSMakeRange(10, 1)]; tenthLetterOutput = [NSString stringWithFormat:@"the tenth letter is: %@", tenthLetter]; // callback that work is done completionCallback(); } - (void)getEveryTenthLetterAndWhenComplete:(void(^)())completionCallback { NSLog(@"getEveryTenthLetter called"); //strip white space NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:@"[a-zA-Z]" options:0 error:NULL]; // loop to get every tenth letter and add it to an array NSMutableArray *everyTenth = [[NSMutableArray alloc] init]; for (int i = 1; i &lt; floor([urlString length]/10); i++) { NSString *letter = [urlString substringWithRange:NSMakeRange(i*10, 1)]; NSInteger match = [regEx numberOfMatchesInString:letter options:0 range:NSMakeRange(0, [letter length])]; if (match &gt; 0) { [everyTenth addObject:letter]; } } // create an output string from this array NSMutableString *stringFromEveryTenthArray = [[NSMutableString alloc] init]; for (NSString *object in everyTenth) { [stringFromEveryTenthArray appendString:[object description]]; [stringFromEveryTenthArray appendString:@", "]; } everyTenthOutput = stringFromEveryTenthArray; // callback that work is done completionCallback(); } - (void)getOccurrencesOfWordInTotal:(NSString *)wordToCount complete:(void(^)())completionCallback { NSLog(@"getOccurrencesOfWordInTotal called"); //replace linebreaks and tabs by spaces to make the separation easier NSString *urlStringWithSpaces = [urlString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]; urlStringWithSpaces = [urlStringWithSpaces stringByReplacingOccurrencesOfString:@"\t" withString:@" "]; urlStringWithSpaces = [urlStringWithSpaces stringByReplacingOccurrencesOfString:@"\r" withString:@" "]; // count total number of words NSArray *wordsInUrlString = [urlStringWithSpaces componentsSeparatedByString:@" "]; NSInteger totalWordCount = [wordsInUrlString count]; // count the wordToCount and generate output string if (![wordToCount isEqualToString:@""]) { // count occurrences of specific word NSInteger occurrencesOfWord = [urlString length] - [[urlString stringByReplacingOccurrencesOfString:wordToCount withString:@""] length]; occurrencesOfWord = occurrencesOfWord / [wordToCount length]; occurrencesOfWordOutput = [NSString stringWithFormat:@"\"%@\" was found %d times in %d words", wordToCount, occurrencesOfWord, totalWordCount]; } else { occurrencesOfWordOutput = [NSString stringWithFormat:@"no search word was found"]; } // callback that work is done completionCallback(); } @end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:49:43.737", "Id": "65070", "Score": "0", "body": "I know that these requests should run simultaneously but you should have us review portions of your code rather than the whole thing, please post a portion of one of the requests as a single review question, maybe a portion that you think looks sloppy or unclear but can't figure out how to write it more clearly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:54:55.880", "Id": "65071", "Score": "0", "body": "the point is tat I really don't know. I wrote it as clean and straightforward as I could. My guess that it's more about the whole structure. Do you see some sloppy stuff on first sight?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:16:11.153", "Id": "65075", "Score": "0", "body": "@Mathijs Oh yes.. Please add a license file in your github repository that states we can copy the code, otherwise I have to remove the code and then this question will get closed." } ]
[ { "body": "<p>I have to agree with the evaluation.</p>\n\n<p><code>10thLetterRequest</code> and <code>Every10thLetterRequest</code> are pretty much exactly the same, except that <code>10thLetterRequest</code> only requires the first letter.</p>\n\n<p>Yet, you decided to use different regexes and have no re-use of code.</p>\n\n<p>The last assignment asks you return all words with a word count, instead of that you search for 1 word. You basically misunderstood the question completely.</p>\n\n<p>Other minor things :</p>\n\n<ul>\n<li><p>The name <code>getTenthLetterAndWhenComplete</code> lies, since you return a string, I would expect this to return just the 10th letter.</p></li>\n<li><p>Returning a comma separate string with the tenth letters is <strong>not</strong> <em>an appropriate data structure</em> for <code>getEveryTenthLetterAndWhenComplete</code>, even worse you build up an entire array and then throw it away.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:25:39.117", "Id": "65077", "Score": "0", "body": "Another minor thing could be a big maximum line length?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:14:54.740", "Id": "38912", "ParentId": "38907", "Score": "6" } }, { "body": "<p>You don't stick to the naming conventions. A class should be named in CamelCase, not camelCase. <code>dataRequest</code> would be <code>DataRequest</code>. furthermore it would be helpful to tell bit more about the request, as you also could request the local file system for something. Some name like <code>HTTPRequest</code> would be better.</p>\n\n<p>Also a method name should explain what it does (but not how). <code>getStringFrom:done:</code> would be better called <code>fetchStringFromURL:completionHandler:</code> or <code>fetchFromURL:completionHandler:</code> as it would be possible to fetch an image or other kind of data.<br>\nthe <code>done:</code> part of the name is also problematic. if you only see the name, you won't know, if you pass in a callback (block, object, selector), or if it is a BOOL reference to tell you, if the fetching went well.<br>\nActually you have no way to tell, if it went well. Either pass in an error object into the completion block, or have to blocks, one for success, one for failure.</p>\n\n<pre><code>fetchFromURL:successHandler:failureHandler:\n</code></pre>\n\n<p>Alternatively, you could call it <code>fetchFromURL:onSuccess:onFailure:</code> as this would clearly tell the user that an action will be fired. You should pass in the response from the fetch into both blocks (or take care that in failure there error object has it), so the programmer using it can react.</p>\n\n<hr>\n\n<p>You are exposing ivars instead of properties in the headers. also names like textView1 are not really good. Synthesizing is not needed since several years (2011) now.</p>\n\n<hr>\n\n<p>The asynchronous dispatching should be hidden from the view controller.</p>\n\n<hr>\n\n<p>My <code>DataRequest</code> could look like:</p>\n\n<pre><code>@implementation DataRequest\n\n\n- (void)fetchFrom:(NSURL *)url\n onSuccess:(void(^)(id response))successBlock\n onFailure:(void (^)(NSError *))failureBlock\n{\n\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n NSError *error;\n NSString *urlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&amp;error];\n\n dispatch_async(dispatch_get_main_queue(), ^{\n if (error) {\n failureBlock(error);\n } else {\n successBlock(urlString);\n }\n });\n });\n\n}\n\n\n\n-(NSArray *)_wordsFromString:(NSString *)string\n{\n NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:@\"[a-zA-Z]+\" options:0 error:NULL];\n\n NSArray *matches = [regEx matchesInString:string\n options:0\n range:NSMakeRange(0, [string length]-1)];\n NSMutableArray *wordArray = [@[] mutableCopy];\n\n [matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *match, NSUInteger idx, BOOL *stop) {\n [wordArray addObject:[string substringWithRange:[match range]]];\n }];\n return wordArray;\n\n}\n\n\n-(NSString *) _flattendedString:(NSString *)string keepWords:(BOOL)keepWords\n{\n return (keepWords) ? [[self _wordsFromString:string] componentsJoinedByString:@\" \"]\n : [[self _wordsFromString:string] componentsJoinedByString:@\"\"] ;\n}\n\n\n-(void)everyTenthLetterFromURL:(NSURL *)url\n onSuccess:(void (^)(NSArray *))success\n onFailure:(void (^)(NSError *))failureBlock\n{\n [self fetchFrom:url\n onSuccess:^(id response) {\n if ([response isKindOfClass:[NSString class]]) {\n NSString *responseString = (NSString *)response;\n responseString = [self _flattendedString:responseString keepWords:NO];\n NSMutableArray *letterArray = [@[] mutableCopy];\n\n [responseString enumerateSubstringsInRange:NSMakeRange(0, [responseString length])\n options:(NSStringEnumerationByComposedCharacterSequences)\n usingBlock:^(NSString *substring,\n NSRange substringRange,\n NSRange enclosingRange,\n BOOL *stop) {\n if (substringRange.location % 10 == 9) {\n [letterArray addObject:substring];\n }\n }];\n success(letterArray);\n }\n } onFailure:^(NSError *error) {\n failureBlock(error);\n }] ;\n\n}\n\n-(void)tenthLetterFromURL:(NSURL *)url\n onSuccess:(void (^)(NSString * letter))success\n onFailure:(void (^)(NSError *))failureBlock\n{\n [self fetchFrom:url\n onSuccess:^(id response) {\n if ([response isKindOfClass:[NSString class]]) {\n NSString *responseString = (NSString *)response;\n\n responseString = [self _flattendedString:responseString keepWords:NO];\n if ([responseString length] &gt; 10) {\n success([responseString substringWithRange:NSMakeRange(9, 1)]);\n }\n }\n } onFailure:^(NSError *error) {\n failureBlock(error);\n }] ;\n}\n\n-(void) allWordsFromURL:(NSURL *)url\n onSuccess:(void (^)(NSArray *words))success\n onFailure:(void (^)(NSError *))failureBlock\n{\n [self fetchFrom:url\n onSuccess:^(id response) {\n if ([response isKindOfClass:[NSString class]]) {\n NSString *responseString = (NSString *)response;\n\n success([self _wordsFromString:responseString]);\n }\n } onFailure:^(NSError *error) {\n failureBlock(error);\n }] ;\n}\n@end\n</code></pre>\n\n<p>Note that I condensed </p>\n\n<pre><code>NSString *urlStringWithoutWhiteSpace = [urlString stringByReplacingOccurrencesOfString:@\" \" withString:@\"\"];\nurlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@\"\\n\" withString:@\"\"];\nurlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@\"\\t\" withString:@\"\"];\nurlStringWithoutWhiteSpace = [urlStringWithoutWhiteSpace stringByReplacingOccurrencesOfString:@\"\\r\" withString:@\"\"];\n</code></pre>\n\n<p>to</p>\n\n<pre><code>NSString* returnString = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@\"\"];\n</code></pre>\n\n<hr>\n\n<p>And I would use it in the ViewController like</p>\n\n<pre><code>@interface ViewController ()\n\n@end\n\n@implementation ViewController\n\n\n- (IBAction)runButton:(id)sender {\n NSURL *url = [NSURL URLWithString:@\"https://www.google.com/\"];\n NSString *wordToCount = @\"google\";\n\n DataRequest *request = [[DataRequest alloc] init];\n [request tenthLetterFromURL:url\n onSuccess:^(NSString* letter) {\n [textView1 setText:letter];\n } onFailure:^(NSError* error) {\n [[[UIAlertView alloc] initWithTitle:@\"error\" message:[error localizedDescription] delegate:nil cancelButtonTitle:@\"dissmiss\" otherButtonTitles: nil] show];\n }];\n\n [request everyTenthLetterFromURL:url\n onSuccess:^(NSArray * letters){\n [textView2 setText: [letters componentsJoinedByString:@\"\"]];\n } onFailure:^(NSError * error) {\n [[[UIAlertView alloc] initWithTitle:@\"error\" message:[error localizedDescription] delegate:nil cancelButtonTitle:@\"dissmiss\" otherButtonTitles: nil] show];\n }];\n\n\n [request allWordsFromURL:url\n onSuccess:^(NSArray *words) {\n __block NSUInteger count =0;\n\n [words enumerateObjectsUsingBlock:^(NSString *word, NSUInteger idx, BOOL *stop) {\n if ([word compare:wordToCount options:NSCaseInsensitiveSearch]) {\n ++count;\n }\n }];\n [textView3 setText:[NSString stringWithFormat:@\"\\\"%@\\\" was found %d times in %d words\", wordToCount, count, [words count]]];\n\n } onFailure:^(NSError *error) {\n [[[UIAlertView alloc] initWithTitle:@\"error\" message:[error localizedDescription] delegate:nil cancelButtonTitle:@\"dissmiss\" otherButtonTitles: nil] show];\n }];\n\n@end\n</code></pre>\n\n<hr>\n\n<p>I want to mention that an object should do exactly one thing, but that perfectly.</p>\n\n<p>So the DataRequest should only fetch data. While I also gave it the responsibilities for getting the tenth letter and such stuff, that should actually be in a separate class. </p>\n\n<p><a href=\"https://github.com/vikingosegundo/iOS-MVC-Example/tree/master\" rel=\"nofollow\">GitHub</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:16:31.277", "Id": "38939", "ParentId": "38907", "Score": "3" } }, { "body": "<p>As I mentioned in my other answer, an object should have just one purpose. </p>\n\n<p>Here I try to achieve that for the DataRequest class by executing a list of blocks for each network request. </p>\n\n<hr>\n\n<pre><code>#import &lt;Foundation/Foundation.h&gt;\ntypedef void(^DataResponseBlock)(id resposeObject);\ntypedef void(^FailurBlock)(NSError *error);\n\n@interface DataRequest : NSObject\n@property (nonatomic, strong) NSArray *operations;\n@property (nonatomic, copy) FailurBlock failureBlock;\n- (void)fetchFrom:(NSURL *)url;\n\n@end\n</code></pre>\n\n<hr>\n\n<pre><code>#import \"DataRequest.h\"\n\n@implementation DataRequest\n\n\n- (void)fetchFrom:(NSURL *)url\n{\n __block NSError *err;\n\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n NSString *responseString = [NSString stringWithContentsOfURL:url\n encoding:NSASCIIStringEncoding\n error:&amp;err];\n\n if (err) {\n if (self.failureBlock) {\n dispatch_async(dispatch_get_main_queue(), ^{\n\n self.failureBlock(err);\n });\n }\n } else {\n for (DataResponseBlock obj in _operations) {\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n\n obj(responseString);\n });\n }\n }\n\n });\n\n}\n\n\n@end\n</code></pre>\n\n<hr>\n\n<p>That is the complete data request class.</p>\n\n<p>We can use it like:</p>\n\n<pre><code>#import \"ViewController.h\"\n#import \"DataRequest.h\"\n\n@interface ViewController ()\n\n@end\n\n@implementation ViewController\n\n\n- (IBAction)runButton:(id)sender {\n NSURL *url = [NSURL URLWithString:@\"https://www.google.com/\"];\n NSString *wordToCount = @\"google\";\n\n DataRequest *request = [[DataRequest alloc] init];\n\n NSMutableArray *operations = [NSMutableArray array];\n\n __block typeof(self) blockSelf = self;\n\n\n DataResponseBlock everyTenthLetter = ^(id response){\n if ([response isKindOfClass:[NSString class]]) {\n NSString *responseString = (NSString *)response;\n responseString = [blockSelf _flattendedString:responseString keepWords:NO];\n NSMutableArray *letterArray = [@[] mutableCopy];\n\n [responseString enumerateSubstringsInRange:NSMakeRange(0, [responseString length])\n options:(NSStringEnumerationByComposedCharacterSequences)\n usingBlock:^(NSString *substring,\n NSRange substringRange,\n NSRange enclosingRange,\n BOOL *stop) {\n if (substringRange.location % 10 == 9) {\n [letterArray addObject:substring];\n }\n }];\n dispatch_async(dispatch_get_main_queue(), ^{\n [textView2 setText:[letterArray componentsJoinedByString:@\"\"]];\n });\n }\n };\n\n\n DataResponseBlock tenthLetter = ^(id response){\n NSString *responseString = (NSString *)response;\n responseString = [blockSelf _flattendedString:responseString keepWords:NO];\n if ([responseString length] &gt; 10) {\n dispatch_async(dispatch_get_main_queue(), ^{\n [textView1 setText:[responseString substringWithRange:NSMakeRange(9, 1)]];\n });\n }\n };\n\n DataResponseBlock occurance = ^(id response){\n NSString *responseString = (NSString *)response;\n NSArray *words = [blockSelf _wordsFromString:responseString];\n __block NSUInteger count =0;\n\n [words enumerateObjectsUsingBlock:^(NSString *word, NSUInteger idx, BOOL *stop) {\n if ([word compare:wordToCount options:NSCaseInsensitiveSearch]) {\n ++count;\n }\n }];\n\n dispatch_async(dispatch_get_main_queue(), ^{\n [textView3 setText:[NSString stringWithFormat:@\"\\\"%@\\\" was found %d times in %d words\", wordToCount, count, [words count]]];\n });\n\n\n\n };\n\n FailurBlock failure = ^(NSError *error){\n [[[UIAlertView alloc] initWithTitle:@\"error\" message:[error localizedDescription] delegate:nil cancelButtonTitle:@\"dissmiss\" otherButtonTitles: nil] show];\n\n };\n\n [operations addObject:[everyTenthLetter copy]];\n [operations addObject:[tenthLetter copy]];\n [operations addObject:[occurance copy]];\n\n\n request.operations = operations;\n request.failureBlock = failure;\n [request fetchFrom:url];\n\n}\n\n\n-(NSString *) _flattendedString:(NSString *)string keepWords:(BOOL)keepWords\n{\n return (keepWords) ? [[self _wordsFromString:string] componentsJoinedByString:@\" \"]\n : [[self _wordsFromString:string] componentsJoinedByString:@\"\"] ;\n}\n\n\n-(NSArray *)_wordsFromString:(NSString *)string\n{\n NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:@\"[a-zA-Z]+\" options:0 error:NULL];\n\n NSArray *matches = [regEx matchesInString:string\n options:0\n range:NSMakeRange(0, [string length]-1)];\n NSMutableArray *wordArray = [@[] mutableCopy];\n\n [matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *match, NSUInteger idx, BOOL *stop) {\n [wordArray addObject:[string substringWithRange:[match range]]];\n }];\n return wordArray;\n\n}\n@end\n</code></pre>\n\n<hr>\n\n<p>Actually there is another improvement. And I would be not surprised, if the interviewer wanted to see that: Make the ViewController re-useable by adding a datasource. </p>\n\n<p><a href=\"https://github.com/vikingosegundo/iOS-MVC-Example/tree/OperationBased\" rel=\"nofollow\">Source code of this iteration</a>.</p>\n\n<hr>\n\n<p>The next step: Introducing a datasource to gain reusable view controllers — or at least avoid a <a href=\"http://doing-it-wrong.mikeweller.com/2013/06/ios-app-architecture-and-tdd-1.html\" rel=\"nofollow\">Massive View Controller</a>.</p>\n\n<p>Traditionally in Cocoa datasources follow the same pattern as delegates. Here I want to do it a little differently.</p>\n\n<p>I create a ViewController that has a datasource with a certain protocol:</p>\n\n<pre><code>@protocol DataSourceProtocol &lt;NSObject&gt;\n\n-(NSArray *)operations;\n-(NSURL *)url;\n@end\n</code></pre>\n\n<p><code>operations</code> will contain blocks with this signature:</p>\n\n<pre><code>typedef id(^DataResponseBlock)(id resposeObject, NSString **blockIdentifier);\n</code></pre>\n\n<p>This time the block will take a response object and returned a processed object. Each block can identify itself via a identifier, the ViewConroller will expect <code>everyTenthLetter</code>, <code>tenthLetter</code> and <code>occurrence</code>.</p>\n\n<p>The DataSource:</p>\n\n<pre><code>@implementation DataSource\n\n-(NSURL *)url\n{\n return [NSURL URLWithString:@\"https://www.google.com/\"];\n}\n\n-(NSArray *)operations\n{\n NSMutableArray *operations = [NSMutableArray array];\n\n __block typeof(self) blockSelf = self;\n\n\n DataResponseBlock everyTenthLetter = ^id(id response, NSString **blockIdentifier){\n if ([response isKindOfClass:[NSString class]]) {\n NSString *responseString = (NSString *)response;\n responseString = [blockSelf _flattendedString:responseString keepWords:NO];\n NSMutableArray *letterArray = [@[] mutableCopy];\n\n [responseString enumerateSubstringsInRange:NSMakeRange(0, [responseString length])\n options:(NSStringEnumerationByComposedCharacterSequences)\n usingBlock:^(NSString *substring,\n NSRange substringRange,\n NSRange enclosingRange,\n BOOL *stop) {\n if (substringRange.location % 10 == 9) {\n [letterArray addObject:substring];\n }\n }];\n *blockIdentifier = @\"everyTenthLetter\";\n return letterArray;\n }\n return nil;\n };\n\n\n DataResponseBlock tenthLetter = ^id(id response, NSString **blockIdentifier){\n *blockIdentifier = @\"tenthLetter\";\n\n NSString *responseString = (NSString *)response;\n responseString = [blockSelf _flattendedString:responseString keepWords:NO];\n if ([responseString length] &gt; 10) {\n return [responseString substringWithRange:NSMakeRange(9, 1)];\n\n }\n return nil;\n };\n\n\n DataResponseBlock occurance = ^id (id response, NSString **blockIdentifier){\n *blockIdentifier = @\"occurrence\";\n\n NSString *responseString = (NSString *)response;\n NSArray *words = [blockSelf _wordsFromString:responseString];\n __block NSUInteger count =0;\n NSString *wordToCount = @\"google\";\n\n [words enumerateObjectsUsingBlock:^(NSString *word, NSUInteger idx, BOOL *stop) {\n if ([word compare:wordToCount options:NSCaseInsensitiveSearch]) {\n ++count;\n }\n }];\n\n return [NSString stringWithFormat:@\"\\\"%@\\\" was found %d times in %d words\", wordToCount, count, [words count]];\n\n\n\n };\n\n [operations addObject:[everyTenthLetter copy]];\n [operations addObject:[tenthLetter copy]];\n [operations addObject:[occurance copy]];\n\n return operations;\n}\n@end\n</code></pre>\n\n<p>The DataRequest now uses a delegate protocol to inform the ViewController about new processed data.</p>\n\n<pre><code>@protocol DataRequestDelegate &lt;NSObject&gt;\n\n-(void)result:(id)result forBlockWithIdenfier:(NSString *)identifier;\n\n@end\n\n\ntypedef id(^DataResponseBlock)(id resposeObject, NSString **blockIdentifier);\ntypedef void(^FailurBlock)(NSError *error);\n\n@interface DataRequest : NSObject\n@property (nonatomic, strong) NSArray *operations;\n@property (nonatomic, copy) FailurBlock failureBlock;\n@property (nonatomic, weak) id&lt;DataRequestDelegate&gt; delegate;\n- (void)fetchFrom:(NSURL *)url;\n\n@end\n</code></pre>\n\n<p>The ViewController conforms to this protocol:</p>\n\n<pre><code>-(void)result:(id)result forBlockWithIdenfier:(NSString *)identifier\n{\n if ([identifier isEqualToString:@\"everyTenthLetter\"]) {\n [textView2 setText:[result componentsJoinedByString:@\"\"]];\n } else if ([identifier isEqualToString:@\"tenthLetter\"]) {\n [textView1 setText:result];\n } else if ([identifier isEqualToString:@\"occurrence\"]) {\n [textView3 setText:result];\n }\n\n}\n</code></pre>\n\n<p>The <code>DataRequest</code> looks like:</p>\n\n<pre><code>#import \"DataRequest.h\"\n\n@implementation DataRequest\n\n\n- (void)fetchFrom:(NSURL *)url\n{\n __block NSError *err;\n\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n NSString *responseString = [NSString stringWithContentsOfURL:url\n encoding:NSASCIIStringEncoding\n error:&amp;err];\n\n if (err) {\n if (self.failureBlock) {\n dispatch_async(dispatch_get_main_queue(), ^{\n\n self.failureBlock(err);\n });\n }\n } else {\n for (DataResponseBlock obj in _operations) {\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n NSString *iden;\n id result = obj(responseString, &amp;iden);\n dispatch_async(dispatch_get_main_queue(), ^{\n [self.delegate result:result forBlockWithIdenfier:iden];\n });\n });\n }\n }\n\n });\n\n}\n\n\n@end\n</code></pre>\n\n<p>Now I have a easy to configure view controller— all I need to do is to write a datasource. With inheritance this could actually mean that I just need to overwrite <code>-url</code> (or make it a property and set it from somewhere) to deal with very different sites. The ViewController and the DataRequest won't need to be changed.</p>\n\n<p><a href=\"https://github.com/vikingosegundo/iOS-MVC-Example/tree/DataSourceBased\" rel=\"nofollow\">GitHub</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T00:47:47.383", "Id": "38955", "ParentId": "38907", "Score": "2" } } ]
{ "AcceptedAnswerId": "38939", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T14:25:26.817", "Id": "38907", "Score": "6", "Tags": [ "mvc", "objective-c", "interview-questions", "ios", "web-scraping" ], "Title": "HTTP site scraper" }
38907
<p>I have designed the following input validation implementation with one goal: DRY. I'd like to know whether it is intuitive and what are the possible shortcomings.</p> <pre><code>$vlad = new \ay\vlad\Vlad(); $test = $vlad-&gt;test([ // Test script [ // Group of selectors and validators. Each selector is assessed against each validator. [ // Selectors 'foo', 'bar', 'baz' ], [ // Validators/ validation options ['fail' =&gt; 'break'], // Define Validator failure scenario: // * 'silent' exclude input from the current validator chain. // * 'soft' record an error and progress to the next Validator. // * 'hard' (default) record an error and exclude the selector from the rest of the Test. // * 'break' record an error and interrupt the Test. 'required', 'not_empty', ['fail' =&gt; 'hard'], // Reset default Validator failure scenario. 'email', ['length', 'max' =&gt; 10] // Length Validator with 'max' option. ] ], [ ['qux', 'quux'], [ // Validate email only if it is non-empty string. ['fail' =&gt; 'silent'], 'not_empty', ['fail' =&gt; 'hard'], 'email' ] ], [ ['password'], [ // 'password' selector value must match 'password_confirm' selector ['match', 'selector' =&gt; 'password_confirm'] ] ] ]); $result = $test-&gt;assess($dummy_input); </code></pre> <p>The entire library documentation and examples are avaiable at <a href="http://anuary.com/vlad" rel="nofollow">http://anuary.com/vlad</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:41:07.797", "Id": "65081", "Score": "0", "body": "This question is not a good candidate for Code Review I feel. You are asking us to review a piece of code that only servers to demonstrate the use of library you wrote.. It would make more sense to review the actual library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:09:09.367", "Id": "65087", "Score": "0", "body": "@tomdemuyt I disagree, interface to the library is just as important (if not more important), than the internal library logic. You usually can change quite easy the internals (without affecting the interface), but not vice-versa. While I would love someone to critique the whole library, I believe this is against the intention of http://codereview.stackexchange.com/. After all, you are asked to post the whole code relavent in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:14:39.667", "Id": "65088", "Score": "0", "body": "And what if my main issue here is the rather non-obvious array parameter (which is basically the whole thing)? That's an issue with the library and how it takes its input, not with this code. I have absolutely no idea what this code does without reading the docs. That's not good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:36:37.383", "Id": "65093", "Score": "1", "body": "DRY is important, but in some cases, repetition _improves_ readability and then, DRY has to take a step back. I much rather use an API that requires me to call `$form->addRule(VALIDATE::EMAIL_TYPE, VALIDATE::REQUIRE_VALUE);` a couple of times, so that I can later see, from the way I build the form, which fields are required and which aren't. I can also easily add/change/remove or even `if(){}` rules out. Your API relies on users writing a single well structured array. That's harder to read" } ]
[ { "body": "<p>Well, since you didn't post your lib code, I'm assuming you're looking for an API-review. I hope you're not going to take this the wrong way, but I wouldn't like to use your validator class at all.<Br/>\nIf I were you, I'd provide the users with an API that uses constants for the supported validation types, and -like I said in my comment- DRY is all well and good, but DOYOC (Do not Obfuscate Your Own Code) is more important, still. </p>\n\n<p>I suggest you bash out an API that would allow me to do this:</p>\n\n<pre><code>$validator = new Validator();//basic\n//or\n$validator = new Validator(\n array(\n Validator::DEFAULT_FAIL =&gt; VALIDATOR::FAIL_BREAK,\n Validator::DEFAULT_VALUE =&gt; VALIDATOR::VALUE_REQUIRED,\n )\n);\n</code></pre>\n\n<p>So pass an array with the default behaviour to the constuctor, and in case no array is passed: provide a <code>setDefaults</code> method + force the constructor to the strictest settings possible by default. Then the user can specify only those settings he wants to loosen up a little. But in general, when it comes to validation: the stricter the better.</p>\n\n<p>Then, add methods to add what you call a selector, I'd call it an entity, which the user can then use to add a validation rule:</p>\n\n<pre><code>$validator-&gt;addEntity(\n $name,//name of entity\n Validator::TYPE_EMAIL,//validation type\n array(\n 'value' =&gt; Validator::VALUE_OPTIONAL //override defaults here\n )\n);\n</code></pre>\n\n<p>This not only makes the resulting code easier to read/maintain, but also makes it more reusable! This, too is DRY! in your case, the user will need to create a new array if he/she wants to validate things differently. I only have to do this:</p>\n\n<pre><code>$emailOptions = array('value'=&gt;Validator::VALUE_OPTIONAL);\nif ($config-&gt;requireEmail) $emailOptions['value'] = Validator::VALUE_REQUIRED;\n</code></pre>\n\n<p>And the rest of the code can remain as-is.<br/>\nWhile testing, I can quickly comment out an <code>addEntity</code> call, or change one of them without having to go over that huge array again.</p>\n\n<p>In light of this (changing rules on-the-fly): provide methods like <code>alterRule</code> or <code>removeRule</code>, too</p>\n\n<p>If, in time, you get to writing form-building classes, you'll probably want your API to be able to deal with instances of a given class, and distill from it the rules required. One way to prepare your code to do so is by adding type-hints for <code>Traversable</code> objects.<br/>\nIf your API grows, it might also be worth wile considering writing <code>Argument</code> classes, that need to be passed to your API</p>\n\n<p>I'm not going to write a full example of how I'd structure a validator class, as I've only briefly looked at your code, and I'm tired. Just thought I'd expand a little on my comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:11:07.853", "Id": "65106", "Score": "0", "body": "Just in case, I did link to the library code http://anuary.com/vlad/. There is a github link, https://github.com/gajus/vlad. I see what you are suggesting. However, there are a number of libraries that do that already (e.g. Zend). Instead, I am trying to innovate the syntax. My argument is that the array syntax has a steeper learning curve, though it is actually easier to use, maintain and re-use in the long term." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T07:58:47.013", "Id": "65193", "Score": "0", "body": "@Guy: I'd have to respectfully disagree with you on array syntax having a steeper learning curve. Anyone can write an array. It does have a steeper _reading_ curve, and the larger the array becomes, the harder it is to read (reading-time-complexity of _O(log n)_ actually). My worry is people will be tempted to in-line the rules, and add new ones as their project grows, so your API is actively encouraging project code to grow organically, which ends up with OO-spaghetti IMO" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T18:31:17.307", "Id": "65274", "Score": "0", "body": "Even if you are right, there are more reasons for using array syntax. One of the planned features of the library is integration with javascript: Vlad will allow to export rules as JSON to be re-used in the frontend Vlad implementation. This would be impossible with rules built using `if` conditions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T18:01:17.613", "Id": "65336", "Score": "0", "body": "@Guy: Ok, so suppose I go to a site that uses your lib, and the front-end side is there: I can tell, by looking at the client-side code that your validator is being used, so I know what server-side technology is being used. If I found a security leak in your code, I could then easily exploit that because the client-side code shows me what is validated and how... BTW: JS is a functional language, PHP isn't. Both have their pro's and cons, and both should be used accordingly. 1 on 1 translations rarely work. I'd still opt for an OO interface, and implement `toJSON` methods" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T18:55:29.513", "Id": "65341", "Score": "0", "body": "The possibility of the afore mentioned exploit is negligible. Even for tier 2 merchant PCI DSS requirements, not exposing the name/version of the underlying system is a nice-to-have. Therefore most people should hardly worry about that. PHP is procedural language with OO support. While there aren't many good examples of PHP and JS library interoperability, well – it is a challenge ahead." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:50:25.753", "Id": "38919", "ParentId": "38911", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:14:36.490", "Id": "38911", "Score": "1", "Tags": [ "php", "form" ], "Title": "What are the drawbacks of DRY input validation configuration?" }
38911
<p>I have this script that moves a box around the screen and the loops the second part of the movement. I have altered the code to drop another three boxes (4 in total) into the animation so the boxes follow each other around the screen.</p> <p>I want it to work exactly like it does, but I'm sure there's a much better way of doing this:</p> <p><a href="http://jsfiddle.net/NF6LU/" rel="nofollow">Here's a js fiddle: http://jsfiddle.net/NF6LU/</a></p> <p>JS</p> <pre><code>function animateNode() { $('.node').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node2').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node3').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node4').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node2').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node3').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node4').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node2').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node3').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node4').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true }); $('.node').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node2').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node3').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true }); $('.node4').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true }); } $('.node').delay(1500).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true }); $('.node2').delay(3000).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true }); $('.node3').delay(4500).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true }); $('.node4').delay(6000).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true }); $('.node').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true }); $('.node2').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true }); $('.node3').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true }); $('.node4').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true }); $(function(){ animateNode(); setInterval(animateNode, 2000); }); </code></pre> <p>HTML</p> <pre><code>&lt;span class="node"&gt;&lt;/span&gt; &lt;span class="node2"&gt;&lt;/span&gt; &lt;span class="node3"&gt;&lt;/span&gt; &lt;span class="node4"&gt;&lt;/span&gt; </code></pre> <p>CSS</p> <pre><code>span.node, span.node2, span.node3, span.node4{ height: 16px; width: 16px; background-color: black; position: absolute; top: 60px; left: 50%; margin-left: -9px; } </code></pre>
[]
[ { "body": "<p>You are repeating yourself a ton here, you should read up on DRY.</p>\n\n<p>You could store the animations in an array and then execute those animations : </p>\n\n<pre><code>var PROPERTIES = 0 , OPTIONS = 1;\nvar animations = \n[ \n [ {top: '425px'} , { duration: 1800, easing : 'linear', queue: true } ],\n [ {marginLeft: '-284px'} , { duration: 2500, easing : 'linear', queue: true } ],\n [ { top: '157px'} , { duration: 1800, easing : 'linear', queue: true } ],\n [ {marginLeft: '264px'} , { duration: 2500, easing : 'linear', queue: true } ]\n] \n\nfunction animateNode( $node )\n{\n animations.forEach( function (animation)\n {\n $node.animate( animation[PROPERTIES] , animation[OPTIONS] ); \n });\n}\n\nfunction animateNodes()\n{\n animateNodes( $('.node') );\n animateNodes( $('.node2') );\n animateNodes( $('.node3') );\n animateNodes( $('.node4') );\n}\n</code></pre>\n\n<p>Ideally of course, you would store the results of <code>$(...)</code> in a variable and use that variable instead of invoking <code>$(...)</code> every single time. Even more ideally, those variables would be in an array over which you can loop.</p>\n\n<p>You can apply this technique to the rest of your code as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:27:37.597", "Id": "65121", "Score": "0", "body": "I refactored my answer, but left that finally part ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:37:34.943", "Id": "65206", "Score": "0", "body": "@tomdemuyt I get an Uncaught SyntaxError: Unexpected identifier" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:01:54.837", "Id": "65219", "Score": "0", "body": "Yes, missing closing bracket on ` $node.animate( animation[PROPERTIES] , animation[OPTIONS] ); ` fixed now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T21:21:12.563", "Id": "65287", "Score": "0", "body": "I think you wanted to call `animateNode` (no s at the end) inside of `animateNodes`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:19:10.897", "Id": "38918", "ParentId": "38915", "Score": "3" } }, { "body": "<p>I agree with @tomdemuyt's overall approach but would suggest a few additional improvements.</p>\n\n<pre><code>$(function(){ \n var nodes = [\n $('.node'),\n $('.node2'),\n $('.node3'),\n $('.node4')\n ];\n\n var animations = [ \n { \n properties: {top: '425px'}, \n options: { duration: 1800, easing : 'linear'} \n },\n { \n properties: {marginLeft: '-284px'}, \n options: { duration: 2500, easing : 'linear'} \n },\n { \n properties: { top: '157px'}, \n options: { duration: 1800, easing : 'linear'} \n },\n { \n properties: {marginLeft: '264px'}, \n options: { duration: 2500, easing : 'linear'} \n }\n ];\n\n function animateNode( $node ){\n // call each animation in the array for the given node\n animations.forEach( function (animation){\n $node.animate( animation.properties , animation.options ); \n });\n\n // once all animations complete, call this function again\n $node.queue(function(next){\n animateNode($node); \n next();\n });\n }\n\n function animateNodes(){\n // call the animateNode function for every node \n nodes.forEach(function($node){\n animateNode($node);\n });\n }\n\n // do the initial animation for each node, incrementing the initial delay by 1.5s each node\n for(var i = 0; i&lt;nodes.length; i++){\n nodes[i].delay(1500 * (i + 1))\n .animate({top: '157px'}, { duration: 1000, easing : 'linear'})\n .animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear'});\n }\n\n // initialize the looping animation\n animateNodes();\n});\n</code></pre>\n\n<ul>\n<li>Store your nodes in an array to make the solution more generic as well as reduce repeated code. This has the added benefit of caching the jquery objects.</li>\n<li>Make your animations an array of objects instead of an array of arrays. This eliminates the need for PROPERTIES and OPTIONS.</li>\n<li>You have an issue that you are calling <code>animateNode</code> every 2 seconds. However, the duration of your animation created by that function is considerably longer than 2 seconds. As a result, your animations are going to continue to build up. The memory usage will continue to grow for as long as the page is running. Open your console and run this fiddle to see the queue length increase <a href=\"http://jsfiddle.net/NF6LU/8/\" rel=\"nofollow\">http://jsfiddle.net/NF6LU/8/</a> . Instead, I have eliminated <code>setInterval</code> all together and used Queue to call <code>animateNode</code> once the previous set of animations completes. Alternatively, you could call it as the callback of the final animation.</li>\n<li>You can eliminate <code>queue: true</code> as that is the default.</li>\n<li>Include all of your code in the ready function to avoid polluting the global space. This also ensure the nodes exist before using them. Your fiddle only worked due to the fact that it was set to run the code onload.</li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/NF6LU/10/\" rel=\"nofollow\">http://jsfiddle.net/NF6LU/10/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T21:48:03.240", "Id": "39029", "ParentId": "38915", "Score": "2" } } ]
{ "AcceptedAnswerId": "38918", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T15:59:33.643", "Id": "38915", "Score": "4", "Tags": [ "javascript", "performance", "jquery", "jquery-ui", "easing" ], "Title": "Delay and queue animation in a function - how can I optimise this by removing duplicate code?" }
38915
<p>This is code for <a href="http://en.wikipedia.org/wiki/Fizz_buzz" rel="nofollow">FizzBuzz</a>. I have also hosted in on my <a href="https://github.com/sarawut-p/FizzBuzz" rel="nofollow">GitHub</a>.</p> <p><strong>FizzChecker Tests</strong></p> <pre><code>[TestClass] public class FizzChecker_Tests { IFizzChecker _fizzChecker; bool isFizz; [TestInitialize] public void TestInitialize() { //Arrange _fizzChecker = new FizzChecker(); isFizz = default(bool); } [TestMethod] public void When_Devisible_By_Three_Return_True() { //Act isFizz = _fizzChecker.IsFizz(3); //Assert Assert.AreEqual(isFizz, true); } [TestMethod] public void When_Not_Devisible_By_Three_Return_False() { //Act isFizz = _fizzChecker.IsFizz(1); //Assert Assert.AreEqual(isFizz, false); } [TestMethod] public void When_Devide_By_Zero_Return_True() { //Act isFizz = _fizzChecker.IsFizz(0); //Assert Assert.AreEqual(isFizz, true); } } </code></pre> <p><strong>Fizz</strong></p> <pre><code>public interface IFizzChecker { bool IsFizz(int number); } public class FizzChecker : IFizzChecker { public bool IsFizz(int number) { return (number % 3) == 0; } } </code></pre> <p><strong>Buzz tests</strong></p> <pre><code>[TestClass] public class BuzzChecker_Tests { BuzzChecker _buzzChecker; bool isFizz; [TestInitialize] public void TestInitialize() { //Arrange _buzzChecker = new BuzzChecker(); isFizz = default(bool); } [TestMethod] public void When_Devisible_By_Fize_Return_True() { //Act isFizz = _buzzChecker.IsBuzz(5); //Assert Assert.AreEqual(isFizz, true); } [TestMethod] public void When_Not_Devisible_By_Three_Return_False() { //Act isFizz = _buzzChecker.IsBuzz(1); //Assert Assert.AreEqual(isFizz, false); } [TestMethod] public void When_Devide_By_Zero_Return_True() { //Act isFizz = _buzzChecker.IsBuzz(0); //Assert Assert.AreEqual(isFizz, true); } } </code></pre> <p><strong>BuzzChecker</strong></p> <pre><code>public interface IBuzzChecker { bool IsBuzz(int number); } public class BuzzChecker : IBuzzChecker { public bool IsBuzz(int number) { return (number % 5) == 0; } } </code></pre> <p>I've written a test for <code>FizzBuzzPrinter</code>. Is it correct to mock the return results on <code>IBuzzChecker</code> and <code>IFizzChecker</code> instead of using concrete implementation? Since I think that I am testing <code>FizzBuzzPrinter</code> on this abstraction, not its dependency, so I mock all the dependency.</p> <pre><code>[TestClass] public class FizzBuzzPrinter_Tests { IFizzBuzzPrinter _fizzBuzzPrinter; Mock&lt;IFizzChecker&gt; _mockFizzChecker; Mock&lt;IBuzzChecker&gt; _mockBuzzChecker; [TestInitialize] public void Initialize() { _mockFizzChecker = new Mock&lt;IFizzChecker&gt;(); _mockBuzzChecker = new Mock&lt;IBuzzChecker&gt;(); _fizzBuzzPrinter = new FizzBuzzPrinter(_mockFizzChecker.Object, _mockBuzzChecker.Object); } [TestMethod] public void When_Number_Is_In_FizzCheckerConditionOnly_Return_Fizz() { //Arrange int number = 3; _mockFizzChecker.Setup(checker =&gt; checker.IsFizz(number)).Returns(true); _mockBuzzChecker.Setup(checker =&gt; checker.IsBuzz(number)).Returns(false); //Act string result = _fizzBuzzPrinter.Print(number); Assert.AreEqual("Fizz", result); } [TestMethod] public void When_Number_Is_In_BuzzCheckerConditionOnly_Return_Fizz() { //Arrange int number = 5; _mockFizzChecker.Setup(checker =&gt; checker.IsFizz(number)).Returns(false); _mockBuzzChecker.Setup(checker =&gt; checker.IsBuzz(number)).Returns(true); //Act string result = _fizzBuzzPrinter.Print(number); Assert.AreEqual("Buzz", result); } [TestMethod] public void When_Number_Is_In_Both_BuzzChecker_And_FizzChecker_Condition_Return_FizzBuzz() { //Arrange int number = 15; _mockFizzChecker.Setup(checker =&gt; checker.IsFizz(number)).Returns(true); _mockBuzzChecker.Setup(checker =&gt; checker.IsBuzz(number)).Returns(true); //Act string result = _fizzBuzzPrinter.Print(number); Assert.AreEqual("FizzBuzz", result); } [TestMethod] public void When_Number_Is_Not_In_Both_BuzzChecker_And_FizzChecker_Condition_Return_Original_Number() { //Arrange int number = 22; _mockFizzChecker.Setup(checker =&gt; checker.IsFizz(number)).Returns(false); _mockBuzzChecker.Setup(checker =&gt; checker.IsBuzz(number)).Returns(false); //Act string result = _fizzBuzzPrinter.Print(number); Assert.AreEqual("22", result); } } </code></pre> <p><strong>FizzBuzzPrinter</strong></p> <pre><code>public interface IFizzBuzzPrinter { string Print(int number); } public class FizzBuzzPrinter : IFizzBuzzPrinter { private IFizzChecker fizzChecker; private IBuzzChecker buzzChecker; public FizzBuzzPrinter(IFizzChecker fizzChecker, IBuzzChecker buzzChecker) { this.fizzChecker = fizzChecker; this.buzzChecker = buzzChecker; } public FizzBuzzPrinter() : this (new FizzChecker(), new BuzzChecker()) { } public string Print(int number) { if (fizzChecker.IsFizz(number) &amp;&amp; buzzChecker.IsBuzz(number)) { return "FizzBuzz"; } if (fizzChecker.IsFizz(number)) { return "Fizz"; } if(buzzChecker.IsBuzz(number)) { return "Buzz"; } return number.ToString(); } } </code></pre> <p>Then in the main <code>Program</code>, I call it like this:</p> <pre><code>class Program { static void Main(string[] args) { IFizzBuzzPrinter fizzBuzzPrinter = new FizzBuzzPrinter(); for (int i = 1; i &lt;= 100; i++) { Console.WriteLine(fizzBuzzPrinter.Print(i)); } Console.ReadKey(); } } </code></pre> <p>Does this follow the proper mindset of SRP and unit-testing? Is there anything wrong that needs to be improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-30T00:16:56.870", "Id": "104941", "Score": "1", "body": "Related: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition" } ]
[ { "body": "<p>I think you're overdoing it. SRP does not mean that every class should have only one method and every method should be a one-liner.</p>\n\n<p>Instead, you should structure your code into parts that are likely to change together (though that's not the only criterion). But here, it's not really possible to guess that, because it's obvious these are not real requirements.</p>\n\n<p>I think that FizzBuzz is a good problem to test that you know the basics of programming (logical way of thinking about problems) or to test that you know the basics of some programming language (ifs, functions). But because of how artificial the problem is, it's not very good for testing things like SRP or unit testing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:03:33.313", "Id": "65105", "Score": "2", "body": "Is there any good practice excercise for SRP ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:37:26.810", "Id": "65110", "Score": "2", "body": "@SarawutPositwinyu take a look at our [tag:weekend-challenge] posts; Rock-Paper-Scissors-Lizard-Spock is a fun one." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:58:32.483", "Id": "38924", "ParentId": "38920", "Score": "11" } }, { "body": "<p>I know this is an old post, but it got bumped and I noticed this oddness:</p>\n\n<blockquote>\n<pre><code> public string Print(int number)\n {\n if (fizzChecker.IsFizz(number) &amp;&amp; buzzChecker.IsBuzz(number))\n {\n return \"FizzBuzz\";\n }\n\n if (fizzChecker.IsFizz(number))\n {\n return \"Fizz\";\n }\n\n if(buzzChecker.IsBuzz(number))\n {\n return \"Buzz\";\n }\n\n return number.ToString();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I would expect a function named \"Print\" to print something (Probably to standard output), not return a string. Considering you have an interface for the printer, and you're printing to the Console, I would say that <code>FizzBuzzPrinter</code> should output directly to console. That way you can avoid doing this. </p>\n\n<pre><code>Console.WriteLine(fizzBuzzPrinter.Print(i));\n</code></pre>\n\n<p>And replace it with:</p>\n\n<pre><code>fizzBuzzPrinter.Print(i);\n</code></pre>\n\n<p>Different implementations of <code>IFizzBuzzPrinter</code> could Print to different outputs as necessary. </p>\n\n<p>@Jamal's <a href=\"https://codereview.stackexchange.com/questions/38920/does-this-fizzbuzz-code-correctly-follow-srp-and-unit-testing/58448#comment104925_58448\">idea in the comments</a> about calling <code>Print()</code> <code>ToString()</code> instead is probably a better idea though. Like @BenAaronson pointed out, <a href=\"https://codereview.stackexchange.com/questions/38920/does-this-fizzbuzz-code-correctly-follow-srp-and-unit-testing/58448#comment104928_58448\">different implementations would require a lot of this duplicated logic</a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T23:24:56.170", "Id": "104925", "Score": "1", "body": "So it should be named `toString()`, I suppose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T23:28:34.393", "Id": "104927", "Score": "0", "body": "That's another good alternative @Jamal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T23:36:30.373", "Id": "104928", "Score": "1", "body": "If different implementations of `IFizzBuzzPrinter.Print` varied by how they did their output, there'd be a lot of repeated logic between them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-30T00:03:30.760", "Id": "104934", "Score": "0", "body": "I've just realized something regarding my naming suggestion. Would that not work since C#'s functions are in PascalCase, and may clash with the system's `ToString()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-30T00:10:06.290", "Id": "104936", "Score": "0", "body": "I believe you would have to over ride it. ToString is a method of Object and all other objects implicitly inherit from Object. So, yeah. I'm pretty sure it works." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T23:22:54.470", "Id": "58448", "ParentId": "38920", "Score": "2" } } ]
{ "AcceptedAnswerId": "38924", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T16:57:34.240", "Id": "38920", "Score": "6", "Tags": [ "c#", "unit-testing", "fizzbuzz" ], "Title": "Does this FizzBuzz code correctly follow SRP and unit-testing?" }
38920
<p>Suppose I have a text file which contains 10,000 random values between 0 and 1, and I want to count the number of values within a specific interval. An example may explain it more clearly.</p> <p>Suppose my Datefile.txt contains data like:</p> <pre><code>0.0102244 0.028072 0.0144578 0.064578 0.08148 0.012749 0.12749.....and 10,000 more values </code></pre> <p>And I want to count the number of values within the interval 0.05 (i.e. it searches for the values within the range 0.0 to 0.05, then 0.05 to 0.1 and so on). For the example above, the output will be:</p> <pre><code>In range 0 to 0.05, total values 4 In range 0.05 to 0.1, total values 2 In range 0.1 to 0.15, total values 1...etc. </code></pre> <p>Here is my code:</p> <pre><code>int main(){ double area; double a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0; ifstream theFile ("Datafile.txt"); while(theFile &gt;&gt;area){ if (area&lt;=0.05){ a++; } else if (area&lt;=0.1){ b++; } else if (area&lt;=0.15){ c++; } else if (area&lt;=0.2){ d++; } else if (area&lt;=0.25){ e++; } else if (area&lt;=0.3){ f++; } else if (area&lt;=0.35){ g++; } else if (area&lt;=0.4){ h++; } else if (area&lt;=0.45){ i++; } else if (area&lt;=0.5){ k++; } else if (area&lt;=0.55){ l++; } else if (area&lt;=0.6){ m++; } else if (area&lt;=0.65){ n++; } else if (area&lt;=0.7){ o++; } else if (area&lt;=0.75){ p++; } else if (area&lt;=0.8){ q++; } else if (area&lt;=0.85){ r++; } else if (area&lt;=0.9){ s++; } else if (area&lt;=0.95){ t++; } else if (area&lt;=1.0){ u++; } } </code></pre> <p>Though my code is working fine, it might not be the most efficient way. So I put my code here for review. Can anyone suggest a better way of doing this?</p> <p><strong>Updated (based on the answer of ChrisWue)</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;vector&gt; #include &lt;fstream&gt; using namespace std; int main(){ const double bucket_size = 0.05; double area=0; int number_of_buckets = (int)ceil(1 / bucket_size); std::vector&lt;int&gt; histogram(number_of_buckets); ifstream theFile("Datafile.txt"); while (theFile &gt;&gt; area) { int bucket = (int)floor(area / bucket_size); histogram[bucket] += 1; } for(auto loop = histogram.begin(); loop != histogram.end();++loop) { cout&lt;&lt;bucket_size&lt;&lt;"\t"&lt;&lt;number_of_buckets&lt;&lt;endl; } return 0; } </code></pre> <p>For the data-</p> <pre><code>0.0102244 0.028072 0.0144578 0.064578 0.08148 0.012749 0.12749..... </code></pre> <p>it gives the output like this-</p> <pre><code>0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 0.05 20 </code></pre> <p>What am I doing wrong?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:47:40.073", "Id": "65100", "Score": "0", "body": "What are your single-letter variables for? It looks like they should be in an array. You also shouldn't use a single letter for any variable, unless it's a loop counter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:54:32.460", "Id": "65101", "Score": "0", "body": "@Jamal I used those letter to count the number of values within that range." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:57:28.910", "Id": "65102", "Score": "2", "body": "Like I said, consider an array to hold those values. Since there are 20 variables, your array will be of that size. You could call it something like `ranges`. If you need more explanation, I can put this into an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:00:40.907", "Id": "65103", "Score": "0", "body": "@Jamal A little more explanation would be lovely. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:24:33.243", "Id": "65109", "Score": "0", "body": "Done. I've also added an example with `std::map` (which may be preferred), and I'll check it in case I've made any mistakes." } ]
[ { "body": "<p>In general, do not to use single letters as variable names, unless they're simple loop counters. This reveals nothing about them and will just make your code harder to understand.</p>\n\n<p>In your example, it looks like you're holding the number of values at different ranges. Not only do your variables reveal nothing about this, but it's harder to read and to maintain.</p>\n\n<p>Instead of this, you could use an array, if you still want to stay simple. Since there are twenty variables, your array can be of that size.</p>\n\n<p>Consider something like this:</p>\n\n<pre><code>int ranges[20] = {};\n</code></pre>\n\n<p>Note that, in C++ (not C), <a href=\"https://stackoverflow.com/a/201116/1950231\">this initializes each element to 0</a>.</p>\n\n<p>So, for your code, you would have this:</p>\n\n<pre><code>while (theFile &gt;&gt; area) {\n\n if (area &lt;= 0.05) {\n ranges[0]++;\n }\n\n else if (area &lt;= 0.1) {\n ranges[1]++;\n }\n\n // remaining conditions...\n}\n</code></pre>\n\n<p>Now, if you wanted to really utilize the STL, you could instead consider an <a href=\"http://en.cppreference.com/w/cpp/container/map\" rel=\"nofollow noreferrer\"><code>std::map</code></a>. This would allow you to set the different ranges as key values, along with the held quantity as mapped values.</p>\n\n<p>Something like this:</p>\n\n<pre><code>std::map&lt;float, int&gt; ranges;\n</code></pre>\n\n<p>You can initialize all of the values at once (which requires C++11):</p>\n\n<pre><code>std::map&lt;float, int&gt; ranges = { {0.05, 0}, {0.1, 0} /* ... */ };\n</code></pre>\n\n<p>If you don't have C++11:</p>\n\n<pre><code>std::map&lt;float, int&gt; ranges;\n\nranges[0.05] = 0;\nranges[0.1] = 0;\n// ...\n</code></pre>\n\n<p>Then in the loop, increment at each range as needed:</p>\n\n<pre><code>while (theFile &gt;&gt; area) {\n\n if (area &lt;= 0.05) {\n ranges[0.05]++;\n }\n\n else if (area &lt;= 0.1) {\n ranges[0.1]++;\n }\n\n // remaining conditions...\n}\n</code></pre>\n\n<p>This may look similar to the first example with the array, but it's actually different. This will create a new key value (a range) and increment its mapped value (its quantity). This does not correspond to indices associated with arrays. Although key values must be unique, the map is designed to only create new key values. If it tries to add another one, it'll ignore it. In this case, it'll just increment its count.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:00:41.460", "Id": "65113", "Score": "1", "body": "The next step would then be to create a vector of upper limits for each bin and iterate over that instead of manually unrolling the loop into this endless `if...else if` cascade." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:06:22.683", "Id": "65115", "Score": "0", "body": "@amon: True. I'm showing this as an example using these loops. Feel free to add an answer about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:37:03.747", "Id": "65168", "Score": "0", "body": "`std::map<float, int>` is setting off all sorts of alarms. Floats are not well-suited to typical equality comparisons. I think the use you show (always literals) is relatively safe, but it's not far from one that calculates the bound through some sort of rounding, and falls prey to floating point inaccuracy. Consider whether `0.1 * 3 == 0.3`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:39:11.797", "Id": "65169", "Score": "0", "body": "@MichaelUrman: I see. Should I make any corrections here, or just remove the parts about the map?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T04:00:17.413", "Id": "65172", "Score": "0", "body": "I'm not 100% sure. It's nice to get logarithmic time. Perhaps using `map::lower_bound` would be enough to not set off alarms, as that will at least avoid creating extra buckets. The advantage over the elegant mathematical approach is you can more easily specify non-uniform ranges." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T04:10:25.820", "Id": "65173", "Score": "0", "body": "@MichaelUrman: I didn't that floating-point as key values could be problematic, especially with the STL. I'll keep my answer as-is until I can find more information on this." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:23:52.240", "Id": "38929", "ParentId": "38922", "Score": "4" } }, { "body": "<p>What you want is a <a href=\"http://en.wikipedia.org/wiki/Histogram\">histogram</a> of your values. If you want it to be flexible in the future with different bucket sizes, then you can use a <code>std::vector</code> and calculate how many buckets you need.</p>\n\n<p>If the values are in range <code>[0, 1]</code> and <code>0 &lt; bucket_size &lt; 1</code>, then the number of buckets you need obviously is <code>ceil(1 / bucket_size)</code>.</p>\n\n<p>So what I'd do would probably look something like this:</p>\n\n<pre><code>const float bucket_size = 0.05;\nint number_of_buckets = (int)ceil(1 / bucket_size); // requires &lt;cmath&gt;\nstd::vector&lt;int&gt; histogram(number_of_buckets);\n\n...\n\nwhile (theFile &gt;&gt; area) {\n int bucket = (int)floor(area / bucket_size);\n histogram[bucket] += 1;\n}\n</code></pre>\n\n<p>No big <code>if</code>-<code>else</code> cascade and easy to adjust for different bucket sizes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:23:12.473", "Id": "65166", "Score": "0", "body": "I love how this transforms the problem to something much more manageable. However as it involves reading input, I would strongly suggest putting some sort of range checks either on `area` or on `bucket` before using it to subscript `histogram`. I presume this was omitted for clarity of answer. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:25:11.623", "Id": "65167", "Score": "0", "body": "@MichaelUrman: Yes, the code operates on the assumption stated above :). In real life you certainly need input checking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:56:10.333", "Id": "65218", "Score": "0", "body": "@ChrisWue This is what I was looking for. But I am having trouble using it (may be some noobie mistakes). I have updated my post and added the new code (based on your answer). Please check. Could you please help me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:56:17.877", "Id": "65270", "Score": "0", "body": "@aries0152: Well, that would be an off-topic question here (we only review working code) but you print out the `bucket_size` and the `number_of_buckets` which are fixed. What you need to print is: `for (std::vector<int>::size_type i = 0; i < histogram.size(); ++i) { cout << (i + 1) * bucket_size << \"\\t\" << histogram[i] << \"\\n\"; }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-20T01:25:13.637", "Id": "497264", "Score": "0", "body": "A small note: it's always tricky with histograms on a closed interval like [0 1] - where the upper bound will get mapped beyond the number of available buckets. In the example above, an area value of 1.0 will get mapped to bucket index 20 (1.0/.05), but you've only allocated 20 buckets (indexes 0 to 19). A common thing is just to include the upper end of the range into the last bucket..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:14:57.767", "Id": "38930", "ParentId": "38922", "Score": "13" } }, { "body": "<p>Given that this is C++, you should try for a more object-oriented design. My recommendation is to create a <code>Histogram</code> class. The interface might look like:</p>\n\n<pre><code>class Histogram {\n public:\n // Pick whichever constructor feels more natural to you\n Histogram(double min, double max, int numberOfBins);\n Histogram(double min, double max, double binWidth);\n\n void record(double datum);\n int bins() const; // Get the number of bins\n int count(int bin) const; // Get the number of data points in some bin\n int countLowerOutliers() const; // Get count of values below the minimum\n int countUpperOutliers() const; // Get count of values at or above the maximum\n double lowerBound(int bin) const; // Get the inclusive lower bound of a bin\n double upperBound(int bin) const; // Get the exclusive upper bound of a bin\n\n virtual ~Histogram();\n\n private:\n double binWidth;\n int binCount;\n int lowerOutlierCount, upperOutlierCount;\n int counts[];\n};\n</code></pre>\n\n<p>It should be implemented using an array.</p>\n\n<pre><code>void Histogram::record(double datum) {\n int bin = (int)((datum - min) / binWidth);\n if (bin &lt; 0) {\n lowerOutlierCount++;\n } else if (bin &gt;= binCount) {\n upperOutlierCount++;\n } else {\n count[bin]++;\n }\n}\n</code></pre>\n\n<p>Then, your <code>main()</code> looks clean.</p>\n\n<pre><code>int main() {\n Histogram histogram(0.0, 1.0, 0.05);\n double area;\n\n ifstream theFile(\"Datafile.txt\");\n while (theFile &gt;&gt; area) {\n histogram.record(area);\n }\n\n for (int i = 0; i &lt; histogram.bins(); ++i) {\n std::cout &lt;&lt; \"In range \" &lt;&lt; histogram.lowerBound(i)\n &lt;&lt; \" to \" &lt;&lt; histogram.upperBound(i)\n &lt;&lt; \", total values \" &lt;&lt; histogram.count(i)\n &lt;&lt; std::endl;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:19:54.267", "Id": "38931", "ParentId": "38922", "Score": "6" } }, { "body": "<p>How about this?</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\nmain (){\n ifstream file(\"datafile.txt\");\n double area;\n int histogram[10][10]={};\n while (file&gt;&gt;area){\n histogram [(int)(area*10)] [((int)(area*100))%10] ++;\n }\n}\n</code></pre>\n\n<p>Much faster to write, it stores your histogram in a 2-dimensional array, you can easily edit this code to store it in whatever structure you need.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:43:31.467", "Id": "65248", "Score": "0", "body": "I think this answer could be expanded, but still +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:56:25.690", "Id": "39004", "ParentId": "38922", "Score": "2" } } ]
{ "AcceptedAnswerId": "38930", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T17:34:22.047", "Id": "38922", "Score": "4", "Tags": [ "c++", "optimization", "statistics" ], "Title": "More efficient way of counting the number of values within an interval?" }
38922
<p>My company has asked me to write a few Java based programs to deal with sending HTTP requests and parsing the response. After playing around with the Apache HTTP Commons library and making plenty of shortsighted programs using it, I've decided to make a little library for us to use and avoid major code duplication. We're a pretty small company working with a really old code base, and they don't seem to have time to do code reviews. So I present to you, my small API (leaving major comments outside to describe classes and break up the code segments). </p> <ul> <li>As a small aside, you may see reference to static class <code>ResponseBodyDisplay</code>, which is a simple helper class (that looks like crap) to pull out the response body. It's not posted, because I didn't write it and it looks like poop. </li> </ul> <pre><code>/** * This class facilitates an easy to use controller for creating HTTP * requests without having a bunch of duplicate code. * * Typical use: * HttpController.processBodyRequest(request, json) * * In retrospect, "getJSONField()" may be a little outside the scope * of an HttpController. Meh! */ public class HttpController { private static DefaultHttpClient httpClient = new DefaultHttpClient(); public static Response processBodyRequest(Request r, String json) throws IOException { r.applyHeaders(); HttpEntityEnclosingRequestBase request = r.getHttpRequest(); ByteArrayEntity dataEntity = new ByteArrayEntity(json.getBytes()); request.setEntity(dataEntity); return executeRequest(request); } private static Response executeRequest(HttpEntityEnclosingRequestBase request) throws IOException { HttpResponse httpResponse = httpClient.execute(request); Header[] headers = httpResponse.getAllHeaders(); Response r = new Response(httpResponse); for (Header h: headers) { r.addHeader(h.getName(), h.getValue()); } r.setJSON(ResponseBodyDisplay._getResponseBody(httpResponse.getEntity())); return r; } public static String getJSONField(Response r, String fieldName) { try { String responseJSON = r.getJSON(); JSONTokener tokener = new JSONTokener(responseJSON); JSONObject responseJSONObject = new JSONObject(tokener); return responseJSONObject.getString(fieldName); } catch (Exception e) { e.printStackTrace(); return null; } } } </code></pre> <pre><code>/** * Object container for header map and JSON String. */ public class HttpObject { protected String json; protected HashMap&lt;String, String&gt; headers; protected HttpObject() { headers = new HashMap&lt;String, String&gt;(); } public void addHeader(String name, String value) { headers.put(name, value); } public void setJSON(String json) { this.json = json; } public String getJSON() { return json; } } </code></pre> <pre><code>/** * Simulates Apache HttpRequest object with the necessary information * needed for us to process and manipulate an HttpRequest. * * Typical use: Request.postRequest(uri) to generate request, then begin * attaching headers until the request is ready to be processed. * * Looking back as I write this, the JSON string should be in here, and * the HttpController should pull it out. Maybe? Maybe not, since we could * be sending over multiple parameters. */ public class Request extends HttpObject { private HttpEntityEnclosingRequestBase httpRequest; private Request() { super(); } public static Request postRequest(String uri) { return createRequest(new HttpPost(uri)); } public static Request putRequest(String uri) { return createRequest(new HttpPut(uri)); } private static Request createRequest(HttpEntityEnclosingRequestBase httpRequest) { Request r = new Request(); r.setHttpRequest(httpRequest); return r; } public HttpEntityEnclosingRequestBase getHttpRequest() { return httpRequest; } public void applyHeaders() { Set&lt;String&gt; keys = headers.keySet(); for (String key : keys) { httpRequest.setHeader(key, headers.get(key)); } } private void setHttpRequest(HttpEntityEnclosingRequestBase httpRequest) { this.httpRequest = httpRequest; } //HttpEntityEnclosingRequestBase can't be a get request. // public void getRequest(String uri) // { httpRequest = new HttpGet(uri); // } } </code></pre> <p>Same as Request really</p> <pre><code>public class Response extends HttpObject { HttpResponse httpResponse; public Response(HttpResponse r) { httpResponse = r; } public HttpResponse getHttpResonse() { return httpResponse; } } </code></pre> <p>Finally, a sample run of the code.</p> <pre><code>public static String loginToLocation() { Request r = Request.postRequest(HOST + "AuthenticateWebSafe"); addCommonHeaders(r); try { Response resp = HttpController.processBodyRequest(r, generateLoginJSON()); return HttpController.getJSONField(resp, "SessionKey"); } catch (IOException e) //Not particularly graceful { e.printStackTrace(); return null; } } private static void addCommonHeaders(Request r) { r.addHeader("accept", "application/json"); } private static String generateLoginJSON() { String loginString = "{\"email\":\"" + email + "\"," + "\"pass\":\"" + pw + "\"}"; return loginString; } </code></pre>
[]
[ { "body": "<p>I think that your exception handling is problematic.</p>\n\n<pre><code>try {\n ...\n} catch (IOException e) {\n e.printStackTrace();\n return null;\n}\n</code></pre>\n\n<p>Besides logging, all that accomplishes is degrade an \"informative\" kind of exception into a <code>null</code>, which creates more problems than it solves:</p>\n\n<ul>\n<li>The caller would have to explicitly check for a <code>null</code> result. The caller cannot use a try-catch block to handle the error condition, which is the preferred way to deal with such exceptional situations.</li>\n<li>If the caller forgets to check for a <code>null</code> result, then you'll probably get a <code>NullPointerException</code> at some point. As a developer, which kind of stack trace would you rather try to diagnose: one with an <code>IOException</code> or one with a <code>NullPointerException</code>?</li>\n<li>Suppose the caller does check for <code>null</code>. What kind of feedback could it present to the user? \"Sorry, your request failed for some reason. We can't tell you why.\" An <code>IOException</code>, on the other hand, <em>can</em> contain more details about why the request failed. You can even choose to handle specific subclasses of <code>IOException</code> and ignore others.</li>\n</ul>\n\n<p>If you catch an exception but aren't able to deal with it effectively, the best thing you could probably do is let it propagate — i.e., don't bother catching it at all in the first place, and declare it in the method signature if appropriate. Alternatively, if you need to avoid a leaky abstraction, you might want to <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html\" rel=\"nofollow\">wrap the exception</a> before re-throwing it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T20:09:07.030", "Id": "65131", "Score": "0", "body": "Thanks for the comment, and I completely agree. I should have given that section a bit more love, especially since I had an error there and it was a pain to deal with. Though ultimately, it was right at the tail end of the execution and I didn't expect much of that exception even if it was caught. I'll change this shortly and edit my original post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:04:15.160", "Id": "65135", "Score": "0", "body": "If you edit the original post, include your enhancements as an addendum; please don't edit out the original code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:59:50.247", "Id": "38935", "ParentId": "38926", "Score": "2" } }, { "body": "<p>This is a bug, bordering on a security risk:</p>\n\n<pre><code>private static String generateLoginJSON() \n{ String loginString = \"{\\\"email\\\":\\\"\" + email + \"\\\",\"\n + \"\\\"pass\\\":\\\"\" + pw + \"\\\"}\";\n return loginString; \n}\n</code></pre>\n\n<p>Never generate JSON by string concatenation, because values need to be escaped. You already use <code>JSONTokener</code>, so use <a href=\"http://www.json.org/javadoc/org/json/JSONStringer.html\" rel=\"nofollow noreferrer\"><code>JSONStringer</code></a> to do the inverse:</p>\n\n<pre><code>private static String generateLoginJSON() {\n return new JSONStringer()\n .object()\n .key(\"email\").value(email)\n .key(\"pass\").value(pw)\n .endObject()\n .toString();\n}\n</code></pre>\n\n<p>Your test case might use values that happen to not require escaping. Nevertheless, careless concatenation is a filthy practice, best to be avoided altogether lest other programmers learn bad habits from your code.</p>\n\n<p>This is, by the way, the same class of bugs as SQL injection, HTML injection, and HTTP header injection. They have the same root cause: building a string by concatenation (or interpolation), to be interpreted in some human-friendly language (text-based protocol). <em>Every</em> such language has special delimiter characters that need to be escaped, and failure to perform the escaping leads to disaster.</p>\n\n<p><img src=\"https://i.stack.imgur.com/pqYtV.png\" alt=\"enter image description here\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T18:55:27.940", "Id": "65563", "Score": "0", "body": "Thank you for the insight. This is not something I would have thought of, and I've corrected it here and in other areas of code. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T00:22:05.557", "Id": "38952", "ParentId": "38926", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:00:46.663", "Id": "38926", "Score": "5", "Tags": [ "java", "library", "http" ], "Title": "Java HTTP Apache - Making my own library" }
38926
<p>There must surely be a nicer way of writing this.</p> <p>The wrinkle of complexity is that <code>prev_seq</code> or <code>next_seq</code> might be an empty string if the user moves the question to the first or last position, but it could also validly be '0.0' so I can't just rely on 'falsiness'.</p> <p>I hope it's clear what I'm trying to achieve from the below (with the comments).</p> <p>How can I improve this?</p> <pre><code>def update_sequence(self): prev_seq = self.request.get('prev_seq') next_seq = self.request.get('next_seq') question_id = int(self.request.get('id')) question = db.get(db.Key.from_path('Questions', question_id)) try: # to slot a question between two numbers we compute the midpoint # for, example, to insert a question between 2.1 and 3.4, the # question would get the sequence of 2.75 new_position = (float(prev_seq) + float(next_seq)) / 2 except ValueError: # if we get here, either prev_seq or next_seq was not submitted # in the request which means the user pushed the question to the # first or last position. try: float(prev_seq) except ValueError: # in this case the question has been moved to the first # position so we should make: # the new position = the next position - 1 new_position = float(next_seq) - 1 try: float(next_seq) except ValueError: # in this case the question has been moved to the last position # so we should make: # the new position = the previous position + 1 new_position = float(prev_seq) + 1 question.sequence_float = new_position question.put() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T20:52:10.880", "Id": "65134", "Score": "0", "body": "Have you tried `if prev_seq == \"\":`? That gives a different result for \"\" and 0." } ]
[ { "body": "<pre><code>def get_new_position(prev_seq, next_seq):\n\n if next_seq == \"\":\n new_position = float(prev_seq) + 1\n elif prev_seq == \"\":\n new_position = float(next_seq) - 1\n else:\n new_position = (float(prev_seq) + float(next_seq)) / 2\n\n return new_position\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:53:50.107", "Id": "65209", "Score": "0", "body": "yes, this is much nicer. for some reason I was trying to avoid testing equality with an empty string, I have no idea why." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:22:43.820", "Id": "38940", "ParentId": "38927", "Score": "1" } } ]
{ "AcceptedAnswerId": "38940", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T18:00:55.773", "Id": "38927", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Function to find midpoint of two floats where one of the floats might be an empty string" }
38927
<p>I have written a function for switching advert image based on <code>$template</code>. Function is working completely fine without any problem and getting everything dynamically with no issue.</p> <p>Concerning performance, I want some feedback and suggestion from you experts to optimize code in better way.</p> <p>Since below code is dynamically getting option key using <code>$template</code> so I am not sure is it good to repeat same code for each case or there is some better way.</p> <pre><code>$this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); </code></pre> <p><strong>Please find below is my full function code</strong></p> <pre><code>function page_advert() { $template = get_request() == '' ? 'home' : get_request_part(0); $advert = option('ops_'.$template.'_advert_image_url'); if((option('ops_'.$template.'_enable_adverts')) &amp;&amp; (!empty($advert))) { $this-&gt;render('&lt;!-- Start page advert --&gt;','&lt;div class="ops-page-advert '.$template.'"&gt;'); switch ($template) { case 'home': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'archive': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'page': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'contact': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'tags': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'categories': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'users': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; case 'admin': $this-&gt;render('&lt;a href="'.option('ops_'.$template.'_advert_destination_link').'" &gt;'); $this-&gt;render('&lt;img src="'.option('ops_'.$template.'_advert_image_url').'" alt="adv-'.$template.'-advert" /&gt;'); $this-&gt;render('&lt;/a&gt;'); break; default: return false; break; } $this-&gt;render('&lt;/div&gt;', '&lt;!-- End page advert --&gt;'); } //endif } </code></pre>
[]
[ { "body": "<p>Ah! what a stupid mistake I have done.. :P Didn't realized that I don't have to use Switch Case either. Here is the final optimized code</p>\n\n<pre><code>function page_advert()\n{\n\n $template = get_request() == '' ? 'home' : get_request_part(0);\n $advert = option('ops_'.$template.'_advert_image_url');\n\n if((option('ops_'.$template.'_enable_adverts')) &amp;&amp; (!empty($advert))) {\n\n $html = '\n &lt;!-- Start page advert --&gt;\n &lt;div class=\"q2am-page-advert '.$template.'\"&gt;\n &lt;a href=\"'.option('ops_'.$template.'_advert_destination_link').'\" &gt;\n &lt;img src=\"'.option('ops_'.$template.'_advert_image_url').'\" alt=\"adv-market-'.$template.'-advert\" /&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;!-- End page advert --&gt;\n ';\n\n $this-&gt;output($html);\n\n } //endif\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:45:54.990", "Id": "65251", "Score": "0", "body": "Why not concatenate all of those lines of HTML and just make 1 render call?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T16:12:09.297", "Id": "65259", "Score": "0", "body": "@jsanc623 how about this now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T18:04:08.797", "Id": "65271", "Score": "0", "body": "looks much better now and only 1 function call vs 5 :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:56:33.673", "Id": "38934", "ParentId": "38933", "Score": "3" } } ]
{ "AcceptedAnswerId": "38934", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T19:43:30.640", "Id": "38933", "Score": "1", "Tags": [ "php", "optimization" ], "Title": "Optimize switch case for dynamic content" }
38933
<p>This is a <code>.wav</code> to <code>.flac</code> <a href="https://en.wikipedia.org/wiki/Encoder" rel="nofollow">encoder</a> that I wrote a little while ago. The only method that is really called is <code>encode()</code>, which takes in a <code>.wav</code> file, converts it to <a href="https://xiph.org/flac/" rel="nofollow">FLAC</a>, and stores it in the <code>.flac</code> file that is taken in as a parameter.</p> <p>I would prefer suggestions on how to improve the method, decrease run-time, or cut down on the length of the code. Any other suggestions are acceptable though.</p> <hr> <p>The header file (<code>encode.h</code>):</p> <pre><code>#include &lt;FLAC/stream_encoder.h&gt; int encode(const char *wavfile, const char *flacfile); static void progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data); </code></pre> <p>The encoding program:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "encode.h" #define READSIZE 1020 static unsigned totalSamples = 0; /* can use a 32-bit number due to WAVE size limitations */ static FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */ static FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/]; int encode(const char *wavfile, const char *flacfile) { FLAC__bool ok = true; FLAC__StreamEncoder *encoder = 0; FLAC__StreamEncoderInitStatus initStatus; FILE *fin; unsigned sampleRate = 0; unsigned channels = 0; unsigned bps = 0; if((fin = fopen(wavfile, "rb")) == NULL) { fprintf(stderr, "ERROR: opening %s for output\n", wavfile); return 1; } /* read wav header and validate it */ if (fread(buffer, 1, 44, fin) != 44 || memcmp(buffer, "RIFF", 4) || memcmp(buffer + 8, "WAVEfmt \020\000\000\000\001\000\002\000", 16) ||memcmp(buffer + 32, "\004\000\020\000data", 8)) { fprintf(stderr, "ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\n"); fclose(fin); return 1; } sampleRate = ((((((unsigned)buffer[27] &lt;&lt; 8) | buffer[26]) &lt;&lt; 8) | buffer[25]) &lt;&lt; 8) | buffer[24]; channels = 2; bps = 16; totalSamples = (((((((unsigned)buffer[43] &lt;&lt; 8) | buffer[42]) &lt;&lt; 8) | buffer[41]) &lt;&lt; 8) | buffer[40]) / 4; /* allocate the encoder */ if((encoder = FLAC__stream_encoder_new()) == NULL) { fprintf(stderr, "ERROR: allocating encoder\n"); fclose(fin); return 1; } ok &amp;= FLAC__stream_encoder_set_verify(encoder, true); ok &amp;= FLAC__stream_encoder_set_compression_level(encoder, 5); ok &amp;= FLAC__stream_encoder_set_channels(encoder, channels); ok &amp;= FLAC__stream_encoder_set_bits_per_sample(encoder, bps); ok &amp;= FLAC__stream_encoder_set_sample_rate(encoder, sampleRate); ok &amp;= FLAC__stream_encoder_set_total_samples_estimate(encoder, totalSamples); /* initialize encoder */ if(ok) { initStatus = FLAC__stream_encoder_init_file(encoder, flacfile, progress_callback); if(initStatus != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { fprintf(stderr, "ERROR: initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[initStatus]); ok = false; } } /* read blocks of samples from WAVE file and feed to encoder */ if(ok) { fprintf(stdout, "Encoding: "); size_t left = (size_t)totalSamples; while(ok &amp;&amp; left) { size_t need = (left&gt;READSIZE ? (size_t)READSIZE : (size_t)left); if (fread(buffer, channels * (bps / 8), need, fin) != need) { fprintf(stderr, "ERROR: reading from WAVE file\n"); ok = false; } else { /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ size_t i; for(i = 0; i &lt; need*channels; i++) { /* inefficient but simple and works on big- or little-endian machines */ pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2 * i + 1] &lt;&lt; 8) | (FLAC__int16)buffer[2 * i]); } /* feed samples to encoder */ ok = FLAC__stream_encoder_process_interleaved(encoder, pcm, need); } left -= need; } } ok &amp;= FLAC__stream_encoder_finish(encoder); fprintf(stdout, "%s\n", ok ? "Succeeded" : "FAILED"); if (!ok) fprintf(stderr, " State: %s\n", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]); FLAC__stream_encoder_delete(encoder); fclose(fin); return 0; } void progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data) { (void)encoder, (void)client_data; fprintf(stderr, "Wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, totalSamples, frames_written, total_frames_estimate); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-22T00:50:15.400", "Id": "283368", "Score": "0", "body": "This code is not written by yourself, you just plagiarism code from xlph.org." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-22T01:05:19.640", "Id": "283369", "Score": "0", "body": "While it was based on their sample, it is not copied from their website. Naturally the code will look similar since it uses their library and does the same thing." } ]
[ { "body": "<p>These two statement could be implemented by the same subroutine:</p>\n\n<pre><code>sampleRate = ((((((unsigned)buffer[27] &lt;&lt; 8) | buffer[26]) &lt;&lt; 8) | buffer[25]) &lt;&lt; 8) | buffer[24];\ntotalSamples = (((((((unsigned)buffer[43] &lt;&lt; 8) | buffer[42]) &lt;&lt; 8) | buffer[41]) &lt;&lt; 8) | buffer[40]) / 4;\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>unsigned read4bytes(FLAC__byte* ptr)\n{\n return ((((((unsigned)*(ptr+3) &lt;&lt; 8) | *(ptr+2)) &lt;&lt; 8) | *(ptr+1)) &lt;&lt; 8) | *(ptr);\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>sampleRate = read4bytes(buffer + 24);\ntotalSamples = read4bytes(buffer + 40);\n</code></pre>\n\n<p>You're using <code>ok</code> to skip processing until you call <code>fclose</code> at the end. Instead all that could be a subroutine ...</p>\n\n<pre><code>fin = fopen(wavfile, \"rb\");\nrc = encodeFile(fin, flacfile);\nfclose(fin);\n</code></pre>\n\n<p>... and then instead of having ok in encodeFile, you can return when (as soon as) you detect an error.</p>\n\n<p>You currently don't fprintf a specific error message if a function call such as <code>FLAC__stream_encoder_set_verify</code> fails.</p>\n\n<p>I don't know why READSIZE value is 1020.</p>\n\n<p>channels and bps could be set to 2 and 16 at the start of the function; or they could be const or macros like READFILE is.</p>\n\n<hr>\n\n<p>For the second subroutine, I had something like the following in mind (untested code ahead).</p>\n\n<ul>\n<li>By eliminating the <code>ok</code> variable I eliminate <code>if</code> statements in the body of the code.</li>\n<li>As soon as encodeFile detects an error, it prints an error and immediately returns.</li>\n<li>The calling routine which opened the file is responsible for closing the file; there's now only one <code>fclose(fin)</code> statement.</li>\n</ul>\n\n<p>I did something similar (i.e. make a subroutine) to wrap the lifetime of the allocated <code>encoder</code> object.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include \"encode.h\"\n\n#define READSIZE 1020\n\nstatic unsigned totalSamples = 0; /* can use a 32-bit number due to WAVE size limitations */\nstatic FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */\nstatic FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/];\n\nint encodeFile2(FILE *fin, FLAC__StreamEncoder *encoder, const char *flacfile)\n{\n unsigned sampleRate = ((((((unsigned)buffer[27] &lt;&lt; 8) | buffer[26]) &lt;&lt; 8) | buffer[25]) &lt;&lt; 8) | buffer[24];\n unsigned channels = 2;\n unsigned bps = 16;\n totalSamples = (((((((unsigned)buffer[43] &lt;&lt; 8) | buffer[42]) &lt;&lt; 8) | buffer[41]) &lt;&lt; 8) | buffer[40]) / 4;\n\n if (!(FLAC__stream_encoder_set_verify(encoder, true)\n &amp;&amp; FLAC__stream_encoder_set_compression_level(encoder, 5)\n &amp;&amp; FLAC__stream_encoder_set_channels(encoder, channels)\n &amp;&amp; FLAC__stream_encoder_set_bits_per_sample(encoder, bps)\n &amp;&amp; FLAC__stream_encoder_set_sample_rate(encoder, sampleRate)\n &amp;&amp; FLAC__stream_encoder_set_total_samples_estimate(encoder, totalSamples)))\n {\n return fprintf(stderr, \"ERROR: setting encoder properties\\n\");\n }\n\n /* initialize encoder */\n FLAC__StreamEncoderInitStatus initStatus = FLAC__stream_encoder_init_file(encoder, flacfile, progress_callback);\n if(initStatus != FLAC__STREAM_ENCODER_INIT_STATUS_OK)\n {\n return fprintf(stderr, \"ERROR: initializing encoder: %s\\n\", FLAC__StreamEncoderInitStatusString[initStatus]);\n }\n\n /* read blocks of samples from WAVE file and feed to encoder */\n fprintf(stdout, \"Encoding: \");\n size_t left = (size_t)totalSamples;\n while(left) \n {\n size_t need = (left&gt;READSIZE ? (size_t)READSIZE : (size_t)left);\n if (fread(buffer, channels * (bps / 8), need, fin) != need) \n {\n return fprintf(stderr, \"ERROR: reading from WAVE file\\n\");\n }\n /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */\n size_t i;\n for(i = 0; i &lt; need*channels; i++)\n {\n /* inefficient but simple and works on big- or little-endian machines */\n pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2 * i + 1] &lt;&lt; 8) | (FLAC__int16)buffer[2 * i]);\n }\n /* feed samples to encoder */\n if (FLAC__stream_encoder_process_interleaved(encoder, pcm, need))\n {\n return fprintf(stderr, \"ERROR: processing WAVE file: %s\\n\", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]);\n }\n left -= need;\n }\n\n if (!FLAC__stream_encoder_finish(encoder))\n {\n return fprintf(stderr, \"ERROR: finishing encoder: %s\\n\", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]);\n }\n\n fprintf(stdout, \"Succeeded\");\n return 0;\n}\nint encodeFile1(FILE *fin, const char *flacfile)\n{\n /* read wav header and validate it */\n /* before allocating the encoder */\n if (fread(buffer, 1, 44, fin) != 44 || memcmp(buffer, \"RIFF\", 4) || memcmp(buffer + 8, \"WAVEfmt \\020\\000\\000\\000\\001\\000\\002\\000\", 16) ||memcmp(buffer + 32, \"\\004\\000\\020\\000data\", 8))\n {\n return fprintf(stderr, \"ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\\n\");\n }\n\n /* allocate the encoder */\n FLAC__StreamEncoder *encoder;\n if((encoder = FLAC__stream_encoder_new()) == NULL) \n {\n return fprintf(stderr, \"ERROR: allocating encoder\\n\");\n }\n\n /* use the encoder */\n rc = encodeFile2(fin, encoder, flacfile);\n\n /* deallocate the encoder */\n FLAC__stream_encoder_delete(encoder);\n return rc;\n}\nint encode(const char *wavfile, const char *flacfile)\n{\n FILE *fin;\n int rc;\n if((fin = fopen(wavfile, \"rb\")) == NULL)\n {\n fprintf(stderr, \"ERROR: opening %s for output\\n\", wavfile);\n return 1;\n }\n rc = encodeFile1(fin, flacfile);\n fclose(fin);\n return (rc) ? 1 : 0;\n}\n</code></pre>\n\n<p>I also changed to location where local variables are defined: instead of defining them at the top of the function, they're now not defined until they're initialized (which you seemed to be doing already, though inconsistently, in your OP; the ability to do so is newer-style C).</p>\n\n<hr>\n\n<p>The above changes are stylistic:</p>\n\n<ul>\n<li>Shorter and simpler</li>\n<li>Easier to verify (by inspection) that allocated resources are closed/freed.</li>\n</ul>\n\n<p>As for performance, the first rule is to use run-time profiler (don't try to guess what's wrong, and don't bother to performance-optimize code which isn't a performance bottle-neck).</p>\n\n<p>Much of the work is perhaps done by the library you're using, which implies there may be little point in optimizing your code.</p>\n\n<p>From looking at the source code, performance hints could include:</p>\n\n<ol>\n<li>Can you use a different encoder library?</li>\n<li>Is fread the most performant file I/O function?</li>\n<li>What's the effect of different READSIZE values</li>\n</ol>\n\n<p>Apart from the file-reading I'd guess that this is your only important work:</p>\n\n<pre><code> /* inefficient but simple and works on big- or little-endian machines */\n pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2 * i + 1] &lt;&lt; 8) | (FLAC__int16)buffer[2 * i]);\n</code></pre>\n\n<p>Search the 'net for different implementations of that; for example, it might be a no-op on some CPUs; some CPUs might have dedicated opcodes for this purpose (<a href=\"https://www.google.com/search?q=bswap\" rel=\"nofollow\">bswap</a>).</p>\n\n<p>Depending on how/whether your compiler optimizes, there might be more efficient source code: instead of combining bytes into an integer and storing the integer to the target buffer, copy bytes from the source buffer into corresponding bytes of the target buffer; using run-time <code>if</code> or compile-time <code>#if</code> to choose the right (machine-specific) implementation of corresponding bytes. An additional complication however is the sign-extension (converting signed int16 to signed int32).</p>\n\n<p>I'd suspect that it's irrelevant though: that the FLAC library has much more work to than that, and so that its the performance of the library which dominates the performance of the whole operation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T01:02:07.820", "Id": "39031", "ParentId": "38944", "Score": "4" } } ]
{ "AcceptedAnswerId": "39031", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T21:55:47.897", "Id": "38944", "Score": "5", "Tags": [ "performance", "c", "memory-optimization" ], "Title": "WAVE to FLAC encoder in C" }
38944
<p>I have been using HTML and CSS for a long time, and just starting to learn jQuery. I created a calculator by myself from research and trial and error. I would like someone to let me know what I'm doing wrong (pertaining to the jQuery) as far as code efficiency, structure, and comments.</p> <p>Here is the HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8 lt-ie7"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="no-js lt-ie9"&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html class="no-js"&gt; &lt;!--&lt;![endif]--&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;meta name="description" content=""&gt; &lt;link rel="stylesheet" href="css/normalize.css"&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;script src="js/vendor/modernizr-2.6.2.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;section&gt; &lt;h1&gt;Calculator&lt;/h1&gt; &lt;table&gt; &lt;input&gt; &lt;tr&gt; &lt;td&gt;&lt;button name="1" class="num-button"&gt;1&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="2" class="num-button"&gt;2&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="3" class="num-button"&gt;3&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="add" class="operation"&gt;+&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;button name="4" class="num-button"&gt;4&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="5" class="num-button"&gt;5&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="6" class="num-button"&gt;6&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="subtract" class="operation"&gt;-&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;button name="7" class="num-button"&gt;7&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="8" class="num-button"&gt;8&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="9" class="num-button"&gt;9&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="multiply" class="operation"&gt;x&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;button name="0" class="num-button"&gt;0&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="." class="num-button"&gt;.&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="equals"&gt;=&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button name="divide" class="operation"&gt;/&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button class="clear"&gt;Clear&lt;/button&gt; &lt;/section&gt; &lt;script src="js/vendor/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;script src="js/main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the jQuery that I need critiqued:</p> <pre><code>$(function() { var input = $('input'); var equals = $('[name="equals"]'); /*when a button with the 'num-button' class is clicked, adds the number of the button via its name to the inputs value*/ $('.num-button').on('click', function() { input.val(input.val() + $(this).attr('name')); }); /*when a button with the 'operation' class is clicked, check if the subtract button was clicked while input field is empty, if so add - to input value, if not add inputs value to the inputs name attribute, then remove any classes attached to the equals button (if any) and then add the operation buttons name to the equals button as a class */ $('.operation').on('click', function() { var opName = $(this).attr('name'); if (opName == 'subtract' &amp;&amp; input.val().length == 0) { input.val('-'); } else { input.attr('name', input.val()); input.val(''); equals.removeClass(); equals.addClass(opName); } }); /*when the equals button is clicked check to find out what the equal buttons class is, then get the values from the inputs attribute that we converted to a name (above), then get the current input value, then convert those string values to floated numbers and follow with the appropriate math operation for the two floated numbers*/ equals.on('click', function() { var firstInput; var secondInput; if (equals.hasClass('add')) { firstInput = parseFloat(input.attr('name')); secondInput = parseFloat(input.val()); input.val(firstInput + secondInput); } else if (equals.hasClass('subtract')) { firstInput = parseFloat(input.attr('name')); secondInput = parseFloat(input.val()); input.val(firstInput - secondInput); } else if (equals.hasClass('multiply')) { firstInput = parseFloat(input.attr('name')); secondInput = parseFloat(input.val()); input.val(firstInput * secondInput); } else if (equals.hasClass('divide')) { firstInput = parseFloat(input.attr('name')); secondInput = parseFloat(input.val()); input.val(firstInput / secondInput); } }); //clears input field when clear button is clicked $('.clear').on('click', function () { input.val(''); }); }); </code></pre>
[]
[ { "body": "<p>You shouldn't specify ALL of your code in the jQuery ready callback. Try and move all your callbacks, etc out. OR if your code is at the end of the page, you can just execute it straight away.</p>\n\n<p>In your <code>equals</code> on click handle, <code>firstInput</code> and <code>secondInput</code> are always the same regards of class so you can make it like this:</p>\n\n<pre><code>equals.on('click', function() {\n var firstInput = parseFloat(input.attr('name'));\n var secondInput = parseFloat(input.val());\n if (equals.hasClass('add')) {\n input.val(firstInput + secondInput);\n } else if (equals.hasClass('subtract')) {\n input.val(firstInput - secondInput);\n } else if (equals.hasClass('multiply')) {\n input.val(firstInput * secondInput);\n } else if (equals.hasClass('divide')) {\n input.val(firstInput / secondInput);\n }\n});\n</code></pre>\n\n<p>*UPDATES:<em>*</em></p>\n\n<p>You should default to using <code>===</code> (triple equals) when doing comparisons instead of <code>==</code> (double equals).</p>\n\n<p>When checking <code>.length</code>, it's handy to remember that <code>0 == false</code> so you could write your code as <code>!input.val().length</code>. Actually, you can make this even more concise because an empty string is also 'falsy', so instead do <code>!input.val()</code>.</p>\n\n<p>You should create a better selector for your main user input, so that if another gets introduced to the page it won't break. Since your page is only going to have one input, I'd use an ID to make it a unique input. <code>&lt;input id=\"input-calculator\"&gt;</code> ... then query for it in your CSS and Javascript as <code>$('#input-calculator')</code>. This remove ambiguity from your code :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:53:36.553", "Id": "65185", "Score": "0", "body": "Set firstInput and secondInput to variables, works. Thanks, I didn't see that. I don't understand what you mean by move all of your callbacks etc. out of the ready function. What should I move outside of the jQuery document.ready function and why? From how I understand it, that function just loads everything inside it after the document has loaded. Why move things outside of it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T23:28:56.837", "Id": "65360", "Score": "0", "body": "jQuery.ready is handy if you're trying to query elements that aren't the page yet. Since your JavaScript is at the end of your DOM, you don't need to use jQuery.ready... this is slowing down your app." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T23:32:10.677", "Id": "65362", "Score": "0", "body": "What meant about the callbacks, is to define the functions as soon as possible so the browser can parse them. Then in jQuery.ready define the handle and pass them a reference to the callback (which is a variable). Blindly wrapping all your code in jQuery.ready is a great way to slow the page for now reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T00:02:52.033", "Id": "65365", "Score": "0", "body": "Makes sense. So when you say jQuery.ready is handy for trying to query elements that are not on the page yet, do you mean just the elements after the script tag, or elements that might be introduced dynamically using javascript, even if the script tag is at the end of the page? In other words, does the ready function have any impact on dynamically created content?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T03:18:05.913", "Id": "65383", "Score": "0", "body": "You really only want $.ready if you're JavaScript is included at the start of the page (i.e. in the `<head>`). But yes, then inside it you only want to query elements. You should try and move as much code out of $.ready as you can." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T04:16:48.813", "Id": "38971", "ParentId": "38947", "Score": "1" } } ]
{ "AcceptedAnswerId": "38971", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T23:17:32.273", "Id": "38947", "Score": "2", "Tags": [ "javascript", "performance", "beginner", "jquery", "calculator" ], "Title": "Basic calculator in jQuery" }
38947
<p>This is a subclass of <code>Backbone.Collection</code> with a method <code>fetchNextPage</code> that returns a Q promise.</p> <p>To find out the next page's URL, it looks in <code>meta.next</code> from server response.<br> The server will return <code>null</code> for the last page.</p> <p>It also has a <code>getState</code> method that returns a <code>state</code> with <code>empty</code> and <code>fetching</code> boolean variables.<br> When this state changes, it fires <code>change:state</code> event.</p> <p>Finally, <code>promiseAt</code> is a convenience method that keeps fetching pages until it can return model <code>at</code> given <code>index</code>, or <code>null</code> if it can't.</p> <pre><code>(function (Backbone, q) { 'use strict'; window.st.Collection.PaginatedCollection = Backbone.Collection.extend({ initialize: function () { _.bindAll(this, 'setFetchPromise'); Backbone.Collection.initialize.apply(this, arguments); this.refreshState(); }, fetchNextPage: function () { if (this.isLastPage()) { return q(); } if (this.fetchPromise) { return this.fetchPromise; } var fetchOptions, fetchPromise; fetchOptions = { remove: false, url: this.getNextPageUrl() }; fetchPromise = this.fetch(fetchOptions) .finally(this.setFetchPromise/*(undefined)*/); return this.setFetchPromise(fetchPromise); }, getNextPageUrl: function () { return this.lastResponse ? this.lastResponse.meta.next : this.url; }, getState: function () { return { empty: this.isEmpty(), fetching: this.isFetching() }; }, isFetching: function () { return !!this.fetchPromise; }, isLastPage: function () { if (!this.url) { return true; } if (!this.lastResponse) { return false; } return !this.lastResponse.meta.next; }, parse: function (response) { this.lastResponse = response; return response.objects; }, refreshState: function () { var newState = this.getState(); if (_.isEqual(newState, this.state)) { return; } this.state = newState; this.trigger('change:state', newState); }, setFetchPromise: function (promise) { this.fetchPromise = promise; this.refreshState(); return promise; }, promiseAt: function (index) { var _this = this; if (index &lt; this.length - 1 || this.isLastPage()) { return q(this.at(index)); } return this.fetchNextPage().then(function () { return _this.promiseAt(index); }); } }); })(Backbone, Q); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T23:36:14.570", "Id": "38950", "Score": "1", "Tags": [ "javascript", "asynchronous", "backbone.js", "pagination", "promise" ], "Title": "Paginated Backbone.Collection subclass" }
38950
<p>This 43 line program is designed to listen for Syslog messages on port 514 and record the messages to an MS SQL Server database table.</p> <p>I would appreciate feedback from experienced node.js developers.</p> <p>I am just starting to learn node.js. I'm average at JavaScript, still getting my head around closures. I am really struggling to get my head around the node.js event driven programming paradigm. </p> <p>If I try to access the SQL server connection outside of the <code>sql.open</code> callback function, I get the error that the database connection is closed.</p> <p>So for this reason I had to place the receive message and save it in database logic inside the <code>sql.open</code> callback function, which seems messy and counter-intuitive, but that is probably due to my not quite fully understanding the event driven model?</p> <p>Anyway the code works (amazingly!) and seems to be quite efficient, saving many dozens of syslog messages per second to the local MS SQL database with negligible CPU impact...</p> <p>Are there any fundamental flaws in this code, and any changes that should be made to improve it?</p> <p>I guess I am amazed that this can be done in just one page of code. node.js is very cool...</p> <pre class="lang-js prettyprint-override"><code>var dgram = require("dgram"); var server = dgram.createSocket("udp4"); var sql = require('msnodesql'); var conn_str = "Driver={SQL Server Native Client 11.0}; Server=.; Database=SYSLOG; UID=xxxxxxx; PWD=xxxxxxxx;"; // open the database connection sql.open(conn_str, function (err, conn) { if (err) { console.log("error", err); return; } //database connection succeeded, log a mesage into the syslog.incoming table conn.queryRaw("insert into Incoming(Source,Message) values('LOCAL','node.js syslog server started')"); //create an event listener for when a syslog message is recieved server.on("message", function (msg, rinfo) { //sanitise the data by replacing single quotes with two single-quotes var message = msg.toString().replace(/'/g, "''") var src = rinfo.address.toString().replace(/'/g, "''") var s = "insert into Incoming(Source,Message) values('"+src+"','"+message+"')"; //send the SQL to the database conn.queryRaw(s, function (err, results) { if (err) { console.log(s); console.log(err); return; } }); }); // end of server.on("message") listener //create an event listener to tell us that the has successfully opened the syslog port and is listening for messages server.on("listening", function () { var address = server.address(); console.log("server listening " + address.address + ":" + address.port); }); //bind the server to port 514 (syslog) server.bind(514); });// end of sql.open() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-19T08:25:40.947", "Id": "115697", "Score": "1", "body": "You probably want to use prepared statements to deal with escaping properly: https://github.com/Azure/node-sqlserver/blob/master/test/query.js#L74" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Comments should be worth the space they take up, my favourite offender is this one:</p>\n\n<pre><code>// open the database connection\nsql.open(conn_str, function (err, conn) {\n</code></pre></li>\n<li>I want to point to <a href=\"https://github.com/Azure/node-sqlserver/issues/171\" rel=\"nofollow\">is msnodesql maintained?</a></li>\n<li>I also want to point out that storing uid/pwd in your script can be dangerous, I hope this is not a production database, which does not have sensitive data</li>\n<li>As Nelson Menezes mentioned, you should look into using prepared statements</li>\n<li><p>In this block, you should either use 1 comma separated <code>var</code> or semicolons:</p>\n\n<pre><code>var message = msg.toString().replace(/'/g, \"''\") \nvar src = rinfo.address.toString().replace(/'/g, \"''\")\nvar s = \"insert into Incoming(Source,Message) values('\"+src+\"','\"+message+\"')\";\n</code></pre></li>\n<li><p>In a script of this size I would consider merging some statements, this</p>\n\n<pre><code>console.log(s);\nconsole.log(err);\nreturn;\n</code></pre>\n\n<p>might as well be</p>\n\n<pre><code>return console.log(s, '\\n', err);\n</code></pre></li>\n<li><code>});// end of sql.open()</code> &lt;- Overkill comments</li>\n</ul>\n\n<p>Still, all in all a solid script.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-03T22:03:44.543", "Id": "130842", "Score": "0", "body": "Thank you for the constructive and helpful feedback, I appreciate it and am studying up on your suggestions :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-03T17:07:31.323", "Id": "71538", "ParentId": "38951", "Score": "2" } } ]
{ "AcceptedAnswerId": "71538", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T00:21:35.967", "Id": "38951", "Score": "4", "Tags": [ "javascript", "sql-server", "node.js", "server" ], "Title": "node.js Syslog server recording to MS-SQL database" }
38951
<p>I have an ASP.NET application which uses a <a href="http://msdn.microsoft.com/en-us/library/bb628652.aspx" rel="nofollow">Service Reference</a> to a (third-party, offsite) payment processor.</p> <p>The service reference class is generated automatically. Its implementation is a subclass of <a href="http://msdn.microsoft.com/en-us/library/ms576141%28v=vs.110%29.aspx" rel="nofollow">ServiceModel.ClientBase</a>, which MSDN documents as, "Any instance members are not guaranteed to be thread safe."</p> <ul> <li>Is the following a good implementation of my wrapper class (to be called from my aspx pages), to guarantee that access to the service reference singleton is thread-safe?</li> <li>Should I prefer to simply make the service reference an instance member of the wrapper class, without any locking? My fear was that would imply more than one concurrent service instance, and I don't know how to test whether the remote server side would handle that successfully. </li> </ul> <hr> <pre><code>class Authorize : IDisposable { private static ServiceSoapClient s_serviceSoap = null; private static object s_locker; // This method is invoked from Global.Application_Start() in Global.asax.cs internal static void Application_Start() { // ServiceSoapClient derives from ServiceModel.ClientBase&lt;ServiceSoap&gt; s_serviceSoap = new ServiceSoapClient(); s_locker = new object(); } private bool lockWasTaken = false; internal Authorize() { // Emulate C# `lock` statement Monitor.Enter(s_locker, ref lockWasTaken); // http://stackoverflow.com/questions/2008382/how-to-heal-faulted-wcf-channels if (s_serviceSoap.InnerChannel.State == System.ServiceModel.CommunicationState.Faulted) { s_serviceSoap.Abort(); s_serviceSoap = new ServiceSoapClient(); } } public void Dispose() { if (lockWasTaken) Monitor.Exit(s_locker); } internal bool IsAlive() { // delegate to the singleton ANetApiResponseType response = s_serviceSoap.IsAlive(); log(response, "IsAlive"); return response.resultCode == MessageTypeEnum.Ok; } // plus other methods which delegate to the singleton } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T02:26:03.853", "Id": "65158", "Score": "1", "body": "@retailcoder I don't have enough reputation to answer [your question in Chat](http://chat.stackexchange.com/transcript/message/13102181?noredirect=1#13102181); I want them to be static because I want them to be thread-safe singletons; perhaps they could be non-static non-singletons instead? Maybe this question depends too much on hoping you have experience with framework classes? Yes the `s_` prefix is ugly buy I like to know when something's static (because static is dangerous and unusual): I didn't call the instance data `m_lockWasTaken`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T18:05:28.630", "Id": "65959", "Score": "1", "body": "FYI `ServiceSoapClient` should also be disposed within your implementation od `Dispose()` as it implements `IDisposable`.\n\nAre you only creating one instance of your wrapper?\n\nIf you are creating a new `Authorize` instance per asp.net request then there will be no threading issue as each instance will be within its own thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:24:57.883", "Id": "66996", "Score": "0", "body": "@MattC I don't think `ServiceSoapClient` should also be disposed, because the singleton **static** `ServiceSoapClient` instance is expected to live for the lifetime of the application. There will be multiple instances of the `Authorize` wrapper (one per `Page`, as needed). Because there are multiple concurrent Page instances (therefore concurrent `Authorize` wrapper instances) there's a \"threading issue\" if they want concurrent access to the **singleton static** `ServiceSoapClient` instance." } ]
[ { "body": "<p>The code in the OP seems thread-safe to me, but may not be the best solution.</p>\n<p>If the channel has many concurrent users, and if using the channel takes for example 100 msec, then 100 concurrent users would queue for up to 10 seconds before being able to use the (single) channel one after the other. A 10-second delay is unacceptable (web users abandon the session).</p>\n<p>If the channel is to a payment processor, authorizing a customer transaction might take longer than 100 msec (not 100++ msec of CPU time for your ASP.NET server, but rather a 100++ msec delay waiting for a network response from the payment processor).</p>\n<p><a href=\"http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx\" rel=\"nofollow noreferrer\">Wenlong Dong's Blog article, &quot;Performance Improvement for WCF Client Proxy Creation in .NET 3.5 and Best Practices&quot; (2007)</a> says,</p>\n<blockquote>\n<p>A common pattern of using ClientBase styled proxies is to perform\ncreation/disposing on each call:</p>\n<pre><code>foreach (string msg in myList)\n{\n // You may add try/catch block here ...\n HelloWorldProxy proxy = new HelloWorldProxy(&quot;MyEndpoint&quot;, new EndpointAddress(address)))\n proxy.Hello(msg);\n proxy.Close();\n // Error handling code here ...\n}\n</code></pre>\n</blockquote>\n<p>This article is not ASP.NET-specific, but it states that concurrent instances of a channel are normal.</p>\n<p>This article also warns that, creating and destroying proxies can be very expensive, gives advice on how to minimize the cost, mentions a performance improvement (implicit cacheing) made in .NET 3.5, and warns what behaviour (i.e. specifying an endpoint) will disable that cacheing.</p>\n<p>A follow-up article titled <a href=\"https://docs.microsoft.com/en-us/archive/blogs/wenlong/a-sample-for-wcf-client-proxy-pooling\" rel=\"nofollow noreferrer\">A Sample for WCF Client Proxy Pooling</a> gives advice on how to implement a pol of proxies.</p>\n<hr />\n<p>See also <a href=\"https://stackoverflow.com/questions/3246634/do-i-need-to-close-a-net-service-reference-client-when-im-done-using-it\">here</a> and <a href=\"http://garrettvlieger.com/blog/2009/09/closing-wcf-service-references/\" rel=\"nofollow noreferrer\">here</a> for warnings about how to close and dispose a WCF channel safely:</p>\n<ul>\n<li>It should be closed before it's disposed</li>\n<li>If there has been a communication error the Close could throw an exception</li>\n<li>In an exception is thrown you should call Abort before trying to Dispose the channel</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:24:14.023", "Id": "66986", "Score": "0", "body": "Credit is due to [this StackOverflow comment and answer](http://stackoverflow.com/questions/21047666/thread-safe-access-to-wcf-channel#comment31744263_21100361) for these observations." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-23T21:24:00.477", "Id": "39914", "ParentId": "38953", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T00:26:47.843", "Id": "38953", "Score": "4", "Tags": [ "c#", ".net", "multithreading", "asp.net", "wcf" ], "Title": "Thread-safe wrapper around WCF ServiceModel.ClientBase subclass" }
38953
<p>The following class's method <code>public IAsyncResult BeginInvoke(Delegate method, object[] args)</code> is called by a third party dll. This dll may or may not be multi-threaded.</p> <p>The dll also calls <code>public bool InvokeRequired { get; }</code> to check if it should call the <code>BeginInvoke</code> method. The third party dll does this every time it gets a socket message from a server.</p> <p>If the <code>InvokeRequired</code> is false, instead of calling <code>BeginInvoke</code> the dll publishes an event of the message to any method that is subscribed.</p> <p>I want to use the <code>MessageSynchronizer</code> class (<em>below</em>) in an ASP.NET application. The class will be created with a new instance on every request.</p> <p>I am fairly new to multithreading, and I would like to know if the way I have designed this class is both thread safe and efficient.</p> <p>An instance would be created like so:</p> <pre><code>var synchronizer = new MessageSynchronizer((x) =&gt; Console.WriteLine(x), MessageSynchronizer.CallbackOptions.Handle | MessageSynchronizer.CallbackOptions.Async); </code></pre> <p>Then the synchronizer instance gets passed to the third parties dll's constructor. Is the below class adequate?</p> <pre><code>using System; using System.ComponentModel; using System.Threading.Tasks; namespace ConsoleApplication1 { class MessageSynchronizer : ISynchronizeInvoke { private readonly object[] _locks = null; private readonly bool _isLockFree = false; /// &lt;summary&gt; /// For manual handling of softdial messages. /// &lt;/summary&gt; public Action&lt;string&gt; Callback { get { return Get(() =&gt; _callback, 0); } set { Set(x =&gt; _callback = x, value, 0); } } private Action&lt;string&gt; _callback = null; public CallbackOptions Options { get { return Get(() =&gt; _options, 1); } set { Set(x =&gt; _options = x, value, 1); } } private CallbackOptions _options = CallbackOptions.None; private T Get&lt;T&gt;(Func&lt;T&gt; field, int locker) { if (_isLockFree) throw new Exception("Cannot get properties as CallbackOptions is set to Never."); lock (_locks[locker]) return field(); } private void Set&lt;T&gt;(Action&lt;T&gt; field, T value, int locker) { if (_isLockFree) throw new Exception("Cannot set properties as CallbackOptions is set to Never."); lock (_locks[locker]) field(value); } /// &lt;summary&gt; /// Use the default CampaignManagerClass's event /// subscriber pattern (recommended). /// &lt;/summary&gt; public MessageSynchronizer(CallbackOptions options = CallbackOptions.None) { _callback = null; _options = options; _isLockFree = options.HasFlag(CallbackOptions.Never); if (!_isLockFree) { _locks = new object[] { new object(), new object() }; } } /// &lt;summary&gt; /// Use custom message reading, the CampaignManagerClass's event callbacks /// will be ignored and your custom message handler will be used instead /// (with the CallbackOptions.HandleCallback flag set). /// &lt;/summary&gt; /// &lt;param name="callback"&gt;A method that takes the raw softdial socket messages.&lt;/param&gt; /// &lt;param name="options"&gt;The callback options when messages are received.&lt;/param&gt; public MessageSynchronizer(Action&lt;string&gt; callback, CallbackOptions options = CallbackOptions.None) :this() { if (callback == null) throw new ArgumentNullException("callback"); _callback = callback; _options = options; } /// &lt;summary&gt; /// The protected override MessageReceived(string) method /// from the RouterNet.RouterConnection (in RouterNet.dll) class calls this method /// when it gets a message from the Sytel.Mdn2.dll and this.InvokeRequired is true. /// The RouterConnection is a static field on the /// CampaignManager.CampaignManagerClass (in RouterNet.dll). /// &lt;/summary&gt; public IAsyncResult BeginInvoke(Delegate method, object[] args) { var message = (string)args[0]; // The args passed from CampaignManagerClass.RouterConnection.MessageReceived is always one, non-null string. var options = Options; /* * * The if statement below is designed in such a way as * to minimise lock contention. While deadloacks aren't possible, * locks are only taken when necessary, this can avoid * thread blocking. Locks are implemented in the properties. */ if (options.HasFlag(CallbackOptions.Handle)) { var callback = Callback; if (callback != null &amp;&amp; message != string.Empty) // The message should never be empty, but just incase. { if (options.HasFlag(CallbackOptions.Async)) { Task.Factory.StartNew(() =&gt; { Callback(message); }); } else { Callback(message); } } } return null; } public object EndInvoke(IAsyncResult result) { throw new NotImplementedException(); } public object Invoke(Delegate method, object[] args) { throw new NotImplementedException(); } public bool InvokeRequired { get { return _isLockFree ? false : Options.HasFlag(CallbackOptions.Handle); } } [Flags] public enum CallbackOptions { /// &lt;summary&gt; /// The callback method will be ignored. /// &lt;/summary&gt; None = 0, /// &lt;summary&gt; /// If provided, the callback method will /// be called with the message from softdial /// instead of default subscribed event. /// &lt;/summary&gt; Handle = 1, /// &lt;summary&gt; /// If when calling the callback method /// the call should be done asynchronously, /// by default it's called synchronously. /// &lt;/summary&gt; Async = 2, /// &lt;summary&gt; /// Any attempt to set the change the callback /// method or CallbackOptions results in an /// exception. This option avoid locks /// altogether, but still remaining thred safe. /// &lt;/summary&gt; Never = 4 } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T01:17:47.000", "Id": "65152", "Score": "0", "body": "I'm not too sure about the lock-objects array. Nice question, welcome to CR!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T01:26:59.147", "Id": "65153", "Score": "0", "body": "@retailcoder Yeh, I could have made two objects for the locks, but the array pattern appeals to me for some reason. I assume even through the locks are in an array they are still mutually exclusive, but I'm not 100% on that. Thanks for the welcome!" } ]
[ { "body": "<p>I'm not entirely sure what exactly you intend to be thread-safe. Right now just the access to the <code>Callback</code> and <code>Options</code> properties is locked and those locks are useless because <a href=\"https://stackoverflow.com/questions/5209623/is-a-reference-assignment-threadsafe\">reference assignment in C# is guaranteed to be atomic</a>.</p>\n\n<p>If you assume that your locking will achieve that the call <code>Callback(message);</code> is mutually exclusive then you are mistaken.</p>\n\n<p>So you can replace this code block:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// For manual handling of softdial messages.\n /// &lt;/summary&gt;\n public Action&lt;string&gt; Callback { get { return Get(() =&gt; _callback, 0); } set { Set(x =&gt; _callback = x, value, 0); } }\n private Action&lt;string&gt; _callback = null;\n\n public CallbackOptions Options { get { return Get(() =&gt; _options, 1); } set { Set(x =&gt; _options = x, value, 1); } }\n private CallbackOptions _options = CallbackOptions.None;\n\n private T Get&lt;T&gt;(Func&lt;T&gt; field, int locker)\n {\n if (_isLockFree)\n throw new Exception(\"Cannot get properties as CallbackOptions is set to Never.\");\n lock (_locks[locker])\n return field();\n }\n\n private void Set&lt;T&gt;(Action&lt;T&gt; field, T value, int locker)\n {\n if (_isLockFree)\n throw new Exception(\"Cannot set properties as CallbackOptions is set to Never.\");\n lock (_locks[locker])\n field(value);\n }\n</code></pre>\n\n<p>with</p>\n\n<pre><code> public Action&lt;string&gt; Callback { get; set; }\n public CallbackOptions Options { get; set; }\n</code></pre>\n\n<p>and it will behave the same as before.</p>\n\n<p>If your goal is that in the case of two threads calling <code>BeginInvoke</code> at the same time the callbacks are executed mutually exclusive then you need to wrap the call in a lock:</p>\n\n<pre><code> private readonly object _callbackLock = new object();\n\n ...\n\n lock (_callbackLock) { Callback(message); }\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>In <code>BeginInvoke</code> you make a local copy <code>callback = Callback</code> but when invoking the action you use the property again rather than the copy - you should fix that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:20:46.193", "Id": "65181", "Score": "0", "body": "Hey Chris, I don't want **Callback(message)** to be _mutually exclusive_, rather I want the settings (_Callback_ and _Options_) on the **MessageSynchronizer** object to take effect when new calls are made to the **BeginInvoke** Method. So what ever thread the **BeginInvoke** is called on never reads old values for **Callback** and **Options**. I want the result such that once you change the public properties, the next callback will use those new values no matter the state of interacting threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:50:31.747", "Id": "65183", "Score": "0", "body": "So are you saying I can remove all the locks and no matter what thread reads or writes to the properties, the reads will never be out of sync with the writes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T08:15:26.883", "Id": "65194", "Score": "0", "body": "@user1909158: I'm not sure what you mean by \"the reads will never be out of sync with the write\", but as it stand yes you can remove the locks - they are not gaining you anything. In `BeginInvoke` you make a local copy `callback = Callback` but when invoking the action you use the property again rather than the copy - you should fix that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:03:47.657", "Id": "65195", "Score": "0", "body": "Good catch on the callback, I didn't realize that. As for _the reads will never be out of sync with the write_ I'm referring to register caching of the reads, so a core might have *bool x = true* on cache, but another core updated *x = false*, and in main memory that's now the real value of *x*. Locking prevents this problem right? Atomic reads and writes mean a variable is always written to or read from in its complete state. i.e. A write isn't interrupted halfway through saving *string s = \"stackexchange.\"*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:18:19.480", "Id": "65197", "Score": "0", "body": "So you are worried about the fact that one thread updates the properties and another thread calls `BeginInvoke` but somehow has the references to the previous property values cached? I doubt that a thread will have these values in the cache across function calls. You could create two backing fields rather than auto-properties and make the backing field volatile - this will enforce a load." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T05:38:10.177", "Id": "38972", "ParentId": "38956", "Score": "2" } } ]
{ "AcceptedAnswerId": "38972", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T01:14:13.123", "Id": "38956", "Score": "4", "Tags": [ "c#", "multithreading", "thread-safety" ], "Title": "Thread safe class" }
38956
<p>I have a business object base class which is inherited by my business objects:</p> <pre><code>public class ErrorBase { public bool HasError { get; set; } public List&lt;Error&gt; ErrorList { get; set; } public ErrorBase() { HasError = false; ErrorList = new List&lt;Error&gt;(); } } </code></pre> <p>Can this be optimized? My concern is that <code>List&lt;Error&gt;</code> is initialized every time a business object is instantiated, regardless of whether an Error object is ever added.</p> <p>The only alternative I can think of is initializing <code>ErrorList = null</code>, then checking <code>ErrorList != null</code> before calling <code>ErrorList.Add()</code>, but I'm not sure that performing that check every time before adding an Error is actually an optimization. It certainly adds steps to the process of adding an Error object to the List&lt;>.</p> <p>Is there another way I'm not thinking of? If not, is one of these approaches considered a best practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:25:33.657", "Id": "65199", "Score": "0", "body": "Answer really depends on how you are going to use that class. Are you going to add errors to each of this class instances? Some of them will not have errors? Or only several will have errors? How often you will add errors to class? What is expected errors count?" } ]
[ { "body": "<p>First: I doubt that creating a new <code>List&lt;&gt;</code> object creates enough overhead which has measurable impact on your system so unless you can prove that it's a problem don't worry about it.</p>\n\n<p>That being said: The classic solution to that problem is lazy instantiation. As you have a property already this can be easily achieved by:</p>\n\n<pre><code>public class ErrorBase\n{\n public bool HasError { get; set; }\n\n private List&lt;Error&gt; _ErrorList = null;\n public List&lt;Error&gt; ErrorList\n {\n get\n {\n if (_ErrorList == null)\n {\n _ErrorList = new List&lt;Error&gt;();\n }\n return _ErrorList;\n }\n }\n\n public ErrorBase()\n {\n HasError = false;\n }\n}\n</code></pre>\n\n<p>If you have multiple threads adding to it then you need to add some locking in the <code>get</code> - but then on the other hand <code>List&lt;&gt;</code> itself is not thread-safe so I assume that's not the case.</p>\n\n<p>In .NET 4.0 and later you have <a href=\"http://msdn.microsoft.com/en-us/library/dd642331%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Lazy&lt;&gt;</code></a> which will make the code a little bit shorter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:58:36.447", "Id": "65210", "Score": "0", "body": "I think using `Lazy<>` doesn't make sense here, since you're avoiding an allocation by making another allocation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:56:33.057", "Id": "38969", "ParentId": "38961", "Score": "4" } } ]
{ "AcceptedAnswerId": "38969", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T02:46:28.247", "Id": "38961", "Score": "4", "Tags": [ "c#" ], "Title": "When to initialize infrequently used base class objects" }
38961
<p>Below is my Interface:</p> <pre><code>public interface IDBClient { public String read(ClientInput input); } </code></pre> <p>This is my implementation of the interface:</p> <pre><code>public class DatabaseClient implements IDBClient { @Override public String read(ClientInput input) { } } </code></pre> <p>Now I have a factory which gets the instance of <code>DatabaseClient</code> like this:</p> <pre><code>IDBClient client = DatabaseClientFactory.getInstance(); .... </code></pre> <p>Now I need to make a call to <code>read</code> method of my <code>DatabaseClient</code> which accepts the <code>ClientInput</code> parameter and below is the class for the same. This class was not written by me so that is the reason I am having a question on this and I am pretty much sure this is the wrong way of doing it.</p> <pre><code>public final class ClientInput { private Long userid; private Long clientid; private Long timeout_ms = 20L; private boolean debug; private Map&lt;String, String&gt; parameterMap; public ClientInput(Long userid, Long clientid, Map&lt;String, String&gt; parameterMap, Long timeout_ms, boolean debug) { this.userid = userid; this.clientid = clientid; this.parameterMap = parameterMap; this.timeout_ms = timeout_ms; this.debug = debug; } } </code></pre> <p>So when customer make a call to <code>read</code> method of <code>DatabaseClient</code>, they will create the <code>ClientInput</code> parameter like this and then use the factory to get the Instance of <code>DatabaseClient</code> and then call the read method accordingly.</p> <pre><code>Map&lt;String, String&gt; paramMap = new HashMap&lt;String, String&gt;(); paramMap.put("attribute", "segmentation"); ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true); IDBClient client = DatabaseClientFactory.getInstance(); client.read(input); </code></pre> <p>Is this the right way of creating the <code>ClientInput</code> and then passing it to the read method? If not, then what's the best way of doing it? Where should I be doing validation check to see whether the customer has passed valid user IDs or valid client ID, etc.?</p>
[]
[ { "body": "<p>I have no major concern with setting the values of <code>ClientInput</code> via the constructor. What is your concern with this anyway? My minor concerns are:</p>\n\n<ol>\n<li>There are already three arguments of the Long type, it may not clear to other developers which position is for which field (especially during those long nights...).</li>\n<li>If more inputs are required, it will make the constructor declaration longer. </li>\n</ol>\n\n<p>Based on the name, I will prefer validation to be done within <code>ClientInput</code>. Oh, and it should have getter methods that your <code>IDBClient</code> implementations can use, and I'm guessing that's already the case as the fields are private.</p>\n\n<p>On a related note, how else will <code>ClientInput</code> be used by <code>IDBClient</code>, besides the <code>read()</code> method?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T05:40:51.013", "Id": "65178", "Score": "0", "body": "Thanks hjk.. ClientInput will be used only to retrieve the various input parameters and use them to make a call and it will be used only at that place.. And I agree with both of your issues.. How can I avoid first issue? Should it be `long` instead of `Long` object. And regarding your second issue, do you think is there any way of avoiding this issue by some better way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T07:19:28.020", "Id": "65190", "Score": "0", "body": "For the first issue, making it `long` or `Long` doesn't matter since the compiler will perform auto-boxing, and only a smart IDE (with the right settings) will prompt you about that. For both issues, consider just using setter methods for `ClientInput`. However, if you really go down this path, then you should re-evaluate why do you need a wrapper class just to 'hold' (layman terms) a bunch of input parameters together. You should consider @rolfl's answer too, if that's the case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:18:49.980", "Id": "38964", "ParentId": "38962", "Score": "2" } }, { "body": "<p>Like most times, it is best to validate your data before you use it. In your case, since the input data needs to be validated by the Database infrastructure, I recommend adding it to the <code>IDBClient</code> interface.</p>\n\n<p>I also assume that the <code>paramMap</code> is the <code>query</code> you want to run, and not part of the user/login information.</p>\n\n<p>I suspect the logical thing to do is to extend your interface to look like:</p>\n\n<pre><code>public interface IDBClient {\n\n public interface SessionHandle extends AutoCloseable, Closeable {\n public boolean isAlive();\n }\n\n public SessionHandle createSession(Long userid, Long clientid,\n Long timeout_ms, boolean debug) throws InvalidLoginException;\n\n public String read(SessionHandle session, Map&lt;String, String&gt; parameterMap)\n throws ReadNotPossibleException, SessionExpiredException;\n}\n</code></pre>\n\n<p>Now you are forced to create a <code>SessionHandle</code> instance that is pre-verified, and immutable. The content of that <code>SessionHandle</code> is whatever it needs to be for your actual <code>IDBClient</code> implementaton. The <code>IDBClient</code> implementation will know which handles are valid, and can do other things with the handle as needed.</p>\n\n<p>Because times are good, and Java7 is better, you should also ensure that your <code>SessionHandle</code> <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html\" rel=\"nofollow\">is <code>AutoCloseable</code></a> so you can <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">use try-with-resources</a>.</p>\n\n<p>Your Exceptions (<a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html\" rel=\"nofollow\">which you should create custom versions of</a>) for your interface should all extend a single Exception class, for example:</p>\n\n<pre><code>public DBClientException extends Exception { ..... }\npublic ReadNotPossibleException extends DBClientException {....}\npublic SessionExpiredException extends DBClientException {...}\n</code></pre>\n\n<p>by doing this, you can allow the user to catch just the database exception, or more-specific database exception sub-types if needed....</p>\n\n<p>The 'user experience' will look like:</p>\n\n<pre><code>IDBClient client = DatabaseClientFactory.getInstance();\ntry (IDBClient.SessionHandle session =\n client.createSession( 109739281L, 20L, 1000L, true) ) {\n\n String result = client.read(session, paramMap);\n\n} catch (DBClientException e) {\n .....\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:21:47.537", "Id": "38965", "ParentId": "38962", "Score": "3" } } ]
{ "AcceptedAnswerId": "38964", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T02:49:51.703", "Id": "38962", "Score": "3", "Tags": [ "java" ], "Title": "Passing input parameters correctly to a method" }
38962
<p>I am struggling with commenting and variable naming. My teacher says my comments need to be more explanatory and explicit. He says my variable names are also sometimes confusing. I was just wondering whether you could go through my code and see whether you are able to understand the comments and add in comments/edit where you feel I should add comments or improve them. Lastly, are there any general rules to follow with commenting?</p> <pre><code>class PPM(object): def __init__(self, infile, outfile): self.infile=infile self.outfile=outfile #Read in data of image data= open(self.infile,"r") datain=data.read() splits=datain.split(None, 4) #Header info and pixel info self.type=splits[0] self.columns=int(splits[1]) self.rows=int(splits[2]) self.colour=int(splits[3]) #(Return a new array of bytes) self.pixels=bytearray(splits[4]) def grey_scale(self): for row in range(self.rows): for column in range(self.columns): start = row * self.columns * 3 + column * 3 end = start + 3 r, g, b = self.pixels[start:end] brightness = int(round( (r + g + b) / 3.0 )) self.pixels[start:end] = brightness, brightness, brightness def writetofile(self): dataout= open(self.outfile, "wb") #Use format to convert back to strings to concatenate them and Those {} in the write function get's replaced by the arguments of the format function. dataout.write('{}\n{} {}\n{}\n{}'.format(self.type, self.columns, self.rows, self.colour, self.pixels)) sample = PPM("cake.ppm", "Replica.ppm") sample.grey_scale() sample.writetofile() </code></pre>
[]
[ { "body": "<p>To steal an old quote: \"There are 2 hard things in computer science. Naming, cache invalidation, and off-by-one errors\". </p>\n\n<p>That being said, there is room for improvement here. Firstly, I'm assuming the class name, <code>PPM</code>, is short for <em>Portable Pixmap Format</em>. However, this isn't immediately obvious, and if you aren't familiar with that format (I'm not), it required a search. Hence, the first thing I'd do is change the name to something a bit more descriptive, and add a docstring explaining something about the format:</p>\n\n<pre><code>class PortablePixmap(object):\n '''A class encapsulating basic operations on images that use the\n portable pixmap format (PPM). \n\n '''\n</code></pre>\n\n<p>Python itself has a style guide known as <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a> that you should try to follow as much as possible. Generally the convention in python is to name <code>ClassesLikeThis</code>, <code>methods_like_this</code>, and <code>variables_like_this</code>. Hence, another change I'd make is to rename <code>infile</code> and <code>outfile</code> to <code>in_file</code> and <code>out_file</code> respectively. </p>\n\n<p>Continuing on, the first comment under <code>__init__</code> is fairly obvious: </p>\n\n<pre><code>#Read in data of image\ndata= open(self.infile,\"r\")\ndatain=data.read()\n</code></pre>\n\n<p>As a minor aside, try and keep the whitespace around operators like <code>=</code> consistent. Again, as per PEP8, these should be:</p>\n\n<pre><code>data = open(self.infile, \"r\")\ndata_in = data.read()\n</code></pre>\n\n<p>I'd also consider renaming <code>data_in</code> to something like <code>raw_image_data</code>.</p>\n\n<p>Back to the comments. The next line has no comment, but needs it far more than the previous 2 lines:</p>\n\n<pre><code># Break up the image data into 4 segments because ...\nsplits = datain.split(None, 4)\n</code></pre>\n\n<p>The comment <code>#(Return a new array of bytes)</code> is both obvious and misleading: this is <code>__init__</code>; you're constructing the object - assigning to <code>self.pixels</code> isn't returning anything!</p>\n\n<p>For <code>grey_scale,</code> your indentation moves to 8 spaces instead of 4. Be careful with this - especially in Python, where whitespace can modify the semantics (meaning) of your program. This function should again have a docstring:</p>\n\n<pre><code>def grey_scale(self):\n '''Converts the supplied image to greyscale.'''\n</code></pre>\n\n<p>The final function, <code>def writetofile(self):</code> should again use <code>_</code> as separators\nto make it easier to read. I'd also probably move the <code>out_file</code> parameter to this function, rather than passing it in <code>__init__</code>:</p>\n\n<pre><code>def write_to_file(self, output_location):\n '''Writes the image file to the location specified output location.\n The file is written in &lt;some description of the file format&gt;.\n\n '''\n</code></pre>\n\n<p>Watch the length of your comments (they should stick to the same line lengths as everything else in your program).</p>\n\n<pre><code>#Use format to convert back to strings to concatenate them and Those {} in the write function get's replaced by the arguments of the format function.\n</code></pre>\n\n<p>The comment itself is also difficult to understand:</p>\n\n<blockquote>\n <p>\"convert back to string to concatenate them and Those {} ...\" </p>\n</blockquote>\n\n<p>That made me do a double take. Try and write comments as complete sentences.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T07:09:32.983", "Id": "65189", "Score": "0", "body": "upvoted twice ... nice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:34:08.660", "Id": "38966", "ParentId": "38963", "Score": "16" } }, { "body": "<p>In python, docstrings are common-place to use to assist in automatic doc generation. You can typically expect a docstring for each class and each function. Take a look at <a href=\"http://epydoc.sourceforge.net/manual-docstring.html\" rel=\"nofollow\">http://epydoc.sourceforge.net/manual-docstring.html</a></p>\n\n<p>As for doc coding standards, there are many. Here's one:</p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">http://www.python.org/dev/peps/pep-0257/</a></p>\n\n<p>Getting fancy, you can structure your docstrings using epytext markup language:</p>\n\n<p><a href=\"http://epydoc.sourceforge.net/manual-epytext.html\" rel=\"nofollow\">http://epydoc.sourceforge.net/manual-epytext.html</a></p>\n\n<p>Example using only docstrings:</p>\n\n<pre><code>class PPM(object):\n '''What does the PPM class do? Comment me here.'''\n def __init__(self, infile, outfile):\n '''what am I expecting for the infile/outfile? is it strings or a file handler'''\n self.infile=infile\n self.outfile=outfile\n\n #Read in data of image - it is good practice to indent comments so you can know where they line up\n data= open(self.infile,\"r\")\n datain=data.read()\n splits=datain.split()\n\n\n # Reads the headers info and writes it\n self.type=splits[0]\n self.columns=int(splits[1])\n self.row=int(splits[2])\n self.colour=splits[3]\n\n\n\n # Splits the pixels and adds them to the matrix using the columns and row information obatined from the image\n pixels= splits[4:]\n self.Lines = []\n\n for rowCount in range(self.row):\n rowStart = rowCount * self.columns*3\n rowEnd = rowStart + (self.columns * 3)\n\n self.Lines.append( pixels[rowStart : rowEnd] )\n\n\n # consider making this write_to_file - be consistent in the spacing (or lack of spacing in your function names)\n def writetofile(self):\n '''what does this function do?'''\n\n #Opens the output file and writes out the header information\n dataout= open(self.outfile, \"w\")\n dataout.write(self.type+\"\\n\" + str(self.columns) + \"\\n\" + str(self.row) +\"\\n\"+ self.colour + \"\\n\")\n\n for line in self.Lines:\n dataout.write(\" \".join(line) + \"\\n\")\n\n dataout.close()\n\n def horizontal_flip(self):\n '''what does this function do?'''\n # inconsistent tabbing (3 tabs spaces here, 2 normally)\n for line in self.Lines:\n FlippedLine = line[::-1]\n # First join values so writing is possible and than, loop through the values to write all data to output.\n for data in FlippedLine:\n Reversed= \" \".join(data) + \" \"\n userInstance.writetofile(Reversed)\n\n\n def flatten_red(self):\n '''Grabs every red value and sets it equal to 0'''\n #Loops till end of row in order to grab all red values\n for row in range(self.row):\n #loops by 3 in order to grab only red values\n for col in range(0, self.columns*3, 3):\n self.Lines[row][col]= str(0)\n\n print(self.Lines)\n\n\n\n\n def negate_red(self):\n '''Grabs every red value and converts it to its negative value by subtracting the colour value from the red value'''\n for row in range(self.row):\n for col in range(0, self.columns*3, 3):\n remainder = int(self.colour) -int((self.Lines [row][col]))\n self.Lines[row][col] = str(remainder)\n print(self.Lines)\n\n\n def grey_scale(self):\n '''Converts the supplied image to greyscale.'''\n\n for row in range(self.row):\n for col in range(0, self.columns*3, 3):\n\n sum = int(self.Lines[row][col]) + int(self.Lines[row][col+1]) + int(self.Lines[row][col+2])\n avg = int(sum/3)\n\n self.Lines[row][col] = str(avg)\n self.Lines[row][col+1] = str(avg)\n self.Lines[row][col+2] = str(avg)\n\n\n\n\n\n\n\n\nprint (\"Portable Pixmap Image Editor\")\n\ninput_file = input(\"Enter the name of image file: \")\n\noutput_file = input(\"Enter the name of the output file: \")\n\nuserInstance = PPM(str(input_file), str(output_file))\n\nprint (\"Here are your choices: [1] Convert to grayscale [2] Flip horizontally [3] Negation of red [4] Elimination of red\")\n\noption1 = input(\"Do you want [1]? (write y or n)\")\n\noption2 = input(\"Do you want [2]? (write y or n)\")\n\noption3 = input(\"Do you want [3]? (write y or n)\")\n\noption4 = input(\"Do you want [4]? (write y or n)\")\n\nif option1 == \"y\":\n userInstance.grey_scale()\n\nif option2 == \"y\":\n userInstance.horizontal_flip()\n\nif option3 == \"y\":\n userInstance.negate_red()\n\nif option4 == \"y\":\n userInstance.flatten_red()\n\nuserInstance.writetofile()\n\nprint(output_file + \" created.\")\n</code></pre>\n\n<p>This example for starters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:40:57.750", "Id": "67022", "Score": "0", "body": "http://www.amazon.com/The-Readable-Code-Theory-Practice/dp/0596802293 is a great resource on the why and when of commenting" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:03:43.607", "Id": "39925", "ParentId": "38963", "Score": "1" } }, { "body": "<p>Yuushi links to PEP8. It has a <a href=\"http://legacy.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow\">section specifically on comments</a>, which might be useful since you asked about general rules for commenting.</p>\n\n<p>I would say comments should talk more about the <em>why</em> of the code than the what. After reading in the header, why split it into four pieces? What does the header look like (when dealing with a particular data format, I find it extremely helpful to provide an example in the comments)? In the last line of the constructor, why do we need the same data in another bytearray?</p>\n\n<p>Other than that, what Yuushi said. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:01:23.717", "Id": "47415", "ParentId": "38963", "Score": "3" } } ]
{ "AcceptedAnswerId": "38966", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T02:50:28.293", "Id": "38963", "Score": "10", "Tags": [ "python", "image", "io" ], "Title": "Writing .ppm images to a file" }
38963
IEnumerable is a .NET interface for iterating (or enumerating) a collection of items.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T03:50:30.547", "Id": "38968", "Score": "0", "Tags": null, "Title": null }
38968
<p>OK, maybe crazy overkill and a little silly, but why not? Here's a Python FizzBuzz Acceptance Test:</p> <pre><code>import unittest from fizzbuzzmodule import fizzbuzz class FizzBuzzAcceptanceTestCase(unittest.TestCase): ''' Test that fizzbuzz(int) returns int unless multiple of 3 (then returns 'fizz') multiple of 5 (then returns 'buzz') multiple of both (then returns 'fizzbuzz') ''' def test_business_as_usual(self): ''' test that an integer &gt;= 0 not evenly divisible by three or five returns the same ''' self.assertEqual(fizzbuzz(1), 1) self.assertEqual(fizzbuzz(2), 2) self.assertEqual(fizzbuzz(4), 4) self.assertEqual(fizzbuzz(7), 7) self.assertEqual(fizzbuzz(998), 998) def test_fizz(self): '''evenly divisible by 3 returns fizz''' self.assertEqual(fizzbuzz(3), 'fizz') self.assertEqual(fizzbuzz(6), 'fizz') self.assertEqual(fizzbuzz(111), 'fizz') self.assertEqual(fizzbuzz(999), 'fizz') def test_buzz(self): '''evenly divisible by 5 returns buzz''' self.assertEqual(fizzbuzz(5), 'buzz') self.assertEqual(fizzbuzz(10), 'buzz') self.assertEqual(fizzbuzz(20), 'buzz') self.assertEqual(fizzbuzz(500), 'buzz') def test_fizz_buzz(self): '''evenly divisible by 3 and 5 returns fizzbuzz''' self.assertEqual(fizzbuzz(15), 'fizzbuzz') self.assertEqual(fizzbuzz(30), 'fizzbuzz') self.assertEqual(fizzbuzz(45), 'fizzbuzz') self.assertEqual(fizzbuzz(600), 'fizzbuzz') # def test_zero(self): # self.assertEqual(fizzbuzz(0), 'fizzbuzz') #?????? def main(): unittest.main() if __name__ == '__main__': main() </code></pre> <p>Typed up a little implementation that passes these tests:</p> <pre><code>def fizzbuzz(number): ''' if number divisible by 3 return 'fizz'; 5, 'buzz'; both, fizzbuzz else return number ''' if not number % 3: if not number % 5: return 'fizzbuzz' else: return 'fizz' if not number % 5: return 'buzz' return number def main(): for i in range(1, 101): print fizzbuzz(i) </code></pre> <p>And when I run the tests:</p> <pre><code>&gt;&gt;&gt; unittest.main() .... ---------------------------------------------------------------------- Ran 4 tests in 0.002s OK </code></pre> <p>And my question is, how would you augment the above? Would you find it useful to run this test on someone's code? Does it clearly define a clean API? Would it be preferable to return a consistent type instead of strings or ints?</p> <p>Should I have done this differently? Have I not considered any edge or corner cases?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:04:24.563", "Id": "65179", "Score": "0", "body": "you should remove the code golf part, or post it on the [Code Golf Stack Site](http://codegolf.stackexchange.com/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:06:31.680", "Id": "65180", "Score": "1", "body": "No code golf! :)" } ]
[ { "body": "<p>For something so simple, it might be less overkill to use the <a href=\"http://docs.python.org/2/library/doctest\" rel=\"nofollow\"><code>doctest</code></a> module. Write the expected calls and outputs in the docstring, then run <code>python -m doctest -v fizzbuzzmodule.py</code>. There's no need to write a separate class.</p>\n\n<p>I've written one of the tests to ensure that the function also works when called with decreasing arguments.</p>\n\n<p>As for the function itself, I believe that the code reads better if you write <code>number % 3 == 0</code> instead of <code>not number % 3</code>. I would also use a <a href=\"http://docs.python.org/2/reference/expressions.html#conditional-expressions\" rel=\"nofollow\">conditional expression</a>, but that's just a matter of personal preference.</p>\n\n<pre><code>def fizzbuzz(number):\n '''\n if number divisible by 3 return 'fizz';\n 5, 'buzz'; both, fizzbuzz\n else return number\n\n &gt;&gt;&gt; fizzbuzz(1)\n 1\n &gt;&gt;&gt; fizzbuzz(2)\n 2\n &gt;&gt;&gt; fizzbuzz(3)\n 'fizz'\n &gt;&gt;&gt; fizzbuzz(4)\n 4\n &gt;&gt;&gt; fizzbuzz(5)\n 'buzz'\n &gt;&gt;&gt; fizzbuzz(15)\n 'fizzbuzz'\n &gt;&gt;&gt; [fizzbuzz(i) for i in range(31, 20, -1)]\n [31, 'fizzbuzz', 29, 28, 'fizz', 26, 'buzz', 'fizz', 23, 22, 'fizz']\n '''\n if number % 3 == 0:\n return 'fizzbuzz' if (number % 5 == 0) else 'fizz'\n if number % 5 == 0:\n return 'buzz'\n return number\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:09:59.477", "Id": "38984", "ParentId": "38973", "Score": "4" } } ]
{ "AcceptedAnswerId": "38984", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T05:49:09.280", "Id": "38973", "Score": "4", "Tags": [ "python", "unit-testing", "fizzbuzz" ], "Title": "Python Fizz Buzz, Acceptance Unit test" }
38973
<p>This was a project I worked on for fun that basically uses a genetic algorithm to produce simple Brainfuck programs that output whatever the user specifies.</p> <p>I was just was hoping for criticism of the code, mainly if I'm doing anything blatantly wrong. I'm not too familiar with the STL, so there may have been algorithms I could've used from there but I'm not sure. I realize this is a somewhat decent amount of code, so if you just want to focus on a single function or section, that's fine.</p> <pre><code>/************************************************************************************************************** * Brainfuck Evolved * * Written by Kurtis Dinelle (http://kurtisdinelle.com) * * * * This program attemps to write programs of its own in the brainfuck language, using a genetic algorithm. * * The fitness function will take into account how close the output matches, and how concise the program is. * * Shorter programs receive a slight bonus. * **************************************************************************************************************/ #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;cmath&gt; #include "interpreter.h" // Don't modify this group of constants. const unsigned CHAR_SIZE = 255; // The max value of a 'cell' in the memory tape. const unsigned NUM_MUTATIONS = 3; // The number of types of mutations: (ADD, DELETE, CHANGE). const char INSTRUCTIONS[] = {'+', '-', '&gt;', '&lt;', '[', ']', '.'}; // The list of brainfuck instructions. const unsigned NUM_INSTRUCTIONS = (sizeof(INSTRUCTIONS) / sizeof(INSTRUCTIONS[0])); // Holds the number of instructions allowed. const unsigned NUM_CHILDREN = 2; // Number of children two parents create upon reproduction. // Modify any constants below. const unsigned POP_SIZE = 10; // The size of the population. This always remains the same between generations. const unsigned MIN_PROGRAM_SIZE = 10; // The minimum size a possible program can be. const unsigned MAX_PROGRAM_SIZE = 500; // The maximum size a possible program can be. const double MUTATION_RATE = 0.01; // The chance of a 'gene' in a child being mutated. const double ERROR_SCORE = 1.0; // The score an erroneous program receives. const double LENGTH_PENALTY = 0.001; // The size of the program is multiplied by this then added to score. const unsigned DISPLAY_RATE = 10000; // How often to display the best program so far. // These aren't constant because they can be changed by the user. std::string GOAL_OUTPUT = "Robots"; size_t GOAL_OUTPUT_SIZE = GOAL_OUTPUT.length(); /* These two functions used to generate either a random double or unsigned int. Why didn't I just overload one function? Slipped my mind at the time. */ double get_random(double low, double high) { return low + static_cast&lt;double&gt;(rand()) / static_cast&lt;double&gt;(static_cast&lt;double&gt;(RAND_MAX) / (high - low)); } unsigned get_random_int(unsigned low, unsigned high) { return (rand() % (high - low + 1)) + low; } char get_random_instruction() { return INSTRUCTIONS[get_random_int(0, NUM_INSTRUCTIONS - 1)]; } void add_instruction(std::string &amp;program, unsigned index) { std::string instr(1, get_random_instruction()); // Need to convert char to string for use by insert. if((program.length() + 1) &lt;= MAX_PROGRAM_SIZE) program.insert(index, instr); } void remove_instruction(std::string &amp;program, unsigned index) { // Subtract 2 instead of 1 to account for the off-by-one difference between a string length and the last element index. if((program.length() - 2) &gt;= MIN_PROGRAM_SIZE) program.erase(index, 1); } void mutate_instruction(std::string &amp;program, unsigned index) { program[index] = get_random_instruction(); } // Creates a random program by first randomly determining its size and then adding that many instructions randomly. std::string create_random_program() { std::string program; unsigned program_size = get_random_int(MIN_PROGRAM_SIZE, MAX_PROGRAM_SIZE); for(unsigned i = 1; i &lt;= program_size; ++i) program += get_random_instruction(); return program; } // Creates the first generation's population by randomly creating programs. void initialize_population(std::string programs[]) { for(unsigned i = 0; i &lt; POP_SIZE; ++i) programs[i] = create_random_program(); } // The Fitness Function. Determines how 'fit' a program is using a few different criteria. double calculate_fitness(const std::string &amp;program, Interpreter &amp;bf) { // The score of the worst program possible (Besides erroneous program, and not taking into account program length). double max_score = GOAL_OUTPUT_SIZE * CHAR_SIZE; double score = 0; double final_score; std::string output = bf.run(program); // Impose a very large penalty for error programs, but still allow them a chance at reproduction for genetic variation. if(output == Interpreter::ERROR) return ERROR_SCORE; /* We need to know whether the goal output or the program's output is larger because that's how many iterations of the next loop need to be done. */ std::string min_str = (output.length() &lt; GOAL_OUTPUT.length()) ? output : GOAL_OUTPUT; std::string max_str = (output.length() &gt;= GOAL_OUTPUT.length()) ? output : GOAL_OUTPUT; // The more each character of output is similar to its corresponding character in the goal output, the higher the score. for(size_t i = 0; i &lt; max_str.length(); ++i) { unsigned output_char = (i &lt; min_str.length()) ? min_str[i] : max_str[i] + CHAR_SIZE; score += abs(output_char - max_str[i]); } score += (program.length() * LENGTH_PENALTY); // Impose a slight penalty for longer programs. /* The lower the score of a program, the better (think golf). However other calculations in the program assume a higher score is better. Thus, we subtract the score from max_score to get a final score. */ final_score = max_score - score; return final_score; } /* Generates a fitness score for each program in the population. This is done by running the program through the brainfuck interpreter and scoring its output. Also returns the best program produced. */ std::string score_population(const std::string programs[], double scores[], int &amp;worst_index, Interpreter &amp;bf) { std::string best_program; double best_score = 0; double worst_score = 9999; // Arbitrarily high number. for(unsigned i = 0; i &lt; POP_SIZE; ++i) { scores[i] = calculate_fitness(programs[i], bf); if(scores[i] &gt; best_score) { best_program = programs[i]; best_score = scores[i]; } else if(scores[i] &lt; worst_score) { worst_index = i; worst_score = scores[i]; } } return best_program; } // Adds every program's fitness score together. double pop_score_total(const double scores[]) { double total = 0; for(unsigned i = 0; i &lt; POP_SIZE; ++i) total += scores[i]; return total; } /* Selects a parent to mate using fitness proportionate selection. Basically, the more fit a program is, the more likely it is to be selected. */ std::string select_parent(const std::string programs[], const double scores[], const std::string &amp;other_parent = "") { double program_chances[POP_SIZE]; // Holds each program's chance of being selected (a # between 0 and 1). double score_total = pop_score_total(scores); double rand_val = get_random(0.0, 1.0); for(unsigned i = 0; i &lt; POP_SIZE; ++i) { // Cast i to int so when we go to subtract 1, if i is 0 it doesn't overflow (as an unsigned int can't be negative). double prev_chance = ((static_cast&lt;int&gt;(i) - 1) &lt; 0) ? 0 : program_chances[i - 1]; /* We add the previous program's chance to this program's chance because that is its range of being selected. The higher the fitness score, the bigger this program's range is. */ program_chances[i] = (scores[i] / score_total) + (prev_chance); // Need to subtract a small amount from rand_val due to floating-point precision errors. Without it, equality check could fail. if(program_chances[i] &gt;= (rand_val - 0.001) &amp;&amp; (programs[i] != other_parent)) return programs[i]; } /* If the other parent was the last program in the list, we might get here. In that case, just return the 1st program. */ return programs[0]; } /* Mutates a program by either inserting, removing, or changing an instruction. This returns a string rather than modifying a a string just due to the way it is used in the program. */ std::string mutate(std::string child) { // Loop through each command and randomly decide to mutate it based on the mutation rate. for(size_t i = 0; i &lt; child.length(); ++i) { if(MUTATION_RATE &gt;= get_random(0.0, 1.0)) { unsigned mutation_type = get_random_int(1, NUM_MUTATIONS); switch(mutation_type) { case 1: mutate_instruction(child, i); break; case 2: add_instruction(child, i); break; case 3: remove_instruction(child, i); break; default: break; } } } return child; } // Performs crossover between two parents to produce two children. void mate(const std::string &amp;parent1, const std::string &amp;parent2, std::string children[]) { // We need to find which program is longest. std::string min_str = (parent1.length() &lt; parent2.length()) ? parent1 : parent2; std::string max_str = (parent1.length() &gt;= parent2.length()) ? parent1 : parent2; // Determine a crossover point at random. unsigned crosspoint = get_random_int(1, max_str.length() - 1); // Find the substring of the program after the crossover point std::string max_str_contrib = max_str.substr(crosspoint); // Then erase after that point max_str.erase(crosspoint); /* If the cross-over point is less than the length of the smaller program, then we need to combine part of it with the larger program. If not, then we do nothing and just take part of the larger program and add it to it. */ if(crosspoint &lt;= min_str.length()) { max_str += min_str.substr(crosspoint); min_str.erase(crosspoint); } // Add the 2nd part of the larger program to the smaller program. min_str += max_str_contrib; // Call the mutate function on the children which has a small chance of actually causing a mutation. children[0] = mutate(min_str); children[1] = mutate(max_str); } bool program_exists(const std::string &amp;program, const std::string programs[]) { for(unsigned i = 0; i &lt; POP_SIZE; ++i) { if(program == programs[i]) return true; } return false; } void replace_program(const std::string &amp;parent, const std::string &amp;child, std::string programs[]) { for(unsigned i = 0; i &lt; POP_SIZE; ++i) { if(parent == programs[i]) { programs[i] = child; break; } } } int main(int argc, char *argv[]) { // Check if ran from command line. if(argc &gt; 1) { GOAL_OUTPUT = argv[1]; GOAL_OUTPUT_SIZE = GOAL_OUTPUT.length(); } // Initialize the brainfuck interpreter and seed random. Interpreter brainfuck; srand(time(0)); std::string programs[POP_SIZE]; double fitness_scores[POP_SIZE]; initialize_population(programs); std::string best_program; bool keep_going = false; // Just used to have the program keep searching after a match is found. unsigned long generations = 0; // And now we just repeat the process of selection and reproduction over and over again. while(1) { int worst_program_index = 0; best_program = score_population(programs, fitness_scores, worst_program_index, brainfuck); // Select two parents randomly using fitness proportionate selection std::string parent1 = select_parent(programs, fitness_scores); std::string parent2 = select_parent(programs, fitness_scores, parent1); // Mate them to create children std::string children[NUM_CHILDREN]; mate(parent1, parent2, children); /* Replace the parent programs with the children. We replace the parents to lessen the chance of premature convergence. This works because by replacing the parents, which are most similar to the children, genetic diversity is maintained. If the parents were not replaced, the population would quickly fill with similar genetic information. */ replace_program(parent1, children[0], programs); replace_program(parent2, children[1], programs); /* Replace the worst program with the best program if it was replaced by its child. (Elitism). This is done to ensure the best program is never lost. */ if(!program_exists(best_program, programs)) programs[worst_program_index] = best_program; // Report on the current best program every so often. if(!(generations % DISPLAY_RATE)) { std::cout &lt;&lt; "\n\nBest program evolved so far: " &lt;&lt; std::endl; std::cout &lt;&lt; best_program &lt;&lt; std::endl; std::string output = brainfuck.run(best_program); std::cout &lt;&lt; "\nOutput: " &lt;&lt; output &lt;&lt; std::endl; if(output == GOAL_OUTPUT &amp;&amp; !keep_going) { std::cout &lt;&lt; "\n\a\a\aProgram evolved!" &lt;&lt; std::endl; std::cout &lt;&lt; "Save source code as a text file? (y/n) "; char answer; std::cin &gt;&gt; answer; if(answer == 'y') { std::ofstream srcfile("bfsrc.txt"); srcfile &lt;&lt; GOAL_OUTPUT &lt;&lt; ":\n\n" &lt;&lt; best_program; std::cout &lt;&lt; "Source code saved as 'bfsrc.txt'\n" &lt;&lt; std::endl; } //std::cout &lt;&lt; "It took roughly " &lt;&lt; generations &lt;&lt; " generations to evolve this program." &lt;&lt; std::endl; std::cout &lt;&lt; "Keep evolving for more efficiency? (y/n) "; std::cin &gt;&gt; answer; // Quit the program if the user doesn't want to continue. if(answer != 'y') return 0; keep_going = true; } } ++generations; } return 0; } </code></pre>
[]
[ { "body": "<p>There's quite a bit of code here, so I'm not going to get through all of it, but I'll do as much as possible. Also, since I don't have access to your <code>interpreter.h</code>, I can't guarantee everything I've written will compile; there may be syntax errors and a few bugs lurking around, so consider yourself forewarned.</p>\n\n<p>I think in general this is a fun idea, so kudos for that. However, the way it is written is very much C-style with <code>std::string</code> thrown in. I'm going to endeavour to give you a reasonable chunk of it rewritten in modern-style C++, explaining as much as I can along the way. I'll start by separating out a few things that I think can be encapsulated nicely in separate classes.</p>\n\n<p>The first class will be responsible for random number generation and random selection. I'm going to give it the (not fantastic, admittedly) name of <code>random_generator</code>. Further, this is going to replace <code>rand()</code> (which is, without mincing words, pretty much crap), with the pseudo-random generation supplied by C++11:</p>\n\n<pre><code>#include &lt;random&gt;\n\nclass random_generator\n{\nprivate:\n\n std::random_device rand_dev;\n std::mt19937 generator;\n\npublic:\n\n random_generator()\n : generator(rand_dev())\n { }\n\n double next(double low, double high)\n {\n std::uniform_real_distribution&lt;&gt; dist(low, high);\n return dist(generator);\n }\n\n std::size_t next(std::size_t low, std::size_t high)\n {\n std::uniform_int_distribution&lt;std::size_t&gt; dist(low, high);\n return dist(generator);\n }\n\n template &lt;typename Sequence&gt;\n typename Sequence::value_type select(const Sequence&amp; seq)\n {\n std::size_t index = next(0, seq.size() - 1);\n return seq[index];\n }\n};\n</code></pre>\n\n<p>The parts that make up this class may be unfamiliar (and a fair bit more complex than simply calling <code>rand()</code>), but will produce much \"better\" random numbers. <code>std::mt19937</code> is simply a source of pseudo-randomness to draw from. From this, we can use <code>uniform_real_distribution</code> and <code>uniform_int_distribution</code>. These generate uniformly distributed numbers that lie between (and including) the 2 parameters passed in.</p>\n\n<p>The final function utilises templates to pick random values from any container satisfying <code>operator[]</code>: so things like <code>std::vector</code> and <code>std::array</code>. </p>\n\n<p>Let's move on to the actual brainfuck program itself. We'll again make a class (named, inventively, <code>brainfuck_program</code>) that encapsulates a single program:</p>\n\n<pre><code>#include &lt;vector&gt;\n\nclass brainfuck_program\n{\nprivate:\n\n static const std::vector&lt;char&gt; instructions;\n static constexpr unsigned num_children = 2;\n static constexpr unsigned char_size = 255; \n static constexpr unsigned num_mutations = 3;\n\n random_generator rand_gen;\n std::string current_program;\n\npublic:\n\n const std::size_t max_program_size;\n const std::size_t min_program_size; \n\n brainfuck_program(std::size_t max_size, std::size_t min_size)\n : max_program_size(max_size),\n min_program_size(min_size)\n { }\n\n char random_instruction()\n {\n return rand_gen.select(instructions);\n }\n\n bool add_instruction(std::size_t index)\n {\n if(index &lt; max_program_size) {\n current_program.insert(index, 1, random_instruction());\n return true;\n }\n return false;\n }\n\n bool remove_instruction(std::size_t index)\n {\n if(current_program.size() - 2 &gt;= min_program_size) {\n program.erase(index, 1);\n return true;\n }\n return false;\n }\n\n void mutate_instruction(std::size_t index)\n {\n current_program[index] = random_instruction();\n }\n\n double fitness(Interpreter&amp; bf)\n {\n ...\n }\n\nprivate:\n\n void create_random_program()\n {\n std::size_t program_size = rand_gen.next(min_program_size, max_program_size);\n for(std::size_t i = 0; i &lt; program_size; ++i) {\n program += random_instruction();\n }\n } \n};\n\nconst std::vector&lt;char&gt; brainfuck_program::instructions = {'+', '-', '&gt;', '&lt;', '[', ']', '.'}; \n\nbool operator==(const brainfuck_program&amp; b1, const brainfuck_program&amp; b2)\n{\n return b1.current_program == b2.current_program;\n}\n</code></pre>\n\n<p>Here, I've moved a lot of the global variables to do with brainfuck programs into <code>static</code> class variables (since they shouldn't be changed by the user, they should be the same for all generated brainfuck programs).</p>\n\n<p>Many of the functions that simply operated on a passed in <code>std::string</code> before are now member functions. They now modify a (class private) <code>string</code> instead. The code itself hasn't changed all that much, although we're now using the <code>random_generator</code> class that we defined before to select our random instructions for us. Also, the <code>string</code> that encapsulates the program is initiated when the constructor is called.</p>\n\n<p>Finally, we'll look at a class that is designed to deal with populations of brainfuck programs. Let's call it <code>population_manager</code>:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;numeric&gt;\n#include &lt;set&gt;\n#include &lt;iterator&gt;\n#include &lt;utility&gt;\n\nclass population_manager\n{\nprivate:\n\n using prog_score_pair = std::pair&lt;double, brainfuck_program&gt;;\n\n struct score_sorter\n {\n bool operator()(const prog_score_pair&amp; p, const prog_score_pair&amp; t) const\n {\n return s.second &gt; t.second;\n }\n };\n\n std::vector&lt;brainfuck_program&gt; populations;\n std::set&lt;prog_score_pair, score_sorter&gt; population_scores;\n\npublic:\n\n const std::size_t population_size;\n\n population(std::size_t pop_size)\n : population_size(pop_size),\n populations(population_size)\n { }\n\n std::pair&lt;brainfuck_program, std::size_t&gt; \n score_population(Interpreter&amp; bf)\n {\n using prog_inserter = std::insert_iterator&lt;std::set&lt;prog_score_pair, score_sorter&gt;&gt;;\n std::transform(populations.begin(), populations.end(), std::prog_inserter,\n [&amp;](const brainfuck_program&amp; p) \n {\n auto score = p.fitness(bf); \n return std::make_pair(score, p); \n });\n\n return *population_scores.begin();\n }\n\n double score_total() const\n {\n return std::accumulate(population_scores.begin(), population_scores.end(),\n 0.0, [](const prog_score_pair&amp; p1, const prog_score_pair&amp; p2)\n { return p1.first + p2.first; });\n }\n\n // Other methods...\n\n};\n</code></pre>\n\n<p>This is more incomplete that the other two classes, but hopefully gives you an outline. Firstly, we use a <code>std::set</code> to store programs in sorted order (descending in this case) of their scores. This allows fast access to each score in order. You lose the ability to find the <code>worst_index</code> (which you use in <code>score_population</code> currently), however this is unused in the rest of the program.</p>\n\n<p>So, that's a fair whack of code, and some of it probably looks a bit strange (depending on your familiarity with some C++ features). What have we gained from this?</p>\n\n<ol>\n<li><p>More type safety: Currently, every program is just a string. Now, that string cannot be accessed directly, but can only be generated and modified through our class interface. This gives us guarantees that certain invariants will be satisfied, and there is less possibility for bugs. </p></li>\n<li><p>We've broken things up into (possibly) reusable pieces. Also, we've separated out things that are logically distinct: random generation is completely separated from the brainfuck programs itself. </p></li>\n<li><p>Logical grouping of things that are NOT distinct. We've removed a lot of global state from the program (to be fair, much of it was <code>const</code> global state, which isn't nearly as bad), but this method makes it more obvious what settings affect what pieces.</p></li>\n</ol>\n\n<p>Again, apologies in advance for any bugs/syntax errors in what I've shown.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:34:52.327", "Id": "38995", "ParentId": "38974", "Score": "5" } } ]
{ "AcceptedAnswerId": "38995", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T05:56:30.417", "Id": "38974", "Score": "7", "Tags": [ "c++", "generics", "brainfuck" ], "Title": "Genetic C++ programming with Brainfuck" }
38974
<p>Say you have a dictionary <code>some_dict</code> and want to make sure there's no key <code>some_key</code> in it. What's the best way to do this stylistically speaking and why?</p> <p><strong>Option 1</strong></p> <pre><code>some_dict.pop(some_key, None) </code></pre> <p><strong>Option 2</strong></p> <pre><code>try: del some_dict[some_key] except KeyError: pass </code></pre> <p><strong>Option 3</strong></p> <pre><code>if some_key in some_dict: del some_dict[some_key] </code></pre> <p>Also feel free to suggest another option.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:23:43.393", "Id": "65223", "Score": "0", "body": "If you happen to need a separate copy there's always `copied_dict = { k : v for (k,v) in some_dict.iteritems() if k != some_key }`. (or `items()` instead of `iteritems()` in python 3)" } ]
[ { "body": "<p>Option 1 looks perfect to me. It does the job in one line and is easy to read. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:48:10.420", "Id": "65227", "Score": "0", "body": "That's what my first instinct is too. But I have a niggle. It's seems implicit (and therefore less Pythonic) that I don't care about the value of `some_key`. In Option 3, my intention that I only care about deleting the key, not its value, is explicit. Of course Option 3 probably slower, but negligibly so in almost all cases. Thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T21:40:54.403", "Id": "65290", "Score": "0", "body": "@Ghopper21 To me it is perfectly clear that you don't care about the value. If you did you would assign it somewhere." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T07:02:04.180", "Id": "38979", "ParentId": "38976", "Score": "4" } }, { "body": "<p>Option 2 vs Option 3 is the classic \"EAFP vs LBYL\" question (see <a href=\"http://docs.python.org/2/glossary.html#term-eafp\" rel=\"nofollow\">glossary</a>). Option 2 is the preferred style.</p>\n\n<p>I don't like Option 1 since the intent isn't clear. You are specifying a <em>default</em> argument only for the side effect of it preventing <code>KeyError</code> from being raised, but the argument itself has nothing to do with your intent (<code>None</code> could be substituted with anything, in fact). However it is most likely the fastest option, since it's implemented in native code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:58:18.583", "Id": "65239", "Score": "0", "body": "+1. Nice reminder re: EAFP v LBYL, which I certain agree with, but I wonder if that's taking the principle too far in such a localized case. Option 3 just seems slightly more... clear in terms of basic code reading and communication of intent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:21:33.350", "Id": "65241", "Score": "0", "body": "@Ghopper21 I think they are both as clear, because seeing \"KeyError\" in the context of that statement communicates the same information as the `if`. It also communicates that you *assume* the key exists, while an `if` is neutral." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:57:06.647", "Id": "65254", "Score": "0", "body": "Good point about assumption. In the specific case which caused me to ask this quesiton, I'm generally assuming it's NOT there, which is why I may explain my (current) instinctive preference for Option 3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:58:19.293", "Id": "65255", "Score": "0", "body": "Btw, yes, the fact that `None` could be anything in Option 1 is what gave me pause as I was writing that in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:23:00.283", "Id": "65266", "Score": "1", "body": "If performance matters, I suspect that in Option 2, creating the exception to be caught would incur some overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:55:39.193", "Id": "65269", "Score": "0", "body": "@200_success Yes, but of course that's only if there is one to be caught. So for performance you need to consider which case is more likely. If the exception will only be raised a few times per several iterations, allowing it to happen will save more time overall than checking on each iteration." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:49:04.553", "Id": "39002", "ParentId": "38976", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T06:32:24.837", "Id": "38976", "Score": "1", "Tags": [ "python" ], "Title": "In Python, stylistically better way to remove a potentially nonexistent key from a dictionary?" }
38976
<p>This is my first shot at implementing a fully static version of the <code>Observer</code> pattern in C++11. It is static in that all notifications are dispatched via CRTP, and therefore there is no virtual overhead. It also has the benefit of catching unimplemented notifications at compile time, by checking available overloads based on the <code>Subject</code> type. Its primary restriction is that all relevant observers must be known at compile time.</p> <p>The motivation is to use this on an embedded system to help decouple systems while additionally providing better type safety. It appears that the initial output of this is exactly how I want it (zero cost) and the restriction of needing to know all observers in advance is reasonable given that the systems are well defined, and typically not dynamic. The platforms I work with typically do not allow <code>malloc</code>/<code>new</code> due to their ability to fail.</p> <pre><code>// static_observer header file #include &lt;utility&gt; #include &lt;tuple&gt; enum class EventType; // CRTP Abstract Base class for implementing static subject. // Example Subclass Usage -- Printing Observer: // class Printer : public Observer&lt;Printer&gt; { // public: // Printer() : timesTriggered_(0) {} // template &lt;typename... Args&gt; // void OnNotify(Pressure&lt;Args...&gt; &amp;subject, EventType event) { // std::cout &lt;&lt; "Observer ID: " &lt;&lt; this-&gt;GetID() &lt;&lt; std::endl; // switch (event) { // case EventType::UNKNOWN: { // std::cout &lt;&lt; "Unknown Event -- Event #" &lt;&lt; timesTriggered_++ // &lt;&lt; std::endl; // std::cout &lt;&lt; "Pressure: " &lt;&lt; subject.GetPressure() &lt;&lt; std::endl; // break; // } // default: { break; } // } // } // // private: // int timesTriggered_; // }; // Note: All Observers must implement OnNotify for any subject types they wish to observe // Any unimplemented subject types that are used will result in a compiler error template &lt;typename Base&gt; class Observer { public: Observer() : obsID_(obsIDTracker_++) {} template &lt;typename T&gt; void OnNotifyImpl(T &amp;subject, EventType event) { static_cast&lt;Base *&gt;(this)-&gt;OnNotify(subject, event); } int GetID() const { return obsID_; } private: int obsID_; static int obsIDTracker_; }; template &lt;typename base&gt; int Observer&lt;base&gt;::obsIDTracker_ = 0; // Recursive helper structs for implementing calls to all observers held within subjects template &lt;int N, typename T, typename... Args&gt; struct NotifyHelper { static void NotifyImpl(T &amp;subject, EventType event, std::tuple&lt;Args...&gt; &amp;obs) { std::get&lt;sizeof...(Args) - N&gt;(obs).OnNotifyImpl(subject, event); NotifyHelper&lt;N - 1, T, Args...&gt;::NotifyImpl(subject, event, obs); } }; template &lt;typename T, typename... Args&gt; struct NotifyHelper&lt;0, T, Args...&gt; { static void NotifyImpl(T &amp;subject, EventType event, std::tuple&lt;Args...&gt; &amp;obs) {} }; // CRTP Abstract Base class for implementing static subject. // Example Subclass Usage -- Pressure Sensor: // template &lt;typename... Obs&gt; // class Pressure : public Subject&lt;Pressure&lt;Obs...&gt;, Obs...&gt; { // public: // typedef Subject&lt;Pressure&lt;Obs...&gt;, Obs...&gt; BaseType; // Pressure(std::tuple&lt;Obs &amp;...&gt; &amp;&amp;observers, int pressure) // : BaseType(std::move(observers)), pressure_(pressure) {} // void Change(int value) { // pressure_ = value; // this-&gt;NotifyAll(EventType::UNKNOWN); // } // int GetPressure() const { return pressure_; } // // private: // int pressure_; // }; // See MakeSubject function for instance usage template &lt;typename T, typename... Obs&gt; class Subject { public: static const int NumberOfObservers = sizeof...(Obs); Subject(std::tuple&lt;Obs &amp;...&gt; &amp;&amp;obs) : observers(obs) {} void NotifyAll(EventType event) { NotifyHelper&lt;NumberOfObservers, T, Obs &amp;...&gt;::NotifyImpl( *static_cast&lt;T *&gt;(this), event, observers); } private: std::tuple&lt;Obs &amp;...&gt; observers; }; // Binding function for use with MakeSubject // Arguments: observer objects to observe subject notifications // Return: tuple of references to observers template &lt;typename... Obs&gt; std::tuple&lt;Obs &amp;...&gt; BindObservers(Obs &amp;... obs) { return std::tuple&lt;Obs &amp;...&gt;(obs...); } // Creator to ease subject creation // Template Arguments: Subject subclass type // Arguments: Result from BindObservers // Any constructor arguments for Subject subclass // Return: Subject subclass // Example Usage: // auto pressure = MakeSubject&lt;Pressure&gt;(BindObservers(printerObs), initialPressure); template &lt;template &lt;typename...&gt; class T, typename... Args, typename... Obs&gt; T&lt;Obs...&gt; MakeSubject(std::tuple&lt;Obs &amp;...&gt; &amp;&amp;obs, Args &amp;&amp;... args) { return T&lt;Obs...&gt;(std::move(obs), args...); } </code></pre> <p>Example using the subclasses in the commented examples:</p> <pre><code>int main() { Printer printerObs1; Printer printerObs2; const int initialPressure = 1; auto pressure = MakeSubject&lt;Pressure&gt;( BindObservers(printerObs1, printerObs2), initialPressure); pressure.Change(12); } </code></pre> <p>Output:</p> <pre><code>Observer ID: 0 Unknown Event -- Event #0 Pressure: 12 Observer ID: 1 Unknown Event -- Event #0 Pressure: 12 </code></pre> <p>In addition to general critique, I also have a couple specific concerns/questions:</p> <ul> <li><p>While the observers will typically be statically stored, there is nothing preventing a programmer from creating an observer in automatic storage then storing a reference to it in a subject that is retained past its destruction. I don't know if there's an easy way to prevent this, but it's a potential issue.</p></li> <li><p>In the <code>Subject</code> super class, I needed to do a cast: <code>*static_cast&lt;T *&gt;(this)</code> as opposed to casting <code>*this</code> to type <code>T</code> (where <code>T</code> is the subclass type.) This allows the <code>Observer</code> to overload based on <code>T</code>, but I'm worried it might not be safe in some scenarios. Is this valid?</p></li> <li><p>I dislike the verbosity required for creating a <code>Subject</code> subclass. Needing to type out the parameter pack so many times seems like it could be hard to work with, but with a good example maybe its okay?</p></li> <li><p>The <code>MakeSubject</code> function seems a little verbose too. Same as above -- is it an okay style if it's simply well-documented?</p></li> </ul>
[]
[ { "body": "<p>Personally (so you can take or leave this advice as this is just a personal pref) I find your style over compact and thus harder than necessary to read:</p>\n\n<pre><code>template &lt;typename Base&gt; class Observer {\n\n// I split this across two lines:\ntemplate &lt;typename Base&gt;\nclass Observer {\n</code></pre>\n\n<p>Also:</p>\n\n<pre><code>class Observer {\npublic:\n Observer() : obsID_(obsIDTracker_++) {}\n template &lt;typename T&gt; void OnNotifyImpl(T &amp;subject, EventType event) {\n static_cast&lt;Base *&gt;(this)-&gt;OnNotify(subject, event);\n }\n int GetID() const { return obsID_; }\nprivate:\n\n// Everything is so squashed to the left:\n// Bit more space to help readability never heart (and the compiler don't care).\n\ntemplate &lt;typename Base&gt;\nclass Observer\n{\n public:\n Observer()\n : obsID_(obsIDTracker_++)\n {}\n\n template &lt;typename T&gt;\n void OnNotifyImpl(T &amp;subject, EventType event)\n {\n static_cast&lt;Base *&gt;(this)-&gt;OnNotify(subject, event);\n }\n\n // I would still do this all in one line.\n int GetID() const { return obsID_; }\n\n private:\n int obsID_;\n static int obsIDTracker_;\n};\n</code></pre>\n\n<p>This line confused me for a while:</p>\n\n<pre><code>Subject(std::tuple&lt;Obs &amp;...&gt; &amp;&amp;obs) : observers(obs) {}\n // ^^ rvalue reference ^^^ no move\n</code></pre>\n\n<p>You are giving the option to pass by r-value reference this implying you are going to rip the guts out of the object. But you are actually just making a copy into <code>observers</code>. A cheap copy as the tuple only contains references. But I think the interface is better if you pass by const reference to more accurately reflect the usage semantics better.</p>\n\n<pre><code>Subject(std::tuple&lt;Obs &amp;...&gt; const&amp; obs) : observers(obs) {}\n</code></pre>\n\n<p>OK found why you have r-value references:</p>\n\n<pre><code>template &lt;template &lt;typename...&gt; class T, typename... Args, typename... Obs&gt;\nT&lt;Obs...&gt; MakeSubject(std::tuple&lt;Obs &amp;...&gt; &amp;&amp;obs, Args &amp;&amp;... args) {\n return T&lt;Obs...&gt;(std::move(obs), args...);\n}\n</code></pre>\n\n<p>For the <code>Obs</code> is is unnecessary; as they are held in the tuple by reference. So <code>std::move()</code> here does not buy you much (apart from me scratching my head for 10 minutes :-)</p>\n\n<p>On the other hand <code>Args</code> it does seem correct to pass by r-value reference, but because you don't use <code>std::move</code> they are decaying into references when you pass them to the constructor (I could be wrong on this last point (still getting my head around this new fangled stuff).</p>\n\n<blockquote>\n <p>While the observers will typically be statically stored, there is nothing preventing a programmer from creating an observer in automatic storage then storing a reference to it in a subject that is retained past its destruction. I don't know if there's an easy way to prevent this, but it's a potential issue.</p>\n</blockquote>\n\n<p>If there is no <code>new</code> usage I can not contrive of a situation where this would happen. As the <code>Oberver</code> must be constructed before the <code>Subject</code> because you add add <code>Observers</code> during the <code>Subject</code> construction.</p>\n\n<p>Also I would argue that <code>typical usage</code> should be everything automatic not static.</p>\n\n<blockquote>\n <p>In the Subject super class, I needed to do a cast: *static_cast(this) as opposed to casting *this to type T (where T is the subclass type.) This allows the Observer to overload based on T, but I'm worried it might not be safe in some scenarios. Is this valid?</p>\n</blockquote>\n\n<p>This looks fine.</p>\n\n<blockquote>\n <p>I dislike the verbosity required for creating a Subject subclass. Needing to type out the parameter pack so many times seems like it could be hard to work with, but with a good example maybe its okay?</p>\n</blockquote>\n\n<p>You have done the hard work. So that the users of your lib don't need to worry about it. So I think you have hidden the details rather well. Its still verbose but with some good examples and an explanation you will be fine.</p>\n\n<blockquote>\n <p>The MakeSubject function seems a little verbose too. Same as above -- is it an okay style if it's simply well-documented?</p>\n</blockquote>\n\n<p>Same comment as above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T23:29:19.027", "Id": "65443", "Score": "0", "body": "Thank you very much for the comments! I appreciate them greatly. I agree on the whitespace, and will adopt some of your changes (need to stick to LLVM-style for policy reasons.) \n\nI'm still trying to wrap my head around best practices for r-value references, so I greatly appreciate your help there. Is there a simple way to pass the `Args` pack by `std::move`?\n\nThanks again Loki! I was starting to worry no one would reply. (Accepted)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T23:39:57.820", "Id": "65446", "Score": "0", "body": "Nevermind -- figured out the `Args` pack: `std::move<Args>(args)...`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T18:35:12.357", "Id": "39095", "ParentId": "38980", "Score": "3" } } ]
{ "AcceptedAnswerId": "39095", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T07:14:39.227", "Id": "38980", "Score": "4", "Tags": [ "c++", "c++11" ], "Title": "Static Observer Pattern in C++11" }
38980
<p>Assume the following requirements:</p> <p><img src="https://i.stack.imgur.com/DzZNJ.png" alt="enter image description here"></p> <p>Is it a good idea to use the Composite design-pattern for this, taking into account that there will be:</p> <ul> <li>Only 1 <code>TestPlan</code></li> <li>a <code>TestPlan</code> can only have <code>TestSequence</code>s</li> <li>a <code>TestSequence</code> can only have <code>Test</code>s</li> <li>a <code>Test</code> can only have <code>Assert</code>s</li> </ul> <p>I've started coding using the <em>Composite pattern</em> but I got the feeling that this pattern cannot enforce the above rules. Is my feeling correct and should I use another design (pattern) here? Or is using the composite pattern here correct but is my implementation of it just wrong? </p> <pre><code>public abstract class TestElement { public TestElement(int id) { this.Id = id; } public virtual void Add(TestElement element) { throw new NotImplementedException(); } public virtual void Remove(TestElement element) { throw new NotImplementedException(); } public virtual IEnumerable&lt;TestElement&gt; GetElements() { throw new NotImplementedException(); } public virtual TestElement GetElement(int index) { throw new NotImplementedException(); } public string Id { get; private set; } public abstract void Setup(); public abstract void Teardown(); } public class TestPlan : TestElement { // Here TestElement should only be of type TestSequence private IList&lt;TestElement&gt; Children = new List&lt;TestElement&gt;(); public TestPlan(int id) : base(id) { } public override void Add(TestElement element) { this.Children.Add(element); } public override void Remove(TestElement element) { this.Children.Remove(element); } public override TestElement GetElement(int index) { return this.Children.ElementAt(index); } public override IEnumerable&lt;TestElement&gt; GetElements() { return this.Children; } public override void Setup() { Console.WriteLine("Setup executed for TestPlan " + Id); } public override void Teardown() { Console.WriteLine("Teardown executed for TestPlan " + Id); } } public class TestSequence : TestElement { // Here TestElement should only be of type Test private IList&lt;TestElement&gt; Children = new List&lt;TestElement&gt;(); public TestSequence(int id) : base(id) { } public override void Add(TestElement element) { this.Children.Add(element); } public override void Remove(TestElement element) { this.Children.Remove(element); } public override TestElement GetElement(int index) { return this.Children.ElementAt(index); } public override IEnumerable&lt;TestElement&gt; GetElements() { return this.Children; } public override void Setup() { Console.WriteLine("Setup executed for TestSequence " + Id); } public override void Teardown() { Console.WriteLine("Teardown executed for TestSequence " + Id); } } public class Test : TestElement { // Here TestElement should only be of type Assert private IList&lt;TestElement&gt; Children = new List&lt;TestElement&gt;(); public Test(int id) : base(id) { } public override void Add(TestElement element) { this.Children.Add(element); } public override void Remove(TestElement element) { this.Children.Remove(element); } public override TestElement GetElement(int index) { return this.Children.ElementAt(index); } public override IEnumerable&lt;TestElement&gt; GetElements() { return this.Children; } public override void Setup() { Console.WriteLine("Setup executed for Test " + Id); } public override void Teardown() { Console.WriteLine("Teardown executed for Test " + Id); } } public class Assert : TestElement { public Assert(int id) : base(id) { } public override void Setup() { throw new NotSupportedException("No setup with Assert."); } public override void Teardown() { throw new NotSupportedException("No teradown with Assert."); } public bool ExecuteAssert() { return true; } </code></pre> <p>}</p>
[]
[ { "body": "<p>I don't think this is an example of composite pattern. Composite is defined as</p>\n\n<blockquote>\n <p>The Composite Pattern allows you to compose objects into tree\n structures to represent part-whole hierarchies. Composite lets clients\n treat individual objects and compositions of objects uniformly.</p>\n</blockquote>\n\n<p>Main idea of Composite is to allow treating whole (several parts) as a individual part. I.e. when client asks Composite to do something, then it means that Composite will ask all it's Components to do same thing. But neither <code>Setup</code> nor <code>Teardown</code> methods of your Composite do not touch collection of <code>TestElements</code>. So, you simply have set of classes with some base class, but that is not Composite.</p>\n\n<p>If you would like to treat <code>TestSequence</code> or <code>TestPlan</code> as a single <code>Test</code> then it would be a Composite. I.e. if you would add <code>Run</code> functionality to your base class (or interface)</p>\n\n<pre><code>public interface ITest\n{\n void Run();\n}\n</code></pre>\n\n<p>and <code>TestSequence</code> would run all it's tests:</p>\n\n<pre><code>public class TestSequence : ITest\n{\n private IList&lt;ITest&gt; tests = new List&lt;ITest&gt;();\n\n public void Run()\n {\n Setup();\n foreach(var test in tests)\n test.Run();\n Teardown();\n }\n\n public void Setup()\n {\n Console.WriteLine(\"Setup executed for Test \" + Id);\n }\n\n public void Teardown()\n {\n Console.WriteLine(\"Teardown executed for Test \" + Id);\n }\n}\n</code></pre>\n\n<p>Then <code>TestSequence</code> would be a <code>Composite</code>, because it's completely transparent for client whether it works with single part (<code>Test</code>) or with a whole (<code>TestSequence</code>, collection of <code>Tests</code>). Same with <code>TestPlan</code> - you can treat it as a single <code>TestSequence</code>. Thus you can treat <code>TestSequence</code> as single <code>Test</code>, then for client <code>TestPlan</code> can also be treated as single <code>Test</code>. Client can run <code>TestPlan</code>, and it will run all it's test sequences, which in their turn will run all tests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:49:58.013", "Id": "65200", "Score": "0", "body": "This makes sence. One more question though: is there a way to enforce that `TestPlan`can only contain `TestSequence`as child (and so on)? Or is that something I can take care of in my Builder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T10:13:49.103", "Id": "65202", "Score": "0", "body": "@Koen yes, you can. All client should know about `TestPlan` or `TestSequence` is that it is runnable. You can create base class `CompositeTest` which will provide collection for storing child tests and method `Run()` which runs all children (as above). In that case restriction of children types goes to builder and interface of composite (e.g. `TestPlan` can have only method `Add (TestSequence sequence)`. If you don't need base composite class, then each composite can hold collection of specific children (i.e. `TestSequece` list for `TestPlan`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T10:32:37.853", "Id": "65203", "Score": "0", "body": "Ok. Thx for the info." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T08:42:34.913", "Id": "38983", "ParentId": "38981", "Score": "4" } } ]
{ "AcceptedAnswerId": "38983", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T08:05:41.240", "Id": "38981", "Score": "4", "Tags": [ "c#", "object-oriented", "design-patterns" ], "Title": "Use of the composite pattern" }
38981
A lambda is an expression that acts as an anonymous function. Use this tag if you would like to discuss the appropriateness of a lambda or anonymous function in your code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:37:47.623", "Id": "38987", "Score": "0", "Tags": null, "Title": null }
38987
<p><strong>Introduction</strong></p> <p>I have a hierarchically nested tree class (like <code>SampleFolder</code>, s.b.) that I want to serialize. </p> <p>The problem arises with the collection of sub items like this one:</p> <pre><code>List&lt;SampleFolder&gt; subFolders; </code></pre> <p><strong>I do not want to load the entire tree but only one folder at a time, when I deserialize!</strong> So instead of creating a list of the actual objects I need to use IDs. Naturally I am using a primitive based data type for reduced overhead: </p> <pre><code>List&lt;Double&gt; subFolders; </code></pre> <p>All good with serialization here. But in a more complex project handling all those <code>Double</code>-IDs, esp. within maps starts to become very confusing during development. As the project increases in complexity it happens that I would hand the wrong ID to a collection. </p> <pre><code>Map&lt;Double, List&lt;Double&gt;&gt; myAssociations; // what? which id goes where? </code></pre> <p>So to battle this issue of lost-type safety I created an interface <code>Item</code> and inner class <code>Id</code> (s.b.). This is the resulting usage (more in-depth example see <code>SampleFolder</code>, below):</p> <pre><code>Map&lt;Id&lt;Car&gt;, List&lt;Id&lt;Wheel&gt;&gt;&gt; myAssociations; // a lot more readable, isn't it? </code></pre> <hr> <p><strong>Question</strong></p> <p>I couldn't find a best-practice for this issue, so if there is a better way to solve this "type-safety" issue please let me know. Even though this seems to work, I am wondering if this is good code in respect to the use of <em>generics</em> and if the implementation of <code>hashCode()</code> and <code>equals()</code> is correct. I am open for optimization suggestions and other critics. </p> <p><strong>code to review: <code>Item</code> with <code>Id</code></strong> </p> <pre><code>interface Item { double getId(); class Id&lt;T extends Item&gt; implements Serializable { private double id; public Id(T item) { this.id = item.getId(); } public Id(double id) { this.id = id; } public double asDouble() { return id; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Id)) { return false; } Id&lt;?&gt; cast = (Id&lt;?&gt;) obj; return id == cast.id; } @Override public int hashCode() { return Double.valueOf(id).hashCode(); } public static &lt;E extends Item&gt; Id&lt;E&gt; from(double id) { return new Id&lt;E&gt;(id); } public static &lt;E extends Item&gt; Id&lt;E&gt; from(E enumItem) { return new Id&lt;E&gt;(enumItem); } @Override public String toString() { return String.valueOf(id); } } } </code></pre> <hr> <p>Sample usage (class not part of the actual project; for illustration purposes only):</p> <pre><code>public class SampleFolder implements Item, Serializable { private final double id; private List&lt;Id&lt;SampleFolder&gt;&gt; subFolders; private List&lt;Id&lt;MoreItem&gt;&gt; moreItems; private List&lt;Id&lt;EvenMoreItem&gt;&gt; evenMoreItems; public SampleFolder() { id = new Date().getTime(); subFolders = new ArrayList&lt;&gt;(); } public SampleFolder(double id, List&lt;Id&lt;SampleFolder&gt;&gt; subFolders) { this.id = id; this.subFolders = subFolders; } @Override public double getId() { return id; } public List&lt;Id&lt;SampleFolder&gt;&gt; getSubFolders() { return subFolders; } public void setSubFolders(List&lt;Id&lt;SampleFolder&gt;&gt; subFolders) { this.subFolders = subFolders; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:24:45.597", "Id": "65211", "Score": "1", "body": "Is this *working code*? Primitive types like `double` cannot be used as type parameters. Also double is not suitable for equals check and thus for being used neither as IDs nor as map keys. `double id = new Date().getTime()`: ???." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:36:11.770", "Id": "65212", "Score": "1", "body": "Here is what's wrong with using `double`s as IDs even if you *do not tamper with them*: `long l = Long.MAX_VALUE;`\n`double d1 = l;`\n`double d2 = l - 1;`\n`boolean wot = d1 == d2;`\n`System.out.println(wot);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T16:45:02.773", "Id": "65263", "Score": "0", "body": "@abuzittingillifirca Yes, the relevant code section compiles and seems to be working. The code fragments in the introduction are probably not. I mixed up `Double` and `double`." } ]
[ { "body": "<p>Do not use floating point numbers as IDs! Floating point is a horrible minefield of gotchas out there to sabotage your program in subtle ways: Losing precision, imprecise equality, NaNs, …. Using a <code>double</code> only defers, but not solves these issues.</p>\n\n<p>For IDs, always use an integral type like <code>long</code>.</p>\n\n<p>Now you've found a sufficiently elegant solution to represent typesafe IDs by using generics. There are a few other possibilities you might want to consider:</p>\n\n<ul>\n<li><p>Lazy self-loading classes. Each instance has a boolean field <code>initialized</code> which defaults to false. In each public method you put in a <code>if (!initialized) this.initialize()</code> test to load the other fields – but only when they are needed.</p>\n\n<p><a href=\"http://ideone.com/rjfvJ7\" rel=\"nofollow\">Usage example</a>:</p>\n\n<pre><code>class LazyThing {\n private boolean initialized = false;\n ... // state that is loaded lazily\n\n private void initialize() {\n ... // initialization code\n initialized = true;\n }\n\n public void frobnicate() {\n if (! initialized) initialize();\n ...\n }\n}\n</code></pre>\n\n<p>The advantage here is that this pattern is completely invisible to the user.</p></li>\n<li><p>A <code>Deferred&lt;T&gt;</code> wrapper which is basically a “promise” or “future” (or any other single-element monad-like container of your choice). A deferral wrapper represents an object that may or may not be fully loaded. You can <code>get()</code> the element to force loading. This is a bit more awkward to use but properly separates the lazy loading from the wrapped type. The full interface might look like:</p>\n\n<pre><code>abstract class Deferred&lt;T&gt; {\n boolean initialized = false;\n T instance;\n\n abstract T initialize(); // sadly, Java does not have traits\n\n public T get() {\n if (! initialized) {\n instance = initialize();\n initialized = true;\n }\n return instance;\n }\n}\n</code></pre>\n\n<p><a href=\"http://ideone.com/jJ6ejs\" rel=\"nofollow\">Usage example</a>:</p>\n\n<pre><code>Deferred&lt;Thing&gt; foo = new Deferred&lt;Thing&gt;() {\n private long id;\n\n // anon classes can't have constructors :(\n Deferred&lt;Thing&gt; init(long id) {\n this.id = id;\n return this;\n }\n\n @Override\n Thing initialize() {\n ... // code to load the instance\n }\n}.init(1234);\n\nfoo.get().frobnicate();\n</code></pre>\n\n<p>This scheme is extremely flexible because it does not assume the existence or type of an ID.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:37:32.123", "Id": "65205", "Score": "0", "body": "The switch to long is a reasonable change since I am using `new Date().getTime()` to generate the id. But I do not really see those double related problems, as they would imho only occur if the double was tampered with. In this context I see it as an immutable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:41:05.397", "Id": "65207", "Score": "0", "body": "The lazing loading is exactly what I need next. But I will probably go with the Future since I don't want the UI thread to possibly lockup because there is hidden lazy loading going on. Great examples - I never really understood Future. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:46:17.937", "Id": "65208", "Score": "1", "body": "(1) `new Date().getTime()` is a concurrency bug when you want to use that as an ID. You might want to use a synchronized factory instead. (2) My `Deferred<T>` is not a future, but it's quite similar. A Future adds ways to compose operations on the contained value, and has ways to manage failures." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T10:50:37.237", "Id": "38989", "ParentId": "38988", "Score": "4" } }, { "body": "<p>Why don't you just use a GUID for an ID? It will serialize, and is (functionally) unique. You don't have the concurrency issue as with this date thing you're doing. The int or long will work but I think sooner or later you'll have a collision there too. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:33:23.510", "Id": "65267", "Score": "0", "body": "Do yo mean [UUID](http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html)? Anyway, good point had me looking at [Java Practices -> Generating unique IDs](http://www.javapractices.com/topic/TopicAction.do?Id=56)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:43:57.167", "Id": "65268", "Score": "0", "body": "You know? It's funny. I am a c# developer. I didn't even get the hint that your code was Java. Yes, UUID in java speak. http://en.wikipedia.org/wiki/Globally_unique_identifier" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:03:07.323", "Id": "39014", "ParentId": "38988", "Score": "2" } }, { "body": "<p>A better way to solve the type safety issue is to use the <a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"nofollow\"><strong>proxy pattern</strong></a>. You basically make a proxy, implementing the interface <code>Car</code> or <code>Wheel</code>, which is actually just a wrapper around the id. When a method is called on the proxy that needs the actual object, it can then load the object itself, and from then on simply delegate all method calls to the actual object.</p>\n\n<p>As others have already pointed out, <code>double</code> is a horrible choice of type for an id.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T18:20:07.910", "Id": "110326", "Score": "0", "body": "I really like this approach and will probably start using this instead as it simplifies usage of the API by making the implementation transparent to the user." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T07:56:26.783", "Id": "39126", "ParentId": "38988", "Score": "2" } } ]
{ "AcceptedAnswerId": "38989", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:46:26.977", "Id": "38988", "Score": "3", "Tags": [ "java", "generics", "collections", "serialization" ], "Title": "Forcing type-safe IDs for use with Collections and Maps" }
38988
<p>In a sorted array, I am trying to find pairs that sum up to a certain value. I was wondering if anyone could help me improve my code in performance or memory. I believe my code is O(n). If there are other method for finding pairs the sum up to a certain value that is much more efficient, I am open to these methods!</p> <pre><code>static int[] intArray = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; public static ArrayList&lt;String&gt; pairSum(int[] j, int sum) { int len = j.length; int pointer1; int pointer2; ArrayList&lt;String&gt; storage = new ArrayList&lt;String&gt;(); for (int i = 0; i &lt; len; i++) { pointer1 = j[i]; for (int k = len - 1; k &gt;= 0; k--) { pointer2 = j[k]; if (pointer1 + pointer2 == sum &amp;&amp; pointer1 != pointer2) { i++; String pair = Integer.toString(pointer1) + " and " + Integer.toString(pointer2) ; storage.add(pair); } } } return storage; } </code></pre> <p>If I ran this code, say <code>pairSum(intArray,16)</code>, I would get:</p> <pre><code>[0 and 16, 2 and 14, 4 and 12, 6 and 10, 9 and 7, 11 and 5, 13 and 3, 15 and 1] </code></pre> <p>If I remove the <code>i++</code>, the output would be:</p> <pre><code>[0 and 16, 1 and 15, 2 and 14, 3 and 13, 4 and 12, 5 and 11, 6 and 10, 7 and 9, 9 and 7, 10 and 6, 11 and 5, 12 and 4, 13 and 3, 14 and 2, 15 and 1, 16 and 0] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:22:40.213", "Id": "65221", "Score": "0", "body": "The `i++;` produces the wrong result. I'd recommend you remove it from your question, since the code under review out to run and produce correct results. Why is it there?" } ]
[ { "body": "<h1>Code improvements</h1>\n\n<p>Before addressing efficiency, let's see if there are any improvements that could be made to the code.</p>\n\n<p>I suspect some of the names could be improved.</p>\n\n<ul>\n<li><code>pointer1</code> -> <code>value1</code></li>\n<li><code>pointer2</code> -> <code>value2</code></li>\n<li><code>j</code> -> <code>values</code></li>\n<li><code>storage</code> -> <code>value_pairs</code></li>\n<li><code>pairSum</code> -> <code>pairsThatAddUpToASum</code></li>\n</ul>\n\n<p>I would consider getting rid of this temporary:</p>\n\n<pre><code>int len = j.length;\n</code></pre>\n\n<p>as it's not carrying its weight. Using <code>j.length</code> inline is not burdensome, and the compiler/runtime are likely to produce adequately fast code without it.</p>\n\n<p>Lastly, I wonder about the decision to return the pairs as strings. This depends upon how the function is being used, but I would often rather return the pairs of numbers, and let the caller worry about formatting. This decouples the function from I/O.</p>\n\n<h1>A bug?</h1>\n\n<p>This term in the if:</p>\n\n<pre><code>pointer1 != pointer2\n</code></pre>\n\n<p>Might be a bug. If the list is guaranteed to contain no duplicates, it will work fine (but might be more communicative as <code>i != k</code>). If, however, the list may contain duplicates, and it is the intent of the code to return the resulting duplicate pairs, then this must be <code>i != k</code>.</p>\n\n<h1>Efficiency.</h1>\n\n<p>In order to be O(n), the algorithm must visit each element a constant number of times. We typically think of a O(n) algorithm as one that visits each element once. In this algorithm, both the outer and inner loop visit each element. That makes this an O(n^2) algorithm.</p>\n\n<p>A google search for \"efficiently finding pairs that add up to a sum\" finds, not surprisingly, several Stack Overflow questions. Here's one of them that may be useful to you: <a href=\"https://stackoverflow.com/questions/1494130/design-an-algorithm-to-find-all-pairs-of-integers-within-an-array-which-sum-to-a\">https://stackoverflow.com/questions/1494130/design-an-algorithm-to-find-all-pairs-of-integers-within-an-array-which-sum-to-a</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:54:17.967", "Id": "65228", "Score": "0", "body": "Thanks for this analysis! My code is O(n^2) didnt realize this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:55:03.050", "Id": "65229", "Score": "0", "body": "Make that `i != k`, as `j` currently refers to the array." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:36:19.740", "Id": "38996", "ParentId": "38994", "Score": "10" } }, { "body": "<p>EDIT: Please see update at end because there is an improved solution that is inspired by <a href=\"https://codereview.stackexchange.com/a/39380/31503\">Mike Chamberlain's answer</a>...</p>\n\n<p>There are two solutions which come to mind for your problem, but first, let's look through your code:</p>\n\n<ul>\n<li>you have the variables <code>pointer1</code> and <code>pointer2</code>. These are very descriptive names, which is great, but unfortunately they are not pointers. They are the <strong>values</strong> at the <code>i</code> and <code>k</code> positions in the array. In other words, <code>i</code> and <code>k</code> are the actual pointers. I would call <code>pointer1</code> and <code>pointer2</code> something like <code>val1</code> and <code>val2</code>. But, in fact, I would drop the pointers entirely, and just use an index in to the data (why copy the data when you don't need to....? )</li>\n<li>In most languages the variable name <code>i</code> is 'reserved' for indexed looping through data, just like you have <code>for (int i = 0; i &lt; len; i++) {...}</code>. It is <em>standard</em> to use <code>j</code> and <code>k</code> as the variable names for any inner/nested loops you need. <code>i</code> is the top level, <code>j</code> is the first nested level, <code>k</code> is the subsequent level, and, if you need more than that, you should be calling a function/method (<strong>Never</strong> use <code>l</code> as a variable name, it is too easy to confuse with <code>1</code>). You are breaking this <em>convention</em> by using <code>j</code> as an array, and going immediately to <code>k</code> inside your loop. My suggestion is to rename <code>j</code> to be <code>data</code>, and to rename <code>k</code> to be <code>j</code>. </li>\n<li>as a general rule, when you have a loop constrained by an index, like you have <code>for (int i = 0; i &lt; len; i++) { ...</code>, you should <strong>never</strong> modify the index inside the loop. I cannot think of a reason why it should ever be necessary, and, certainly, it should never be <strong>conditionally</strong> modified (inside an if-statement inside another loop). This will lead to bugs. In fact, the simple fact that you have that inner <code>i++</code> tells me you do not understand your own code's behaviour.</li>\n<li>Your method should return the interface type <code>List&lt;String&gt;</code> instead of the concrete class <code>ArrayList&lt;String&gt;</code> since there is no reason for outsiders to know the physical implementation.</li>\n<li><code>storage</code> is not a great name for a variable.... <strong>everything</strong> could be called <code>storage</code> since all variables store things... I would choose something like: <code>results</code>.</li>\n<li>Your inner <code>if</code> condition makes sure that the sums are a match, but also checks <code>pointer1 != pointer2</code>. This second check is a problem, because it should not be testing the <strong>values</strong>, but the <strong>indexes</strong>.... For example what if the data is <code>[4,4]</code> and the target sum is <code>8</code>?</li>\n<li>To get your result pair as a String you do: <code>String pair = Integer.toString(pointer1) + \" and \" + Integer.toString(pointer2)</code>.... this is serious overkill, try this instead: <code>String pair = pointer1 + \" and \" + pointer2</code>. In Java the <code>+</code> String operator will implicitly convert the integers to a String... no need to do it yourself.</li>\n</ul>\n\n<p>So, you have some style problems, and some concerns about your inner workings.</p>\n\n<p>Now, let's talk about your algorithm..... It loops through each value. For each value, it then compares it against every other value (except itself). So, you loop <code>n</code> times, and, for each <code>n</code> you do <code>m</code> checks. Your complexity is <em>O(n x m)</em>, but, in reality, <code>n</code> and <code>m</code> are the same, so your complexity is <em>O(n<sup>2</sup>)</em></p>\n\n<p>Now, about that <code>i++</code> inside the <code>k</code> loop.... the reason you need it is because your <code>k</code> loop is starting from the wrong place. your algorithm is wrong. Let me explain.</p>\n\n<p>If you have the data <code>[ 0, 1, 2, 3, 4, 5 ]</code> , you are using your <code>i</code> index to loop through all the data. Your first data will be <code>0</code>. You sum this with <code>5</code> (<strong>Note, you have summed <code>0 + 5</code> now</strong>), and check the result, then with <code>4</code>, and so on. When you are done, you move <code>i</code> to the value <code>1</code>, and you keep moving <code>i</code> until you get to the value <code>5</code> for <code>i</code>. You then compare **this value <code>5</code> to all the other values, including <code>0</code>. This is **the second time you sum the items <code>0 + 5</code> (but it is now <code>5 + 0</code>) **.</p>\n\n<p>You need to change the algorithm to only scan those values that have not yet been scanned. The easiest way to do this is to modify your inner/nested loop. Consider <strong>your</strong> code:</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i &lt; len; i++) {\n ...\n for (int k = len - 1; k &gt;= 0; k--) {\n ...\n</code></pre>\n</blockquote>\n\n<p>Now, we change the inner loop as follows:</p>\n\n<pre><code>for (int i = 0; i &lt; len; i++) {\n ....\n for (int j = i + 1; j &lt; len; j++) {\n</code></pre>\n\n<p>(note, I have renamed <code>k</code> to be <code>j</code>). We start our <code>j</code> index at <code>i + 1</code>, because we don't need to sum values before <code>i</code> since that sum was done already when <code>i</code> was smaller.....</p>\n\n<p>Now, our loops only calculate the <code>sum</code> value once for each pair of values.</p>\n\n<p>Unfortunately, our complexity is still <em>O(n<sup>2</sup>)</em> because even though our inner loop is only testing half (on average) the values, we have not actually changed the way the algorithm scales (if you double the input data, you with quadruple the execution time).</p>\n\n<p>Still, even with this algorithm change, and some variable renaming, and some bug fixing, your code will look like:</p>\n\n<pre><code>public static List&lt;String&gt; pairSum(int[] data, int sum) {\n int len = data.length;\n int val1;\n int val2;\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n for (int i = 0; i &lt; len; i++) {\n val1 = data[i];\n for (int j = i + 1; j &lt; len; j++) {\n val2 = data[j];\n if (val1 + val2 == sum) {\n String pair = val1 + \" and \" + val2;\n results.add(pair);\n }\n }\n }\n return results;\n}\n</code></pre>\n\n<p>This is <em>OK</em>, but my preference would be to strip all the <code>val1</code> variables entirely, and you can simplify some other things too. Consider the following more 'compact' code:</p>\n\n<pre><code>public static List&lt;String&gt; pairSum(int[] data, int sum) {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n for (int i = 0; i &lt; data.length; i++) {\n for (int j = i + 1; j &lt; data.length; j++) {\n if (data[i] + data[j] == sum) {\n results.add(data[i] + \" and \" + data[j]);\n }\n }\n }\n\n return results;\n}\n</code></pre>\n\n<p>That is what I would recommend for a simple, easy-to-read option that is <em>O(n<sup>2</sup>)</em>. For small data sets (say less than 50 or so), this solution will be great.</p>\n\n<p>But, if you have more data, a better solution would be more complicated, but faster.</p>\n\n<p>In your example code, you have an input test array that is all positive, sorted, and the values are unique. Let's assume that all the data will be this way (we can modify this assumption later).</p>\n\n<p>Consider the algorithm that does:</p>\n\n<pre><code>take all values that are less than half the target `sum`.\nfind a value that is the difference\n</code></pre>\n\n<p>It would look like:</p>\n\n<pre><code>public static List&lt;String&gt; pairSumFast(int[] data, int sum) {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n int limit = sum / 2;\n for (int i = 0; i &lt; data.length &amp;&amp; data[i] &lt;= limit; i++) {\n int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);\n if (match &gt;= 0) {\n results.add(data[i] + \" and \" + data[match]);\n }\n }\n\n return results;\n}\n</code></pre>\n\n<p>This has the complexity of <em>O( nlog(n) )</em> for the loop, and the binary-search respectively.</p>\n\n<p>If your data set is large, and the values are unique, but the data is unsorted, then I would recommend the change:</p>\n\n<pre><code>public static List&lt;String&gt; pairSumFast(int[] indata, int sum) {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n int[] data = Arrays.copyOf(indata, indata.length);\n Arrays.sort(data);\n\n int limit = sum / 2;\n for (int i = 0; i &lt; data.length &amp;&amp; data[i] &lt;= limit; i++) {\n int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);\n if (match &gt;= 0) {\n results.add(data[i] + \" and \" + data[match]);\n }\n }\n\n return results;\n}\n</code></pre>\n\n<p>This is <em>O(n log(n) )</em> for the complexity still... (it scales this way, even through it does more computation....)</p>\n\n<p>Finally, if the data is not unique, then you will get duplicate output values. To accommodate that, I would add an inner loop to the match....:</p>\n\n<pre><code>public static List&lt;String&gt; pairSumFast(int[] data, int sum) {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n int limit = sum / 2;\n for (int i = 0; i &lt; data.length &amp;&amp; data[i] &lt;= limit; i++) {\n int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);\n if (match &gt;= 0) {\n String pair = data[i] + \" and \" + data[match];\n results.add(pair);\n // binary search will return the index of one match, look around to find others.\n int more = match - 1;\n while (more &gt;=0 &amp;&amp; data[more] == data[match]) {\n results.add(pair);\n more--;\n }\n more = match + 1;\n while (more &lt; data.length &amp;&amp; data[more] == data[match]) {\n results.add(pair);\n more++;\n }\n }\n }\n\n return results;\n}\n</code></pre>\n\n<h2>EDIT: A better solution...</h2>\n\n<p><a href=\"https://codereview.stackexchange.com/a/39380/31503\">Mike Chamberlain suggests</a> using a Map to preserve the values you have seen in order to match the pairs in a single <em>O(n)</em> iteration of the list.</p>\n\n<p>This single-iteration made me realize that there is a much simpler solution to this problem... iterate from both sides of the data.... consider the following:</p>\n\n<pre><code>public static List&lt;String&gt; pairSumFastest(int[] data, int sum) {\n ArrayList&lt;String&gt; results = new ArrayList&lt;String&gt;();\n\n int low = 0;\n int high = data.length - 1;\n while (low &lt; high) {\n while (low &lt; high &amp;&amp; data[low] + data[high] &lt; sum) {\n low++;\n }\n while (low &lt; high &amp;&amp; data[low] + data[high] &gt; sum) {\n high--;\n }\n if (low &lt; high) {\n results.add( data[low] + \" and \" + data[high]);\n low++;\n high--;\n }\n }\n\n return results;\n}\n</code></pre>\n\n<p>This has true <em>O(n)</em> complexity, and has no memory overhead either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:08:16.907", "Id": "65232", "Score": "0", "body": "Much more comprehensive than my answer. I hope the OP gives this one the checkmark." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:10:25.813", "Id": "65233", "Score": "0", "body": "Yes thank you so much for taking the time to write this ! I really appreciate it! I learn a lot!! @WayneConrad thank you for your answer as well!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:10:40.157", "Id": "65234", "Score": "0", "body": "Thanks! I was 2-thirds through the answer when I saw your's pop up .... and I figured I covered things you had not, so I posted.... That's why there's a lot of duplication between our answers, sorry ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:16:46.990", "Id": "65236", "Score": "0", "body": "@rolfi, One of the things I like about codereview is that the fastest gun doesn't always win. I've been out of the Java game for a _long_ time, so I'm glad someone who knows it well was able to cover what I missed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:30:48.497", "Id": "65237", "Score": "0", "body": "A few things I saw, the `results` declaration should be `List<String>`, `int more` can be directly set and there's a stray space at `more --`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-30T02:26:44.113", "Id": "104963", "Score": "0", "body": "@rolfl I have a problem similar to this problem that I was hoping you could advise me on. I have an unsorted list of unique numbers. I have to find two unique pairs that sum to the same value. Also, this value has to be as small as possible. Eg, the set {1, 4, 3, 2} would give 5 because (1, 4) and (2, 3) will be the pairs. If I had {1, 4, 2, 3, 30, 10, 25, 15} I would not get 40 with (25, 15) and (30, 10) because it is not the minimum possible sum. 5 is." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:57:43.877", "Id": "38998", "ParentId": "38994", "Score": "18" } }, { "body": "<p>I believe you can do this in O(n).</p>\n\n<p>The algorithm below loops through the list only once. It keeps track of the numbers it's seen using a HashSet. For each number, it works out its required complement. If it's seen the complement already then it's found a match. If not, it adds the number to the set - we may see its complement later.</p>\n\n<p>This actually works for unordered as well as ordered data, with the same performance characteristics. It also works for non-unique values (though we get n-1 repeated pairs of x for n repeated values of x - possibly not what you want, but a final stage could be to remove the duplicates if you so wished).</p>\n\n<p>Note that the order of the pairs returned, and indeed the order of two numbers in a pair, may not be the same as your original algorithm. It wasn't specified if this was important, but I'm guessing not.</p>\n\n<p>This reduced complexity comes at the expense of memory, as it must keep track of the numbers its seen in a separate data structure.</p>\n\n<p>One thing I would point out is that the algorithm is more flexible if it returns raw data, rather than formatted strings. Pretty-printing can be done by the caller.</p>\n\n<p>I've done this in C# because that's what I'm familiar with. I guess it should be trivial to convert to Java.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing NUnit.Framework;\n\nnamespace FindSummingPairs\n{\n public static class Algorithm\n {\n public static Tuple&lt;int, int&gt;[] FindSummingPairs(int[] input, int sumTarget)\n {\n var result = new List&lt;Tuple&lt;int, int&gt;&gt;();\n\n // holds the numbers we have seen so far\n var seenValues = new HashSet&lt;int&gt;();\n\n // loop through our input\n foreach(var number in input)\n {\n // work out the required value to make our target sum\n var required = sumTarget - number;\n\n // have we seen our required value in the list already?\n if (seenValues.Contains(required))\n {\n // score!\n result.Add(new Tuple&lt;int, int&gt;(number, required));\n }\n else\n {\n // not found, so add it to the set - we might see its complement later\n seenValues.Add(number);\n }\n }\n\n return result.ToArray();\n }\n }\n\n [TestFixture]\n internal class Tests\n {\n [Test]\n public void EmptyInput()\n {\n var input = new int[0];\n var result = Algorithm.FindSummingPairs(input, 0);\n Assert.False(result.Any());\n }\n\n [Test]\n public void SingleNumberAsInput()\n {\n var input = new[] {1};\n var result = Algorithm.FindSummingPairs(input, 2);\n Assert.IsTrue(result.Length == 0);\n }\n\n [Test]\n public void TwoNumbersThatDontSum()\n {\n var input = new[] {1, 2};\n var result = Algorithm.FindSummingPairs(input, 2);\n Assert.IsTrue(result.Length == 0);\n }\n\n [Test]\n public void TwoNumbersThatDoSum()\n {\n var input = new[] {1, 2};\n var result = Algorithm.FindSummingPairs(input, 3);\n var expected = new[] { new Tuple&lt;int, int&gt;(1, 2) };\n Assert.IsTrue(AreEquivalent(expected, result));\n }\n\n [Test]\n public void LotsOfNumbers()\n {\n var input = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n var result = Algorithm.FindSummingPairs(input, 10);\n var expected = new[]\n {\n new Tuple&lt;int, int&gt;(1, 9),\n new Tuple&lt;int, int&gt;(2, 8),\n new Tuple&lt;int, int&gt;(3, 7),\n new Tuple&lt;int, int&gt;(4, 6)\n };\n Assert.IsTrue(AreEquivalent(expected, result));\n }\n\n [Test]\n public void LotsOfNumbersThatDontSum()\n {\n var input = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n var result = Algorithm.FindSummingPairs(input, 20);\n Assert.IsTrue(result.Length == 0);\n }\n\n [Test]\n public void TestCaseFromQuestion()\n {\n var input = new[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};\n\n var result = Algorithm.FindSummingPairs(input, 16);\n var expected = new[]\n {\n new Tuple&lt;int, int&gt;(0, 16),\n new Tuple&lt;int, int&gt;(1, 15),\n new Tuple&lt;int, int&gt;(2, 14),\n new Tuple&lt;int, int&gt;(3, 13),\n new Tuple&lt;int, int&gt;(4, 12),\n new Tuple&lt;int, int&gt;(5, 11),\n new Tuple&lt;int, int&gt;(6, 10),\n new Tuple&lt;int, int&gt;(7, 9)\n };\n Assert.IsTrue(AreEquivalent(expected, result));\n }\n\n // calculates whether two pair arrays are equivalent, without respect to the order of the pairs\n private bool AreEquivalent(Tuple&lt;int, int&gt;[] e1, Tuple&lt;int, int&gt;[] e2)\n {\n if (e1.Length != e2.Length)\n return false;\n\n foreach(var pair1 in e1)\n {\n foreach (var pair2 in e2)\n {\n if (AreEquivalent(pair1, pair2))\n return true;\n }\n }\n return false;\n }\n\n // calculates whether 2 pairs are equivalent, without respect to the order of the numbers\n private bool AreEquivalent(Tuple&lt;int, int&gt; pair1, Tuple&lt;int, int&gt; pair2)\n {\n return (pair1.Item1 == pair2.Item1 &amp;&amp; pair1.Item2 == pair2.Item2)\n || (pair1.Item2 == pair2.Item1 &amp;&amp; pair1.Item2 == pair2.Item1);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T12:30:38.830", "Id": "39380", "ParentId": "38994", "Score": "5" } } ]
{ "AcceptedAnswerId": "38998", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:50:21.257", "Id": "38994", "Score": "15", "Tags": [ "java", "performance" ], "Title": "Finding pair of sum in sorted array" }
38994
<p>I'm working on a simple program and am trying to make it faster.</p> <pre><code>import time import numpy as np import matplotlib.pyplot as plt import pp first_file = open("ac_data.dat", 'r') #real dataset includes about 20000 terms res_file = open("res.dat", 'w') times_file = open("times.dat", 'a') #times = [0.000000, 0.000500, 0.001000, 0.001500, 0.002000, 0.002500, 0.003000, 0.003500, 0.004000, 0.004500, 0.005000, 0.005500, 0.006000, 0.006500, 0.007000, 0.007500, 0.008000, 0.008500, 0.009000, 0.009500] #magn = [-13.876622, -10.014824, -16.356894, -11.639914, -13.103313, -14.335239, -12.250072, -10.727098, -8.701272, -9.632907, -9.673712, -10.541722, -14.075446, -13.097790, -12.495679, -10.322924, -14.979391, -14.895666, -11.874325, -9.287736] times = [] magn = [] for i in first_file: dat = [float(j) for j in i.split()] times.append(dat[0]) magn.append(dat[1]) length = len(magn) #supposed to be equal 20000 for original data #autocorrelation function def rxx_func(amp): N = len(amp) rxx = [0]*N for m in xrange(N): for n in xrange(N-m): rxx[m]+=amp[n]*amp[n+m] return rxx #just prove with in-built def autocorr(x): result = np.correlate(x, x, mode='full') return result[result.size/2:] #Parallel or ordinary? answer = int(raw_input('Non-arallel = 0, parallel = 1 ')) if answer == 0: print 'Non-parallel calc was started' start = time.time() rxx = rxx_func(magn) end = time.time() calc_time = end - start time_string = 'Non-parallel: N = %i T = %f\n'%(length,calc_time) else: print 'Parallel calc was started' ppservers = () ncp = 4 job_server = pp.Server(ncp, ppservers=ppservers) print "Starting pp with", job_server.get_ncpus(), "workers" arg_n = tuple(magn) job = job_server.submit(rxx_func, (arg_n,), (), ()) start = time.time() rxx = job() job_server.print_stats() end = time.time() calc_time = end - start time_string = 'Parallel with %i CPUs: N = %i T = %f\n'%(ncp,length,calc_time) print (" \n Task for %i terms takes %f seconds for calc" %(length, calc_time)) print (" Max value of Autocorrelation func achieves %f" %(max(rxx))) print (" And it'll be normalized to 50 \n") #normalization to 50 norm_const = 50/max(rxx) proves = autocorr(magn) for k in xrange(length): rxx[k] = rxx[k]*norm_const proves[k] = proves[k]*norm_const #plotting plt.plot(times, magn) plt.plot(times, rxx) plt.plot(times, proves,'*') plt.show() for j in xrange(length): #saving results st = '%f %f %f\n'%(times[j], rxx[j], proves[j]) res_file.write(st) times_file.write(time_string) #saving calc times for comparsion first_file.close() res_file.close() times_file.close() </code></pre> <p>The program reads datasets from files to lists. Typical datasets look like commented #magn and #time. Real datasets will consist of 20000 lines or more.</p> <p>I've trying use the "parallel Python" package, but it runs even more slower than non-parallel code.</p> <p>For example, some results:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Non-parallel: N = 20000 T = 74.530000 sec Parallel with 2 CPUs: N = 20000 T = 80.229000 sec Parallel with 4 CPUs: N = 20000 T = 80.594000 sec </code></pre> </blockquote> <p>And I can't figure out why. Maybe I don't understand how it must be used.</p>
[]
[ { "body": "<p>I don't do much python so I might be wrong but to my understanding, this:</p>\n\n<pre><code>job = job_server.submit(rxx_func, (arg_n,), (), ())\n</code></pre>\n\n<p>just submits a single job but it doesn't automatically parallelize it. If you want to process the input in parallel you need to submit <code>n</code> jobs each working on 1-nth of the input and then combine the results. I think your parallel execution code should look something like this:</p>\n\n<pre><code>slice_size = len(magn) / ncp;\n\n# submit a job for each chunk\njobs = [job_server.submit(rxx_func, (magn,(i-1)*slice_size, slice_size), (), ()) for i in xrange(ncp)]\n\n# combine the results into one list, requires #import itertools\nrxx = list(itertools.chain.from_iterable([job() for job in jobs]))\n</code></pre>\n\n<p>You will have to change your <code>rxx_func</code> to accept a start index and a count which defines for how many items it is responsible:</p>\n\n<pre><code>def rxx_func(amp, start_index, count):\n N = len(amp)\n rxx = [0]*count\n\n for m in xrange(start_index, start_index + count - 1):\n for n in xrange(N-m):\n rxx[m]+=amp[n]*amp[n+m]\n return rxx\n</code></pre>\n\n<p>I'm sure there is plenty which can be optimized in the above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T14:06:55.590", "Id": "65324", "Score": "0", "body": "Yes, your main idea is brilliant and right, thank you. But for this task these usage will provide wrong results, because for one RXX value calculation needs using whole list of terms (all magn list). But every RXX value can be calculated differently, there is no dependance between RXX[1] and RXX[200]. So for now I trying understand how make ParallelPython do this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T17:52:42.073", "Id": "65334", "Score": "0", "body": "@Mikic: True, I missed that, I changed my example code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T23:46:50.837", "Id": "65364", "Score": "0", "body": "for unknown (so far) reason I get an error \"jobs = [job_server.submit(rxx_func, (magn,(i-1)*slice_size, slice_size), (), ()) for i in ncp]\nTypeError: 'int' object is not iterable\". But, as your code is example I should figure it out by myself, because your approach, I think, is quite right and optimization should keeps in that way. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T00:04:56.700", "Id": "65366", "Score": "0", "body": "should have been `xrange(ncp)`, fixed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T20:35:32.340", "Id": "65422", "Score": "0", "body": "After a sleepless night I figured out how the program should work. Added correct, in my opinion, code in question. Sadly increase was not as great as I expected (only 2 times), but the fact of proper work encourages. Unfortunately, I can not mark your answer as helpful, \"experience\" is not enough, but you was absolutely right. Also sorry, don't understand how \"itertools\" should works." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T10:17:57.913", "Id": "39044", "ParentId": "38999", "Score": "1" } } ]
{ "AcceptedAnswerId": "39044", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:59:33.307", "Id": "38999", "Score": "2", "Tags": [ "python", "optimization", "beginner" ], "Title": "Reading datasets from files to lists" }
38999
<p>I have implemented the shuffling algorithm of Fisher-Yates in C++, but I've stumbled across the modulo bias. Is this random number generation by <code>rand()</code> correct for Fisher-Yates?</p> <pre><code>srand(time(NULL)); vector&lt;int&gt; elements; // push numbers from 1 to 9 into the vector for (int i = 1; i &lt; 9; ++i) { elements.push_back(i); } // the counter to be used to generate the random number int currentIndexCounter = elements.size(); for (auto currentIndex = elements.rbegin(); currentIndex != elements.rend() - 1; currentIndex++ , --currentIndexCounter) { int randomIndex = rand() % currentIndexCounter; // if its not pointing to the same index if (*currentIndex != elements.at(randomIndex)) { //then swap the elements swap(elements.at(randomIndex), *currentIndex); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T18:37:39.430", "Id": "65421", "Score": "4", "body": "rand() is well know for its bad distribution. But you are using it correctly. Note: `rand() % currentIndexCounter` does not give you a perfect distribution unless `currentIndexCounter` is an exact divisor of `RAND_MAX`. You may want to look at C++11 random header and the generators provided inside." } ]
[ { "body": "<p>@Loki Astari is correct in his comment:</p>\n\n<blockquote>\n <p><code>rand()</code> is well know for its bad distribution. But you are using it correctly. Note: <code>rand() % currentIndexCounter</code> does not give you a perfect distribution unless <code>currentIndexCounter</code> is an exact divisor of <code>RAND_MAX</code>. You may want to look at C++11 random header and the generators provided inside.</p>\n</blockquote>\n\n<p>Since you're using C++11, you should instead utilize the <a href=\"http://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a> library. It includes things such as pseudo-random number generators and random number distributions.</p>\n\n<hr>\n\n<p>Beyond that, I'll just point out some additional things:</p>\n\n<ul>\n<li><p>With C++11, you should now be using <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> instead of <code>NULL</code>.</p>\n\n<p>This should be changed in <code>srand()</code>:</p>\n\n<pre><code>std::srand(std::time(nullptr));\n</code></pre>\n\n<p>However, as mentioned above, you should not be using this with C++11. But in any situation where you must stay with <code>rand</code>, the above would be recommended.</p></li>\n<li><p>With C++11, you should also have access to initializer lists. This will allow you to initialize the vector instead of calling <code>push_back()</code> multiple times:</p>\n\n<pre><code>std::vector&lt;int&gt; elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n</code></pre>\n\n<p>Also note that your <code>push_back()</code> was only pushing numbers 1-8 into the vector, despite what your comment said. You've used <code>&lt;</code> instead of <code>&lt;=</code> in the loop statement, so the 9 was excluded.</p></li>\n<li><p><code>currentIndexCounter</code> should be of type <code>std::vector&lt;int&gt;::size_type</code>, which is the return type of <code>size()</code> (or you can just use <code>auto</code>). This should've given you compiler warnings as it's a type-mismatch and a possible loss of data. Make sure your compiler warnings are turned up high.</p></li>\n<li><p><code>currentIndex</code> is a misleading name because it's being used with <em>iterators</em>, not <em>indices</em>.</p>\n\n<p>Here, <code>auto</code> gives <code>currentIndex</code> the type <a href=\"http://en.cppreference.com/w/cpp/iterator/reverse_iterator\" rel=\"nofollow noreferrer\"><code>std::reverse_iterator</code></a> from <code>std::rbegin()</code>. You could simply name this something like <code>iter</code>. It's okay for iterator names to be short.</p></li>\n<li><p>In the second <code>for</code> loop, you just need <code>elements.rend()</code>, without the <code>- 1</code>. The iterator will already go through the entire vector and stop at the last reverse element.</p></li>\n<li><p>The iterator increment should be prefix instead in order to improve performance a bit by avoiding a copy. It's best to do this with all nontrivial types such as iterators.</p></li>\n<li><p>I've tested this by giving <code>randomIndex</code> a value greater than <code>elements.size()</code>, causing an exception to be thrown. Even if <code>std::rand()</code> or another RNG is guaranteed to give you an intended value, it may be best to handle this properly.</p></li>\n</ul>\n\n<p>Here's the final version with my own given changes, which I've also ran <a href=\"http://ideone.com/xVXeeN\" rel=\"nofollow noreferrer\">here</a>. I've also included a concise way of displaying the vector before and after the shuffling.</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;random&gt;\n#include &lt;vector&gt;\n\nint main()\n{\n // seed the RNG\n std::random_device rd;\n std::mt19937 mt(rd());\n\n std::vector&lt;int&gt; elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\n std::cout &lt;&lt; \"Before: \";\n std::copy(elements.cbegin(), elements.cend(),\n std::ostream_iterator&lt;int&gt;(std::cout, \" \"));\n\n auto currentIndexCounter = elements.size();\n\n for (auto iter = elements.rbegin(); iter != elements.rend();\n ++iter, --currentIndexCounter)\n {\n // get int distribution with new range\n std::uniform_int_distribution&lt;&gt; dis(0, currentIndexCounter);\n const int randomIndex = dis(mt);\n\n if (*iter != elements.at(randomIndex))\n {\n std::swap(elements.at(randomIndex), *iter);\n }\n }\n\n std::cout &lt;&lt; \"\\nAfter: \";\n std::copy(elements.cbegin(), elements.cend(),\n std::ostream_iterator&lt;int&gt;(std::cout, \" \"));\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>Before: 1 2 3 4 5 6 7 8 9\nAfter: 7 9 3 2 4 5 6 1 8\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-05T05:57:36.470", "Id": "456353", "Score": "0", "body": "is it not possible that ```randomIndex = elements.size()``` on the first iteration of the loop thus resulting in undefined behavior? Unless the prefix decrement on ```currentIndexCounter``` executes on entry of the for loop, possibly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T01:48:51.273", "Id": "456651", "Score": "0", "body": "@z.karl: That is possible, though that's not one aspect that I caught from the OP's code previously (I only added `auto`)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T18:06:45.797", "Id": "39669", "ParentId": "39001", "Score": "14" } }, { "body": "<p>Here is my take on it with the modern <code>&lt;random&gt;</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>static const void fisher_yates_shuffle(std::deque&lt;card&gt;&amp; cards)\n{\n std::random_device random ;\n std::mt19937 mersenne_twister(random());\n std::uniform_int_distribution&lt;std::uint8_t&gt; distribution ;\n for (auto i = cards.size() - 1; i &gt; 0; --i)\n {\n distribution.param(std::uniform_int_distribution&lt;std::uint8_t&gt;::param_type(0, i));\n std::swap(cards[i], cards[distribution(mersenne_twister)]);\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:18:58.120", "Id": "452536", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T19:20:16.217", "Id": "452731", "Score": "0", "body": "If you only have read the flow of the answers, you would have noticed that they advise using the modern <random> to tackle the problem regarding modulo bias. This solution utilizes <random> and furthermore does not unnecessarily reinstantiate the uniform int distribution which is rather expensive. Despite being human, you are worse than a bot at grasping context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:36:19.930", "Id": "455701", "Score": "1", "body": "I just used this to implement a fisher_yates_shuffle on a Poker program and it works wonderfully, better than other answers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:06:55.087", "Id": "231909", "ParentId": "39001", "Score": "-1" } } ]
{ "AcceptedAnswerId": "39669", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T14:14:43.483", "Id": "39001", "Score": "13", "Tags": [ "c++", "algorithm", "c++11", "shuffle" ], "Title": "Fisher-Yates modern shuffle algorithm" }
39001
<p>I want to share something with this community. I did a class connection between Python and MySQL. I hope you can help me with this project and help me do a better class.</p> <p>Here is the class connection code:</p> <pre><code>import mysql __author__ = 'Alejandro' import mysql.connector from mysql.connector import errorcode class Mysql(object): __instance = None __host = None __user = None __password = None __database = None __session = None __connection = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = super(Mysql, cls).__new__(cls, *args, **kwargs) return cls.__instance def __init__(self, host='localhost', user='root', password='', database=''): self.__host = host self.__user = user self.__password = password self.__database = database #Open connection with database def _open(self): try: cnx = mysql.connector.connect(host=self.__host, user=self.__user, password=self.__password, database=self.__database) self.__connection = cnx self.__session = cnx.cursor() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print 'Something is wrong with your user name or password' elif err.errno == errorcode.ER_BAD_DB_ERROR: print 'Database does not exists' else: print err def _close(self): self.__session.close() self.__connection.close() def insert(self, table, *args, **kwargs): values = None query = "INSERT INTO %s " % table if kwargs: keys = kwargs.keys() values = kwargs.values() query += "(" + ",".join(["`%s`"]*len(keys)) % tuple(keys) + ") VALUES(" + ",".join(["%s"]*len(values)) + ")" elif args: values = args query += " VALUES(" + ",".join(["%s"]*len(values)) + ")" self._open() self.__session.execute(query, values) self.__connection.commit() self._close() return self.__session.lastrowid def select(self, table, where=None, *args): result = None query = "SELECT " keys = args l = len(keys) - 1 for i, key in enumerate(keys): query += "`"+key+"`" if i &lt; l: query += "," query += " FROM %s" % table if where: query += " WHERE %" % where self._open() self.__session.execute(query) self.__connection.commit() for result in self.__session.stored_results(): result = result.fetchall() self._close() return result def update(self, table, index, **kwargs): query = "UPDATE %s SET" % table keys = kwargs.keys() values = kwargs.values() l = len(keys) - 1 for i, key in enumerate(keys): query += "`"+key+"`=%s" if i &lt; l: query += "," query += " WHERE index=%d" % index self._open() self.__session.execute(query, values) self.__connection.commit() self._close() def delete(self, table, index): query = "DELETE FROM %s WHERE uuid=%d" % (table, index) self._open() self.__session.execute(query) self.__connection.commit() self._close() def call_store_procedure(self, name, *args): result_sp = None self._open() self.__session.callproc(name, args) self.__connection.commit() for result in self.__session.stored_results(): result_sp = result.fetchall() self._close() return result_sp </code></pre> <p>Here is how its use looks like:</p> <pre><code>from Mysql import Mysql connection = Mysql(host='localhost', user='root', password='', database='test') #Assuming that our table have the fields id and name in this order. #we can use this way but the parameter should have the same order that table #connection.insert('table_name',parameters to insert) connection.insert('test',1, 'Alejandro Mora') #in this case the order isn't matter #connection.insert('table_name', field=Value to insert) connection.insert('test',name='Alejandro Mora', id=1) #connection.select('Table', where="conditional(optional)", field to returned) connection.select('test', where="name = 'Alejandro Mora' ") connection.select('test', None,'id','name') #connection.update('Table', id, field=Value to update) connection.update('test', 1, name='Alejandro') #connection.delete('Table', id) connection.delete('test', 1) #connection.call_store_procedure(prodecure name, Values) connection.call_store_procedure('search_users_by_name', 'Alejandro') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-09T11:00:04.977", "Id": "222326", "Score": "0", "body": "Can you explain me which args must passed for Select method here ? cheers" } ]
[ { "body": "<p>Everything looks quite neat. Here are a few comments.</p>\n\n<pre><code> query = \"SELECT \"\n l = len(keys) - 1\n for i, key in enumerate(keys):\n query += \"`\"+key+\"`\"\n if i &lt; l:\n query += \",\"\n query += \" FROM %s\" % table\n</code></pre>\n\n<p>can be rewritten :</p>\n\n<pre><code>query = \"SELECT `\" + \"`,`\".join(keys) + \"` FROM \" + table\n</code></pre>\n\n<p>(I know that string concatenation might not be the best but it's just to join how you could use join to do what you want to do). The same kind of argument would hold for <code>update</code>.</p>\n\n<p>In <code>select</code> and in <code>call_store_procedure</code>, is this :</p>\n\n<pre><code> for result in self.__session.stored_results():\n result = result.fetchall()\n</code></pre>\n\n<p>any better than :</p>\n\n<pre><code> for result in self.__session.stored_results():\n result.fetchall()\n</code></pre>\n\n<p>?</p>\n\n<p>Also, just some food for thought as I haven't studied the issue in depth : how do you handle parameters that don't need to be in quotes such as numbers ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T05:20:17.493", "Id": "65314", "Score": "0", "body": "Hi thanks for the recomendations.\nI handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T16:57:54.383", "Id": "39013", "ParentId": "39009", "Score": "3" } }, { "body": "<p>An error maybe happen when the number of date base is two or more in your project. Example as:</p>\n\n<pre><code>class Mysql(object):\n __instance = None\n\n __host = None\n __user = None\n __password = None\n __database = None\n\n __session = None\n __connection = None\n\n def __new__(cls, *args, **kwargs):\n if not cls.__instance:\n cls.__instance = super(Mysql, cls).__new__(cls, *args, **kwargs)\n return cls.__instance\n\n def __init__(self, host='localhost', user='root', password='', database=''):\n self.__host = host\n self.__user = user\n self.__password = password\n self.__database = database\n\n def prin(self):\n print(self.__host, self.__user, self.__password, self.__database)\n\na = Mysql('192.168.1.12', 'user', 'user1234', 'test')\na.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')\nb = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')\nb.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')\na.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T23:47:37.387", "Id": "413926", "Score": "0", "body": "its correct but i think that is the behavior of singleton object, right?, when i did the connection class I did't think that it was used for have two databases but it is a good observation i think that i could include the posibility of have two o more databases in the future." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T05:37:33.730", "Id": "213932", "ParentId": "39009", "Score": "1" } } ]
{ "AcceptedAnswerId": "39013", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:42:57.837", "Id": "39009", "Score": "8", "Tags": [ "python", "mysql" ], "Title": "Python Connection with MySQL" }
39009
<pre><code>&lt;?php /** *session.php *danutz0501 *@copyright 2013 **/ //defined('BASE_PATH')||(header("HTTP/1.1 403 Forbidden")&amp;die('403 - Acces direct interzis.')); class session{ private $db, $table_name = 'session_data', $session_name = 'PDOSESSID', $session_litetime = 1440; private static $instance = null; public static function init(PDO $pdo, $table_name = null, $session_name = null, $session_lifetime = null){ if(self::$instance == null) self::$instance = new self($pdo, $table_name, $session_name, $session_lifetime); return self::$instance; } private function __construct($pdo, $table_name, $session_name, $session_lifetime){ $this-&gt;db = $pdo; $this-&gt;table_name = (is_null($table_name)) ? $this-&gt;table_name : $table_name; $this-&gt;session_name = (is_null($session_name)) ? $this-&gt;session_name : $session_name; $this-&gt;session_litetime = (is_null($session_lifetime)) ? $this-&gt;session_litetime : $session_lifetime; session_set_save_handler( [$this, 'open'], [$this, 'close'], [$this, 'read'], [$this, 'write'], [$this, 'destroy'], [$this, 'gc'] ); register_shutdown_function('session_write_close'); ini_set('session_auto_start', 0); ini_set('session.cookie_httponly',1); ini_set('session.use_only_cookies',1); ini_set('session.gc_probability', 25); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', $this-&gt;session_litetime); session_name($this-&gt;session_name); session_start(); $this-&gt;regenerate_id(); } private function __clone(){} public function open($save_path, $session_name){ return true; } public function close(){ $this-&gt;gc($this-&gt;session_litetime); return true; } public function read($session_id){ $session = $this-&gt;fetch_session($session_id); return ($session === false) ? false : $session['data']; } public function write($session_id, $session_data){ $session = $this-&gt;fetch_session($session_id); if($session === false) $stmp = $this-&gt;db-&gt;prepare('INSERT INTO '.$this-&gt;get_table().' (id, data, unixtime) VALUES (:id, :data, :time)'); else $stmp = $this-&gt;db-&gt;prepare('UPDATE '.$this-&gt;get_table().' SET data = :data, unixtime = :time WHERE id = :id'); $stmp-&gt;execute([':id' =&gt; $session_id, ':data' =&gt; $session_data, ':time' =&gt; time()]); } public function destroy($session_id){ $stmp = $this-&gt;db-&gt;prepare('DELETE FROM '.$this-&gt;get_table().' WHERE id = :id'); $stmp-&gt;execute([':id' =&gt; $session_id]); } public function gc($session_lifetime){ $stmp = $this-&gt;db-&gt;prepare('DELETE FROM '.$this-&gt;get_table().' WHERE unixtime &lt; :time'); $stmp-&gt;execute([':time' =&gt; (time() - (int) $session_lifetime)]); } private function get_table(){ $table = $this-&gt;db-&gt;quote($this-&gt;table_name); return ($table) ? $table : $this-&gt;table_name; } private function regenerate_id(){ $old_session = session_id(); session_regenerate_id(); $new_session = session_id(); $stmp = $this-&gt;db-&gt;prepare('UPDATE '.$this-&gt;get_table().' SET id = :new_id WHERE id = :old_id'); $stmp-&gt;execute([':new_id' =&gt; $new_session, ':old_id' =&gt; $old_session]); } private function fetch_session($session_id){ $smtp = $this-&gt;db-&gt;prepare("SELECT id, data FROM ".$this-&gt;get_table()." WHERE id = :id AND unixtime &gt; :unixtime"); $smtp-&gt;execute(['id' =&gt; $session_id, 'unixtime' =&gt; (time() - (int) $this-&gt;session_litetime)]); $session = $smtp-&gt;fetchAll(); return empty($session) ? false : $session[0]; } public static function set($key, $value){ if(!self::check_dot($key)) $_SESSION[$key] = $value; else self::set_dot($_SESSION, $key, $value); } public static function get($key){ if(!self::check_dot($key)) return (isset($_SESSION[$key])) ? $_SESSION[$key] : false; else return self::get_dot($_SESSION, $key); } private static function set_dot(&amp;$root, $key, $value){ $keys = explode('.', $key); while(count($keys) &gt; 1) { $key1 = array_shift($keys); if(!isset($root[$key1])) { $root[$key1] = []; } $root = &amp;$root[$key1]; } $key1 = reset($keys); $root[$key1] = $value; } private static function get_dot(&amp;$root, $key){ foreach(explode('.', $key) as $key1){ if(!is_array($root) || !array_key_exists($key1, $root)) return false; $root = &amp;$root[$key1]; } return $root; } public static function delete(){ $_SESSION = []; if(isset($_COOKIE[session_name()])){ $params = session_get_cookie_params(); setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } session_destroy(); } private static function check_dot($val){ return (bool) (strpos($val, '.')) ? true : false; } public static function check_data($key, $val){ foreach($key as $k){ if(!array_key_exists($k, $_SESSION) || $_SESSION[$k] != array_shift($val)) return false; } return true; } } </code></pre> <p>I just want some opinions about my session class. How bad is it? What can I improve? What's wrong about my class? I am trying to use a dot syntax for writing multi-dimensional arrays. EDIT: including some calling code, really simple</p> <pre><code>$pdo = new PDO('sqlite:data.db'); $pdo-&gt;exec('CREATE TABLE IF NOT EXISTS session_data(id INT, data TEXT, unixtime INT)'); include 'session.php'; session::init($pdo); session::set('abc1.abc2.abc3.abc4.abc5','test'); echo session::get('abc1.abc2.abc3.abc4.abc5'); session::set('abc1.abc2.abc31', 45); echo '&lt;br /&gt;'.session::get('abc1.abc2.abc31').'&lt;pre&gt;'; print_r($_SESSION); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T00:10:23.583", "Id": "65454", "Score": "0", "body": "How about including some calling code?" } ]
[ { "body": "<p>For one thing, to increase readability and cleanliness, try organizing your code a little better. You can read more on that <a href=\"http://framework.zend.com/manual/1.12/en/doc-standard.html\" rel=\"nofollow\">here</a>.</p>\n\n<p>In <code>init()</code>, you can use <code>if(is_null(self::$instance))</code> instead of <code>if(self::$instance == null)</code>.</p>\n\n<p>In <code>__construct()</code>, I don't believe your ternaries need parentheses around the <code>is_null</code> functions.</p>\n\n<p>Hopefully you'll be adding to <code>open()</code> because right now it has no purpose. And then in your setter and getter, I suppose you could switch the <code>if</code> statement around so instead of <code>if (!self::check_dot($key))</code> you'll have <code>if (self::check_dot($key))</code>.</p>\n\n<p>Other than though, your connection looks good and you seem to be handling everything okay!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T03:32:15.073", "Id": "72442", "Score": "2", "body": "You've recently spiked in activity on this site! You should come join us in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T03:07:41.167", "Id": "42100", "ParentId": "39010", "Score": "3" } }, { "body": "<p>I was under the impression that the native session functions in the session handling class (open, close, read, write, destroy, gc) should all return values (read--string, the others bool). For instance, your read method returns inconsistent types (string or false), and write/destroy/gc methods return nothing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-18T18:59:22.017", "Id": "88139", "Score": "1", "body": "That is a nice observation. How about recommending a consistent behaviour, or showing the benefits and drawbacks of the respective approaches? That would make an **even better** answer ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-18T18:25:17.540", "Id": "51079", "ParentId": "39010", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:44:45.840", "Id": "39010", "Score": "4", "Tags": [ "php", "classes", "session" ], "Title": "Custom session class" }
39010
<p>So I have built a clock widget. It basically has 2 hands and displays a time, either the current time or a selected time. There is another option which tells the clock if it should move around as the time does. </p> <p>Is this a good way to do this? It seems to work well in my app but I was wondering if there might be some performance issues? What are the alternatives?</p> <p><strong>--EDIT--</strong></p> <p>I am aware that it's poor form to hard code lengths when drawing the lines. I will change that</p> <pre><code>public class ClockView extends RelativeLayout { private Animation minuteRotationAnimation; private Animation hourRotationAnimation; private LayoutInflater layoutInflater; private HandView minuteHandView; private HandView hourHandView; public ClockView(Context context, AttributeSet attrs) { super(context, attrs); layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); RelativeLayout relativeLayout = (RelativeLayout) layoutInflater.inflate(R.layout.clock_view, null); minuteHandView = (HandView) relativeLayout.findViewById(R.id.secondHandView); hourHandView = (HandView) relativeLayout.findViewById(R.id.hourHandView); hourHandView.setHeightPercentage(50); // hourHandView.setHalf(true); addView(relativeLayout); minuteRotationAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate_minutes); hourRotationAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate_hour); } public void setAsCurrentTime() { final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); Date date = cal.getTime(); int hour = date.getHours(); int minute = date.getMinutes(); setTime(hour, minute, false); } public void setTime(long timestamp, boolean stop) { final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timestamp); Date date = cal.getTime(); int hour = date.getHours(); int minute = date.getMinutes(); setTime(hour, minute, false); } public void setTime(int hour, int minute, boolean stop) { int minuteDegrees = getDegrees(false, minute); int hourDegrees = getDegrees(true, hour); RotateAnimation hourStartAnimation = getRotateAnimation(hourDegrees); RotateAnimation minuteStartAnimation = getRotateAnimation(minuteDegrees); minuteHandView.startAnimation(minuteStartAnimation); if (stop == false) { AnimationSet hourAnimationSet = getAnimationSet(hourStartAnimation, hourRotationAnimation); AnimationSet minuteAnimationSet = getAnimationSet(minuteStartAnimation, minuteRotationAnimation); hourHandView.startAnimation(hourAnimationSet); minuteHandView.startAnimation(minuteAnimationSet); } else { hourHandView.startAnimation(hourStartAnimation); minuteHandView.startAnimation(minuteStartAnimation); } } private AnimationSet getAnimationSet(Animation animation1, Animation animation2) { AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(animation1); animationSet.addAnimation(animation2); return animationSet; } private RotateAnimation getRotateAnimation(int degrees) { RotateAnimation animation = new RotateAnimation(0, degrees, 50, 50); animation.setDuration(1000); animation.setRepeatCount(0); animation.setRepeatMode(Animation.REVERSE); animation.setFillAfter(true); return animation; } private int getDegrees(boolean hour, int value) { int multiple; if (hour) { multiple = 12; } else { multiple = 60; } return (360 / multiple) * value; } } public class HandView extends View { private Paint paint = new Paint(); private int heightPercentage = 100; private boolean half = false; public void setHalf(boolean half) { this.half = half; } public HandView(Context context, AttributeSet attrs) { super(context, attrs); paint.setColor(context.getResources().getColor(R.color.clockBlue)); paint.setStrokeWidth(5); paint.setAntiAlias(true); } public void setHeightPercentage(int heightPercentage) { this.heightPercentage = heightPercentage; } public void setWidth(float width) { paint.setStrokeWidth(width); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); int height; if (half) { height = 30; } else { height = 10; } Rect rect = canvas.getClipBounds(); canvas.drawLine(rect.exactCenterX(), rect.exactCenterY(), rect.exactCenterX(), height, paint); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T18:13:58.310", "Id": "65273", "Score": "1", "body": "Is this an Android **widget** or an **application**? It seems like an application to me. You're confusing me when you're saying that it's a widget." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-11T13:31:29.820", "Id": "65321", "Score": "0", "body": "maybe view would be the correct word. It's certainly not an application" } ]
[ { "body": "<p>Just a few Java-related notes:</p>\n\n<ol>\n<li><p>About <code>getDegrees</code>:</p>\n\n<blockquote>\n <p>Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It\n immediately complicates the signature of the method, loudly proclaiming that this function\n does more than one thing. It does one thing if the flag is true and another if the flag is false!</p>\n</blockquote>\n\n<p>Source: Clean Code by Robert C. Martin, Chapter 3: Functions.</p>\n\n<p>I'd create two separate functions for hours and minutes:</p>\n\n<pre><code>public int getMinuteDegrees(final int minutes) {\n final int multiplier = 60;\n return getDegrees(minutes, multiplier);\n}\n\npublic int getHourDegrees(final int hours) {\n final int multiplier = 12;\n return getDegrees(hours, multiplier);\n}\n\nprivate int getDegrees(final int value, final int multiplier) {\n return (360 / multiplier) * value;\n}\n</code></pre>\n\n<p>Notice the explanatory variable (<code>multiplier</code>) in both methods. References: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em></p></li>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852\" rel=\"nofollow\">Code Conventions for the Java Programming Language, 3.1.3 Class and Interface Declarations</a>, methods should be after constructors, so the <code>setHalf()</code> method should be after the constructor declaration.</p></li>\n<li><p>The logic in <code>setAsCurrentTime</code> and <code>setTime()</code> almost the same. You could extract out a method here to remove the duplication:</p>\n\n<pre><code>public void setAsCurrentTime() {\n long currentTimeMillis = System.currentTimeMillis();\n setTime(currentTimeMillis);\n}\n\npublic void setTime(final long timestamp, final boolean stop) {\n setTime(timestamp);\n}\n\nprivate void setTime(final long timestamp) {\n final Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(timestamp);\n final Date date = cal.getTime();\n final int hour = date.getHours();\n final int minute = date.getMinutes();\n setTime(hour, minute, false);\n}\n</code></pre></li>\n<li><p><code>setTime(long timestamp, boolean stop)</code> does not use the <code>stop</code> flag. It might be a bug but if it's just unnecessary remove it.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T09:11:50.090", "Id": "68685", "Score": "1", "body": "Nice feedback! I am a big fan of Robert C. Martin so it was good you referenced him" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:04:57.650", "Id": "40687", "ParentId": "39011", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:57:49.370", "Id": "39011", "Score": "7", "Tags": [ "java", "android", "datetime" ], "Title": "Clock View in Android" }
39011