body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>is this class ok? any and all advice very welcome. Would it be better to pass the config file path array into the constructor or even through the static register method</p> <pre><code>namespace dh_mvc2\autoloaders; use dh_mvc2\classes\Config; /** * * @namespace dh_mvc2\autoloaders * @uses dh_mvc2\classes\Config in class constructor to include paths defined * via config file * */ class BasicAutoloader { private static $_instance; private $pathsArray = array (); /** * * @access private construct to force singleton creation * @example Basicautoloader::register( (array) $extraPaths ); * @uses dh_mvc2\classes\Config to include paths defined via config file * @see BasicAutoloader::register * @see Config::get_paths */ private function __construct() { $this-&gt;pathsArray = array_change_key_case ( ( array ) Config::get_paths (), CASE_UPPER ); self::$_instance = $this; } public static function getInstance() { if (! isset ( self::$_instance )) { new self (); } return self::$_instance; } /** * adds paths to autoloader directory array and defines paths to their array key * @example * array("example_dir" =&gt; "c:/www/nest/example") will * define('EXAMPLE_DIR', 'c:/www/nest/example/') nb.! trailing / added * @param array $paths * paths to add to autoloader * @return array full list of paths included */ public function addPaths(array $paths = NULL) { $paths = array_change_key_case ( (array) $paths, CASE_UPPER ); $this-&gt;pathsArray = array_merge_recursive ( $this-&gt;pathsArray, $paths ); foreach ( $this-&gt;pathsArray as $key =&gt; $path ) { $path = str_replace ( "\\", "/", (rtrim ( $path, '/' ) . "/") ); $this-&gt;pathsArray [$key] = $path; defined ( $key ) || define ( $key, $path ); } return ( array ) $this-&gt;pathsArray; } /** * static call to register this autoloader with extra paths as optional * paramater. * this method creates a singleton which reads in config paths on its * creation * * @param array $pathsArray * to add to autoloader not defined in config file * @return \dh_mvc2\autoloaders\BasicAutoloader */ public static function register(array $pathsArray = NULL) { $self = self::getInstance (); $self-&gt;addPaths ( $pathsArray ); spl_autoload_register ( array ( $self, 'loader' ) ); return $self; } /** * spl_autoload_register's autoload function */ private function loader($className) { // swap \ for / for namespaces to be found on unix systems $className = str_replace ( "\\", "/", $className ) . '.php'; foreach ( $this-&gt;pathsArray as $key =&gt; $path ) { $fullFilePath = constant ( $key ) . DIRECTORY_SEPARATOR . $className; if (file_exists ( $fullFilePath )) { require ($fullFilePath); return; } } } } </code></pre> <p>My revised class file after reading Mogria's suggestions below. Have removed static singleton and sending array of paths rather than expect the class to retrieve from config object/class as before</p> <pre><code>namespace dh_mvc2\autoloaders; /** * * @namespace dh_mvc2\autoloaders * */ class BasicAutoloader { private $_pathsArray = array (); /** * creates instance of base autoloader and registers autoload function. * @param array $paths optional paths to add to autoloaders directories array */ public function __construct(array $paths = NULL) { $this-&gt;_pathsArray = $this-&gt;change_to_unix_seperator(( array ) $paths); spl_autoload_register ( array ( $this, 'loader' ) ); } /** * ensures paths have unix directory serperators * @param array $paths * @return array */ private function change_to_unix_seperator(array $paths){ foreach ($paths as $key =&gt; $path){ $path = str_replace ( "\\", "/", (rtrim ( $path, '/' ) . "/") ); } return (array) $paths; } /** * adds paths to autoloader directory array * * @param array $paths * paths to add to autoloader * @return array full list of paths included */ public function addPaths(array $paths = NULL) { $paths=$this-&gt;change_to_unix_seperator((array)$paths); $this-&gt;_pathsArray = array_merge_recursive ( $this-&gt;_pathsArray, $paths ); return ( array ) $this-&gt;_pathsArray; } /** * spl_autoload_register's autoload function */ private function loader($className) { // swap \ for / for namespaces to be found on unix systems $className = str_replace ( "\\", "/", $className ) . '.php'; foreach ( $this-&gt;_pathsArray as $key =&gt; $path ) { $fullFilePath = $path . '/' . $className; if (file_exists ( $fullFilePath )) { require ($fullFilePath); return; } } } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:08:59.487", "Id": "37167", "Score": "0", "body": "On this line you simply use `/` as directory separator. `$className = str_replace ( \"\\\\\", \"/\", $className ) . '.php';`, but on this line `$fullFilePath = constant ( $key ) . DIRECTORY_SEPARATOR . $className;` you use `DIRECTORY_SEPARATOR`. Use `DIRECTORY_SEPARATOR` for both." } ]
[ { "body": "<p>Generally your class relies on multiple global states and is therefore tightly coupled with the environment.</p>\n\n<p>For instance:</p>\n\n<pre><code>private function __construct() {\n $this-&gt;pathsArray = array_change_key_case ( ( array ) Config::get_paths (), CASE_UPPER );\n self::$_instance = $this;\n}\n</code></pre>\n\n<p>Instead of supplying the configuration as an Parameter to the constructor you simply call one specific implementation of <code>Config</code>. What if you later have classes like <code>FileConfig</code> which loads the configuration from a file, or <code>DatabaseConfig</code> which loads the configuration from the Database or some kind, You'd need to change <code>Config</code> everywhere in your source code.</p>\n\n<p>One way to solve this isse (if you need/want to) is by using <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">Dependency Injection</a>:</p>\n\n<p>You simply define an interface for which every Configuration class needs to implement, like this:</p>\n\n<pre><code>interface Config {\n public function get($key); // returns a config value\n // more ...\n};\n</code></pre>\n\n<p>Then you simply say in your class that you need an object which implements the <code>Config</code> interface like this.</p>\n\n<pre><code>private function __construct(Config config) {\n $this-&gt;pathsArray = array_change_key_case ( ( array ) config-&gt;get('paths'), CASE_UPPER );\n // code ...\n}\n</code></pre>\n\n<hr>\n\n<p>An other issue which you may want to rethink is, that your Autoloader class is an Singleton. This creates the following issues:</p>\n\n<ul>\n<li>Every other class which uses the Autoloader via <code>Autoloader::getInstance</code> is coupled to this specific implementation.</li>\n<li>You may want to have multiple instances, if you wan't two different objects for different directories.</li>\n<li>You can't control the lifetime of the Object. Once registered every class which which is required goes through this autoloader, so you can't turn it off or on.</li>\n</ul>\n\n<p>Why do you create these constants? It's not really required by your class and it simply pollutes the global namespace. And if other classes use these then they are dependent on the fact that the method which creates these constant gets executed before the classes get used.</p>\n\n<pre><code>defined ( $key ) || define ( $key, $path );\n</code></pre>\n\n<hr>\n\n<p>An other little issue is that you're not consistent with using <code>DIRECTORY_SEPARATOR</code>, either use <code>/</code> everywhere (because they work on windows &amp; unix) and deal with the fact that some paths on windows may look ugly because they have mixed <code>/</code> and <code>\\</code> in it. Or use <code>DIRECTORY_SEPARATOR</code> everywhere and type a bit more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:55:19.757", "Id": "37179", "Score": "0", "body": "Thanks Mogria for your review. I think I changed all of what you suggest, apart from I'm sending an array of paths to the constructor as opposed to a Config object." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:34:07.763", "Id": "24099", "ParentId": "24092", "Score": "1" } } ]
{ "AcceptedAnswerId": "24099", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:17:50.640", "Id": "24092", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "php autloader class reviews welcome" }
24092
<p>There are two aspects to formatting:</p> <h2>Report layout</h2> <p>How the output is presented, such as in columns or as a chart.</p> <h2>Formatting data items</h2> <p>How individual items are converted from internal representation to human-friendly output.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-19T11:17:59.597", "Id": "24094", "Score": "0", "Tags": null, "Title": null }
24094
For programs that are concerned with producing meaningful or clearer output. A typical example would be the transformation of a decimal into a particular currency format with the correct number of decimal places. (Note that code layout is always in scope for answers, so this tag is not used to indicate perceived issues with that).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-19T11:17:59.597", "Id": "24095", "Score": "0", "Tags": null, "Title": null }
24095
<p>I've been porting python Keyczar to work under 2to3 conversion (<a href="https://github.com/jbtule/keyczar-python2to3" rel="nofollow">Github</a>). I wanted to consolidate its streaming AES encrypt/decrypt backend interface with its string decrypt/encrypt. So I wrote a new implementation using <code>io.BufferReader</code> and <code>io.BufferedWriter</code>. In my construction, I decrypt up until the last block and then check the MAC before decrypting that block and unpadding.</p> <p>I feel a bit unsure of whether this is the right thing to do, as it's not my typical construction, and whether instead I should just buffer the whole thing and not decrypt at all until the MAC is checked.</p> <p>I'm not a Python developer so any API or idiomatic suggestions are very welcome too.</p> <p>These snippets are covered under the Apache license, follow the links to see whole code.</p> <p><strong><a href="https://github.com/jbtule/keyczar-python2to3/blob/master/python/keyczar/keys.py#L456" rel="nofollow">Encrypt</a></strong></p> <pre><code> def EncryptIO(self, reader , writer): """ Write ciphertext byte stream containing Header|IV|Ciph|Sig. """ mac = self.hmac_key.CreateStreamable() #Write and update mac for header header = self.Header() writer.write(header) mac.Update(header) #Generate, write, and update mac for IV iv_bytes = util.RandBytes(self.block_size) writer.write(iv_bytes) mac.Update(iv_bytes) buffer_size = self.block_size * 4 cipher = self.__CreateCipher(self.key_bytes, iv_bytes) more = True while more: data = util.ReadLength(reader, buffer_size) more = len(data) == buffer_size if not more: data = self._Pad(data) #encrypt, update mac and write out ciphertext ciph_bytes = cipher.encrypt(data) mac.Update(ciph_bytes) writer.write(ciph_bytes) #call final mac and write whatever is returned ciph_bytes = cipher.final() mac.Update(ciph_bytes) writer.write(ciph_bytes) #write mac and flush writer.write(mac.Sign()) writer.flush() </code></pre> <p><strong><a href="https://github.com/jbtule/keyczar-python2to3/blob/master/python/keyczar/keys.py#L502" rel="nofollow">Decrypt</a></strong></p> <pre><code> def DecryptIO(self, header, reader, writer): mac = self.hmac_key.CreateStreamable() #update mac of header mac.Update(header) #read out iv and update mac iv_bytes = util.ReadLength(reader, self.block_size) mac.Update(iv_bytes) cipher = self.__CreateCipher(self.key_bytes, iv_bytes) more = True # buffer_size is a block multiple -- req'd buffer_size = self.block_size * 4 # read out one more byte into starting tag buff # so on a valid ciphertext we will know we are on # the last block to unpad initial_len = util.HLEN + 1 tagbuff = util.ReadLength(reader, initial_len) while more: buff = util.ReadLength(reader, buffer_size) more = len(buff) == buffer_size tempbuff = tagbuff + buff if more: buff = tempbuff[:buffer_size] tagbuff = tempbuff[buffer_size:] else: buff = tempbuff[:-util.HLEN] tagbuff = tempbuff[-util.HLEN:] mac.Update(buff) if not more: #check the mac before we try and finish decryption calctag = mac.Sign() if not util.ConstantTimeCompare(tagbuff, calctag): raise errors.InvalidSignatureError() ptext = cipher.decrypt(buff) if not more: #remove padding now that we know the ciphertext is valid ptext += cipher.final() ptext = self._UnPad(ptext) writer.write(ptext) writer.flush() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:55:28.317", "Id": "24101", "Score": "3", "Tags": [ "python", "security", "cryptography" ], "Title": "Streamed encrypt then MAC construction" }
24101
<blockquote> <p>Implement atoi to convert a string to an integer.</p> <p>Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p> <p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p> <p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p> <p>If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.</p> </blockquote> <p>The following is my code:</p> <pre><code>int atoi(const char *str) { int sign = 1; long long i = 0, j = 0; while ((*str) != '\0' &amp;&amp; isspace(*str)) { ++str; } if (((*str)!='\0') &amp;&amp; ((*str) == '+' || (*str) == '-')) { if ((*str) == '-') { sign = -1; } ++str; } if (((*str) != '\0') &amp;&amp; (!isdigit(*str))) { return 0; } while (((*str) != '\0') &amp;&amp; (isdigit(*str))) { i = i * 10 + (*str - '0'); j = i * sign; cout &lt;&lt; j &lt;&lt; endl; if (j &gt; INT_MAX) { return INT_MAX; } if (j &lt; INT_MIN) { return INT_MIN; } ++str; } return j; } </code></pre>
[]
[ { "body": "<pre><code>if (((*str) != '\\0') &amp;&amp; (!isdigit(*str))) {\n return 0;\n}\n</code></pre>\n\n<p>You don't need this condition, because of the condition in the while loop afterwards. If that fails the first time <code>j</code> with value <code>0</code> is returned anyway.</p>\n\n<p>And a minimal (and maybe unnecessary) optimization:</p>\n\n<pre><code>if (j &gt;= INT_MAX) {\n return INT_MAX;\n}\nif (j &lt;= INT_MIN) {\n return INT_MIN;\n}\n</code></pre>\n\n<p>Why look for the next character in the string which would only get appended to the number and would increase the value, if the number already has the maximumk/minimum value possible (<code>INT_MAX</code>/<code>INT_MIN</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:32:45.367", "Id": "37269", "Score": "0", "body": "Why look for the next character which only makes the number bigger if you already reached INT_MAX/INT_MIN? Can you explain this sentence more detail. I don't understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:17:06.320", "Id": "37280", "Score": "0", "body": "@FihopZz, I edited my answer, I hope its understandable now (English is not my native language)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T22:40:43.610", "Id": "37293", "Score": "0", "body": "If the number already has the maximum/minimum value, which is checked by `if (j >= INT_MAX)` and `if (j <= INT_MIN)` in my code, there is no necessary to check the next character. It seems that this is what I do. :-)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:48:05.810", "Id": "37303", "Score": "0", "body": "In your code you return if `j > INT_MAX`, but you don't return if `j` is already equal to `INT_MAX`, so better IMO would be returning if `j >= INT_MAX` like I suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:23:28.677", "Id": "412224", "Score": "0", "body": "`if (j >= INT_MAX)` tests it too late to prevent undefined behavior of the prior `i = i * 10 + (*str - '0');` on platforms where `INT_MAX == LLONG_MAX`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:17:56.867", "Id": "24105", "ParentId": "24103", "Score": "2" } }, { "body": "<p>You seem to have too many checks for '\\0'. They don't add anything. Also too many brackets, but better too many than too few.</p>\n\n<p>Also, is <code>long long</code> guaranteed to be bigger than <code>int</code>? I don't think it is. Here's another version that doesn't need a bigger representation than that of <code>int</code>: </p>\n\n<pre><code>int atoi(const char *str)\n{\n int n = 0;\n int sign = 1;\n\n while (isspace(*str)) {\n ++str;\n }\n if (*str == '-') {\n sign = -1;\n ++str;\n } else if (*str == '+') {\n sign = 1;\n ++str;\n }\n while (isdigit(*str)) {\n if (n &gt; INT_MAX/10) { /* EDIT: protect against overflow */\n break;\n }\n n *= 10;\n int ch = *str - '0';\n\n if (n &gt; INT_MAX - ch) {\n break;\n }\n n += ch;\n ++str;\n }\n if (isdigit(*str)) {\n return sign == 1 ? INT_MAX : INT_MIN;\n }\n return sign * n;\n}\n</code></pre>\n\n<p>EDIT: I added a check to prevent overflow of the <code>n *= 10</code></p>\n\n<p>EDIT2: improved to avoid using an unsigned int - it was a hack</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:01:19.047", "Id": "37275", "Score": "0", "body": "very nice!!!!!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:33:39.353", "Id": "412227", "Score": "0", "body": "Minor `is...(*str)` is UB when `*str < 0`. Consider `isspace((unsigned char) *str)`, `isdigit((unsigned char) *str)` ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:36:12.460", "Id": "412230", "Score": "0", "body": "This code has a novel and functionally correct way to prevent overflow. Clarity to add: `if (isdigit(*str)) {` is true in 2 conditions: overflow and when forming a non-overflow result of `INT_MIN`. e.g. `atoi(\"-2147483648\")`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T02:52:14.957", "Id": "24137", "ParentId": "24103", "Score": "4" } }, { "body": "<p><strong><code>is...()</code> UB</strong></p>\n\n<p><code>is...(c)</code> can be <em>undefined behavior</em> (UB) when <code>c &lt; 0</code>. To prevent, cast to <code>unsigned char</code>.</p>\n\n<pre><code>// isspace(*str);\nisspace((unsigned char) *str);\n\n// isdigit(*str);\nisdigit((unsigned char) *str);\n</code></pre>\n\n<p><strong>Invalid C code</strong></p>\n\n<p><code>cout &lt;&lt; j &lt;&lt; endl;</code> is not well defined in C. I suspect OP is using a non-C compiler.</p>\n\n<p><strong>Code assumes <code>long long</code> wider than <code>int</code></strong></p>\n\n<p><code>if (j &gt; INT_MAX)</code> is not possible when <code>INT_MAX == LLONG_MAX</code>. Prior <code>i = i * 10</code> can readily overflow signed integer math which is UB.</p>\n\n<p>In any case, the approach of needing wider math fails when trying to code <code>atoll()</code>.</p>\n\n<p>Better to detect potential overflow using <code>int</code> math. Alternative:</p>\n\n<pre><code>int neg_sum = 0;\nwhile (isdigit((unsigned char) *str))) {\n int digit = *str++ - '0';\n if (neg_sum &lt;= INT_MIN/10 &amp;&amp; (neg_sum &lt; INT_MIN/10 || digit &gt; -(INT_MIN%10))) {\n neg_sum = INT_MIN; // out of range\n break;\n } \n neg_sum = neg_sum*10 - digit;\n}\n\nif (sign == 1) {\n if (neg_sum &lt; -INT_MAX) {\n return INT_MAX; \n }\n return -neg_sum; \n}\nreturn neg_sum; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:56:25.750", "Id": "213096", "ParentId": "24103", "Score": "1" } } ]
{ "AcceptedAnswerId": "24105", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:21:55.447", "Id": "24103", "Score": "2", "Tags": [ "c", "strings", "interview-questions" ], "Title": "string to integer (implement atoi)" }
24103
<p>I've taken this class and made it my own but I'm curious to know what other think of it? Are there things I'm missing? Anything you can recommend?</p> <pre><code>class Database { private $host = ''; private $user = ''; private $pass = ''; private $dbname = ''; private $dbh; private $error; private $stmt; public function __construct() { $dsn = 'mysql:dbname=' . $this -&gt; dbname . ';host=' . $this -&gt; host . ''; // Set options $options = array(PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION); // Create a new PDO instanace try { $this -&gt; dbh = new PDO($dsn, $this -&gt; user, $this -&gt; pass, $options); } catch(PDOException $e) { $this-&gt;error = $e -&gt; getMessage(); } } public function query($query) { $this -&gt; stmt = $this -&gt; dbh -&gt; prepare($query); } public function bind($param, $value, $type = null) { if (is_null($type)) { switch (true) { case is_int($value) : $type = PDO::PARAM_INT; break; case is_bool($value) : $type = PDO::PARAM_BOOL; break; case is_null($value) : $type = PDO::PARAM_NULL; break; default : $type = PDO::PARAM_STR; } } $this -&gt; stmt -&gt; bindValue($param, $value, $type); } public function execute() { return $this -&gt; stmt -&gt; execute(); } public function fetchAll() { $this -&gt; execute(); return $this -&gt; stmt -&gt; fetchAll(PDO::FETCH_ASSOC); } public function fetch() { $this -&gt; execute(); return $this -&gt; stmt -&gt; fetch(PDO::FETCH_ASSOC); } public function rowCount() { return $this -&gt; stmt -&gt; rowCount(); } public function countAll($arr) { return count($arr); } public function lastInsertId() { return $this -&gt; dbh -&gt; lastInsertId(); } } </code></pre>
[]
[ { "body": "<pre><code> private $host = '';\n private $user = '';\n private $pass = '';\n private $dbname = '';\n\n // ....\n\n public function __construct() {\n $dsn = 'mysql:dbname=' . $this -&gt; dbname . ';host=' . $this -&gt; host . '';\n\n // ...\n }\n</code></pre>\n\n<p>Two things here:</p>\n\n<ul>\n<li><p>How can I set the connection credentials? The properties are private and I see no setters or parameters to the constructor?</p></li>\n<li><p>Why use PDO if you only use mysql?</p></li>\n</ul>\n\n<p>And an other thing:</p>\n\n<pre><code>public function bind($param, $value, $type = null) {\n if (is_null($type)) {\n switch (true) {\n case is_int($value) :\n $type = PDO::PARAM_INT;\n break;\n case is_bool($value) :\n $type = PDO::PARAM_BOOL;\n break;\n case is_null($value) :\n $type = PDO::PARAM_NULL;\n break;\n default :\n $type = PDO::PARAM_STR;\n }\n }\n $this -&gt; stmt -&gt; bindValue($param, $value, $type);\n}\n</code></pre>\n\n<p>This can be dangerous. Let's say you have code like this:</p>\n\n<pre><code>$db-&gt;bind('param', $_POST['id']);\n</code></pre>\n\n<p>Your method would detect it's a string, but it should be an integer!</p>\n\n<p>After all your class doesn't bring much value, it mostly forwards calls to PDO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:42:32.973", "Id": "37187", "Score": "0", "body": "Thanks for the reply. The connection details are entered in the class itself with the private variables. I just took them out. Thanks for the param suggestion. Also, why doesn't this class bring value? It speeds up my process and handles PDO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:11:44.563", "Id": "37279", "Score": "0", "body": "@SeanWM Most of the methods just forward the calls to other methods (And passing some constants, BTW you could set the fetch mode in pdo with the following function too: http://php.net/manual/en/pdostatement.setfetchmode.php). Except the `bind()` method, which IMO is dangerous to use. It's basicly a wrapper which reduces the functionality (because you can only use it for mysql in your case, and only a certain set of PDO methods) and security." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T23:44:06.557", "Id": "37576", "Score": "0", "body": "`$db->bind('param', $_POST['id']);` in my demo I just ran, it does in fact NOT return this as a string for me. It works as expected" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T06:59:16.087", "Id": "37593", "Score": "0", "body": "@jasondavis I can not reproduce that. Every `$_POST` value I pass is treated as string (because it is a string). Did you cast it before passing it to the function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T07:03:08.530", "Id": "37595", "Score": "0", "body": "@Mogria I confess I didn't test a REAL post, only simulated so I get what you are saying, perhaps his function could be modified though to detect int" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:25:29.500", "Id": "24106", "ParentId": "24104", "Score": "0" } }, { "body": "<p>I have set up something very similar with a couple changes. In <code>__contruct()</code> I assign the credentials to variables, then call an instance to start the <code>PDO</code> connection. I also use <code>try-catch</code> for each PDO statement to make sure that I am not getting any errors.</p>\n\n<pre><code>private $_pdo = null;\nprivate $_host, $_dbname, $_uname, $_pass;\nprivate $_sql, $_result;\nprivate $_preparedStmt;\n\npublic function __construct($host, $dbname, $username, $password) {\n // You could run checks here to make sure that...\n // no values or specific values are not equal to ''\n $this-&gt;_host = $host;\n $this-&gt;_dbname = $dbname;\n $this-&gt;_uname = $username;\n $this-&gt;_pass = $password;\n $this-&gt;startPDO();\n}\n\n// ... Later on in code, under Private functions comment tag\nprivate function startPDO() {\n try {\n $this-&gt;_pdo = new PDO('mysql:host='.$this-&gt;_host.';dbname='.$this-&gt;_dbname, $this-&gt;_uname, $this-&gt;_pass);\n $this-&gt;_pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n } catch (PDOException $e) {\n //$this-&gt;handleFatalErr($e-&gt;getMessage(), 'connection'); // 'die' error handling\n //$this-&gt;handleErr($e-&gt;getMessage(), 'connection'); // Non-'die' error handling\n }\n}\n</code></pre>\n\n<p>In each function I check the connection, I would recommend something similar. You could either kill the script if there is no connection or you could re-connect using the current variables <code>$this-&gt;_host</code>, etc:</p>\n\n<pre><code>public function query($sql) {\n $this-&gt;checkConnection();\n $this-&gt;_sql = $sql; // This is used for logging and for a getter function\n try {\n $this-&gt;_result = $this-&gt;_pdo-&gt;query($this-&gt;_sql);\n } catch (PDOException $e) {\n //$this-&gt;handleFatalErr($e-&gt;getMessage(), 'connection');\n }\n}\n\nprivate function checkConnection() {\n ($this-&gt;getPDO() === null) ? die('There is no connection to the database, please re-establish connection.') : NULL;\n //$this-&gt;handleFatalErr(self::ERR_CONNECTION_LOST, 'CONNECTION_LOST');\n}\n\nprivate function getPDO() {\n return $this-&gt;_pdo;\n}\n\npublic function close() {\n (isset($this-&gt;_pdo) &amp;&amp; $this-&gt;_pdo != null) ? $this-&gt;_pdo = null : NULL;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:34:51.980", "Id": "24107", "ParentId": "24104", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:56:44.260", "Id": "24104", "Score": "2", "Tags": [ "php", "classes", "pdo" ], "Title": "PDO database class review" }
24104
<p>the requirement for our search query is to look for all search words in the beginning of vehicle manufacturer, model and variant name. Case insensitive. The word being a string of characters separated by space.</p> <p>E.g. when search for "AU A3 TDI" you would find a vehicle with the following attributes: <code>Vehicle { ManufacturerName = "Audi", ModelName = "A3", Name = "2.0L TDI" }</code></p> <p>...but would <code>not</code> return this vehicle: <code>Vehicle { ManufacturerName = "Renault", ModelName = "A3", Name = "2.0L TDI" }</code> because no words start with <code>au</code>.</p> <p>I'm using specification with LINQ Expression and the code I wrote works fine and is tested however I believe it smells a bit. It's not very readable IMHO but most importantly, there might be a clear performance improvement you could point out?</p> <pre><code>public string[] SearchTerms = searchText.Split(); Expression&lt;Func&lt;SearchVehicleVariant, bool&gt;&gt; expression = c =&gt; SearchTerms.All( s =&gt; string.Format( " {0} {1} {2}", c.ManufacturerName != null ? c.ManufacturerName.ToUpper() : string.Empty, c.ModelName != null ? c.ModelName.ToUpper() : string.Empty, c.Name != null ? c.Name.ToUpper() : string.Empty).Contains( string.Concat(" ", s.Trim().ToUpper()))); </code></pre>
[]
[ { "body": "<p>I'm not entirely sure how your second example fails to match, because the string <code>\"Renault A3 2.0L TDI\"</code> contains all of \"AU\", \"A3\", and \"2.0\".</p>\n\n<p>That being said, here's an attempt at a cleaner rewrite:</p>\n\n<pre><code>Expression&lt;Func&lt;SearchVehicleVariant, bool&gt;&gt; expression = \n c =&gt; SearchTerms.Select(s =&gt; s.Trim())\n .All(s =&gt; \n TestField(c.ManufacturerName ?? \"\", s)\n || TestField(c.ModelName ?? \"\", s)\n || TestField(c.Name ?? \"\", s)\n );\n\n// Helper function\nbool TestField(string field, string test)\n{\n return field.Split(' ').Any(x =&gt; x.StartsWith(s, StringComparison.InvariantCultureIgnoreCase);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:08:41.113", "Id": "37237", "Score": "1", "body": "\"AU\" must be in the beginning of any word in the ManufactuerName || ModelName || Name" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T13:47:32.243", "Id": "37246", "Score": "0", "body": "@Chuck - Ah, there could be multiple words in each field? That wasn't clear from your example. Edited." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:43:42.680", "Id": "24115", "ParentId": "24111", "Score": "1" } }, { "body": "<p>Given your requirements, it seems you would be best using <a href=\"http://msdn.microsoft.com/en-us/library/ms131452.aspx\" rel=\"nofollow\">String.StartsWith</a> and a <code>StringComparison</code> value which ignores case (i.e., <code>CurrentCultureIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>OrdinalIgnoreCase</code>). This should be a little cleaner and faster than doing case conversions.</p>\n\n<pre><code>Expression&lt;Func&lt;SearchVehicleVariant, bool&gt;&gt; expression = \n c =&gt; SearchTerms.All (\n (c.ManufacturerName ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase)\n || (c.ModelName ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase)\n || (c.Name ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:07:26.853", "Id": "37236", "Score": "0", "body": "thanks. sorry but this wouldn't fulfil my requirements. The search is done on every word, not just the first word of each of the attributes. I've modified the search criterion in my q to make it clearer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:00:24.373", "Id": "24117", "ParentId": "24111", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:46:16.027", "Id": "24111", "Score": "6", "Tags": [ "c#", ".net", "linq" ], "Title": "Left hand search in string" }
24111
<p>Can anyone help me optimize my code? I really don't know what to do about all the var rectangles and <code>var</code> colors.</p> <pre><code>package PO; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.text.Text; import javafx.scene.text.Font; import javafx.scene.shape.Rectangle; import javafx.scene.paint.Color; import javafx.scene.control.Button; var rectangle1: Rectangle; var rectangle2: Rectangle; var rectangle3: Rectangle; var rectangle4: Rectangle; var rectangle5: Rectangle; var rectangle6: Rectangle; var rectangle7: Rectangle; var rectangle8: Rectangle; var rectangle9: Rectangle; var rectangle10: Rectangle; var rectangle11: Rectangle; var rectangle12: Rectangle; var rectangle13: Rectangle; var rectangle14: Rectangle; var rectangle15: Rectangle; var rectangle16: Rectangle; var kleur1 = "red"; var kleur2 = "red"; var kleur3 = "red"; var kleur4 = "red"; var kleur5 = "red"; var kleur6 = "red"; var kleur7 = "red"; var kleur8 = "red"; var kleur9 = "red"; var kleur10 = "red"; var kleur11 = "red"; var kleur12 = "red"; var kleur13 = "red"; var kleur14 = "red"; var kleur15 = "red"; var kleur16 = "red"; var tekst = "beginnen maar"; var aantalclicks = 0; var kaartkeuze = ["",""]; var scene: Scene; var button: Button; function KaartControle (){ if (aantalclicks == 2){ if(kaartkeuze [0] == kaartkeuze[1]){ tekst = "goed bezig!"; aantalclicks = 0; } } else if (aantalclicks == 3) { tekst = "jammer!"; kleur1 = "red"; kleur2 = "red"; kleur3 = "red"; kleur4 = "red"; kleur5 = "red"; kleur6 = "red"; kleur7 = "red"; kleur8 = "red"; kleur9 = "red"; kleur10 = "red"; kleur11 = "red"; kleur12 = "red"; kleur13 = "red"; kleur14 = "red"; kleur15 = "red"; kleur16 = "red"; aantalclicks = 0; } } Stage { title: "Memory" scene: Scene { width: 500 height: 300 content: [ Text { font: Font { size: 16 } x: 10 y: 30 content: bind tekst; } button = Button { translateX: 300 translateY: 150 text: "reset" visible: true action: function() { kleur1 = "red"; kleur2 = "red"; kleur3 = "red"; kleur4 = "red"; kleur5 = "red"; kleur6 = "red"; kleur7 = "red"; kleur8 = "red"; kleur9 = "red"; kleur10 = "red"; kleur11 = "red"; kleur12 = "red"; kleur13 = "red"; kleur14 = "red"; kleur15 = "red"; kleur16 = "red"; aantalclicks = 0; } } //Kaart 1 rectangle1 = Rectangle { width: 50 height: 50 x: 10 y: 50 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur1) onMouseClicked: function(event) { if (kleur1 == "red"){ kleur1 = "green"; kaartkeuze[aantalclicks]="1"; aantalclicks ++; KaartControle() } } } //Kaart 2 rectangle2 = Rectangle { width: 50 height: 50 x: 10 y: 110 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur2) onMouseClicked: function(event) { if (kleur2 == "red"){ kleur2 = "green"; kaartkeuze[aantalclicks]="1"; aantalclicks ++; KaartControle() } } } //Kaart 3 rectangle3 = Rectangle { width: 50 height: 50 x: 10 y: 170 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur3) onMouseClicked: function(event) { if (kleur3 == "red"){ kleur3 = "blue"; kaartkeuze[aantalclicks]="2"; aantalclicks ++; KaartControle() } } } //Kaart 4 rectangle4 = Rectangle { width: 50 height: 50 x: 10 y: 230 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur4) onMouseClicked: function(event) { if (kleur4 == "red"){ kleur4 = "blue"; kaartkeuze[aantalclicks]="2"; aantalclicks ++; KaartControle() } } } //Kaart 5 rectangle5 = Rectangle { width: 50 height: 50 x: 70 y: 50 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur5) onMouseClicked: function(event) { if (kleur5 == "red"){ kleur5 = "yellow"; kaartkeuze[aantalclicks]="3"; aantalclicks ++; KaartControle() } } } //Kaart 6 rectangle6 = Rectangle { width: 50 height: 50 x: 70 y: 110 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur6) onMouseClicked: function(event) { if (kleur6 == "red"){ kleur6 = "yellow"; kaartkeuze[aantalclicks]="3"; aantalclicks ++; KaartControle() } } } //Kaart 7 rectangle7 = Rectangle { width: 50 height: 50 x: 70 y: 170 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur7) onMouseClicked: function(event) { if (kleur7 == "red"){ kleur7 = "purple"; kaartkeuze[aantalclicks]="4"; aantalclicks ++; KaartControle() } } } //Kaart 8 rectangle8 = Rectangle { width: 50 height: 50 x: 70 y: 230 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur8) onMouseClicked: function(event) { if (kleur8 == "red"){ kleur8 = "purple"; kaartkeuze[aantalclicks]="4"; aantalclicks ++; KaartControle() } } } //Kaart 9 rectangle9 = Rectangle { width: 50 height: 50 x: 130 y: 50 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur9) onMouseClicked: function(event) { if (kleur9 == "red"){ kleur9 = "grey"; kaartkeuze[aantalclicks]="5"; aantalclicks ++; KaartControle() } } } //Kaart 10 rectangle10 = Rectangle { width: 50 height: 50 x: 130 y: 110 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur10) onMouseClicked: function(event) { if (kleur10 == "red"){ kleur10 = "grey"; kaartkeuze[aantalclicks]="5"; aantalclicks ++; KaartControle() } } } //Kaart 11 rectangle11 = Rectangle { width: 50 height: 50 x: 130 y: 170 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur11) onMouseClicked: function(event) { if (kleur11 == "red"){ kleur11 = "pink"; kaartkeuze[aantalclicks]="6"; aantalclicks ++; KaartControle() } } } //Kaart 12 rectangle12 = Rectangle { width: 50 height: 50 x: 130 y: 230 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur12) onMouseClicked: function(event) { if (kleur12 == "red"){ kleur12 = "pink"; kaartkeuze[aantalclicks]="6"; aantalclicks ++; KaartControle() } } } //Kaart 13 rectangle13 = Rectangle { width: 50 height: 50 x: 190 y: 50 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur13) onMouseClicked: function(event) { if (kleur13 == "red"){ kleur13 = "orange"; kaartkeuze[aantalclicks]="7"; aantalclicks ++; KaartControle() } } } //Kaart 14 rectangle14 = Rectangle { width: 50 height: 50 x: 190 y: 110 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur14) onMouseClicked: function(event) { if (kleur14 == "red"){ kleur14 = "orange"; kaartkeuze[aantalclicks]="7"; aantalclicks ++; KaartControle() } } } //Kaart 15 rectangle15 = Rectangle { width: 50 height: 50 x: 190 y: 170 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur15) onMouseClicked: function(event) { if (kleur15 == "red"){ kleur15 = "black"; kaartkeuze[aantalclicks]="8"; aantalclicks ++; KaartControle() } } } //Kaart 16 rectangle16 = Rectangle { width: 50 height: 50 x: 190 y: 230 arcWidth: 10 arcHeight: 10 fill: bind Color.web(kleur16) onMouseClicked: function(event) { if (kleur16 == "red"){ kleur16 = "black"; kaartkeuze[aantalclicks]="8"; aantalclicks ++; KaartControle() } } } ] } } </code></pre>
[]
[ { "body": "<p>You could reduce a some of your code by declaring your Rectangles and colors (kleur) as arrays. Then you could initialize (or reset) the kleur array elements within a loop.</p>\n\n<p>For example:\nInstead of </p>\n\n<pre><code>var rectangle1: Rectangle;\nvar rectangle2: Rectangle;\nvar rectangle3: Rectangle;\nvar rectangle4: Rectangle;\n//...\n</code></pre>\n\n<p>try</p>\n\n<pre><code>var rectangle[16]: Rectangle;\n</code></pre>\n\n<p>and instead of</p>\n\n<pre><code>var kleur1 = \"red\";\nvar kleur2 = \"red\";\nvar kleur3 = \"red\";\n//...\n</code></pre>\n\n<p>try</p>\n\n<pre><code>var kleur[16];\nvar x;\nfor (x=0; x&lt;16; x++)\n kleur[x] = \"red\";\n</code></pre>\n\n<p>Then, wherever you say</p>\n\n<pre><code>kleur1\n</code></pre>\n\n<p>you can say</p>\n\n<pre><code>kleur[1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T11:48:50.000", "Id": "37242", "Score": "0", "body": "Can you tell me how i should do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:33:56.760", "Id": "37258", "Score": "0", "body": "Okay. I added a few code examples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:22:10.410", "Id": "37268", "Score": "0", "body": "thank you :), but now it keeps telling me i forgot the ';' but it's there, exactly like you did" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:51:59.127", "Id": "37272", "Score": "0", "body": "Could you please post your revised code above (as a revision to the original code)? I'll see if I can spot the missing semicolon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:10:06.430", "Id": "37277", "Score": "0", "body": "I did, but only changed the var's, not rest of the code, because there were '!' signs all the time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:18:46.433", "Id": "37281", "Score": "0", "body": "You also need to replace each kleur1 with kleur[1] and kleur2 with kleur[2], etc. Same with rectangle1, etc" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T19:33:05.800", "Id": "24123", "ParentId": "24112", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:48:44.410", "Id": "24112", "Score": "1", "Tags": [ "javascript", "optimization", "game" ], "Title": "Optimizing memory game" }
24112
<p>Please could you review and critic my code and logic? Is this is along the right lines of an MVC application class or not?</p> <pre><code>namespace dh_mvc2; use dh_mvc2\dispatchers\Base_Dispatcher; use dh_mvc2\routers\Base_Router; use dh_mvc2\autoloaders\Basic_Autoloader; use dh_mvc2\classes\Config; class Application { protected $_config; protected $_autoloader; protected $_app_path; protected $_framework_path; protected $_router; protected $_dispatcher; /** * * @param string $app_path * "path/to/application/directory"; * @throws \DH_MVC2_Application_Exeption */ public function __construct($app_path, $run = TRUE) { if (! is_dir ( $app_path )) { require_once 'exeptions/DH_MVC2_Application_Exeption.php'; throw new \DH_MVC2_Application_Exeption ( "Must supply a path to an application directory" ); } $this-&gt;_framework_path = realpath ( dirname ( __DIR__ ) ); $this-&gt;_app_path = $app_path; $this-&gt;set_ini_default_paths (); $this-&gt;init (); if ($run) { $this-&gt;run (); } } /** * add the framework dir and application dir to include path */ private function set_ini_default_paths() { $paths = explode ( PATH_SEPARATOR, get_include_path () ); if (array_search ( $this-&gt;_app_path, $paths ) === false) { array_push ( $paths, $this-&gt;_app_path ); } if (array_search ( $this-&gt;_framework_path, $paths ) === false) { array_push ( $paths, $this-&gt;_framework_path ); } set_include_path ( implode ( PATH_SEPARATOR, $paths ) ); spl_autoload_register (); } /** * links to the app and framework default config files and inits them * registers autoloader */ private function init() { $config_file = '/config/config.ini.php'; $config_files ['DH_MVC'] = __DIR__ . $config_file; //framework config $config_files ['APP'] = $this-&gt;_app_path . $config_file; //app config $this-&gt;_config = new Config ( $config_files ); $config_paths = $this-&gt;_config-&gt;get_paths (); $this-&gt;_autoloader = new Basic_Autoloader ( $config_paths ); } /** * creates new base router instance which reads the url request and routes * application onto Action Controllers */ public function run() { $this-&gt;_router = new Base_router ( $this-&gt;_config ); $route = $this-&gt;_router-&gt;run (); if ($route) { $this-&gt;_dispatcher = new Base_Dispatcher ( $route ); $this-&gt;_dispatcher-&gt;run (); } } } </code></pre> <p>Not moved the initialization of new router to construct in order to remove protected <code>$_config</code> as I might use this attribute depending on how I develop the class. If not used I will remove.</p> <pre><code>$config_files ['DH_MVC'] = __DIR__ . $config_file; </code></pre> <p>It uses <code>__DIR__</code> as <code>$_framework_path</code> is parent of <strong>DIR</strong>. $_framework_path takes into account my namespace dh_mvc2 thats used as the first directory, by the spl_autoload, from the framework basepath</p> <pre><code>namespace dh_mvc2\application; use dh_mvc2\classes\Config; use dh_mvc2\dispatchers\Base_Dispatcher; use dh_mvc2\routers\Base_Router; use dh_mvc2\autoloaders\Basic_Autoloader; class Application { protected $_config; protected $_autoloader; protected $_app_path; protected $_framework_path; protected $_router; protected $_dispatcher; /** * * @param string $app_path * "path/to/application/directory"; * @throws \DH_MVC2_Application_Exeption */ public function __construct($app_path, $run = TRUE) { if (! is_dir ( $app_path )) { require_once 'exeptions/DH_MVC2_Application_Exeption.php'; throw new \DH_MVC2_Application_Exeption ( "Must supply a path to an application directory" ); } $this-&gt;_framework_path = realpath ( dirname ( __DIR__ ) ); $this-&gt;_app_path = $app_path; $this-&gt;set_ini_default_paths (); $this-&gt;init (); $d = new Config (); if ($run) { $this-&gt;run (); } } /** * add the framework dir and application dir to include path */ private function set_ini_default_paths() { spl_autoload_register (); $paths = explode ( PATH_SEPARATOR, get_include_path () ); array_push ( $paths, $this-&gt;_app_path ); array_push ( $paths, $this-&gt;_framework_path ); $paths = array_unique ( $paths ); set_include_path ( implode ( PATH_SEPARATOR, $paths ) ); } /** * links to the app and framework default config files and inits them * registers autoloader */ private function init() { $config_file = '/config/config.ini.php'; $config_files ['DH_MVC'] = __DIR__ . $config_file; // framework config $config_files ['APP'] = $this-&gt;_app_path . $config_file; // app config $this-&gt;_config = new Config ( $config_files ); $config_paths = $this-&gt;_config-&gt;get_paths (); $this-&gt;_autoloader = new Basic_Autoloader ( $config_paths ); } /** * creates new base router instance which reads the url request and routes * application onto Action Controllers */ public function run() { $this-&gt;_router = new Base_router ( $this-&gt;_config ); $route = $this-&gt;_router-&gt;run (); if ($route) { $this-&gt;_dispatcher = new Base_Dispatcher ( $route ); $this-&gt;_dispatcher-&gt;run (); } else { require_once 'exeptions/DH_MVC2_Router_Exeption.php'; throw new \DH_MVC2_Router_Exeption ( "Failed to discover route" ); } } } </code></pre>
[]
[ { "body": "<p>this looks pretty good to me.</p>\n\n<p>Some thoughts for entertainment;</p>\n\n<ul>\n<li><p>If you created the router in init(), then _config would not be required any more as a protected property, one less private property</p></li>\n<li><p>There seems to be no error handling when <code>$this-&gt;_router-&gt;run ()</code> fails. </p></li>\n<li><p><code>set_ini_default_paths</code> violates DRY, but only once, have you considered just adding the paths and then calling <code>array_unique</code>. Not sure that is the right way to go, but it could be considered.</p></li>\n<li><p>_autoloader is nowhere used, and it is private. Seems pointless?</p></li>\n<li><p>Should <code>$config_files ['DH_MVC'] = __DIR__ . $config_file;</code> not use <code>$this-&gt;_framework_path</code> ?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:20:25.390", "Id": "37203", "Score": "0", "body": "Thanks Tom. The autoloader class registers an spl_autoload_register callback function that uses the conifg paths passed to its constructor. The call back function is one of the autoloaders own methods. Hopefully allowing me to inherit and override the autoload callback for other 'types' of autoloaders. If that all made sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:22:09.077", "Id": "37205", "Score": "0", "body": "your other points will be implemented now though. Well after looking at that array function to try fix the DRY issue" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:11:13.217", "Id": "24119", "ParentId": "24114", "Score": "2" } }, { "body": "<p>I have some criticism on details you didn't ask, but which should be addressed:</p>\n\n<h3>Autoloading</h3>\n\n<p>Make use of it! There is no need to make manual calls to <code>require_once()</code>.</p>\n\n<p>There even is a standard: <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">PSR-0</a>, which defines how you should structure your class and namespace names together with the directory and file structure. When I look at your code, I see some issues: Because the underscore was used as a separator before PHP got namespaces, it is considered a separation character in class names.</p>\n\n<h3>Namespaces</h3>\n\n<p>Make use of it! I cannot see a reason why the exception \\DH_MVC2_Application_Exeption is located in the root namespace, and not called \\dh_mvc2\\application\\Exception. It would be so much easier to simply <code>throw new Exception();</code> inside the \"\\dh_mvc2\\application\" namespace.</p>\n\n<h3>Whitespace and coding style</h3>\n\n<p>Endless debates might occur, but I really don't like yours. Especially the inconsistent placement of parentheses. Personally, I'd rather prefer not to use that much spaces, but if you really have to, use them everywhere. For example, if you want to find the function \"set_ini_default_paths\", and want to make sure not to find \"set_ini_default_paths_directory\", you'd search for \"set_ini_default_paths(\" - which will find only function definitions, but not usage. To find these, you'd have to search \"set_ini_default_paths (\".</p>\n\n<h3>Dependency injection</h3>\n\n<p>Doesn't take place. Objects are created inside your class. There is no way I would be able to change for example the Config object if I'd use your class, I must use yours. I even cannot change the config filename!</p>\n\n<h3>Include path</h3>\n\n<p>Be careful what you add here. If a PSR-0 autoloader is used, there is no need to add anything to the include path. In fact, you'll get a good amount of performance if you include as few directories as possible, preferably only \".\", to be able to include files with a relative path.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:22:20.540", "Id": "37308", "Score": "0", "body": "Thanks Sven. I'm kind of confused with the DI thing people keep mentioning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:25:44.593", "Id": "37309", "Score": "0", "body": "Zend framework for example (ignoring the code) needs its config and application configs defined a certain way right? ok admittedly you can define the config zend uses in one of several ways but still define to their framework standard? And also i may be mistaken but Zend also requires the config to be in a set place within dir structure and without checking, named to a set convention also?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:33:47.973", "Id": "37310", "Score": "0", "body": "Your comments about Namespaces and auto-loading though I understand. And currently trying to get both to work correctly without require/includes. My class would still be called DH_MVC2_Application_Exeption but located in the dir dh_mvc2\\application\\Exception right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T11:25:26.657", "Id": "37312", "Score": "0", "body": "Looking at zend again, with respect to configs. You can specify the path to config file, and can have one of several formats. So maybe i should allow for my config to be located anywhere. But i'm still confused as to why requiring-'coupling' my application class to use a 'known' config (and autoloader) is wrong. Am i missing something big here? Or could i write a config file/autoloader how i wanted and throw it at zend and other frameworks and they would happily use them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:45:35.947", "Id": "37319", "Score": "0", "body": "I think i figured out why I was struggling with auto-loading thanks to your link to the PSR-0. DH_MVC2_Application_Exception would work if my directory was DH/MVC2/Application/Exception but my root dir was DH_MVC2 which auto-loader resolves as DH/MVC2 (if i understand it right?). Thank you for that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:48:14.780", "Id": "37349", "Score": "0", "body": "Have a look at the code of \"public/index.php\" [here](http://framework.zend.com/manual/1.12/en/zend.application.quick-start.html) and realize that the full path to the application.ini file is passed to the Zend_Application object. This file can be located anywhere (I'd be able to pass \"/etc/zend/global_app_config.ini\" if I want to), and only because of convention it is usually located in \"config/application.ini\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:50:16.223", "Id": "37350", "Score": "0", "body": "And please do not look too closely at Zend Framework version 1. PHP and technology have improved dramatically since it's creation, and some examples used in this old version should rather be considered harmful today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:32:28.957", "Id": "37374", "Score": "0", "body": "This might well be where I'm going very wrong!! My zend studio version is old and I've been avoiding ZF2 simply because the thought of setting it up with the IDE scares me! But I think you may have figured out why I'm struggling. trying to mix new 'thoughts' while trying to mimic an old frameworks methodology... So bye bye ZF1 (if i can get 2 up and running!)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T00:24:12.017", "Id": "24180", "ParentId": "24114", "Score": "1" } } ]
{ "AcceptedAnswerId": "24119", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:39:44.920", "Id": "24114", "Score": "1", "Tags": [ "php", "object-oriented", "mvc", "url-routing" ], "Title": "MVC application class" }
24114
<p>For class, I was asked to write a (linear probing) hash table in Java. (I was also asked to write a linear-chaining hash table, which is why I named this one <code>HashtableB</code> as opposed to just <code>Hashtable</code>.) I'm think my code is correct, but please tell me if I've messed up.</p> <p>Primarily, though, my questions are:</p> <ul> <li>Is my style (e.g. naming conventions, whitespace, line length, etc.) correct?</li> <li>Do I have too few comments? Too many?</li> <li>I've heard about Javadocs. Should I be using that? What would that look like?</li> <li>Is my code clear and concise?</li> <li>Is correctly object-oriented (e.g., should I have getters and setters for Pair)?</li> <li>Am I using generics correctly?</li> <li>Should I only be importing the specific parts of the standard libraries, or is importing <code>java.utils.*</code> okay?</li> </ul> <p>The <code>ST&lt;K, V&gt;</code> interface is because I've written other symbol table implementations and wanted to be able to use/test them interchangeably.</p> <p><strong>HashtableB.java</strong></p> <pre><code>import java.util.*; import java.lang.reflect.Array; // A linear-probing hash table implementation public class HashtableB&lt;K, V&gt; implements ST&lt;K, V&gt; { private static final int MIN_CAP = 11; // The minimum size of the array; when smaller than this, no down-sizing will occur. private Pair[] arr; // The array holding all the key/value pairs private int size; // The current number of elements. private int cap; // Current capacity of the array. private double max; // determines how full the array can get before resizing occurs; default 1/2 private double min; // determines how empty the array can get before resizing occurs; default 3/4 private double set; // determines how full the array should be made when resizing; default 1/4 // Primary constructor. // Set determines how full the array should be made when resizing // Maximum determines how full the array can get before resizing occurs // Minimum determines how empty the array can get before resizing occurs public HashtableB(double maximum, double minimum, double set){ assert set &lt; maximum &amp;&amp; maximum &lt; 1; assert 0 &lt; minimum &amp;&amp; minimum &lt; set; size = 0; cap = MIN_CAP; max = maximum; min = minimum; this.set = set; arr = (Pair[]) Array.newInstance(Pair.class, cap); // Make the new array; } // Default the set-size ratio to 1/2 public HashtableB(double maximum, double minimum){ this(maximum, minimum, 0.5); } // Default the max-size ratio to 3/4 and the min-size ratio to 1/4. public HashtableB(){ this(0.75, 0.25); } // Get the given key. public V get(K key){ assert key != null; // Find the key. int i = hash(key) % cap; while(!key.equals(arr[i].k)){ i = (i+1) % cap; } return arr[i]==null? null : arr[i].v; // If there's nothing there, return null. Otherwise, return the value. } // Sets the given key to the given value. public void put(K key, V val){ assert key != null; int i = hash(key) % cap; while (arr[i]!=null &amp;&amp; !key.equals(arr[i].k)) { i = (i+1) % cap; } if(arr[i] == null) // If we are putting a new key in, increase the size. size++; arr[i] = new Pair(key, val); resize(); // If we need to resize, do so. } // A hash of the key. I used the absolute value of the key's hashcode so that I didn't get weird negative indices. private int hash(K key){ return Math.abs(key.hashCode()); } // Resize the array if necessary. private void resize(){ if(!((size&lt;cap*min &amp;&amp; cap&gt;MIN_CAP) || size&gt;cap*max)){ return; } int newcap = (int) (size/set); // The size of the new array @SuppressWarnings("unchecked") Pair[] a = (Pair[]) Array.newInstance(Pair.class, newcap); // Make the new array for(int j=0; j&lt;cap; j++){ Pair q = arr[j]; if(q==null) continue; int i = hash(q.k) % newcap; while (a[i]!=null &amp;&amp; !q.k.equals(a[i].k)) { i = (i+1) % newcap; // get next index } a[i] = q; } this.arr = a; this.cap = newcap; } // In here for development purposes only. public boolean checkSize(){ int x = 0; for(int i=0; i&lt;cap; i++){ if(arr[i] != null) x++; } return x == size; } // Return the number of elements currently contained in this hashtable. public int size(){ return size; } // Return a list of all the keys currently contained in this hashtable. public Set&lt;K&gt; getAll(){ Set&lt;K&gt; set = new HashSet&lt;K&gt;(size); for(Pair p : arr) if(p != null) set.add(p.k); return set; } // Remove the given key from the hashtable. public void delete(K key){ assert key != null; List&lt;Pair&gt; pairs = new ArrayList&lt;Pair&gt;(); // Find our key. int i = hash(key) % cap; while(arr[i]!=null &amp;&amp; !key.equals(arr[i].k)){ i = (i+1) % cap; if(arr[i] == null) System.out.printf("Delete could not find key %s %n", key.toString()); } // Remove all the keys that could have been "forced over" by this key. while(arr[i] != null){ pairs.add(arr[i]); arr[i] = null; size--; i = (i+1) % cap; } pairs.remove(0); // Remove the key we're deleting. for(Pair p : pairs) this.put(p.k, p.v); // Put the rest back in the hashtable. } public String toString(){ return String.format("Hashtable(%.2f, %.2f, %.2f)", max, min, set); } // A key-value pair. class Pair{ K k; V v; public Pair(K key, V val){ k = key; v = val; } } } </code></pre> <p><strong>ST.java</strong></p> <pre><code>import java.util.*; // Symbol table matching keys (of type K) with values (of type V). public interface ST&lt;K, V&gt; { V get(K key); // Get the value associated with the given key. void put(K key, V value); // Set the value associated with the given key. The key can be in the dictionary already or not. void delete(K key); // Remove the value associated with the given key (this should decrement the size). Set&lt;K&gt; getAll(); // Get all the keys in this symbol table. int size(); // Get the number of elements currently in the symbol table. boolean checkSize(); // For development only. Checks that the stored size and actual size match. } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:43:24.120", "Id": "37228", "Score": "1", "body": "Your IDE will likely generate skeleton javadoc for you (and actually, that belongs on the interface definition, for those methods). I can't speak to the rest of your implementation, but usually end-of-line comments are fairly worthless - they tend to just repeat what code does; comments should be for explaining _why_, really. `Pair` should be `private`, and probably immutable as well - don't worry about getters so much for this type of internal class." } ]
[ { "body": "<p>I highly recommend <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\"><em>Clean Code: A Handbook of Agile Software Craftsmanship</em></a> by Robert C. Martin. It's an excellent source of great advice precisely aimed at your questions. The earlier you start, the fewer bad habits you'll need to unlearn later on.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>Your line length and whitespace seem okay, though you a little off from Sun's (now Oracle's) <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\">Java Style Guide</a>. I always put whitespace around keywords (<code>if</code>, <code>while</code>) and between closing parentheses and opening braces.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Ignoring <code>HashtableB</code> and <code>ST</code> which you've already explained, I would get in the habit of using fully-spelled-out variable names now. They are clearer and help you practice your typing skills. There are a few abbreviations that everyone will understand such as <code>max</code> and <code>min</code>, but they don't make good names by themselves.</p>\n\n<ul>\n<li><code>arr</code>: Are you a pirate? <br/>\nInstead of naming the variable based on its type, name it for what it contains such as <code>elements</code> or <code>pairs</code>.</li>\n<li><code>cap</code>: Is this a baseball cap? <br/>\nSpell this out as <code>capacity</code>.</li>\n<li><code>max</code>: Maximum what? Speed? Value? <br/>\nGo for clarity with <code>maxSize</code>.</li>\n<li><code>resize</code>: Does this always resize? <br/>\nNo, thus your comment when calling it. Use <code>resizeIfNeeded</code> instead.</li>\n<li><code>getAll</code>: All what: keys or values? <br/>\nJava's <code>Map</code> interface defines <code>keySet</code> and <code>values</code>.</li>\n</ul>\n\n<p><strong>Comments</strong></p>\n\n<p>You can remove a lot of these extraneous comments simply by using more expressive names. One of the main problems with comments is that they aren't compiled or checked for correctness. They can flat out lie to you like \"Get the given key\" which actually returns the <em>value</em> for the given key. Comments like \"Find the key\" in a method that by it's name obviously looks for the given key don't add anything.</p>\n\n<p>99% of your comments should explain <em>why</em> you are doing something in a particular way when it's not obvious or trivial. If the code is so complicated that you can't tell what it does, rewrite it rather than adding a comment. In other words, avoid comments that merely translate the code into prose.</p>\n\n<p><strong>JavaDoc</strong></p>\n\n<p>Yes! It's never too early to build good habits, and they are very easy to write. Here's an example:</p>\n\n<pre><code>/**\n * Returns the value that is mapped to the given key.\n *\n * @param key the key to locate\n * @return the value mapped to {@code key} or {@code null} if not found\n */\npublic V get(K key) { ... }\n</code></pre>\n\n<p><strong>Clarity</strong></p>\n\n<p>For the most part your code is pretty clean. Once you make the names more expressive it would be pretty easy to see what it does. Here are a few points:</p>\n\n<ul>\n<li><p>You don't need reflection. Instead of <code>Array.newInstance</code> use <br/></p>\n\n<pre><code>Pair[] newItems = new Pair[newCapacity];\n</code></pre></li>\n<li>Consider implementing <code>java.util.Map</code> instead of creating your own <code>ST</code> interface. It has all the same methods as yours except <code>checkSize</code> which you can add just in your implementation as <code>hasCorrectSize</code>.</li>\n<li>Don't specify a size for <code>HashSet</code>. Most of the time you should let the libraries work it out.</li>\n<li>Using <code>ArrayList</code> in <code>delete</code> seems a little like cheating. ;)</li>\n</ul>\n\n<p><strong>OOP and Generics</strong></p>\n\n<p>The design looks pretty good, and your usage of generics looks correct.</p>\n\n<ul>\n<li><code>Pair</code> should be static since it doesn't need a reference to its enclosing hashtable. It should also be private unless you need it for testing.</li>\n<li>Since <code>Pair</code> is internal, I don't see a need for getters. You might want to make it immutable by creating a new one instead of overwriting the value, but again it's internal and won't matter in this case.</li>\n</ul>\n\n<p><strong>Importing Classes</strong></p>\n\n<p>I used to prefer to import each class separately (no <code>*</code>) so you can see at a glance what the class uses. However, as I focus more on creating smaller classes it's not such a big deal. I still do it, but I'm not anal about it like I used to be. Pick a style and stick to it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:32:56.413", "Id": "24132", "ParentId": "24116", "Score": "11" } }, { "body": "<p>In the <code>get</code> method in the <code>while</code> loop, are you not getting a NullPointerException? I believe you should be checking for <code>arr[i] != null</code>.</p>\n\n<p>Also, when you calculate a hash and the key you are looking for is not at that position, you move ahead to search for that key. To do that, why don't you use <code>i = (i+1) % cap</code>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T04:16:56.930", "Id": "45911", "ParentId": "24116", "Score": "0" } } ]
{ "AcceptedAnswerId": "24132", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:55:49.787", "Id": "24116", "Score": "11", "Tags": [ "java", "homework", "hash-map" ], "Title": "Hash table implementation in Java" }
24116
<p>I have the following markup, and I'm wondering how best to locate the nearest previous <code>dpicker</code> input element and give it focus with jQuery when <code>a.dpicon</code> is clicked.</p> <pre><code>&lt;div class="eight mobile-two columns"&gt; &lt;input autocomplete="off" class="dpicker" type="text" name="mdpdate" id="mdpdate"&gt; &lt;/div&gt; &lt;div class="one mobile-one columns"&gt; &lt;span class="postfix"&gt; &lt;a href="#" id="startdatecalicon" class="dpicon"&gt;&lt;i class="foundicon-calendar infoicon"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've used this, and it works, but it seems pretty cumbersome:</p> <pre><code>$(".dpicon").click(function(){ $(this).parent().parent().prev().children(".dpicker").focus(); }); </code></pre> <p>Also, there will be times that the 'dpicon' element will be before the input in markup, not after it. Is there a way to catch both instances?</p>
[]
[ { "body": "<p>I would make the link between the 2 implicit.</p>\n\n<p><code>&lt;a href=\"#mdpdate\" id=\"startdatecalicon\" class=\"dpicon\"&gt;</code></p>\n\n<p>Then the code is </p>\n\n<pre><code>$(\".dpicon\").click(function(){\n $( this.href ).focus()\n}\n</code></pre>\n\n<p>It is a creative (ab)use of href, but it still follows the spirit in my mind.</p>\n\n<p>If you have the luxury of going HTML5, you can go with a data attribute.</p>\n\n<p><code>&lt;a href=\"#\" id=\"startdatecalicon\" class=\"dpicon\" data-dpicker=\"#mdpdate\"&gt;</code></p>\n\n<p>Then the code is </p>\n\n<pre><code>$(\".dpicon\").click(function(){\n $( this.getAttribute( \"data-dpicker\" ) ).focus()\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:42:28.223", "Id": "37210", "Score": "1", "body": "+1 I definitely think the link between the two controls needs to be made explicit although I was thinking about using a data attribute - I like the inventive use of the href (but at the same time, I can't help thinking it's abusing it). :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:30:30.783", "Id": "37226", "Score": "0", "body": "Both good ideas thanks. I was trying for something that didn't require the existing inputs and links to have anything 'custom' about them (as the will be built dynamically by php) but using the ID like that will be fine! I think I'll use data-picker instead of href. Thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:24:07.490", "Id": "24120", "ParentId": "24118", "Score": "3" } } ]
{ "AcceptedAnswerId": "24120", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:03:51.160", "Id": "24118", "Score": "1", "Tags": [ "javascript", "jquery", "html" ], "Title": "Locating child of a nearby ancestor with jQuery" }
24118
<p>I am very new to JavaScript and was wondering what kind of process or design pattern is most common among JavaScript developers.</p> <p>So far I have following code</p> <h2><code>index.html</code></h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Interactive Guide&lt;/title&gt; &lt;!--------------------------CSS/ FONT ASSETS-------------------------&gt; &lt;link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'&gt; &lt;link href='//fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'&gt; &lt;link rel="stylesheet" type="text/css" href="CSS/mainStyle.css"&gt; &lt;!-------------------------------------------------------------------&gt; &lt;!----------------------------JAVASCRIPT ASSETS----------------------&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="./JavaScript/utilities.js"&gt;&lt;/script&gt; &lt;script src="./JavaScript/mainScript.js"&gt;&lt;/script&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;!--------------------------------------------------------------------&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrap"&gt; &lt;div class="upper"&gt; &lt;div id="heading1"&gt;Copyright and Plagiarism&lt;/div&gt; &lt;div id="time"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="content"&gt; &lt;canvas id="myCanvas" width="1024" height="550"&gt;Get support for canvas- go and get Chrome dude!&lt;/canvas&gt; &lt;!--&lt;div id="rect"&gt;&lt;/div&gt;--&gt; &lt;/div&gt; &lt;footer&gt; Ankur Sharma - Copyright 2013 &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h2><code>mainScript.js</code></h2> <pre><code>window.addEventListener('load', windowLoaded, false); function windowLoaded() { updateClock(); iniScene(); } function iniScene() { var canvas = getCanvas(); iniInterface(canvas.context, canvas.canvasH, canvas.canvasW); } </code></pre> <h2><code>utilities.js</code></h2> <pre><code>//---------------------------------UTILITY FUNCTIONS------------------------------ function getCanvas() { if(canvas) { return canvas; } else { var canvas = {}; canvas.node = document.getElementById("myCanvas"); canvas.context = canvas.node.getContext('2d'); canvas.canvasH = canvas.node.height || 500; canvas.canvasW = canvas.node.width || 800; return canvas; } } function iniInterface(ctx, canvasH, canvasW) { drawLine(ctx, 50, canvasH-50, canvasW-50, canvasH-50, 'rgb(255, 255, 255)', 'rgb(255, 255, 255)'); } //-------------------------------OBJECTS----------------------------// //-------------------------------DRAW FUNCTIONS---------------------// function drawLine(ctx, sX, sY, eX, eY, sRGB, fRGB, lWidth, capStyle) { ctx.beginPath(); ctx.moveTo(sX, sY); ctx.lineTo(eX, eY); ctx.lineWidth = lWidth||5; ctx.strokeStyle = 'rgb(49, 129, 48)'; ctx.lineCap = 'round'; ctx.stroke(); ctx.closePath(); } function loadImage(ctx, src, x, y, width, height) { var img = new Image(); img.onload = function() { ctx.drawImage(img, x, y, width, height); }; img.src = src; } //---------------------------------TIME---------------// function updateClock() { var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); var seconds = currentTime.getSeconds(); if(minutes&lt;10) { minutes = "0"+minutes; } if(seconds&lt;10) { seconds = "0"+seconds; } if(hours&lt;10) { hours = "0"+hours; } $("#time").html(hours + ":" + minutes + ":" + seconds); if(hours&gt;11) { $("#time").append(" PM"); } else { $("#time").append(" AM"); } setTimeout(updateClock, 1000); } </code></pre>
[]
[ { "body": "<p>First of all, your code's just fine as-is. Still, there are improvements that could be made.</p>\n\n<ol>\n<li><p>This isn't about the JavaScript, but the HTML: You're loading a lot of stuff twice for some reason. Both the google fonts and jQuery are loaded both as <code>//</code> and as <code>http://</code>. Only use the latter option: <code>http://</code>.<br>\nWhen the browser sees a URL starting with <code>//</code>, it'll simply reuse the protocol of the page. This is clever on a site that might be <code>http</code> or <code>https</code> since the browser will use the appropriate protocol. But it won't work if you're viewing the site directly on you own computer using a <code>file://</code> url, because the browser will try to find <code>file://fonts.googleapis.com/...</code> etc.. So just use the <code>http:</code> urls - they'll work fine everywhere.</p></li>\n<li><p>You've split the javascript into 2 files, but they're very dependent on each other. So if one file gets loaded, but the other one doesn't, it won't work. I'd put it all in a single file - especially as <code>mainScript.js</code> contains very little code.</p></li>\n<li><p>Since you're using jQuery, use it. In <code>mainScript.js</code> you're using <code>addEventListener</code> which won't work in all browsers - instead use jQuery's <code>.on()</code> which is cross-browser.<br>\nBetter yet, use jQuery's own shortcut by simply passing a function to <code>$()</code>:</p>\n\n<pre><code>$(function () {\n // code to call when the window has loaded\n});\n</code></pre></li>\n<li><p>Don't pollute the global scope. If you keep everything in one file, nothing needs to be in the global scope to be accessible. Instead use the code above, and put <em>everything</em> into that function. It'll all be nicely kept out of the global scope.</p></li>\n<li><p>Don't use the \"curly-brace on newline\" style in JavaScript. In other languages it's OK, but JavaScript will sometimes treat a linebreak as an end-of-line and <em>insert a semi-colon that it thinks you forgot</em>.<br>\nThis is obviously weird, but that's the way it is, unfortunately. See <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow\">Douglas Crockford's page</a> for more.</p></li>\n<li><p>Just a quick tip: Instead of checking for <code>x &lt; 10</code> to see if you need a leading zero, just add 2 zeros in front, and take the last 2 characters/digits of the resulting string:</p>\n\n<pre><code>function updateClock() {\n var currentTime = new Date(),\n hours = currentTime.getHours(),\n minutes = currentTime.getMinutes(),\n seconds = currentTime.getSeconds(),\n suffix = hours &gt; 11 ? \"PM\" : \"AM\";\n\n // internal helper function\n function pad(value) {\n return (\"00\" + value).slice(-2); // take the last 2 digits\n }\n\n $(\"#time\").text( pad(hours) + \":\" + pad(minutes) + \":\" + pad(seconds) + \" \" + suffix );\n\n setTimeout(updateClock, 1000);\n}\n</code></pre></li>\n</ol>\n\n<p>Technically, you should also subtract 11 from the hours, if you're using the AM/PM notation and it's PM. Saying that the time is \"23:14:20 PM\" is sort of redundant - of course it's PM.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:27:24.187", "Id": "37209", "Score": "0", "body": "wow! those were some great tips. Thanks very much. But one thing that I was really doubtful about was the way I have a function called drawLine with so many arguments. I am going to have more functions like this like drawCircle, drawRect etc. It might become a bit too much code, too many arguments. Is that okay or would it better to do something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:06:42.043", "Id": "37213", "Score": "1", "body": "@AnkurSharma You can have as many arguments as you want, but it can sometimes look and feel like too much. But for canvas-related stuff, it's difficult to avoid. The alternatives are to either just use the canvas drawing functions directly, or make ever-more specific functions, e.g. a `drawCenteredCricle()` which doesn't need position arguments. It can then call a more generic `drawCircle` function, which then calls the canvas functions, and so on. Personally, I'd probably set the colors using the native canvas API, and use the custom functions to just draw the shapes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:25:50.167", "Id": "37217", "Score": "0", "body": "Ok thanks very much. But I was thinking about the global scope that you mentioned. Are you saying that if I put a variable or function outside everything it is global, even if i declared it with a `var` keyword?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:34:27.603", "Id": "37218", "Score": "0", "body": "I have just put all my functions and everything withing the $(function(){}). But now I have to keep expanding this function forever, I feel like I cannot use a external file like utilities.js anymore because all the stuff has to be put in this function or else it will be global. Is is ok to feel so, is that how most JavaScript developers work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:34:33.203", "Id": "37219", "Score": "1", "body": "@AnkurSharma Yes, they'll be global. The `var` keyword basically means \"declare a variable in the current scope\", so if your current scope is the global scope (which it is, if you're \"outside everything\"), then that variable will naturally be global. The most common trick is to use an immediately-invoked anonymous function to create a scope: `(function () { ... your code }());`. Since it's anonymous, it won't itself end up in global scope. In your case, though, `$(function () {...});` will do the same trick; an anonymous function invoked on load instead of immediately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:41:22.450", "Id": "37220", "Score": "1", "body": "@AnkurSharma to have stuff available globally, it's best practice to create a namespace for your code, and only let that be global. Start each file with `window.myNamespace || (window.myNamespace = {});` to create the `myNamespace` object if it's missing. Then add functions to that: `myNamespace.drawSomething = function () { ... };` or `myNamespace.someVar = 42;`. Then you can access it anywhere \"through\" the `myNamespace` namespace. See [this answer](http://stackoverflow.com/a/9254330/167996) for more (it's about CoffeeScript, but the strategy is the same)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:44:42.607", "Id": "37221", "Score": "0", "body": "Thanks. Just brilliant. One of the most helpful answers I have ever read. Clears up more doubts than I would have done by reading tutorials or books. +10000000 . This namespace technique looks great. Thanks very much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:52:12.160", "Id": "37222", "Score": "0", "body": "@AnkurSharma No problem. Thanks for the kind words :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:13:34.740", "Id": "24124", "ParentId": "24121", "Score": "2" } } ]
{ "AcceptedAnswerId": "24124", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:43:19.183", "Id": "24121", "Score": "0", "Tags": [ "javascript", "datetime", "image", "canvas" ], "Title": "Updating clock with Canvas" }
24121
<p>A large .csv file I was given has a large table of flight data. A function I wrote to help parse it iterates over the column of Flight IDs, and then returns a dictionary containing the index and value of every unique Flight ID in order of first appearance.</p> <pre><code>Dictionary = { Index: FID, ... } </code></pre> <p>This comes as a quick adjustment to an older function that didn't require having to worry about <code>FID</code> repeats in the column (a few hundred thousand rows later...).</p> <p>Example:</p> <pre><code>20110117559515, ... 20110117559515, ... 20110117559515, ... 20110117559572, ... 20110117559572, ... 20110117559572, ... 20110117559574, ... 20110117559587, ... 20110117559588, ... </code></pre> <p>and so on for 5.3 million some rows.</p> <p>Right now, I have it iterating over and comparing each value in order. If a unique value appears, it only stores the first occurrence in the dictionary. I changed it to now also check if that value has already occurred before, and if so, to skip it.</p> <pre><code>def DiscoverEarliestIndex(self, number): result = {} columnvalues = self.column(number) column_enum = {} for a, b in enumerate(columnvalues): column_enum[a] = b i = 0 while i &lt; (len(columnvalues) - 1): next = column_enum[i+1] if columnvalues[i] == next: i += 1 else: if next in result.values(): i += 1 continue else: result[i+1]= next i += 1 else: return result </code></pre> <p>It's very inefficient, and slows down as the dictionary grows. The column has 5.2 million rows, so it's obviously not a good idea to handle this much with Python, but I'm stuck with it for now.</p> <p>Is there a more efficient way to write this function?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:20:04.877", "Id": "37238", "Score": "0", "body": "You are not always retrieving the first occurrence because \"If a value is equal to the value after it, it skips it.\"" } ]
[ { "body": "<p>One thing that slows you down is <code>if next in thegoodshit.values()</code> because it has to iterate through the values.</p>\n\n<p>A simple way to eliminate duplicate values is to first construct a dictionary where values are the key:</p>\n\n<pre><code>unique_vals = {val: i for i, val in enumerate(columnvalues)}\nreturn {i: val for val, i in unique_vals.iteritems()}\n</code></pre>\n\n<p>If there are duplicates, this will give the last index of each value, because duplicates get overwritten in the construction of <code>unique_vals</code>. To get the first index instead, iterate in reverse:</p>\n\n<pre><code>unique_vals = {val: i for i, val in reversed(list(enumerate(columnvalues)))}\nreturn {i: val for val, i in unique_vals.iteritems()}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T10:08:15.517", "Id": "24148", "ParentId": "24126", "Score": "2" } }, { "body": "<p>You've given us a small piece of your problem to review, and <a href=\"https://codereview.stackexchange.com/a/24148/11728\">Janne's suggestion</a> seems reasonable if that piece is considered on its own. But I have the feeling that this isn't the only bit of analysis that you are doing on your data, and if so, you probably want to think about using a proper database.</p>\n\n<p>Python comes with a built-in relational database engine in the form of the <a href=\"http://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow noreferrer\"><code>sqlite3</code> module</a>. So you could easily read your CSV directly into a SQLite table, either using the <code>.import</code> command in SQLite's command-line shell, or via Python if you need more preprocessing:</p>\n\n<pre><code>import sqlite3\nimport csv\n\ndef load_flight_csv(db_filename, csv_filename):\n \"\"\"\n Load flight data from `csv_filename` into the SQLite database in\n `db_filename`.\n \"\"\"\n with sqlite3.connect(db_filename) as conn, open(csv_filename, 'rb') as f:\n c = conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS flight\n (id INTEGER PRIMARY KEY AUTOINCREMENT, fid TEXT)''')\n c.execute('''CREATE INDEX IF NOT EXISTS flight_fid ON flight (fid)''')\n c.executemany('''INSERT INTO flight (fid) VALUES (?)''', csv.reader(f))\n conn.commit()\n</code></pre>\n\n<p>(Obviously you'd need more fields in the <code>CREATE TABLE</code> statement, but since you didn't show them in your question, I can't guess what they might be.)</p>\n\n<p>And then you can analyze the data by issuing SQL queries:</p>\n\n<pre><code>&gt;&gt;&gt; db = 'flight.db'\n&gt;&gt;&gt; load_flight_csv(db, 'flight.csv')\n&gt;&gt;&gt; conn = sqlite3.connect(db)\n&gt;&gt;&gt; from pprint import pprint\n&gt;&gt;&gt; pprint(conn.execute('''SELECT MIN(id), fid FROM flight GROUP BY fid''').fetchall())\n[(1, u'20110117559515'),\n (4, u'20110117559572'),\n (7, u'20110117559574'),\n (8, u'20110117559587'),\n (9, u'20110117559588')]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:26:57.540", "Id": "37253", "Score": "0", "body": "Great example, sorry for skipping out on a csv information. I didn't have a good way to illustrate 41 columns by 5.3 million rows in a csv of mixed integers and strings. I've looking for an example like this, I'm still getting used to sqlite3 syntax. Upvoting as soon as I have enough rep." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T12:00:59.990", "Id": "24156", "ParentId": "24126", "Score": "3" } }, { "body": "<p>So here is what I came up with, now that I had access to a computer:</p>\n\n<p>raw_data.csv:</p>\n\n<pre><code>20110117559515,1,10,faa\n20110117559515,2,20,bar\n20110117559515,3,30,baz\n20110117559572,4,40,fii\n20110117559572,5,50,bir\n20110117559572,6,60,biz\n20110117559574,7,70,foo\n20110117559587,8,80,bor\n20110117559588,9,90,boz\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>import csv\nfrom collections import defaultdict\nfrom pprint import pprint\nimport timeit\n\n\ndef method1():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = cols[0].index(x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method2():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = next(index for index,fid in enumerate(cols[0]) if fid == x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method3():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n indexes = [cols[0].index(x) for x in set(cols[0])]\n\n for index in indexes:\n yield (index,rows[index])\n\n\nif __name__ == '__main__':\n\n results = method1() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = method2() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = dict(method3())\n print 'indexed:'\n pprint(results)\n\n #--- Timeit ---\n\n print 'method1:', timeit.timeit('dict(method1())', setup=\"from __main__ import method1\", number=10000)\n print 'method2:', timeit.timeit('dict(method2())', setup=\"from __main__ import method2\", number=10000)\n print 'method3:', timeit.timeit('dict(method3())', setup=\"from __main__ import method3\", number=10000)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>indexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n\nmethod1: 0.283623933792\nmethod2: 0.37960600853\nmethod3: 0.293814182281\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:59:54.303", "Id": "37351", "Score": "0", "body": "An issue with this script, it's sucking up a TON of memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:26:45.067", "Id": "37373", "Score": "0", "body": "Tried with 2 other methods, but it looks like the initial one is still the fastest.\nPlease compare which is the best in terms of memory consumption on runtime, using your big data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:29:04.500", "Id": "37401", "Score": "0", "body": "FYI I tried to implement an 100% python way of solving your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:15:10.837", "Id": "24170", "ParentId": "24126", "Score": "1" } } ]
{ "AcceptedAnswerId": "24170", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:40:52.533", "Id": "24126", "Score": "3", "Tags": [ "python", "performance", "parsing", "csv", "iteration" ], "Title": "Retrieving the first occurrence of every unique value from a CSV column" }
24126
<p>Go, commonly referred to as "golang", is a fast, statically typed, compiled language created by Google. The language was initially developed as an alternative to C++ for server infrastructure and has native support for concurrency.</p> <h3>See also</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Go_%28programming_language%29" rel="nofollow">Wikipedia page</a></li> <li><a href="https://golang.org/" rel="nofollow">Official website</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:00:56.223", "Id": "24128", "Score": "0", "Tags": null, "Title": null }
24128
Go, commonly referred to as "golang", is a fast, statically typed, compiled language created by Google. The language was initially developed as an alternative to C++ for server infrastructure and has native support for concurrency.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T21:00:56.223", "Id": "24129", "Score": "0", "Tags": null, "Title": null }
24129
<p>I'm trying to solve a graph traversal problem I found, and was wondering how I could improve my implementation. Currently it seems a little convoluted and long. </p> <p>The problem is as follows: I have a matrix of size (rows x cols). This matrix has some cells that are empty (designated by a 0) and some cells that are blocked off (designated by a 1). Given a length, I would like to find a consecutive set of empty cells (ie, a path) of size length.</p> <p>For this specific code instance, I actually hardcoded the matrix, as well as the length. My approach was:</p> <ul> <li>to loop through the matrix;</li> <li>at each position try to find a path, if that position was empty and not yet visited;</li> <li>if so, then find all adjacent positions that fit the same condition (ie, empty and not visited);</li> <li>if adjacent positions exist, continue finding further adjacent positions until my path is complete in size;</li> <li>if a path is not possible, then print "impossible".</li> </ul> <p>My code is as follows:</p> <pre><code>def positionInGraph(pos): return ((pos[0] &gt;= 0) and (pos[1] &gt;= 0)) and ((pos[0] &lt; rows) and (pos[1] &lt; cols)) def positionNotVisited(pos): return not(pos in visited) def positionIsEmpty(pos): return (graph[pos[0]][pos[1]]==0) def getAdjacent(posx, posy): adjQueue = [(posx-1,posy), (posx, posy+1), (posx+1, posy), (posx, posy-1)] for i in adjQueue: if (positionInGraph(i) and positionNotVisited(i) and positionIsEmpty(i)): yield i def getOnePath(pos): counter = 0 pathList = [] processQueue = [] if (not(positionIsEmpty(pos)) or (pos in visited)): return (pathList, counter) else: processQueue.append(pos) while (processQueue and (counter &lt; length)): currentPos = processQueue.pop() visited.add(currentPos) pathList.append(currentPos) counter = counter + 1 adjQueue = getAdjacent(currentPos[0],currentPos[1]) if (not(adjQueue) and counter &lt; length): pathList.pop(currentPos) counter -= 1 for i in adjQueue: processQueue.append(i) print pathList return (pathList, counter) def findFinalPath(): #5 4 8 # oxoo # xoxo # ooxo # xooo # oxox for i in xrange(0,rows): for j in xrange(0,cols): path = getOnePath((i,j)) if path[1] == length: return path[0] return "impossible" visited = set() graph = [[0,1,0,0],[1,0,1,0],[0,0,1,0],[1,0,0,0],[0,1,0,1]] rows = 5 cols = 4 length = 8 findFinalPath() </code></pre>
[]
[ { "body": "<h3>1. Bug</h3>\n\n<p>I tried a different test case:</p>\n\n<pre><code>graph = [[1, 0, 0, 0, 1], [1, 1, 0, 1, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 0, 0, 0, 0]]\nrows = 5\ncols = 5\nlength = 8\n</code></pre>\n\n<p>and then <code>findFinalPath</code> returned the following path:</p>\n\n<pre><code>[(0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0), (3, 2), (4, 2)]\n</code></pre>\n\n<p>This is not a legal path, since (2, 0) is not adjacent to (3, 2).</p>\n\n<p>I give an explanation for this bug in 2.18 below, but it would be a good exercise to for you to try to figure out for yourself what's going wrong here. How does your search manage to step from (2, 0) to (3, 2)?</p>\n\n<h3>2. Comments on your code</h3>\n\n<ol>\n<li><p>No docstrings! What do your functions do, and how do you call them?</p></li>\n<li><p>This kind of program is an excellent candidate for <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p></li>\n<li><p>The use of global variables makes your code difficult to re-use. For example, the global variable <code>graph</code> means that it would be awkward if you ever wanted to find paths in two different graphs.</p>\n\n<p>When you have persistent state (like your graph) with associated operations (like your function <code>positionInGraph</code>) it's often a good idea to organize your code into <a href=\"http://docs.python.org/3/tutorial/classes.html\" rel=\"nofollow\">classes and methods</a> respectively. See section 3 below for how I would do this in your case.</p></li>\n<li><p>You don't guard the execution of the test program with <a href=\"http://docs.python.org/3/library/__main__.html\" rel=\"nofollow\"><code>if __name__ == __main__:</code></a>. This means that when I import your program into an interactive Python interpreter, it immediately starts running, which makes it harder for me to test. Put your test code into test functions or doctests.</p></li>\n<li><p>Returning the string <code>\"impossible\"</code> when no path is found isn't the best way to design the interface. Returning an exceptional value to indicate failure tends to be error-prone: it's too easy for the caller to forget to check. It's usually better to <a href=\"http://docs.python.org/3/tutorial/errors.html\" rel=\"nofollow\">raise an exception</a> when exceptional circumstances are encountered.</p></li>\n<li><p>You represent your coordinates as a pair (<em>y</em>, <em>x</em>). It would be slightly easier to understand the output of your program if you represented coordinates in the usual way (<em>x</em>, <em>y</em>). This would of course require a corresponding change, either looking up cells with <code>graph[pos[1]][pos[0]]</code> (preferred) or transposing your matrix so that it is in column-major order.</p></li>\n<li><p>You set the number of rows and columns by hand but these numbers are easy to determine: they are <code>len(graph)</code> and <code>len(graph[0])</code> respectively. (I prefer to call these numbers <em>height</em> and <em>width</em> myself.)</p></li>\n<li><p>Your functions <code>positionInGraph</code>, <code>positionNotVisited</code> and <code>positionIsEmpty</code> all take a <code>pos</code> as their argument, but <code>getAdjacent</code> takes two arguments <code>posx</code> and <code>posy</code> (which are wrongly named: <code>posx</code> is the y-coordinate and vice versa). You should generally strive to be consistent in little details like this: it makes it easier to remember how to call functions.</p></li>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>) says that \"Function names should be lowercase, with words separated by underscores as necessary to improve readability\" and the same for variable names. So you should consider changing <code>positionIsEmpty</code> to <code>position_is_empty</code> and so on. (You're not obliged to follow PEP8 but it makes it easier for other Python programmers to read your code.)</p></li>\n<li><p>You can use <a href=\"http://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> to avoid nested loops.</p></li>\n<li><p>The loop</p>\n\n<pre><code>for i in adjQueue:\n processQueue.append(i)\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code>processQueue.extend(adjQueue)\n</code></pre></li>\n<li><p>You have a variable called <code>processQueue</code> but it is not a queue. A <a href=\"http://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29\" rel=\"nofollow\"><em>queue</em></a> is a data structure where you add elements to one end of a list and remove them from the <em>other</em> end (in Python you would use <a href=\"http://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow\"><code>collections.deque</code></a>). A data structure where you add and remove elements at the same end is called a <a href=\"http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29\" rel=\"nofollow\"><em>stack</em></a>.</p></li>\n<li><p>You have a variable <code>counter</code> that you increment and decrement in parallel with adding and removing positions to <code>pathList</code>, so that <code>counter</code> is always the length of <code>pathList</code>. It would be better to drop <code>counter</code> and call <code>len(pathList)</code> instead: one less thing to go wrong. (If you were worried that <code>len(pathList)</code> might be an O(<em>n</em>) operation as it is in some languages, you can look at the <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow\">TimeComplexity</a> page on the Python wiki for reassurance.)</p></li>\n<li><p>If you have an algorithm that uses a stack, it's often easiest and clearest to implement it as a recursive function (you can implicitly use the function call stack instead of having to explicitly push and pop your own stack). See section 3 below for how to do this.</p></li>\n<li><p>You give the maze once in a comment:</p>\n\n<pre><code># oxoo\n# xoxo\n# ooxo\n# xooo\n# oxox\n</code></pre>\n\n<p>and then again in code:</p>\n\n<pre><code>graph = [[0,1,0,0],[1,0,1,0],[0,0,1,0],[1,0,0,0],[0,1,0,1]]\n</code></pre>\n\n<p>This violates the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY principle</a> (Don't Repeat Yourself): it would be easy for you to make a mistake when encoding your maze as a matrix of 1s and 0s. Why not get the computer to do it for you?</p></li>\n<li><p>Similarly, it's hard for you to check the results of your program, because the path comes out as a list of coordinates, which is tedious and error-prone to check by eye. Even in the buggy example I gave in section 1 above, it would be easy to give it a quick look and miss the error. It would be better to present the results in a form that's easy for you to check. (See section 3 below for how I did this.)</p></li>\n<li><p>Your code has much unnecessary use of parentheses. The lines</p>\n\n<pre><code>return ((pos[0] &gt;= 0) and (pos[1] &gt;= 0)) and ((pos[0] &lt; rows) and (pos[1] &lt; cols))\nreturn not(pos in visited)\nreturn (graph[pos[0]][pos[1]]==0)\nif (not(positionIsEmpty(pos)) or (pos in visited)):\nwhile (processQueue and (counter &lt; length)):\nreturn (pathList, counter)\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code>return 0 &lt;= pos[0] &lt; rows and 0 &lt;= pos[1] &lt; cols\nreturn pos not in visited\nreturn graph[pos[0]][pos[1]] == 0\nif not positionIsEmpty(pos) or pos in visited:\nwhile processQueue and counter &lt; length:\nreturn pathList, counter\n</code></pre>\n\n<p>respectively. \"<a href=\"http://drj11.wordpress.com/2008/10/02/c-return-and-parentheses/\" rel=\"nofollow\">Program as if you know the language</a>\"!</p></li>\n<li><p>Explanation for the bug in section 1: your back-tracking implementation doesn't backtrack all your search state, so that the search state becomes inconsistent. When your search reaches a dead end, it pops the last position from <code>pathList</code> and decrements <code>counter</code>, but does not update the rest of the search state. This means that the next <code>currentPos</code> that gets popped from <code>processQueue</code> will not (in general) be adjacent to the end of the path. When you backtrack in a search, you need to backtrack <em>all</em> your state: in your case <code>pathList</code>, <code>counter</code>, <code>processQueue</code>, and <code>visited</code> all need to be backtracked, but you only update the first two of these, and so it goes wrong.</p>\n\n<p>See the revised code for how I keep the search state consistent. Every addition to the state as the search goes forward:</p>\n\n<pre><code>path.append(p)\nvisited.add(p)\n</code></pre>\n\n<p>is matched by a corresponding deletion as the search backtracks:</p>\n\n<pre><code>visited.remove(p)\npath.pop()\n</code></pre>\n\n<p>(There's more to say about this issue, but I've moved this to section 4 below.)</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>from itertools import product\n\nclass Found(Exception): pass\nclass NotFoundError(Exception): pass\n\nclass Maze(object):\n \"\"\"A rectangular matrix of cells representing a maze.\n\n Describe the maze to the constructor in the form of a string\n containing dots for empty cells and any other character for walls.\n\n &gt;&gt;&gt; m = Maze('''.#..\n ... #.#.\n ... ..#.\n ... #...\n ... .#.#''')\n &gt;&gt;&gt; print(m.format(m.path(8)))\n .#.o\n #.#o\n oo#o\n #ooo\n .#.#\n &gt;&gt;&gt; print(m.format(m.path(10)))\n ... # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n NotFoundError: no path of length 10\n\n \"\"\"\n def __init__(self, maze):\n self.matrix = [[c != '.' for c in line] for line in maze.split()]\n self.height = len(self.matrix)\n self.width = len(self.matrix[0])\n assert all(len(row) == self.width for row in self.matrix)\n\n def in_bounds(self, p):\n \"\"\"Return True if `p` is a legal position in the matrix.\"\"\"\n return 0 &lt;= p[0] &lt; self.width and 0 &lt;= p[1] &lt; self.height\n\n def empty(self, p):\n \"\"\"Return True if `p` is an empty position in the matrix.\"\"\"\n return not self.matrix[p[1]][p[0]]\n\n def neighbours(self, p):\n \"\"\"Generate legal positions adjacent to `p`.\"\"\"\n for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):\n q = p[0] + dx, p[1] + dy\n if self.in_bounds(q):\n yield q\n\n def path(self, n):\n \"\"\"Find a path of length `n` in the maze, or raise NotFoundError if\n there is no such path.\n\n \"\"\"\n path = []\n visited = set()\n def search(p):\n path.append(p)\n visited.add(p)\n if len(path) == n:\n raise Found()\n for q in self.neighbours(p):\n if self.empty(q) and q not in visited:\n search(q)\n visited.remove(p)\n path.pop()\n try:\n for p in product(range(self.width), range(self.height)):\n if self.empty(p):\n search(p)\n except Found:\n return path\n else:\n raise NotFoundError('no path of length {}'.format(n))\n\n def format(self, path=()):\n \"\"\"Format the maze as a string. If optional argument path (an\n iterable) is given, highlight cells in the path.\n\n \"\"\"\n path = set(path)\n def row(y):\n for x in range(self.width):\n p = x, y\n if not self.empty(p): yield '#'\n elif p in path: yield 'o'\n else: yield '.'\n return '\\n'.join(''.join(row(y)) for y in range(self.height))\n</code></pre>\n\n<h3>4. Extra credit: encapsulation of search state</h3>\n\n<p>In 2.18 above I discussed the need to update your search state properly when implementing a back-tracking search. As with any kind of data consistency problem, it's good practice to encapsulate operations that must be performed together.</p>\n\n<p>An easy way to do this in Python is via a <a href=\"http://docs.python.org/3/reference/datamodel.html#context-managers\" rel=\"nofollow\">context manager</a>. A \"context manager\" is just an object with <code>__enter__</code> and <code>__exit__</code> methods: when the context manager is the subject of a <code>with</code> statement, the <code>__enter__</code> method is called on entry to the <code>with</code> statement, and the <code>__exit__</code> method on exit. By putting your forward operations in the <code>__enter__</code> method and the back-tracking operations in the <code>__exit__</code> method you can be sure that these pair up properly.</p>\n\n<p>But an even easier way to do this is to use <a href=\"http://docs.python.org/3/library/contextlib.html#contextlib.contextmanager\" rel=\"nofollow\"><code>contextlib.contextmanager</code></a> to build the context manager for you, like this:</p>\n\n<pre><code>from contextlib import contextmanager\n\ndef path(self, n):\n \"\"\"Find a path of length `n` in the maze, or raise NotFoundError if\n there is no such path.\n\n \"\"\"\n path = []\n visited = set()\n\n @contextmanager\n def visit(p):\n path.append(p) # Forward: add p to path.\n visited.add(p) # Forward: mark p as visited.\n yield # Rest of search happens here.\n visited.remove(p) # Backtrack: mark p not visited.\n path.pop() # Backtrack: remove p from path.\n\n def search(p):\n with visit(p):\n if len(path) == n:\n raise Found()\n for q in self.neighbours(p):\n if self.empty(q) and q not in visited:\n search(q)\n try:\n for p in product(range(self.width), range(self.height)):\n if self.empty(p):\n search(p)\n except Found:\n return path\n else:\n raise NotFoundError('no path of length {}'.format(n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T11:37:26.560", "Id": "37313", "Score": "1", "body": "It seems you forgot: if __name__ == \"__main__\":\n import doctest\n doctest.testmod()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T11:41:35.553", "Id": "37314", "Score": "1", "body": "I run doctests using `python -mdoctest program.py`, so the omission is deliberate on my part. But your comment might be helpful for the OP." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:54:00.000", "Id": "24197", "ParentId": "24136", "Score": "8" } } ]
{ "AcceptedAnswerId": "24197", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T02:00:11.330", "Id": "24136", "Score": "6", "Tags": [ "python", "graph" ], "Title": "My first graph traversal code" }
24136
<p>As a Java programmer, I'm new to the OOP-Approach of JavaScript and it's hard for me to find the best way to write code based on objects. I read a lot <a href="https://developer.mozilla.org/en-US/docs/JavaScript" rel="nofollow">MDN</a> and across the web to find a good way to code with JavaScript.</p> <p>Just to see how can it look like, I realized the following functions: Add two INPUT-Elements to a video-element to provide a StartTime (second) and a EndTime (second) to enable a looping of the video in this give time range. </p> <p>I expect there are already nice frameworks for dealing with video-elements (e. g. VideoJS) - but I just want to know how I can improve the object oriented parts of the code, how to handle events nicely, what is a really good approach to create and use objects, to add methods and so on...</p> <p>Especially the event-handling (dealing with this inside a addEventListener-Function...) is interesting to me.</p> <p>I hope this question is interesting also for others and somebody experienced can give me some hints.</p> <p>Here is the code <code>&lt;HTML-site: index.html&gt;</code>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="script.js" type="text/javascript"&gt;&lt;/script&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="controls" style="text-align: center"&gt;&lt;/div&gt; &lt;div style="text-align: center"&gt; &lt;video id="video1" width="420"&gt; &lt;source src="somevideo.webm" type='video/webm' /&gt; &lt;/video&gt; &lt;p&gt; &lt;input id="startFrom" type="number" name="startFrom" min="0" max="1000" value="0"&gt; &lt;input id="runUntil" type="number" name="runUntil" min="0" max="1000" value="0" &gt; &lt;/p&gt; &lt;/div&gt; &lt;div id="info" style="text-align: center; margin-top: 20px"&gt; &lt;input id="currentTime" type="number" min="0" value="0" readonly&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And here is the corresponding JavaScript script.js:</p> <pre><code>/** * This script adds two input controls &lt;startFrom&gt;, &lt;runUntil&gt; to a "VideoPlayer" * and allows to loop a certain range inside the given video * * Only works with HTML5 compatible browsers */ ; (function(window, undefined) { var document = window.document; /** * Initial function to ensure the DOM-Content of the website is avaiable */ function go() { document.addEventListener("DOMContentLoaded", function() { console.log("DOM ready"); new VideoPlayer(); }, false); } ; /** * Wrapper-Class for the Video, which provides the video-Element, * the control-button and the EventHandling for changing * the startFrom and runUntil-Input-Elements */ function VideoPlayer() { //global variable for the Video-Handler _Vid_ = new Video("video1"); _Vid_.setControls(); var startFrom = document.getElementById("startFrom"); var runUntil = document.getElementById("runUntil"); startFrom.addEventListener("change", function(event) { var value = event.target.value; _Vid_.startTime = value; console.log("StartFromValue: " + value); }, false); runUntil.addEventListener("change", function(event) { var value = event.target.value; if(value==0) _Vid_.endTime = _Vid_.duration; else _Vid_.endTime = value; console.log("RunUntilValue: " + value); }, false); } /** * Video-Class (Video-Handler) which provides all fields and methods necessary to * steer the video * * Also initializes the video-instance with everything needed */ function Video(elementId) { this.elementId = elementId; if (this.elementId === undefined) { console.log('No Video-Element given!'); return null; } console.log("creating element Video"); this.elementId = elementId; this.videoElement = new Object(); this.videoIsReady = false; this.startTime = 0.0; this.endTime = 0.0; this.duration = 0.0; this.currentTime = 0.0; this.source = "none"; this.loopEnabled = false; this.videoElement = document.getElementById(this.elementId); this.videoElement.addEventListener("loadedmetadata", function() { console.log("metadata loaded..."); _Vid_.videoIsReady = true; _Vid_.endTime = _Vid_.videoElement.duration; _Vid_.duration = _Vid_.videoElement.duration; _Vid_.source = _Vid_.videoElement.currentSrc.toString(); console.log(_Vid_.getInfos()); }, false); //this Event and it's function realizes the loop capability this.videoElement.addEventListener("timeupdate", function() { var ct = _Vid_.videoElement.currentTime.valueOf(); _Vid_.currentTime = ct; var ctElement = document.getElementById("currentTime"); ctElement.setAttribute("value", ct); if (ct &gt;= _Vid_.endTime) { _Vid_.videoElement.currentTime = _Vid_.startTime; console.log("LOOP"); } }, false); this.getInfos = function getInfos() { console.log("getInfos()"); var outputTxt = "StartTime: " + _Vid_.startTime; outputTxt += "\nDuration: " + _Vid_.duration; outputTxt += "\nSource: " + _Vid_.source; return outputTxt; }; } //another kind of how to set up a class-method Video.prototype.setControls = function() { var playPauseBtn = new VideoControl("playPause", "Play/Pause", "click", function() { if (_Vid_.videoElement.paused) _Vid_.videoElement.play(); else _Vid_.videoElement.pause(); }); var layer = document.getElementById("controls"); layer.appendChild(playPauseBtn.btn); }; //Class for realizing VideoControl-Buttons function VideoControl(name, text, event, fn) { this.name = name; this.text = text; this.event = event; this.btn = document.createElement("button"); var txt = document.createTextNode(text); this.btn.appendChild(txt); this.btn.addEventListener(event, fn, false); } //call the start function go(); })(window); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:09:13.133", "Id": "37252", "Score": "0", "body": "I realize your program is in vanilla JS but if you check out the following video on handling events in jQuery, it just might provide some clarity on the JS subject. You should check out the methods covered in the jQuery source code so you can get a deeper understanding of how you can apply them to your JS. http://training.bocoup.com/screencasts/more-efficient-event-handlers/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:34:18.377", "Id": "37255", "Score": "0", "body": "Thank you for this nice hint/link! Going to dive in... So far I didn't want to use any framework to understand the core javascript better (good approach?)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:38:00.433", "Id": "37257", "Score": "0", "body": "Yeah! Great way to approach the subject. I posted that link so you can see how the guys at jQuery do it. Not that you should use their framework, but so you can see this in a practical real world example." } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Not sure if this occurred during the copy pasting of your code, but the indentation is bad, for example this:</p>\n\n<pre><code>//another kind of how to set up a class-method\nVideo.prototype.setControls = function() {\n\nvar playPauseBtn = new VideoControl(\"playPause\", \"Play/Pause\", \"click\", function() {\n\n if (_Vid_.videoElement.paused)\n _Vid_.videoElement.play();\n else\n _Vid_.videoElement.pause();\n\n});\n\nvar layer = document.getElementById(\"controls\");\nlayer.appendChild(playPauseBtn.btn);\n\n};\n</code></pre>\n\n<p>should be this:</p>\n\n<pre><code> //another kind of how to set up a class-method\n Video.prototype.setControls = function() {\n\n var playPauseBtn = new VideoControl(\"playPause\", \"Play/Pause\", \"click\", function() {\n\n if (_Vid_.videoElement.paused)\n _Vid_.videoElement.play();\n else\n _Vid_.videoElement.pause();\n\n });\n\n var layer = document.getElementById(\"controls\");\n layer.appendChild(playPauseBtn.btn);\n\n };\n</code></pre></li>\n<li>You could also exchange the <code>if</code> in that snippet with a ternary operation</li>\n<li>You only use <code>layer</code> once, you might as well merge that line with the next one</li>\n<li><p>That would give:</p>\n\n<pre><code> Video.prototype.setControls = function() {\n\n var playPauseBtn = new VideoControl(\"playPause\", \"Play/Pause\", \"click\", function() {\n Vid_.videoElement.paused ? _Vid_.videoElement.play() : _Vid_.videoElement.pause();\n });\n document.getElementById(\"controls\").appendChild(playPauseBtn.btn);\n };\n</code></pre></li>\n<li>JsHint.com could not find anything serious</li>\n<li>Do not use <code>console.log</code> in production code</li>\n<li><p>So that this:\n runUntil.addEventListener(\"change\", function(event) {</p>\n\n<pre><code> var value = event.target.value;\n if(value==0)\n _Vid_.endTime = _Vid_.duration;\n else\n _Vid_.endTime = value;\n console.log(\"RunUntilValue: \" + value);\n\n}, false);\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>runUntil.addEventListener(\"change\", function(event) {\n var value = event.target.value;\n _Vid_.endTime = value ? value : _Vid_.duration;\n}, false);\n</code></pre></li>\n<li>Since you put everything into an IIFE, you could put 'use strict'; after<code>(function(window, undefined) {</code></li>\n<li><code>_Vid_</code> is a bad name, don't overdo the underscores</li>\n<li>Since you should not do <code>console.log</code> in production code, you don't need <code>this.getInfos</code> at all.</li>\n</ul>\n\n<p>All in all, I think your usage of <code>_Vid_</code> breaks the OOP approach, I am pretty sure that you cannot run 2 instances of the video element which means it's broken.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T20:16:51.760", "Id": "43979", "ParentId": "24142", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T07:13:55.517", "Id": "24142", "Score": "1", "Tags": [ "javascript" ], "Title": "Adding loop capability to video-element" }
24142
<p>I have a pipeline with loops of filters and one input filter. The rest are splitters, transform and output.</p> <p>I would like my code to go over the filters and push them into a queue (order is important). However, if I have a loop, I only want to count the end of the loop once.</p> <p>Here is my working code. Please review it.</p> <pre><code>queue&lt;string&gt; CEngineInternal::GetFiltersListToRun() { queue&lt;string&gt; filtersBFS; queue&lt;string&gt; filtersToRun; set&lt;string&gt; alreadyFoundFilters; // add input filters to the list for(BaseFilterMap::const_iterator it = m_Filters.begin(); it != m_Filters.end(); it++) { string FilterName = (*it).first; const CBaseFilter *filter = (*it).second; if(filter-&gt;IsInputFilter()) { //push the input filter filtersBFS.push(FilterName); filtersToRun.push(FilterName); alreadyFoundFilters.insert(FilterName); } } while (!filtersBFS.empty()) { string filterName = filtersBFS.front(); filtersBFS.pop(); //get the OutputPin connections for the next filter FilterConnection* filterConnection = m_Connections[filterName]; ASSERT(filterConnection != NULL); PinConnectionVector&amp; outPinConnections = filterConnection-&gt;GetOutputPinConnections(); if (outPinConnections.size() != 0) { // find all the output pin connections for (size_t i = 0; i &lt; outPinConnections.size(); ++i) { //add connected filters id's to the list const std::string&amp; oFilterName = outPinConnections[i].ConnectedFilterName(); if (oFilterName.empty()) { continue; } if (alreadyFoundFilters.find(oFilterName) != alreadyFoundFilters.end()) { continue; } else { filtersBFS.push(oFilterName); filtersToRun.push(oFilterName); alreadyFoundFilters.insert(oFilterName); } } } } return filtersToRun; } </code></pre>
[]
[ { "body": "<p>As far as I can tell, this code seems pretty easy to follow, especially with the comments. Here are several things that stood out to me:</p>\n\n<ul>\n<li><p>Since you haven't provided your own <code>queue</code> implementation, I assume you're using <code>std::queue</code>. If so, remove <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a> and use <code>std::</code> where necessary.</p></li>\n<li><p>This entire method should be <code>const</code>. You're modifying three local containers and returning one, while not modifying any class members. By making this <code>const</code>, data members will stay immutable (modifications will cause compiler errors) and the reader will be aware of this.</p>\n\n<pre><code>queue&lt;string&gt; CEngineInternal::GetFiltersListToRun() const\n</code></pre></li>\n<li><p><code>filtersBFS</code> is not a very descriptive name; we know this program is about BFS. It's also not the local queue that is returned, so it is unclear what this is used for within the function.</p></li>\n<li><p>Your functions start with a capital letter, which is not proper naming in C++. Only user-defined types should be named this way. Your variables (except for <code>FilterName</code>) <em>are</em> named correctly, however. Both variables and functions should start with a lowercase letter.</p></li>\n<li><p>For this line:</p>\n\n<pre><code>for(BaseFilterMap::const_iterator it = m_Filters.begin(); it != m_Filters.end(); it++)\n</code></pre>\n\n<p>It may be more readable to declare the iterator type before the loop.</p>\n\n<p>In addition, it may be better to use pre-increment since you're not dealing with basic types. This could also potentially avoid an extra copy.</p>\n\n<pre><code>BaseFilterMap::const_iterator it;\n\nfor (it = m_Filters.begin(); it != m_Filters.end(); ++it) {}\n</code></pre>\n\n<p>However, if you're using C++11, consider <a href=\"http://en.cppreference.com/w/cpp/language/auto\" rel=\"nofollow noreferrer\"><code>auto</code></a> instead of your current iterator. The compiler will determine the correct type, and it's more readable. You may also keep it inside the loop statement.</p>\n\n<pre><code>for (auto it = m_Filters.begin(); it != m_Filters.end(); ++it) {}\n</code></pre>\n\n<p>Better yet, if you're using C++11, consider a <a href=\"http://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based <code>for</code>-loop</a>:</p>\n\n<pre><code>for (auto&amp; it : m_Filters) {}\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if (outPinConnections.size() != 0)\n</code></pre>\n\n<p>should instead use <code>!empty()</code>:</p>\n\n<pre><code>if (!outPinConnections.empty())\n</code></pre></li>\n<li><p>For here:</p>\n\n<pre><code>for (size_t i = 0; i &lt; outPinConnections.size(); ++i) {}\n</code></pre>\n\n<p>If this <em>is</em> the size type returned by <code>size()</code>, make it <code>std::size_t</code> since this is C++. Otherwise, make sure you're using the correct size type to avoid potential loss-of-data warnings.</p></li>\n<li><p>These:</p>\n\n<pre><code>(*it).first;\n(*it).second;\n</code></pre>\n\n<p>should use the more readable <code>-&gt;</code> operator:</p>\n\n<pre><code>it-&gt;first;\nit-&gt;second;\n</code></pre></li>\n<li><p>You say:</p>\n\n<blockquote>\n <p>If I have a loop, I only want to count the end of the loop once.</p>\n</blockquote>\n\n<p>But I don't see that anywhere in the code, plus there are multiple loops used here. If you're still receiving the correct output and no errors associated with them, then they should be okay.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T00:52:39.030", "Id": "68211", "Score": "1", "body": "+1, although if you're using C++11, I'd highly recommend using `auto` for iterators - much more readable I think." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T03:13:21.130", "Id": "40237", "ParentId": "24144", "Score": "11" } } ]
{ "AcceptedAnswerId": "40237", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:34:04.443", "Id": "24144", "Score": "6", "Tags": [ "c++", "queue", "breadth-first-search" ], "Title": "BFS for creating a queue without repetitions and with loops in the graph" }
24144
<p>In graph theory, <a href="http://en.wikipedia.org/wiki/Breadth-first_search" rel="nofollow">breadth-first search</a> (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal.</p> <p>BFS is an uninformed search method that aims to expand and examine all nodes of a graph or combination of sequences by systematically searching through every solution. In other words, it exhaustively searches the entire graph or sequence without considering the goal until it finds it. It does not use a heuristic algorithm.</p> <h2>Algorithm</h2> <p>From the standpoint of the algorithm, all child nodes obtained by expanding a node are added to a <strong>FIFO</strong> (i.e., First In, First Out) queue. In typical implementations, nodes that have not yet been examined for their neighbors are placed in some container (such as a queue or linked list) called <em>open</em> and then once examined are placed in the container <em>closed</em>.</p> <ol> <li>Enqueue the root node</li> <li>Dequeue a node and examine it <ul> <li>If the element sought is found in this node, quit the search and return a result.</li> <li>Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.</li> </ul></li> <li>If the queue is empty, every node on the graph has been examined – quit the search and return "not found".</li> <li>If the queue is not empty, repeat from Step 2.</li> </ol> <h2>Applications</h2> <ul> <li>Finding all nodes within one connected component</li> <li>Copying Collection, Cheney's algorithm</li> <li>Finding the shortest path between two nodes u and v (with path length measured by number of edges)</li> <li>Testing a graph for bipartiteness</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Breadth-first_search" rel="nofollow">Source</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T10:49:44.787", "Id": "24151", "Score": "0", "Tags": null, "Title": null }
24151
In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T10:49:44.787", "Id": "24152", "Score": "0", "Tags": null, "Title": null }
24152
<p>I need to map from one enum type to another. Here is the enum I am given:</p> <pre><code>enum CfgFruitType { CFGNoFruit, CFGApple, CFGApricot, CFGBanana, CFGMango, CFGKiwi, CFGFig, CFGGrape, CFGMelon, CFGLemon, CFGNectarine, CFGPineapple, CFGWatermelon, CFGCherry, CFGPear, CFGStrawberry }; </code></pre> <p>and I need to map this to a second enum:</p> <pre><code>enum FAddressType { AddressTypeUnknown, AddressTypeCherry, AddressTypeApple, AddressTypePear, AddressTypePlum, AddressTypeStrawberry }; </code></pre> <p>Here is my implementation:</p> <pre><code>FAddressType maptype(CfgFruitType cfgtype) { int mapper[16][2] = { { CFGNoFruit, AddressTypeUnknown }, { CFGApple, AddressTypeApple }, { CFGApricot, AddressTypeUnknown }, { CFGBanana, AddressTypeUnknown }, { CFGMango, AddressTypeUnknown }, { CFGKiwi, AddressTypeUnknown }, { CFGFig, AddressTypeUnknown }, { CFGGrape, AddressTypeUnknown }, { CFGMelon, AddressTypeUnknown }, { CFGLemon, AddressTypeUnknown }, { CFGNectarine, AddressTypeUnknown }, { CFGPineapple, AddressTypeUnknown }, { CFGWatermelon, AddressTypeUnknown }, { CFGCherry, AddressTypeCherry }, { CFGPear, AddressTypePear }, { CFGStrawberry, AddressTypeStrawberry } }; return cfgtype &lt; 16 ? (FAddressType)mapper[cfgtype][1] : AddressTypeUnknown; } </code></pre> <p>Is this the best approach? How can it be improved?</p>
[]
[ { "body": "<p>If I were you I'd write a function to convert from one to the other which would perform a switch on your input.</p>\n\n<p>My motivation to do so would be to :</p>\n\n<ul>\n<li>have warnings/errors whenever a case is not handled. If you do so and you update the enum, you can't forget to update your code performing handling the conversion (<a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Warning-Options.html\" rel=\"nofollow\">-Wswitch</a> : \nWarn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration)</li>\n<li>you can easily update your code if you need to.</li>\n</ul>\n\n<p>And the overhead in terms of code and</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T14:24:37.267", "Id": "24159", "ParentId": "24154", "Score": "0" } }, { "body": "<p>You made a look-up table. Here's 2 things to note:</p>\n\n<ol>\n<li><p>Your look up table is between 2 types, but your table is only 1 type. You break type safety. They are <code>enum</code>s and it's 'safe' <em>if</em> the enums have the same underlying type, but dirty either way.</p></li>\n<li><p>A <code>switch</code> frequently generates a look up table for you, and in this case definitely will on any decent compiler. It will not generate an if-if else-else chain. See the following:</p></li>\n</ol>\n\n<p>:</p>\n\n<pre><code>FAddressType maptype(CfgFruitType cfgtype)\n{\n switch(cfgtype)\n {\n case CFGNoFruit: return AddressTypeUnknown;\n case CFGApple: return AddressTypeApple;\n case CFGApricot: return AddressTypeUnknown;\n case CFGBanana: return AddressTypeUnknown;\n case CFGMango: return AddressTypeUnknown;\n case CFGKiwi: return AddressTypeUnknown;\n case CFGFig: return AddressTypeUnknown;\n case CFGGrape: return AddressTypeUnknown;\n case CFGMelon: return AddressTypeUnknown;\n case CFGLemon: return AddressTypeUnknown;\n case CFGNectarine: return AddressTypeUnknown;\n case CFGPineapple: return AddressTypeUnknown;\n case CFGWatermelon: return AddressTypeUnknown;\n case CFGCherry: return AddressTypeCherry;\n case CFGPear: return AddressTypePear;\n case CFGStrawberry: return AddressTypeStrawberry;\n default: assert(!\"Not a valid CfgFruitType!\"); return AddressTypeUnknown;\n }\n}\n</code></pre>\n\n<p>Shorter code, very clear, easy to add new cases, very likely to outperform (by a negligible margin) your code.</p>\n\n<p>Or, you could be less explicit and make it really short:</p>\n\n<pre><code>switch(cfgtype)\n{\ncase CFGApple: return AddressTypeApple;\ncase CFGCherry: return AddressTypeCherry;\ncase CFGPear: return AddressTypePear;\ncase CFGStrawberry: return AddressTypeStrawberry;\ndefault: return AddressTypeUnknown;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:05:28.997", "Id": "24199", "ParentId": "24154", "Score": "14" } } ]
{ "AcceptedAnswerId": "24199", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T11:17:39.280", "Id": "24154", "Score": "11", "Tags": [ "c++", "enum", "hash-map" ], "Title": "Mapping enum to enum" }
24154
<p>How can I simplify this .less code to require less repetition (i.e., so that I can have many buttons with normal, rollover, and pressed states without using 3 lines for each button):</p> <pre><code>.SBtnM(@urlprefix, @width, @height, @urlsuffix) { width: @width; height: @height; background-image: url(%("%s_%s.png", @urlprefix,@urlsuffix)); } @url1prefix : 'chrome://xtoolbar/skin/img1'; toolbarbutton &gt; .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px,'normal');} toolbarbutton:hover &gt; .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px, 'rollover');} toolbarbutton[checked="true"] &gt; .btnCSS1 {.SBtnM(@url1prefix, 42px, 24px, 'pressed');} </code></pre> <p>Ideally, I would want to be able to use a one-liner to handle all 3 states. E.g., something like this:</p> <pre><code>.SBtnM(@urlprefix, @width, @height) { //Magic Happens. This part may become more complicated } .btnCSS1 {.SBtnM('chrome://xtoolbar/skin/img1', 42px, 24px);} </code></pre> <p>Output, for reference:</p> <pre><code>toolbarbutton &gt; .btnCSS1 { width: 42px; height: 24px; background-image: url("chrome://xtoolbar/skin/img1_normal.png"); } toolbarbutton:hover &gt; .btnCSS1 { width: 42px; height: 24px; background-image: url("chrome://xtoolbar/skin/img1_rollover.png"); } toolbarbutton[checked="true"] &gt; .btnCSS1 { width: 42px; height: 24px; background-image: url("chrome://xtoolbar/skin/img1_pressed.png"); } </code></pre> <p>As far as I can tell, .less doesn't have any sort of parent selector for mixins.</p>
[]
[ { "body": "<p>I don't see anything wrong with what you are doing but. it can be written shorter just as you asked.</p>\n\n<pre><code>.SBtnM(@selector, @urlprefix, @width, @height)\n{\n .@{selector}\n { \n .toolbarbutton &gt; &amp;\n {\n @url: %(\"%s_normal.png\", @urlprefix);\n width: @width;\n height: @height;\n background-image:url(@url);\n }\n .toolbarbutton:hover &gt; &amp;\n {\n @url:%(\"%s_rollover.png\", @urlprefix);\n background-image:url(@url);\n }\n .toolbarbutton[checked=\"true\"] &gt; &amp;\n {\n @url:%(\"%s_pressed.png\", @urlprefix);\n background-image:url(@url);\n }\n }\n}\n\n.SBtnM(btnCSS1, 'chrome://xtoolbar/skin/img1', 42px, 24px);\n</code></pre>\n\n<p>For me this produces:</p>\n\n<pre><code>.toolbarbutton &gt; .btnCSS1 {\n width: 42px;\n height: 24px;\n background-image: url(\"chrome://xtoolbar/skin/img1_normal.png\");\n}\n.toolbarbutton &gt; .btnCSS1 {\n background-image: url(\"chrome://xtoolbar/skin/img1_rollover.png\");\n}\n.toolbarbutton[checked=\"true\"] &gt; .btnCSS1 {\n background-image: url(\"chrome://xtoolbar/skin/img1_pressed.png\");\n}\n</code></pre>\n\n<p>Works for <strong>LESS 1.3.1+ ONLY</strong>. For previous versions the syntax is <a href=\"http://lesscss.org/#-selector-interpolation\" rel=\"nofollow\">slightly different</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T07:25:44.903", "Id": "35746", "ParentId": "24157", "Score": "2" } } ]
{ "AcceptedAnswerId": "35746", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T13:29:56.627", "Id": "24157", "Score": "5", "Tags": [ "css", "less-css" ], "Title": "How can I reduce this .less call to one line per image" }
24157
<p>Can I combine this two classes and have one fake db class?</p> <pre><code>public class FakeDb : Dictionary&lt;string, List&lt;string&gt;&gt; { public const string Table1 = "Table1"; public void AddToTable(string tableName, string line) { if(!ContainsKey(tableName)) Add(tableName, new List&lt;string&gt;()); List&lt;string&gt; rows = GetTableData(tableName); rows.Add(line); } internal List&lt;string&gt; GetTableData(string tableName) { return this[tableName]; } } </code></pre> <hr> <pre><code>public class FakeComplexDb : Dictionary&lt;string, List&lt;Dictionary&lt;string,List&lt;string&gt;&gt;&gt;&gt; { public void AddToTable(string tableName, Dictionary&lt;string, List&lt;string&gt;&gt; line) { if (!ContainsKey(tableName)) Add(tableName, new List&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt;()); List&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt; rows = GetTableData(tableName); rows.Add(line); } internal List&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt; GetTableData(string tableName) { return this[tableName]; } } </code></pre>
[]
[ { "body": "<p>Why not use generics:</p>\n\n<pre><code>public class FakeDb&lt;TList&gt; : Dictionary&lt;string, List&lt;TList&gt;&gt;\n{\n public const string Table1 = \"Table1\";\n\n public void AddToTable(string tableName, TList line)\n {\n if (!ContainsKey(tableName))\n {\n Add(tableName, new List&lt;TList&gt;());\n }\n\n List&lt;TList&gt; rows = GetTableData(tableName);\n rows.Add(line);\n }\n\n private List&lt;TList&gt; GetTableData(string tableName)\n {\n return this[tableName];\n }\n}\n</code></pre>\n\n<p>Then to use:</p>\n\n<pre><code>var simpleDB = new FakeDb&lt;string&gt;();\nvar complexDb = new FakeDb&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt;();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T16:00:11.250", "Id": "24162", "ParentId": "24158", "Score": "5" } } ]
{ "AcceptedAnswerId": "24162", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T13:49:04.810", "Id": "24158", "Score": "1", "Tags": [ "c#" ], "Title": "Eliminate duplication in similar fake data access classes" }
24158
<p>I wrote a Python program that performs an integration of data using Simpson's rule. The program takes the areas to be integrated from a foo.ref file, with the following syntax:</p> <blockquote> <pre><code># peak m/z charge window LAG_H4N4F1S1 4244.829467 1+ 0.06 LAG_H4N4F1S1 4245.832508 1+ 0.06 LAG_H4N4F1S1 4246.835549 1+ 0.06 LAG_H4N4F1S1 4247.838590 1+ 0.06 </code></pre> </blockquote> <p>The data that the program parses is taken from all the .xy files in the current directory, with the following syntax:</p> <blockquote> <pre><code>3497.7552 0 3497.7619 410646 3497.7685 397637 3497.7752 363672 3497.7819 321723 3497.7886 286960 </code></pre> </blockquote> <p>The program's final output is a tab seperated file that can be opened directly in excel, the performance is ... a lot worse than I was expecting however and I was wondering if anyone could offer some tricks to increase that (and also to have a general look at the code, if it is correct Python).</p> <pre><code>#! /usr/bin/env python import glob import os import fileinput print "&lt;SimpInt.py&gt; a script to quickly calculate the area for a set" print "of analytes. Written by Bas Jansen, Leiden University Medical" print "Center, March 20th 2013." print "" # Simpson's rule def integrate(y_vals,h): i=1 total=y_vals[0]+y_vals[-1] for y in y_vals[1:-1]: if i%2 == 0: total+=2*y else: total+=4*y i+=1 return total*(h/3.0) # Reads the reference file ref=[] for refs in glob.glob("*.ref"): fr=open(refs) for line in fr.readlines(): parts=line.rstrip('\n').split('\t') ref.append(parts) fr.close() # Initialize the output file f=open('output.xls','w') for i in range(1,len(ref)): f.write(ref[i][0]+"\n") f.close() # Find XY files in current directory xy_files=[] for files in glob.glob("*.xy"): xy_files.append(files) x=[] area=[] print "Parsing: "+files fh=open(files) for line in fh.readlines(): y=[float(i) for i in line.split()] x.append(y) fh.close() # Pick the XY window print "Progress indicator:" print "0%" for i in range(1,len(ref)): obs=[] vals=0 low=float(ref[i][1])-float(ref[i][3]) high=float(ref[i][1])+float(ref[i][3]) # Progress indicator if i %(len(ref)/10) == 0: print str(i/(len(ref)/10))+"0%" for j in range(0,len(x)): if x[j][0] &gt; low and x[j][0] &lt; high: coords=[float(l) for l in x[j]] obs.append(coords) vals+=1 if obs: y_vals=[] h=(obs[len(obs)-1][0]-obs[0][0])/len(obs) for k in range(0,len(obs)): y_vals.append(obs[k][1]) area.append(integrate(y_vals,h)) # Neat trick to append the area from other input files l = 0 for line in fileinput.input('output.xls',inplace=1): print "%s\t%s\n" % (line.rstrip(),area[l]), l+=1 # Display the legend (&amp; filenames) at bottom of output file f=open('output.xls','a') legend = "Peak" for m in range(0,len(xy_files)): legend+="\t"+str(xy_files[m]) legend+="\n" f.write(legend) f.close() # Being polite raw_input("Finished, press any key to exit") </code></pre> <p>I have performed some various tests today with disabling chunks of the code and seeing what causes the biggest increase in processing time and that appears the searching of the lists.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:14:46.913", "Id": "37304", "Score": "1", "body": "Use NumPy and SciPy for numerical tasks. [scipy.integrate.simps](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html)" } ]
[ { "body": "<pre><code>#! /usr/bin/env python\nimport glob\nimport os\nimport fileinput\nprint \"&lt;SimpInt.py&gt; a script to quickly calculate the area for a set\"\nprint \"of analytes. Written by Bas Jansen, Leiden University Medical\"\nprint \"Center, March 20th 2013.\"\nprint \"\"\n\n# Simpson's rule\ndef integrate(y_vals,h):\n</code></pre>\n\n<p>The recommendation for python is four spaces for indentation, you appear to be using 2</p>\n\n<pre><code> i=1\n total=y_vals[0]+y_vals[-1]\n</code></pre>\n\n<p>It's also recommended to have spaces around binary operators</p>\n\n<pre><code> for y in y_vals[1:-1]:\n</code></pre>\n\n<p>Use <code>for i, y in enumerate(y_vals, 1):</code> rather then counting your own i value</p>\n\n<pre><code> if i%2 == 0:\n total+=2*y\n else:\n total+=4*y\n i+=1\n return total*(h/3.0)\n\n# Reads the reference file\nref=[]\n</code></pre>\n\n<p>I'd recommended not using an abbreviation her</p>\n\n<pre><code>for refs in glob.glob(\"*.ref\"):\n fr=open(refs)\n</code></pre>\n\n<p>It's recommended to use a with block:</p>\n\n<pre><code> with open(refs) as fr:\n do stuff with file\n file will be automatically closed here\n</code></pre>\n\n<p>That ensures your file will be closed even if an exception occours</p>\n\n<pre><code> for line in fr.readlines():\n parts=line.rstrip('\\n').split('\\t')\n ref.append(parts)\n</code></pre>\n\n<p>You shouldn't really store the header ref here.</p>\n\n<pre><code> fr.close()\n\n\n\n# Initialize the output file\nf=open('output.xls','w')\nfor i in range(1,len(ref)):\n f.write(ref[i][0]+\"\\n\")\nf.close()\n\n\n\n# Find XY files in current directory\nxy_files=[]\nfor files in glob.glob(\"*.xy\"):\n xy_files.append(files)\n x=[]\n area=[]\n print \"Parsing: \"+files\n fh=open(files)\n for line in fh.readlines():\n</code></pre>\n\n<p>Actually this is the same as <code>for line in fh:</code></p>\n\n<pre><code> y=[float(i) for i in line.split()]\n x.append(y)\n fh.close()\n\n # Pick the XY window\n print \"Progress indicator:\"\n print \"0%\"\n for i in range(1,len(ref)):\n</code></pre>\n\n<p>Whenever possible, don't iterate over indexes. Instead iterate over the lists. So something like <code>for line in ref[1:]:</code> If you really need the indexes us enumerate</p>\n\n<pre><code> obs=[]\n vals=0\n low=float(ref[i][1])-float(ref[i][3])\n high=float(ref[i][1])+float(ref[i][3])\n # Progress indicator\n if i %(len(ref)/10) == 0:\n print str(i/(len(ref)/10))+\"0%\"\n</code></pre>\n\n<p>Why divide by 10 just to add the 0 back?</p>\n\n<pre><code> for j in range(0,len(x)):\n</code></pre>\n\n<p>Use <code>for j in x:</code> and then avoid the indexing</p>\n\n<pre><code> if x[j][0] &gt; low and x[j][0] &lt; high:\n coords=[float(l) for l in x[j]]\n obs.append(coords)\n vals+=1\n</code></pre>\n\n<p>What's this for?</p>\n\n<pre><code> if obs:\n y_vals=[]\n h=(obs[len(obs)-1][0]-obs[0][0])/len(obs)\n for k in range(0,len(obs)):\n y_vals.append(obs[k][1])\n area.append(integrate(y_vals,h))\n\n # Neat trick to append the area from other input files\n l = 0\n for line in fileinput.input('output.xls',inplace=1):\n</code></pre>\n\n<p>If you need to iterate over multiple sources at once, use a zip.</p>\n\n<pre><code> print \"%s\\t%s\\n\" % (line.rstrip(),area[l]),\n l+=1\n</code></pre>\n\n<p>Your neat trick is what's killing you. This is designed for processing the output of some other program. Its not good for continually adding to the end of lines you have already written. What you should do is store everything in a big list and then output it at the end.</p>\n\n<pre><code># Display the legend (&amp; filenames) at bottom of output file\nf=open('output.xls','a')\nlegend = \"Peak\"\nfor m in range(0,len(xy_files)):\n legend+=\"\\t\"+str(xy_files[m])\nlegend+=\"\\n\"\nf.write(legend)\nf.close()\n\n# Being polite\nraw_input(\"Finished, press any key to exit\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:39:51.133", "Id": "37260", "Score": "0", "body": "That's a lot of comments, thank you :) The reason why I use my 'trick' is that I don't know how many data files a user wants to parse, typical numbers would be between 100 to 10.000 files and as such I assumed that keeping that all in memory is not really an option, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:54:11.363", "Id": "37264", "Score": "0", "body": "@BasJansen, actually I think you'd be fine to store that much stuff in memory. If not, it still make sense to rearrange the program to output things one line of output at a time rather then what you've done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:58:30.783", "Id": "37307", "Score": "0", "body": "I divide by 10 and then add the 0% back to ensure that it actually lists 10%, 20% and so on, removing the division will just display 00%, 00% and so on. I will use your other comments about indexing, with open (for files) and more however so thank you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T16:12:23.053", "Id": "24163", "ParentId": "24160", "Score": "2" } } ]
{ "AcceptedAnswerId": "24163", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:06:06.377", "Id": "24160", "Score": "4", "Tags": [ "python", "performance", "mathematics", "csv", "floating-point" ], "Title": "Integration of data using Simpson's rule" }
24160
<p>How many tests could you write for the enum class below. I am looking for the following output given the following command:</p> <pre><code>java fileName HORIZON_BOX, HORIZON_BOX_WITH_CC, HORIZON_BOX_WITH_CC 1 HORIZON_BOX: 20.00 2 HORIZON_BOX_WITH_CC @ 30.00 : 60.00 GRAND TOTAL : 80.00 </code></pre> <p>What is the best solution approach that you would go about solving this problem?</p> <pre><code>public enum Product { HORIZON_BOX(30.00), HORIZON_BOX_WITH_CC(50.00), HORIZON_BOX_WITH_CC_2_TB(100.00), HORIZON_MULTIROOM(75.00), HUB(20.00); private double price; private Product(double price) { this.price = price; } public double getPrice() { return price; } } </code></pre> <p>The tests I have are as follows:</p> <pre><code>public class ProductTest { /** * Test that fails as we cannot access the private constructor of the Enum * Written before any code is written to test */ @Test public void testProductNothingImplemented() { // Product("Nothing has been implemented yet"); } /** * Test expectedvalue of 20 */ @Test public void testProductHORIZONBoxHUB() { assertEquals(20, Product.HUB.getPrice(), 0); } /** * Test expectedvalue of 50 for HORIZON_BOX_WITH_HD */ @Test public void testProductHORIZON_BOX_WITH_HD() { assertEquals(50, Product.HORIZON_BOX_WITH_CC.getPrice(), 0); } /** * Test expectedvalue of 100 for HORIZON_BOX_WITH_HD_2_TB */ @Test public void testProductHORIZON_BOX_WITH_HD_2_TB() { assertEquals(100, Product.HORIZON_BOX_WITH_CC_2_TB.getPrice(), 0); } /** * Test expectedvalue of 75 for HORIZON_MULTIROOM */ @Test public void testProductHORIZON_MULTIROOM() { assertEquals(75, Product.HORIZON_MULTIROOM.getPrice(), 0); } /** * Test expectedvalue of 30 for HORIZON_BOX */ @Test public void testProductHORIZON_BOX() { assertEquals(30, Product.HORIZON_BOX.getPrice(), 0); } /** * test method to compute total with zero products */ @Test public void testComputeEmptyMap() { Map&lt;String, Integer&gt; testMap = new HashMap&lt;String, Integer&gt;(); //setup map Horizon Horizon = new Horizon(); assertEquals(new Double(0), Horizon.computeAndPrintTotal(testMap)); } /** * test method to compute total with two elements but second element is ) products */ @Test public void testComputeAndPrintTotalWithOneProductHavingZeroFrequency() { Map&lt;String, Integer&gt; testMap = new HashMap&lt;String, Integer&gt;(); //setup map testMap.put("HUB", 1); testMap.put("HORIZON_BOX", 0); Horizon Horizon = new Horizon(); assertEquals(new Double(20), Horizon.computeAndPrintTotal(testMap)); } /** * test method to compute total with two products */ @Test public void testComputeAndPrintTotalPass() { Map&lt;String, Integer&gt; testMap = new HashMap&lt;String, Integer&gt;(); testMap.put("HUB", 1); testMap.put("HORIZON_BOX", 2); Horizon Horizon = new Horizon(); assertEquals(new Double(80), Horizon.computeAndPrintTotal(testMap)); } } ####################################################################################### </code></pre> <p>What I have is the following: The Main class that executes is </p> <pre><code>public class Horizon { private Map&lt;String, Integer&gt; argFrequencyCount = new HashMap&lt;String, Integer&gt;(); double total = 0; @SuppressWarnings("rawtypes") public static void main(String[] args) { Horizon horizon = new Horizon(); for (String productName : args) { Integer frequency = horizon.argFrequencyCount.get(productName); horizon.argFrequencyCount.put(productName, (frequency == null) ? 1 : frequency + 1); } horizon.argFrequencyCount = horizon.sortProductMapByFrequency(horizon.argFrequencyCount); for (Iterator iterator = horizon.argFrequencyCount.entrySet().iterator(); iterator .hasNext();) { @SuppressWarnings("unchecked") Map.Entry&lt;String, Integer&gt; productCount = (Map.Entry&lt;String, Integer&gt;) iterator .next(); horizon.outputPrintHelper(productCount.getKey(), productCount.getValue()); } horizon.computeAndPrintTotal(horizon.argFrequencyCount); } /** * method to print total * * @param argFrequencyCount */ public Double computeAndPrintTotal(Map&lt;String, Integer&gt; argFrequencyCount) { for (Iterator&lt;Map.Entry&lt;String, Integer&gt;&gt; iterator = argFrequencyCount.entrySet().iterator(); iterator .hasNext();) { Map.Entry&lt;String, Integer&gt; productCount = (Map.Entry&lt;String, Integer&gt;) iterator .next(); total = total + productCount.getValue() * Product.valueOf(productCount.getKey()).getPrice(); } System.out.println("GRAND TOTAL : £" + total); return total; } /** * Method to print the items and corresponding item total * * @param prod * @param numberOfItems */ private void outputPrintHelper(String prod, int numberOfItems) { Product product = Product.valueOf(prod); switch (product) { case HUB: if (numberOfItems == 1) { System.out.println(numberOfItems + " HUB : £" + Product.HUB.getPrice()); } else { System.out.println(numberOfItems + " HUB @ £" + Product.HUB + " : £" + numberOfItems * Product.HUB.getPrice()); } break; case HORIZON_BOX: if (numberOfItems == 1) { System.out.println(numberOfItems + " HORIZON_BOX : £" + Product.HORIZON_BOX.getPrice()); } else { System.out.println(numberOfItems + " HORIZON_BOX @ £" + Product.HORIZON_BOX.getPrice() + " : £" + numberOfItems * Product.HORIZON_BOX.getPrice()); } break; case HORIZON_BOX_WITH_CC: if (numberOfItems == 1) { System.out.println(numberOfItems + " HORIZON_BOX_WITH_CC : £" + Product.HORIZON_BOX_WITH_CC.getPrice()); } else { System.out.println(numberOfItems + " HORIZON_BOX_WITH_CC @ £" + Product.HORIZON_BOX_WITH_CC.getPrice() + " : £" + numberOfItems * Product.HORIZON_BOX_WITH_CC.getPrice()); } break; case HORIZON_BOX_WITH_CC_2_TB: if (numberOfItems == 1) { System.out.println(numberOfItems + " HORIZON_BOX_WITH_CC_2_TB : £" + Product.HORIZON_BOX_WITH_CC_2_TB.getPrice()); } else { System.out.println(numberOfItems + " HORIZON_BOX_WITH_CC_2_TB @ £" + Product.HORIZON_BOX_WITH_CC_2_TB.getPrice() + " : £" + numberOfItems * Product.HORIZON_BOX_WITH_CC_2_TB.getPrice()); } break; case HORIZON_MULTIROOM: if (numberOfItems == 1) { System.out.println(numberOfItems + " HORIZON_MULTIROOM : £" + Product.HORIZON_MULTIROOM.getPrice()); } else { System.out.println(numberOfItems + " HORIZON_MULTIROOM @ £" + Product.HORIZON_MULTIROOM.getPrice() + " : £" + numberOfItems * Product.HORIZON_MULTIROOM.getPrice()); } } } /** * Sort the HashMap by number of items in descending order * */ private Map&lt;String, Integer&gt; sortProductMapByFrequency( Map&lt;String, Integer&gt; passedMap) { List&lt;String&gt; mapKeys = new ArrayList&lt;String&gt;(passedMap.keySet()); List&lt;Integer&gt; mapValues = new ArrayList&lt;Integer&gt;(passedMap.values()); Collections.sort(mapValues); Collections.sort(mapKeys); LinkedHashMap&lt;String, Integer&gt; sortedMap = new LinkedHashMap&lt;String, Integer&gt;(); Iterator&lt;Integer&gt; valueIt = mapValues.iterator(); while (valueIt.hasNext()) { Object val = valueIt.next(); Iterator&lt;String&gt; keyIt = mapKeys.iterator(); while (keyIt.hasNext()) { Object key = keyIt.next(); String comp1 = passedMap.get(key).toString(); String comp2 = val.toString(); if (comp1.equals(comp2)) { passedMap.remove(key); mapKeys.remove(key); sortedMap.put((String) key, (Integer) val); break; } } } return sortedMap; } } </code></pre>
[]
[ { "body": "<p><code>Product.getPrice</code> is too trivial to warrant a test on its own, and testing the price of each product alone only tests your typing ability. If the test passes, it only means you typed the same price in the code and the test; it doesn't prove that the price is correct since you could have the same typo in both places.</p>\n\n<p>Test code should have very little logic. As tests become more complicated, they will need to be tested themselves. This invites errors. But already you can see problems with the design of <code>Horizon</code> in the tests: the class should maintain the map of product frequencies itself--not in the test code or in <code>Horizon.main</code>.</p>\n\n<p>You're essentially building a shopping cart for the <code>Horizon</code> program. It requires a simple API given the code you have.</p>\n\n<pre><code>public class Cart {\n void add(Product item);\n Set&lt;Product&gt; getItems();\n int getCount(Product item);\n double getTotal();\n}\n</code></pre>\n\n<p>Here are some tests I would start with:</p>\n\n<pre><code>Cart fixture = new Cart();\n\n@Test\nvoid startsEmpty() {\n assertThat(fixture.getItems(), empty());\n}\n\n@Test\nvoid oneItem() {\n fixture.add(Product.HORIZON_BOX);\n assertThat(fixture.getItems(), contains(Product.HORIZON_BOX));\n assertThat(fixture.getCount(Product.HORIZON_BOX), is(1));\n assertThat(fixture.getTotal(), is(30.0));\n}\n\n@Test\nvoid combinesSameItems() {\n fixture.add(Product.HORIZON_BOX);\n fixture.add(Product.HORIZON_BOX);\n assertThat(fixture.getItems(), contains(Product.HORIZON_BOX));\n assertThat(fixture.getCount(Product.HORIZON_BOX), is(2));\n assertThat(fixture.getTotal(), is(60.0));\n}\n\n@Test\nvoid doesNotCombineDifferentItems() {\n fixture.add(Product.HORIZON_BOX);\n fixture.add(Product.HORIZON_MULTIROOM);\n assertThat(fixture.getItems(), containsInAnyOrder(Product.HORIZON_BOX, HORIZON_MULTIROOM));\n assertThat(fixture.getCount(Product.HORIZON_BOX), is(1));\n assertThat(fixture.getCount(Product.HORIZON_MULTIROOM), is(1));\n assertThat(fixture.getTotal(), is(105.0));\n}\n</code></pre>\n\n<p>Note that I'm using the <a href=\"https://github.com/hamcrest/JavaHamcrest\" rel=\"nofollow\">Hamcrest assertions</a> which are more expressive and easier to use and combine. The more recent versions of JUnit 4 (last couple years) are designed to use them as well. Also, when using <code>@Test</code> you don't need to start your test method names with <code>test</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T21:06:19.280", "Id": "24171", "ParentId": "24161", "Score": "3" } }, { "body": "<p>@David Harkness answered the question about Testing well enough, nothing important to add there. \nIn the second question review of the design is asked, there are important issues with the design also, but I did not want the following points go unmade:</p>\n\n<ul>\n<li><p>You seem to be new to generics:</p>\n\n<pre><code>@SuppressWarnings(\"rawtypes\")\n</code></pre>\n\n<p>If you had used <code>Iterator&lt;Map.Entry&lt;String, Integer&gt;&gt;</code> instead of a raw <code>Iterator</code> you would avoid not only this warning but also the unchecked cast (and the accompanying warning also)</p></li>\n<li><p>You should prefer for-each syntax when you iterate over a collection, unless you are adding or removing elements within the loop. Compare:</p>\n\n<pre><code>for (Iterator iterator = horizon.argFrequencyCount.entrySet()\n .iterator(); iterator.hasNext();) {\n @SuppressWarnings(\"unchecked\")\n Map.Entry&lt;String, Integer&gt; productCount = \n (Map.Entry&lt;String, Integer&gt;) iterator.next();\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>for (Map.Entry&lt;String, Integer&gt; productCount : \n horizon.argFrequencyCount.entrySet()) {\n</code></pre></li>\n<li><p>Various <code>Map&lt;String, Integer&gt;</code> should be changed to <code>Map&lt;Product, Integer&gt;</code>; as these maps hold the \"number of each <em>product</em>\".</p></li>\n<li><p>You are losing type information here:</p>\n\n<pre><code>Iterator&lt;Integer&gt; valueIt = mapValues.iterator();\nObject val = valueIt.next(); \n\n\nIterator&lt;Integer&gt; valueIt = mapValues.iterator();\nint val = valueIt.next(); \n// you should use Integer val = valueIt.next(); \n// if val could be null, not needed here\n</code></pre>\n\n<p>For-each loops help here, too.</p></li>\n<li><p>And because you lost the type info, above; you are comparing the objects \nby comparing their string representations:</p>\n\n<pre><code>String comp1 = passedMap.get(key).toString();\nString comp2 = val.toString();\nif (comp1.equals(comp2)) {\n</code></pre>\n\n<p>Instead you could have written:</p>\n\n<pre><code>if (passedMap.get(key).equals(val)) {\n</code></pre></li>\n<li><p>Another point with this snippet is <code>passedMap</code>, <code>key</code> and <code>val</code> are not descriptive at all. \n Now compare:</p>\n\n<pre><code> if (passedMap.get(key).equals(val)) {\n</code></pre>\n\n<p>with:</p>\n\n<pre><code> if (productFrequencies.get(product).equals(productFrequency)) {\n</code></pre>\n\n<p>Which reads better? Names are important.</p></li>\n<li><p>Here is the signature of <code>sortProductMapByFrequency</code>:</p>\n\n<pre><code>private Map&lt;Product, Integer&gt; sortProductMapByFrequency(\n Map&lt;Product, Integer&gt; passedMap) {\n</code></pre>\n\n<p>The contract of the return value should be evident from the signature. \nIf you are sorting a collection, the return value should have a definite order.\nSo at least you should return a <code>LinkedHashMap</code> explicitly.</p>\n\n<p>If you are sorting the entries of a map according to the keys, you should return a <code>SortedMap</code>.\nSince you sort the entries depending on value, not just on key, you cannot.\nThen I would expect a <code>List&lt;Map.Entry&lt;X,Y&gt;&gt;</code>, if you are sorting the entries of a <code>Map&lt;X,Y&gt;</code>. [You cannot use <code>SortedMap</code>, <em>straightforwardly</em>, but you can use sorted multimaps, e.g. if you have Apache Commons or Guava. There is a maintainability trade-off there]</p></li>\n<li><p>Also when you iterate over a map and use both keys and value you should use entrySet to iterate, as you did elsewhere. Your nested loop could then be a single loop, more efficient more readable. Or you could do this:</p>\n\n<pre><code>private List&lt;Map.Entry&lt;Product, Integer&gt;&gt; sortProductMapByFrequency(\n Map&lt;Product, Integer&gt; productFrequencies) {\n\n List&lt;Entry&lt;Product, Integer&gt;&gt; entries \n = new ArrayList&lt;Entry&lt;Product, Integer&gt;&gt;(productFrequencies.entrySet());\n\n Collections.sort(entries, compareProductFrequencies());\n\n return entries;\n}\n\nprivate Comparator&lt;Entry&lt;Product, Integer&gt;&gt; compareProductFrequencies() {\n return new Comparator&lt;Entry&lt;Product, Integer&gt;&gt;() {\n @Override\n public int compare(Entry&lt;Product, Integer&gt; lhs,\n Entry&lt;Product, Integer&gt; rhs) {\n\n return lhs.getValue().compareTo(rhs.getValue());\n }};\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T07:02:12.707", "Id": "24237", "ParentId": "24161", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:22:36.807", "Id": "24161", "Score": "2", "Tags": [ "java", "tdd" ], "Title": "TDD Approach and Simple Solution" }
24161
<p>I have a model class <code>Product</code> that gets populated from a service DTO object (using AutoMapper). The service is used to power many different applications and for each one the Product Model might need to behave a bit differently. After a bit of research I decided the <a href="http://www.dofactory.com/Patterns/PatternDecorator.aspx" rel="nofollow">'Decorator'</a> pattern might be a good choice to accompany these differences. Here is how I currently have implemented it. </p> <p>These classes are part of a library that gets included in each of the applications</p> <pre><code>public class Product { public virtual string ProductName { get; set; } public virtual Decimal Price { get; set; } public virtual string ImageUrl { get; set; } public virtual string GetImageUrl(){ return ImageUrl; } } public abstract class ProductDecorator : Product { private Product decoratedProduct; // the product being decorated protected ProductDecorator(Product decoratedProduct) { this.decoratedProduct = decoratedProduct; } public override string ProductName { get { return decoratedProduct.ProductName; } set { decoratedProduct.ProductName = value; } } public override decimal Price { get { return decoratedProduct.Price; } set { decoratedProduct.Price= value; } } public override string ImageUrl { get { return decoratedProduct.ImageUrl; } set { decoratedProduct.ImageUrl= value; } } } </code></pre> <p>In each application there may be need to slightly change the model.</p> <pre><code>public class FooProduct : Model.ProductDecorator { public FooProduct (Model.Product product) :base(product){} //we want to serve the image through a cdn public override string GetImageUrl() { return string.Format("cnd.network.com?url={0}", HttpUtility.HtmlEncode(ImageUrl)); } } </code></pre> <p>Usage would be something like this:</p> <pre><code> FooProduct prod = new FooProduct(productClient.GetProduct(23213)); Response.Write(prod.GetImageUrl()); </code></pre> <p>This is my first time using this pattern and I'm not sure if I've got it quite right or if it really applies to this scenario. Are there any foreseeable issues with this solution?</p> <h2>Update</h2> <p>I think I need to explain a little more how I got here.</p> <p>I created a class library to encapsulate an wcf service. The library takes the DTO's returned by the service and using <a href="http://automapper.codeplex.com/" rel="nofollow">AutoMapper</a>, maps the DTO to the Product class. The issue is that the product model needs to be a bit different for each of the applications consuming the service. Just using simple inheritance not quite right because a <code>FooProduct</code> needs to pretty much be exactly the same as a <code>Product</code> but just handle the data a bit differently. </p> <pre><code>// this returns a Product, but for this site I need a FooProduct var product = Client.GetProduct(232); </code></pre> <p>This problem is probably a result of bad design in lower layers and from the use of AutoMapper in Client Library. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:48:32.497", "Id": "37262", "Score": "2", "body": "This doesn't look right; you're creating an abstract class which cannot be instantiated, and inheriting from a class that can. In addition, when I think of \"decoration,\" I think of adding attributes to classes, not class inheritance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:51:58.580", "Id": "37271", "Score": "0", "body": "@RobertHarvey thanks for moving it here. I wasn't aware of this site!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:52:36.113", "Id": "37321", "Score": "1", "body": "It's a way to use the decorator pattern. :) Whether it's a good candidate for it is another question. I'd keep image base urls in some config instead and have a helper generate the full urls somewhere in the client project. Hence no need for FooProduct.\nBUT, if you have more \"business-related\" things you need to decorate a product with, I'd move the decoration into the service. Use some kind of reflection or IoC to find the relevant decorator(s) and do it before the UI/client code gets it. It can continue using it as a Product." } ]
[ { "body": "<p>I think you've misunderstood what decorator pattern is. As described in <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow\">Wikipedia</a></p>\n\n<p>\"In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.\"</p>\n\n<p>What you are doing is simple inheritance.</p>\n\n<p>You can do this with an interface, but you don't have too. You have to ask yourself the question \"Do I need to use the Product class?\" If you do, then leave it as is, if you don't, make it an interface, or mark it abstract.</p>\n\n<p>I'm going to assume you need it.</p>\n\n<p>Your class definition looks the same:</p>\n\n<pre><code>public class Product\n{\n public virtual string ProductName { get; set; }\n public virtual Decimal Price { get; set; }\n public virtual string ImageUrl { get; set; }\n\n public virtual string GetImageUrl()\n {\n return ImageUrl;\n }\n}\n</code></pre>\n\n<p>You would then inherit from this class for any other class you need:</p>\n\n<pre><code>public class FooProduct : Product\n{\n //we want to serve the image through a cdn\n public override string GetImageUrl()\n {\n return string.Format(\"cnd.network.com?url={0}\", HttpUtility.HtmlEncode(ImageUrl)); \n }\n}\n</code></pre>\n\n<p>You can now use either class as required:</p>\n\n<pre><code>var productInstance = new Product();\n\nvar fooProductInstance = new FooProduct();\n</code></pre>\n\n<p>The nice part is, you can now pass FooProduct in anywhere a Product is expected:</p>\n\n<pre><code>public void DoSomethingWithProduct(Product product)\n{\n // Do some processing\n}\n</code></pre>\n\n<p>Can be called:</p>\n\n<pre><code>processor.DoSomethingWithProduct(product);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>processor.DoSomethingWithProduct(fooProduct);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:48:28.190", "Id": "37270", "Score": "0", "body": "The issue with this design is that I don't have control on the Product instantiation since its coming from a Client Library using Automapper to go from my DTO's to the Product class. I guess I was trying to use the Decorator pattern so developers don't have to write mapping code every time they extend the Product. (essentially I'm an looking for some way to cast from a parent class to a derived class). Since these models will be passed into controls they will never build additional logic but instead just override methods" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:55:43.637", "Id": "37273", "Score": "0", "body": "How do you differentiate between Product and FooProduct then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:59:44.287", "Id": "37274", "Score": "0", "body": "Not quite sure what you mean by differentaite... Also I can still pass FooProduct anywhere that product is expected with the code in my answer. This solution probably arose from other issues in lower layers of the design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:02:48.290", "Id": "37276", "Score": "0", "body": "I mean, how do you determine if you need a Product or a FooProduct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:10:51.890", "Id": "37278", "Score": "1", "body": "From reading that Wiki it appears the OP has done exactly what it has said. The Window example they gave is essentially exactly the implementation here. What would be different from the Wiki Window example (apart from the fact Window is abstract) to the OP example??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:35:36.737", "Id": "37283", "Score": "1", "body": "Gotcha! From what I understood from your original question, I thought you were just trying to inherit Product into a FooProduct. I don't think there is much you can do if you need the different classes, but can't get them from the lower level. Is the imdateurl the only property that can be changed in the Product class, or is this just an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:37:35.597", "Id": "37284", "Score": "0", "body": "Are you using MVC or MVVM architecture for the front end applications?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:40:20.647", "Id": "37285", "Score": "0", "body": "@JeffVanzella The application Layer will define a FooProduct if they need to modify or extend the Product behavior. The developer simply gets a Product from the client, wraps it as a FooProduct and passes it along to any view or control that is expecting a Product. If extended functionality is needed from methods that don't exist in the Product then the View will need to accept the FooProduct definition. This is acceptable because most of the view will be defined in the application layer. (I deleted the previous comment to make edits)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T19:42:22.767", "Id": "37286", "Score": "0", "body": "@JeffVanzella the code is just an example. Unfortunately we are currently stuck in webforms but I'm pushing for adoption to MVC on new Applications. The code needs to work across both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:41:10.523", "Id": "37291", "Score": "0", "body": "There are better ways to go when using MVC (you can take your Product class and change what you need in your controller/model), but for now, I don't see any way around what you are doing." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:13:55.327", "Id": "24168", "ParentId": "24165", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:45:42.590", "Id": "24165", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "Is this correct usage of the \"Decorator\" Pattern?" }
24165
<p>I'm writing a pong game in Python and I created classes for the game objects. </p> <p>The top level class is <code>Object</code>, and <code>Ball</code> and <code>Paddle</code> inherit from it. And <code>ComputerPaddle</code> is a child class of <code>Paddle</code>. </p> <pre><code># classes.py # 3/19/2013 import pygame import random # Paddle properties PADDLE_WIDTH = 25 PADDLE_HEIGHT = 100 PADDLE_COLOR = (0, 0, 0) PADDLE_SPEED = 6 # Ball properties BALL_RADIUS = 20 BALL_COLOR = (0, 0, 0) BALL_INITIAL_VX = -5 BALL_INITIAL_VY = -5 # Base object class class Object: # Initializes the object with coordinates, size and color def __init__(self, x, y, w, h, color): self.x = x self.y = y self.w = w self.h = h self.vx = 0 self.vy = 0 self.color = color # Updates object by moving it and checking if it's in screen range def update(self, screenWidth, screenHeight): self.x += self.vx self.y += self.vy if self.x &lt; 0: self.x = 0 if self.y &lt; 0: self.y = 0 if self.x &gt; screenWidth - self.w: self.x = screenWidth - self.w if self.y &gt; screenHeight - self.h: self.y = screenHeight - self.h # Must be implemented by child classes def draw(self, surface): pass # Returns whether object collides with another object (rectangular collision detection) def collides(self, obj): return self.y &lt; obj.y + obj.h and self.y + self.h &gt; obj.y and self.x &lt; obj.x + obj.w and self.x + self.w &gt; obj.x # Called when object collides with anoher object, must be implemented by child classes def onCollide(self, obj): pass # Paddle class class Paddle(Object): # Initializes Paddle object def __init__(self, x, y): super(Paddle, self).__init__(x, y, PADDLE_WIDTH, PADDLE_HEIGHT, PADDLE_COLOR) # Draws paddle with a rectangle def draw(self, surface): pygame.draw.rect(surface, self.color, (self.x, self.y, self.w, self.h)) # Moves paddle up def moveUp(self): self.vy -= PADDLE_SPEED # Moves paddle down def moveDown(self): self.vy = PADDLE_SPEED # Stops moving the paddle def stopMoving(self): self.vy = 0 # ComputerPaddle class class ComputerPaddle(Paddle): # Initializes ComputerPaddle object def __init__(self, x, y): super(ComputerPaddle, self).__init__(x, y) # Adjust Y-velocity based on speed and direction of ball def update(self, ball, screenWidth, screenHeight): super(ComputerPaddle, self).update(screenWidth, screenHeight) if ball.vx &lt; 0: self.stopMoving() return ballX = ball.x ballY = ball.y ballVX = ball.vx ballVY = ball.vy while ballX + ball.w &lt; self.x: ballX += ballVX ballY += ballVY if ballY &lt; 0 or ballY &gt; screenHeight - ball.h: ballVY = -ballVY if ballY &gt; self.y + self.h: self.moveDown() elif ballY + ball.h &lt; self.y: self.moveUp() else: self.stopMoving() # Ball class class Ball(Object): # Initializes the Ball object along with initial velocities def __init__(self, x, y): super(Ball, self).__init__(x, y, BALL_RADIUS, BALL_RADIUS, BALL_COLOR) self.startX = x self.startY = y self.vx = BALL_INITIAL_VX self.vy = BALL_INITIAL_VY # Updates the ball object, if it hits screen edge then negate velocity def update(self, screenWidth, screenHeight): super(Ball, self).update(screenWidth, screenHeight) if self.x == 0 or self.x == screenWidth - self.w: self.vx = -self.vx if self.y == 0 or self.y == screenHeight - self.h: self.vy = -self.vy # Resets the ball back to its initial coordinates def reset(self): self.x = self.startX self.y = self.startY self.vx = BALL_INITIAL_VX self.vy = BALL_INITIAL_VY # Draws a circle onto screen to represent the ball def draw(self, surface): pygame.draw.circle(surface, self.color, (self.x, self.y), self.w) # If ball collides with another object, then negate both velocities by a random amount def onCollide(self, obj): # If ball is "inside" of paddle, then reposition it so it's just outside the paddle if self.x &lt; obj.x + obj.w: self.x = obj.x + obj.w elif self.x + self.w &gt; obj.x: self.x = obj.x - self.w if self.y &lt; obj.y + obj.h: self.y = obj.y + obj.h elif self.y + self.h &gt; obj.y: self.y = obj.y - self.h rx = int(random.uniform(-3, 5)) ry = int(random.uniform(-2, 4)) self.vx = -self.vx + rx self.vy = -self.vy + ry </code></pre> <p>Any ideas how to make this code better?</p>
[]
[ { "body": "<p>Instead of using 4 different fields to keep track of your object's position and size, I suggest you just use a <a href=\"http://www.pygame.org/docs/ref/rect.html\"><code>Rect</code></a>:</p>\n\n<pre><code>def __init__(self, x, y, w, h, color):\n self.rect = Rect(x, y, w, h)\n self.vx = 0\n self.vy = 0\n self.color = color\n</code></pre>\n\n<p>This way, you can simplify your code a lot.</p>\n\n<p><strong>Example:</strong> <a href=\"http://www.pygame.org/docs/ref/rect.html#Rect.colliderect\"><em>Collision detection</em></a></p>\n\n<pre><code>def collides(self, obj):\n return self.y &lt; obj.y + obj.h and self.y + self.h &gt; obj.y and self.x &lt; obj.x + obj.w and self.x + self.w &gt; obj.x\n</code></pre>\n\n<p>just becomes:</p>\n\n<pre><code>def collides(self, obj):\n return self.rect.colliderect(obj.rect)\n</code></pre>\n\n<p><strong>Example:</strong> <a href=\"http://www.pygame.org/docs/ref/rect.html#Rect.move_ip\">movement</a> and <a href=\"http://www.pygame.org/docs/ref/rect.html#Rect.clamp_ip\">bounds checking</a></p>\n\n<pre><code>def update(self, screenWidth, screenHeight):\n self.x += self.vx\n self.y += self.vy\n\n if self.x &lt; 0: self.x = 0\n if self.y &lt; 0: self.y = 0\n if self.x &gt; screenWidth - self.w: self.x = screenWidth - self.w\n if self.y &gt; screenHeight - self.h: self.y = screenHeight - self.h\n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>def update(self, screenWidth, screenHeight): \n self.rect.move_ip(self.vx, self.vy)\n self.rect.clamp_ip(Rect(0, 0, screenWidth, screenHeight)\n</code></pre>\n\n<p><strong>Example:</strong> <a href=\"http://www.pygame.org/docs/ref/draw.html#pygame.draw.rect\"><em>drawing</em></a></p>\n\n<pre><code>def draw(self, surface):\n pygame.draw.rect(surface, self.color, (self.x, self.y, self.w, self.h))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>def draw(self, surface):\n pygame.draw.rect(surface, self.color, self.rect)\n</code></pre>\n\n<p>Also, I probably wouldn't name a class <code>Object</code>, since there's already the <code>object</code> class.</p>\n\n<p>Otherwise, I think your code is fine so far.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T07:48:37.817", "Id": "24189", "ParentId": "24167", "Score": "6" } }, { "body": "<p>You may want to move the BALL and PADDLE properties to class attributes:</p>\n\n<pre><code># I wouldn't call your base class Object, as already noted\nclass Ball(Thing):\n radius = 20\n color = (0, 0, 0)\n</code></pre>\n\n<p>Then you can refer to <code>Ball.radius</code> whenever you need it. I'd use this approach because it would encapsulate data about the objects within their class definitions, and it would make it easier to use this as a module later -- you wouldn't need to use <code>from Things import Ball, BALL_RADIUS, BALL_COLOR</code>, just <code>from Things import Ball</code>. </p>\n\n<p>Another suggestion:\nUnless you're using the BALL_INITIAL_V values elsewhere, or want to change them on the fly, I would just use them in the <code>__init__</code> methods:</p>\n\n<pre><code>def __init__(self):\n self.Vx = -5\n self.Vy = -5\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:06:01.807", "Id": "24209", "ParentId": "24167", "Score": "2" } } ]
{ "AcceptedAnswerId": "24189", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T18:08:20.880", "Id": "24167", "Score": "3", "Tags": [ "python", "object-oriented", "classes", "helper", "pygame" ], "Title": "Pong game in Python" }
24167
<p>I need a function to get the value of the name attribute of each element with class="class". I was wondering what is the best way to do this, performance-wise.</p> <p>Currently I'm using jQuery and doing it like this:</p> <pre><code>$("#Button").click(function() { var myElements = $(".class"); for (var i=0;i&lt;myElements.length;i++) { alert(myElements.eq(i).attr("name")); } }); </code></pre> <p>Alert is just to show what it does, of course. For the following HTML:</p> <pre><code>&lt;input type="checkbox" class="class" name="1"&gt; &lt;input type="checkbox" class="nope" name="2"&gt; &lt;input type="checkbox" class="class" name="3"&gt; </code></pre> <p>It would issue:</p> <pre><code>alert("1") alert("3") </code></pre> <p>I was wondering if using pure Javascript would be faster, or if there is any other (better) way of doing it. I apologize if this question is not on this website's scope, please move it to Stackoverflow if that's the case.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T03:52:12.053", "Id": "37332", "Score": "3", "body": "Please, always replace alert by console.log\nAlert is blocking code execution and forces you to click ok or press enter as many times as a result is found." } ]
[ { "body": "<p>To do this is in 'pure' JavaScript, you do something like this, if using ES6 syntax:</p>\n\n<pre><code>var elements = document.getElementsByClassName('class');\nelements.forEach(e =&gt; { alert(e.name) });\n</code></pre>\n\n<p>For any browsers not supporting ES6 (including all versions of IE):</p>\n\n<pre><code>var elements = document.getElementsByClassName('class');\nelements.forEach(function(e) { alert(e.name); });\n</code></pre>\n\n<p>If IE8 support is required:</p>\n\n<pre><code>var elements = document.querySelectorAll('.class');\nfor (var i = 0; i &lt; elements.length; i++) {\n alert(elements[i].name);\n}\n</code></pre>\n\n<p>Which will be a bit faster compared to using jQuery. However, jQuery will still be the shortest code:</p>\n\n<pre><code>$('.class').each(e =&gt; { alert(e.name); });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T22:45:44.820", "Id": "37294", "Score": "0", "body": "Thank you. I might be dealing with 100+ elements, since this will be used in a comments section. I'll do some benchmarking with both codes and give some feedback when everything is done. I was wondering if it would be possible to use `document.getElementsByClassName()` and a for loop instead. I tried but couldn't get it to work. I used the same for loop and `document.getElementsByClassName('class')[i].name`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-20T21:54:27.797", "Id": "24173", "ParentId": "24172", "Score": "3" } }, { "body": "<p>Instead of storing them in an array, you can use <code>$.each</code> function for looping through them. Like this:</p>\n\n<pre><code>$(\"#Button\").click(function() {\n $(\".class\").each( function() {\n alert( $(this).attr(\"name\") );\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T21:56:09.780", "Id": "24174", "ParentId": "24172", "Score": "5" } }, { "body": "<p>You can use <code>document.querySelectorAll</code> to retrieve the desired elements:</p>\n\n<pre><code>var namedEls = document.querySelectorAll('input.class');\nfor (var i=0;i&lt;namedEls.length;i+=1){\n console.log(namedEls[i].name);\n} //=&gt; 1, 3\n</code></pre>\n\n<p>Or as one liner to retrieve names as <code>Array</code>:</p>\n\n<pre><code>var names = [].slice.call(document.querySelectorAll('input.class'))\n .map(function(el){return el.name});\n//=&gt; names is now [1,3]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:23:07.277", "Id": "37329", "Score": "0", "body": "Why `input[class=\"class\"]` and not `input.class`? (Unless you specifically want to exclude elements with multiple classes.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T07:29:05.033", "Id": "37470", "Score": "0", "body": "No particular reason, so changed the answer. Doesn't change the results." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:23:57.530", "Id": "24186", "ParentId": "24172", "Score": "1" } }, { "body": "<h2>Pure JS vs jQuery</h2>\n\n<p>Pure JavaScript will be significantly faster as you can see by <a href=\"http://jsperf.com/jquery-class-vs-getelementsbyclassname-class\">this jsPerf</a> which pits <code>document.getElementByClassName</code> vs the jQuery selector. Here are the results for Chrome 25:</p>\n\n<ul>\n<li><code>$('.class')</code> - <strong>4355</strong> operations per second</li>\n<li><code>getElementsByClassName('class')</code> - <strong>94636</strong> operations per second</li>\n</ul>\n\n<p>As you can see, for this simple operation the jQuery option is approximately 22 times slower than the pure-JavaScript equivalent. You can easily see why this is the case by checking out the <a href=\"http://code.jquery.com/jquery-1.9.1.js\">jQuery development source</a>, since the jQuery 'selector function' is so general it needs to do a lot of checks to see what the input is before it can act upon it.</p>\n\n<h2>Pure JS implementation</h2>\n\n<p>I've left the jQuery <code>click</code> event in as it looks like you already have a dependency on jQuery so no point changing the way you're hooking up your events.</p>\n\n<p><a href=\"http://jsfiddle.net/Tyriar/rs64D/\">jsFiddle</a></p>\n\n<pre><code>$(\"#Button\").click(function() {\n var items = document.getElementsByClassName('class');\n for (var i = 0; i &lt; items.length; i++)\n alert(items[i].name);\n});\n</code></pre>\n\n<h3>getElementsByClassName</h3>\n\n<p>Also note that I used <code>getElementsByClassName</code>. It is pretty important to choose the ideal selector if you care about performance. Since we care about all elements with a certain class we can immediately dismiss the others like <code>getElementsByTagName</code> and <code>querySelectorAll</code> and opt for the function that was built for finding elements of a particular class.</p>\n\n<h2>jQuery implementation</h2>\n\n<p>This would be my implementation using jQuery, notice that I didn't bother getting the jQuery object for <code>this</code> (ie. <code>$(this)</code>) because the plain JavaScript attribute is much easier in this case.</p>\n\n<p><a href=\"http://jsfiddle.net/Tyriar/BKCvh/\">jsFiddle</a></p>\n\n<pre><code>$(\"#Button\").click(function() {\n $(\".class\").each(function() {\n alert(this.name);\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:35:10.073", "Id": "37305", "Score": "0", "body": "Perfect. Although I like jQuery I avoid it when it can easily be done with pure Javascript. For some reason I couldn't make it work before, probably some dumb syntax error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:36:29.553", "Id": "37306", "Score": "0", "body": "Ditto. Takes a while to get your head around all the JS functions, make sure you're looking at your browser errors to debug it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:25:15.483", "Id": "37330", "Score": "1", "body": "Depending on what you want to do with the `name`s you could use [jQuery's `.map()`](http://api.jquery.com/map/) to get an array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:52:53.280", "Id": "37337", "Score": "1", "body": "@RoToRa I think it would be just as useful as `$(\".class\").each( function() {//stuff});` in this case, but thanks!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:19:46.057", "Id": "24190", "ParentId": "24172", "Score": "9" } }, { "body": "<pre><code>parent.querySelectorAll([name='value']);\n</code></pre>\n\n<p>Depending on your knowledge of your Dom, can be super efficient; you can select the parent node to search within or just go document if you have no specific Dom knowledge. </p>\n\n<p>If using custom elements or custom name space it can be very powerful and requires no library add ons. Works in all modern browsers. </p>\n\n<p>The platform is growing and can now do amazing things. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-05T17:03:27.437", "Id": "143337", "ParentId": "24172", "Score": "0" } } ]
{ "AcceptedAnswerId": "24190", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T21:32:12.717", "Id": "24172", "Score": "9", "Tags": [ "javascript", "jquery", "html", "dom" ], "Title": "Get the value of the name attribute of each element with class=\"class\"" }
24172
<p>I have began doing the problems found on Project Euler and have just solved problem 3. However, I feel as if my code is very long and too brute-force. I was hoping somebody could give it a look and give me some guidelines for this problem and for future programming in general. This would help me with cleaning it up or even just revealing better ways of solving this.</p> <p>Problem 3 states:</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29.</p> <p>What is the largest prime factor of the number 600851475143?</p> </blockquote> <pre><code>int primeFactor = 0; int pfCounter = 0; int[] pf = new int [1229]; int[] numbers = new int[10000]; long number = 600851475143L; int p = 0; //initialize the array numbers to include all numbers //from 1 to 1000 for determining prime numbers for(int i = 0; i &lt; numbers.length; i++) { numbers[i] = i+1; } //determining which numbers are prime numbers for(int i = 0; i &lt;numbers.length; i++) { //divide each number by every number below it //to see if the pfCounter = 1 which would mean //it is only divisible by itself and 1 for(int j = i; j &gt; 0; j--) { if(numbers[i] % j == 0) { pfCounter++; } } //if the number only has 1 in it's pfCounter //insert the number from the numbers array into the //pf array and restart the counter to 0 else restart //the counter to 0 and try again if(pfCounter == 1) { pf[p] = numbers[i]; pfCounter = 0; p++; } else { pfCounter = 0; } } /* for(p = 0; p &lt; pf.length; p++) { System.out.println(pf[p]); }*/ for(int i = 0; i &lt; pf.length; i++) { if(number % pf[i] == 0) { primeFactor = pf[i]; } } System.out.println(primeFactor); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T01:08:51.577", "Id": "37511", "Score": "0", "body": "If you are trying to find all primes in a given range, take a look at the sieve of Eratosthenes. It is the easiest and probably fastest way for integer/long. Rest is already answered. An other approach to the given problem could be to try to divide by all smaller numbers until the current sqrt. The last number is the result." } ]
[ { "body": "<p>If I may give you one <strong>tip</strong> right away: try to write out the variable names and don't use abbreviations. If <code>primeFactorCounter</code> seems too long to you, just say <code>counter</code>. Right now your code is short and you know what <code>pfCounter</code>means, but it is just hard to read for someone else or for you when you read it again in 2 Weeks. </p>\n\n<p>By the way nicely documented, it was really easy to understand your code that way :)</p>\n\n<p>Anyway, back to your question. </p>\n\n<ul>\n<li><p>the first for loop fills an array with the natural numbers. This is not necessary. the numbers won't change, so instead of looping through the array every time to get the number, just use the loop's index <code>for(int i=1; i&lt;=n; i++)</code> where <code>n</code>would be the <code>10000</code> instead of the array's length. </p></li>\n<li><p>another little tweak to speed things up could be to stop the loop when you find out that you have no use for the number. But you would have to change the loops conditions a little bit. You only need to test the numbers that are smaller than the one you are investigating and bigger than 1 (because every number can be divided by one or itself):</p></li>\n</ul>\n\n<p>so instead of: </p>\n\n<pre><code>for (int j = i; j &gt; 0; j--) {\n if (numbers[i] % j == 0) {\n pfCounter++;\n }\n}\n</code></pre>\n\n<p>try</p>\n\n<pre><code>for (int j = i-1; j &gt; 1; j--) {\n if (numbers[i] % j == 0) {\n break; // this breaks out of the loop\n }\n}\n</code></pre>\n\n<p>Now you don't have to test if your <code>pfCounter</code> is bigger than 1. (PS: I didn't replace the <code>numbers[i]</code> by <code>i</code> just start the \"i-loop\" with <code>i=1</code>and you'll be fine!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:17:25.267", "Id": "37328", "Score": "0", "body": "Great! These were the little things I was looking for! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T23:40:20.353", "Id": "24179", "ParentId": "24178", "Score": "3" } }, { "body": "<p>If a number <em>x</em> (with <em>x</em> > 2) is not a prime number, there exists a prime <em>p</em> so that <em>x</em> is divisible by <em>p</em> and <em>p</em> &lt; <em>x</em>.</p>\n\n<p>This means to determine if a number is a prime number, you only have to test it against smaller primes (which you already know). We need one prime (2) to start this process, so we will begin to search for primes from 3 onward.</p>\n\n<p>This technique is known as memoization, which you will find quite useful for many PE problems.</p>\n\n<p>This would lead to the following code (incorporating the points of GameDroids):</p>\n\n<pre><code>int[] primes = new int[somethingSufficientlyLarge];\nprimes[0] = 2;\nprimeCounter = 1; // a \"pointer\" to the next prime\n\nfor (int n = 3; n &lt; 10000; n += 2) { // only odd numbers can be primes (except 2)\n bool isAPrime = true;\n for (int i = 0; i &lt; primeCounter; i++) {\n if (n % primes[primeCounter] == 0) {\n isAPrime = false;\n break;\n }\n }\n if (isAPrime) {\n primes[primeCounter] = n;\n primeCounter++\n }\n}\n</code></pre>\n\n<p>Note that using a (Linked) List will make hardcoding the length of the prime array unneccessary. However, there may or may not be performance implications.</p>\n\n<p>But you do not know that the largest prime factor is in fact smaller than 10000. It could be ⌊600851475143/2⌋ for all we know. This would be the proper bound of your search space.</p>\n\n<p>Maybe we can reduce that bound: Every time we find a prime in our sieve loop, we test if <code>number</code> is divisible by that prime. We then do so until the number isn't divisible by that factor. If the result is 1, we can break the loop, as the largest prime factor was found.\nThe loop runs from 2 to <code>bound</code>, where <code>bound</code> initially is <code>floor(number/2)</code>, but once the first factor is found, the <code>bound</code> is the number divided by every factor. If no factor was found, then the number itself is the largest factor.</p>\n\n<p>Example 1:</p>\n\n<ol>\n<li>Factorization of the number 15. Bound is floor(15/2) = 7.</li>\n<li>First prime is 2. Not a factor.</li>\n<li>Next candidate 3 is prime, is a factor. New bound is 5.</li>\n<li>Next candidate 5 is prime, is a factor. Bound drops to 1 → break.</li>\n<li>Largest prime factor is 5.</li>\n</ol>\n\n<p>Example 2:</p>\n\n<ol>\n<li>Factorization of the number 13. Bound is floor(13/2) = 6.</li>\n<li>First prime is 2. Not a factor.</li>\n<li>Next candidate 3 is prime, not a factor.</li>\n<li>Next candidate 5 is prime, not a factor.</li>\n<li>Loop exits without factor found. 13 itself must be a prime, and its largest prime factor.</li>\n</ol>\n\n<p>General hints:</p>\n\n<ul>\n<li>In your original code you tested for factors in the range <code>(0, n]</code> where n is the number you wanted to factorize. But as no factor can be larger than n/2, you could have reduced the range to <code>(0, ⌊n/2⌋]</code>. This would have reduced substantial overhead. Try to find such cases that can never occur (factors in the range <code>[⌈n/2⌉, n]</code>) and optimize.</li>\n<li><p>In your fist factorization loop you started with the largest factor first. This is bad, as ½ of numbers are divisible by 2, ⅓ by 3, ⅕ by 5 and so on. I.e. you can weed out many non-primes by testing a very small set of numbers. Try to find common cases, and test for them befoe testing for uncommon cases. Also, try to “fail early” (which is wisdom not only applicable to programming).</p>\n\n<p>However, when factorizing your large <code>number</code>, you should have started with the largest possible prime first, count downwards, and stop once you found a factor, instead of looping through <em>all</em> primes</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:16:53.297", "Id": "37327", "Score": "0", "body": "Awesome! This is exactly the kind of information I was looking for. I'm still an amateur programmer so I'm trying to find ways to better my overall coding and I appreciate the help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T12:55:03.863", "Id": "37398", "Score": "0", "body": "@aelsedoudi If you are just trying to learn programming (and not neccessarily learn Java), switching the language could be beneficial: Java has some painful restrictions. C# is very Java-like but more convenient. Languages like Perl, Python, Ruby are very powerful and don't require a seperate compilation step. More arcane languages like Ocaml, Scheme, Go or even Haskell are extremely fascinating, but require a different mindset. “Object orientation”, the thing Java requires, is hard to get right. Especially [Python](http://www.learnpython.org/) might be a good choice to learn programming." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T03:22:26.847", "Id": "24183", "ParentId": "24178", "Score": "6" } }, { "body": "<p>A complete running program to solve this problem should take well under 20 lines of Java code; any more than that and you're working too hard.</p>\n\n<p>Hints:</p>\n\n<ul>\n<li>By inspection, 600851475143 has no even factors.</li>\n<li><p>There is no need to construct a list of primes or test any of the factors for primality. The heart of the solution is…</p>\n\n<pre><code>for (int factor = 3; ; factor += 2) {\n while (n % factor == 0) {\n // As long as you try the factors in increasing order, \n // factor is guaranteed to be prime at this point.\n n /= factor;\n }\n …\n}\n</code></pre></li>\n</ul>\n\n<p>That's all! You should be able to figure out the terminating condition for the loop.</p>\n\n<p><em>(Why is that comment true? What happens if you replace the <code>while</code> with <code>if</code>?)</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:30:06.933", "Id": "40715", "ParentId": "24178", "Score": "2" } } ]
{ "AcceptedAnswerId": "24183", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T23:06:20.050", "Id": "24178", "Score": "2", "Tags": [ "java", "project-euler", "primes" ], "Title": "Project Euler Problem #3 - largest prime factor" }
24178
<h1>Background</h1> <p>The following code (part of a natural language processor) was written to eliminate duplicate code by using <code>isLeft</code> as a conditional throughout the method:</p> <pre><code>private void doInsideChartBinaryRules( boolean isLeft, int state, int start, int end, int[] narrowLExtent_end, int[] narrowRExtent_start, int[] wideLExtent_end, int[] wideRExtent_start, float[] iScore_start_end, float[][] iScore_start, float[][][] iScore, boolean lengthNormalization ) { int narrowR = narrowRExtent_start[ state ], narrowL = narrowLExtent_end[ state ]; BinaryRule[] rules = ( isLeft ) ? bg.splitRulesWithLC( state ) : bg.splitRulesWithRC( state ); for( BinaryRule rule : rules ) { int leftChild = rule.leftChild; int rightChild = rule.rightChild; if( isLeft ) { narrowL = narrowLExtent_end[ rightChild ]; // can this right constituent fit next to the left constituent? if( narrowL &lt; narrowR ) { continue; } } else { narrowR = narrowRExtent_start[ leftChild ]; if( narrowR &gt; narrowL ) { continue; } } int min2 = ( isLeft ) ? wideLExtent_end[ rightChild ] : wideLExtent_end[ state ]; int min = ( narrowR &gt; min2 ? narrowR : min2 ); int max1 = ( isLeft ) ? wideRExtent_start[ state ] : wideRExtent_start[ leftChild ]; int max = ( max1 &lt; narrowL ? max1 : narrowL ); if( min &gt; max ) { continue; } float pS = rule.score; int parentState = rule.parent; float oldIScore = iScore_start_end[ parentState ]; float bestIScore = oldIScore; boolean foundBetter; if( !lengthNormalization ) { // find the split that can use this rule to make the max score for( int split = min; split &lt;= max; split++ ) { boolean skip = false; for( ParserConstraint c : constraints ) { if( ( ( start &lt; c.start &amp;&amp; end &gt;= c.end ) || ( start &lt;= c.start &amp;&amp; end &gt; c.end ) ) &amp;&amp; split &gt; c.start &amp;&amp; split &lt; c.end ) { skip = true; break; } if( ( start == c.start &amp;&amp; split == c.end ) ) { String tag = isLeft ? stateIndex.get( state ) : stateIndex.get( leftChild ); Matcher m = c.state.matcher( tag ); if( !m.matches() ) { skip = true; break; } } if( ( split == c.start &amp;&amp; end == c.end ) ) { String tag = isLeft ? stateIndex.get( rightChild ) : stateIndex.get( state ); Matcher m = c.state.matcher( tag ); if( !m.matches() ) { skip = true; break; } } } if( skip ) { continue; } float lS = ( isLeft ) ? iScore_start[ split ][ state ] : iScore_start[ split ][ leftChild ]; if( lS == Float.NEGATIVE_INFINITY ) { continue; } float rS = ( isLeft ) ? iScore[ split ][ end ][ rightChild ] : iScore[ split ][ end ][ state ]; if( rS == Float.NEGATIVE_INFINITY ) { continue; } float tot = pS + lS + rS; if( tot &gt; bestIScore ) { bestIScore = tot; } } foundBetter = bestIScore &gt; oldIScore; } else { int bestWordsInSpan = wordsInSpan[ start ][ end ][ parentState ]; float oldNormIScore = oldIScore / bestWordsInSpan; float bestNormIScore = oldNormIScore; for( int split = min; split &lt;= max; split++ ) { float lS = ( isLeft ) ? iScore_start[ split ][ state ] : iScore_start[ split ][ leftChild ]; if( lS == Float.NEGATIVE_INFINITY ) { continue; } float rS = ( isLeft ) ? iScore[ split ][ end ][ rightChild ] : iScore[ split ][ end ][ state ]; if( rS == Float.NEGATIVE_INFINITY ) { continue; } float tot = pS + lS + rS; int newWordsInSpan = ( isLeft ) ? wordsInSpan[ start ][ split ][ state ] + wordsInSpan[ split ][ end ][ rightChild ] : wordsInSpan[ start ][ split ][ leftChild ] + wordsInSpan[ split ][ end ][ state ]; float normTot = tot / newWordsInSpan; if( normTot &gt; bestNormIScore ) { bestIScore = tot; bestNormIScore = normTot; bestWordsInSpan = newWordsInSpan; } } foundBetter = bestNormIScore &gt; oldNormIScore; if( foundBetter ) { wordsInSpan[ start ][ end ][ parentState ] = bestWordsInSpan; } } if( foundBetter ) { iScore_start_end[ parentState ] = bestIScore; if( oldIScore == Float.NEGATIVE_INFINITY ) { if( start &gt; narrowLExtent_end[ parentState ] ) { narrowLExtent_end[ parentState ] = start; wideLExtent_end[ parentState ] = start; } else { if( start &lt; wideLExtent_end[ parentState ] ) { wideLExtent_end[ parentState ] = start; } } if( end &lt; narrowRExtent_start[ parentState ] ) { narrowRExtent_start[ parentState ] = end; wideRExtent_start[ parentState ] = end; } else { if( end &gt; wideRExtent_start[ parentState ] ) { wideRExtent_start[ parentState ] = end; } } } } } } </code></pre> <h1>Problem</h1> <p>This has caused a 10% performance <em>decrease</em>.</p> <h1>Question</h1> <p>How would you refactor the code to eliminate all the checks for <code>isLeft</code> so as to regain (or exceed) the performance that was lost?</p> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T00:14:09.880", "Id": "37508", "Score": "0", "body": "Even if it is already answered, I suggest to think about using objects and/or split the logic in several functions. Such a number of arguments is a good indicator to introduce an object. You could use polymorphism to simplify the code and logic, you could probably remove all of this `isLeft` flag. Besides that, you should use a profiler and provide a working example if expecting good answers." } ]
[ { "body": "<p>The first thing checked was where and how <code>isLeft</code> is used by removing code repetition around it:</p>\n\n<pre><code> float rS = ( isLeft ) ?\n iScore[ split ][ end ][ rightChild ] :\n iScore[ split ][ end ][ state ];\n</code></pre>\n\n<p>became </p>\n\n<pre><code> float rS = iScore[ split ][ end ][ isLeft ? rightChild : state ];\n</code></pre>\n\n<p>then it became clear that the same patterns were appearing a bit everywhere : <code>isLeft ? rightChild : state</code> and <code>isLeft ? state : leftChild</code>. Storing these values in a variable as soon as possible could save a few computations. The corresponding code could would be:</p>\n\n<pre><code>private void doInsideChartBinaryRules( boolean isLeft, int state, int start,\n int end, int[] narrowLExtent_end,\n int[] narrowRExtent_start,\n int[] wideLExtent_end,\n int[] wideRExtent_start,\n float[] iScore_start_end,\n float[][] iScore_start,\n float[][][] iScore,\n boolean lengthNormalization ) {\n int narrowR = narrowRExtent_start[ state ],narrowL = narrowLExtent_end[ state ];\n\n BinaryRule[] rules = isLeft ? bg.splitRulesWithLC( state ) : bg.splitRulesWithRC( state );\n\n for( BinaryRule rule : rules ) {\n int leftChild = rule.leftChild;\n int rightChild = rule.rightChild;\n\n if( isLeft ) {\n narrowL = narrowLExtent_end[ rightChild ];\n // can this right constituent fit next to the left constituent?\n if( narrowL &lt; narrowR ) {\n continue;\n }\n }\n else {\n narrowR = narrowRExtent_start[ leftChild ];\n if( narrowR &gt; narrowL ) {\n continue;\n }\n }\n\n int state1 = isLeft ? rightChild : state;\n int state2 = isLeft ? state : leftChild;\n\n int min2 = wideLExtent_end[ state1];\n int min = ( narrowR &gt; min2 ? narrowR : min2 );\n int max1 = wideRExtent_start[ state2 ];\n int max = ( max1 &lt; narrowL ? max1 : narrowL );\n\n if( min &gt; max ) {\n continue;\n }\n\n float pS = rule.score;\n int parentState = rule.parent;\n float oldIScore = iScore_start_end[ parentState ];\n float bestIScore = oldIScore;\n boolean foundBetter;\n\n if( !lengthNormalization ) {\n // find the split that can use this rule to make the max score\n for( int split = min; split &lt;= max; split++ ) {\n\n boolean skip = false;\n for( ParserConstraint c : constraints ) {\n if( ( ( start &lt; c.start &amp;&amp; end &gt;= c.end ) ||\n ( start &lt;= c.start &amp;&amp; end &gt; c.end ) ) &amp;&amp; split &gt; c.start &amp;&amp;\n split &lt; c.end ) {\n skip = true;\n break;\n }\n\n if( ( start == c.start &amp;&amp; split == c.end ) ) {\n String tag = stateIndex.get( state2 );\n Matcher m = c.state.matcher( tag );\n if( !m.matches() ) {\n skip = true;\n break;\n }\n }\n\n if( ( split == c.start &amp;&amp; end == c.end ) ) {\n String tag = stateIndex.get( state1 );\n Matcher m = c.state.matcher( tag );\n if( !m.matches() ) {\n skip = true;\n break;\n }\n }\n }\n\n if( skip ) {\n continue;\n }\n\n float lS = iScore_start[ split ][ state2];\n\n if( lS == Float.NEGATIVE_INFINITY ) {\n continue;\n }\n\n float rS = iScore[ split ][ end ][ state1];\n\n if( rS == Float.NEGATIVE_INFINITY ) {\n continue;\n }\n float tot = pS + lS + rS;\n\n if( tot &gt; bestIScore ) {\n bestIScore = tot;\n }\n }\n\n foundBetter = bestIScore &gt; oldIScore;\n }\n else {\n int bestWordsInSpan = wordsInSpan[ start ][ end ][ parentState ];\n float oldNormIScore = oldIScore / bestWordsInSpan;\n float bestNormIScore = oldNormIScore;\n\n for( int split = min; split &lt;= max; split++ ) {\n float lS = iScore_start[ split ][ state2];\n\n if( lS == Float.NEGATIVE_INFINITY ) {\n continue;\n }\n\n float rS = iScore[ split ][ end ][ state1];\n\n if( rS == Float.NEGATIVE_INFINITY ) {\n continue;\n }\n\n float tot = pS + lS + rS;\n int newWordsInSpan = \n wordsInSpan[ start ][ split ][ state2] +\n wordsInSpan[ split ][ end ][ state1];\n float normTot = tot / newWordsInSpan;\n\n if( normTot &gt; bestNormIScore ) {\n bestIScore = tot;\n bestNormIScore = normTot;\n bestWordsInSpan = newWordsInSpan;\n }\n }\n\n foundBetter = bestNormIScore &gt; oldNormIScore;\n\n if( foundBetter ) {\n wordsInSpan[ start ][ end ][ parentState ] = bestWordsInSpan;\n }\n }\n if( foundBetter ) {\n iScore_start_end[ parentState ] = bestIScore;\n\n if( oldIScore == Float.NEGATIVE_INFINITY ) {\n if( start &gt; narrowLExtent_end[ parentState ] ) {\n narrowLExtent_end[ parentState ] = start;\n wideLExtent_end[ parentState ] = start;\n }\n else {\n if( start &lt; wideLExtent_end[ parentState ] ) {\n wideLExtent_end[ parentState ] = start;\n }\n }\n if( end &lt; narrowRExtent_start[ parentState ] ) {\n narrowRExtent_start[ parentState ] = end;\n wideRExtent_start[ parentState ] = end;\n }\n else {\n if( end &gt; wideRExtent_start[ parentState ] ) {\n wideRExtent_start[ parentState ] = end;\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>My variable names are not good because I have no idea what this is all about. Anyway, at this stage, there almost no check related to isLeft anymore.</p>\n\n<p>Then, a little detail I noticed is that rightChild is not used sometimes so we can avoid getting it in the first place by noticing that we could move the variables introduced previously (the check on isLeft ensures that we consider the right value) :</p>\n\n<pre><code>for( BinaryRule rule : rules ) {\n int state1 = isLeft ? rule.rightChild : state;\n int state2 = isLeft ? state : rule.leftChild;\n\n if( isLeft ) {\n narrowL = narrowLExtent_end[ state1 ];\n // can this right constituent fit next to the left constituent?\n if( narrowL &lt; narrowR ) {\n continue;\n }\n }\n else {\n narrowR = narrowRExtent_start[ state2 ];\n if( narrowR &gt; narrowL ) {\n continue;\n }\n }\n</code></pre>\n\n<p>Then, a thing to notice in the code above is the duplicated logic which can be extracted :</p>\n\n<pre><code>for( BinaryRule rule : rules ) {\n int state1 = isLeft ? rule.rightChild : state;\n int state2 = isLeft ? state : rule.leftChild;\n\n if( isLeft ) {\n narrowL = narrowLExtent_end[ state1 ];\n }\n else {\n narrowR = narrowRExtent_start[ state2 ];\n }\n // can this right constituent fit next to the left constituent?\n if( narrowR &gt; narrowL ) {\n continue;\n }\n</code></pre>\n\n<p>At this stage, everything we've done should be either without effect or with a good effect on performance. I am not so confident that this will be true for the next change but I'd rather give it to you as an option anyway.</p>\n\n<p>One can notice that <code>narrowR</code> is either <code>narrowRExtent_start[ state ]</code> or <code>narrowRExtent_start[ leftChild ]</code> depending on the value of <code>isLeft</code>. In a concise way, <code>narrowR = narrowRExtent_start[isLeft ? state : leftChild]</code> which is <code>narrowR = narrowRExtent_start[state2]</code>. The same applies to <code>narrowL</code>. Thus, the code can be written :</p>\n\n<pre><code>for( BinaryRule rule : rules ) {\n int state1 = isLeft ? rule.rightChild : state;\n int state2 = isLeft ? state : rule.leftChild;\n\n int narrowL = narrowLExtent_end[ state1 ];\n int narrowR = narrowRExtent_start[ state2 ];\n</code></pre>\n\n<p>This removes yet another check on <code>isLeft</code> but it comes at a cost.</p>\n\n<p>In the original code, we get values from <code>narrowXExtend_xxx</code> twice at the beginning and then once per iteration. In my case, we don't do it at the beginning but then we do it twice per iteration. If the size of <code>rules</code> is bigger than 2, it could lead to a slightly less efficient code. This might be worth doing it to get rid of any code repetition but this is up to you.</p>\n\n<p>Now, just a comment not related to the logic around <code>isLeft</code> :</p>\n\n<pre><code> if( end &lt; narrowRExtent_start[ parentState ] ) {\n narrowRExtent_start[ parentState ] = end;\n wideRExtent_start[ parentState ] = end;\n }\n else {\n if( end &gt; wideRExtent_start[ parentState ] ) {\n wideRExtent_start[ parentState ] = end;\n }\n }\n</code></pre>\n\n<p>could be rewritten :</p>\n\n<pre><code> if( end &lt; narrowRExtent_start[ parentState ] ) {\n narrowRExtent_start[ parentState ] = end;\n wideRExtent_start[ parentState ] = end;\n }\n else if( end &gt; wideRExtent_start[ parentState ] ) {\n wideRExtent_start[ parentState ] = end;\n }\n</code></pre>\n\n<p>It doesn't change the performances but is easier to read. The same comment applies to different places in the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:12:18.297", "Id": "37368", "Score": "1", "body": "I moved `BinaryRule[] rules = isLeft ? bg.splitRulesWithLC( state ) : bg.splitRulesWithRC( state );` outside the function (by adding `BinaryRule rules[]` as an additional parameter) and now see big performance gains. Thank you for all the help and extensive analysis." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:04:24.617", "Id": "24185", "ParentId": "24181", "Score": "3" } } ]
{ "AcceptedAnswerId": "24185", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T01:48:18.407", "Id": "24181", "Score": "1", "Tags": [ "java", "optimization", "performance" ], "Title": "Optimization: Eliminate conditional expression within common code" }
24181
<p>Part 1 of 4 is complete.</p> <p>I would like to know if what I have done could be improved. Please don't worry about output - that is a work in progress.</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;time.h&gt; #include &lt;conio.h&gt; struct Accounts { int accountNumber; char accountName[30]; double accountBalance; double lastPaymentAmount; }; int main(int argc, char *argv[] ) { int count; FILE *cfPtrSource; FILE *cfPtrDesitination; char strYesNo[4]; char mystring [200]; char *field; size_t length; struct Accounts accounts; //Check for the proper number of arguments. If incorrect, display a useful error message to the user and exit the program. //print out the arguments and count the arguments printf("Arg count: %d\n", argc); for (count = 1; count &lt; argc; count++) { printf("%d Value entered: %s\n", count, argv[count]); } //check to see if there are min two arguments entered if(!(count-1 == 2) ) { printf("\nERROR!! FAIL!! Please enter two arguments\n\n"); exit(1); } //check to see if source data file exist if ((cfPtrSource = fopen( argv[1], "rb" )) == NULL) { printf("The source file: %s could not be opened.\n", argv[1]); exit(1); }else{ printf("The source file: %s was opened\n", argv[1]); fclose( cfPtrSource ); printf("The source file: %s was closed\n", argv[1]); } //check to see if the destination file exist if (( cfPtrDesitination = fopen( argv[2], "rb")) == NULL) { printf( "The destination file: %s could not be opened.\n", argv[2] ); //Create the file if the file does not exist. if (( cfPtrDesitination = fopen( argv[2], "wb")) == NULL) { printf("the destination file: %s was not created\n", argv[2]); exit(1); }else{ printf("The destination file: %s was created\n", argv[2]); fclose(cfPtrDesitination);// Should I close the file at this point? } }else{ //If the file exists, display the filename printf("The destiination file: %s was opened\n", argv[2]); //warn the user it will be over written printf("Would you like to over write the file: %s (YES / NO)\n", argv[1]); //ask if they want to continue scanf( "%3s", strYesNo); printf("The user input was: %s\n",strYesNo); //Check the user response from step c (if applicable). if((strYesNo[0] == 'Y') | (strYesNo[0] == 'y') ) { printf("\nuser said Y\n\n"); }else{ printf("\nuser said N\n"); printf("exit the progam\n"); exit(1); } fclose(cfPtrDesitination); } //Process the file if the user response is Yes otherwise exit the program //file created/opened cfPtrSource = fopen(argv[1], "rb"); printf("Source file opened: %s\n", argv[1]); cfPtrDesitination = fopen(argv[2], "wb"); printf("Desitination file opened: %s\n", argv[2]); //parses each line, populates an appropriately defined struct and writes the struct to a file in binary format while (fgets(mystring, sizeof(mystring), cfPtrSource) != NULL) { //check for a new line character and replace if it exist length = strlen(mystring); //printf("1nd: %s",mystring); if (mystring[length - 1] == '\n') { mystring[length - 2] = '\0'; } //printf("2nd: %s",mystring); field = strtok(mystring, ","); printf("account Number:'%s'\n", field); accounts.accountNumber = atoi(field); field = strtok(NULL, ","); printf("account Name: '%s'\n", field); strcpy(accounts.accountName, field); field = strtok(NULL, ","); printf("account balance: '%s'\n", field); accounts.accountBalance = atof(field); field = strtok(NULL, ","); printf("account lastpay: '%s'\n", field); accounts.lastPaymentAmount = atof(field); printf( "struct-lastPaymentAmount: %s\n", accounts.lastPaymentAmount ); fwrite( &amp;accounts, sizeof(struct Accounts), 1, cfPtrDesitination ); } //clean up and close the files fclose(cfPtrSource); fclose(cfPtrDesitination); printf("\n\nfile closed\n\n"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:56:10.163", "Id": "37605", "Score": "0", "body": "In addition to what has already been said, you need to split your \"monster-main\" into several smaller functions." } ]
[ { "body": "<p>Nothing super huge, but here's a brain dump:</p>\n\n<ul>\n<li>typedef the accounts struct so you don't have to include <code>struct</code> each time</li>\n<li>you have a lot of debugging type code that shouldn't be in a final program (for example, dumping back out the passed arguments)\n<ul>\n<li>typically when you're doing debugging type output, you'll want to use stderr</li>\n<li>Edit: whoops, just remembered that you said to ignore output</li>\n</ul></li>\n<li>Lots of things wrong with this: <code>if(!(count-1 == 2) )</code>\n<ul>\n<li>You have an extra space there before the last closing parenthesis</li>\n<li>Rather than abusing the left overs of the debugging loop, just check argc directly</li>\n<li>use <code>if(argc != 2)</code> rather than <code>if(!(argc == 2))</code></li>\n</ul></li>\n<li>I would use <code>return</code> instead of <code>exit</code> in your situations\n<ul>\n<li>The differences are going to be very subtle, but I feel like the actual intention is <code>return</code> moreso than <code>exit()</code></li>\n<li>Other than the requirement of <code>stdlib.h</code> to pull in <code>exit</code>, I'm not sure if there is actually any meaningful difference in C.</li>\n<li>In C++, there is indeed a subtle but potentially important difference: <code>return</code> will have local objects destruct; <code>exit</code> will not.</li>\n</ul></li>\n<li>Your indentation is all kinds of crazy.\n<ul>\n<li>Short rule: Inside blocks should be indented at one level</li>\n</ul></li>\n<li>Your use of <code>if(</code>, <code>if (</code> and <code>while (</code> irks me. Pick either a space or no space and stick with it.</li>\n<li>\"destination\", not \"desitination\"</li>\n<li>The flow of your \"ask the user if he wants to overwrite the file if it already exists\" section is a bit confusing</li>\n<li>With regards to: <code>if((strYesNo[0] == 'Y') | (strYesNo[0] == 'y') )</code>\n<ul>\n<li>When you mean logical or (<code>||</code>), use logical or.</li>\n<li><code>|</code> does not short circuit, meaning you can run into all kinds of fun issues with this if it becomes a habit</li>\n</ul></li>\n<li>Some of your comments are completely unnecessary, or in the wrong place.\n<ul>\n<li>Example of unnecessary: <code>//clean up and close the files</code></li>\n<li>Example of wrong place: <code>//Check for the proper number of arguments. If incorrect, display a useful error message to the user and exit the program.</code></li>\n<li><em>Also unneccessary</em></li>\n</ul></li>\n<li>You have way too much going on in your main. Try to identify abstract concerns, push those into their own functions, and then let main chain those together:\n<ul>\n<li>Open the source file</li>\n<li>Open the destination file</li>\n<li>Parse the CSV</li>\n<li>Write the parsed data out to a file</li>\n</ul></li>\n<li>You seem to have some extra headers. I'd need to look closer, but I think you just need: stdio.h, stdlib.h, string.h\n<ul>\n<li>As long as the effort is fairly minimal (as it is in this application), I like to stay cross platform. <code>conio.h</code> instantly murders that.</li>\n<li>Comes down to opinion though. If you're 100% sure that your application will always stay on your platform, then go at it.</li>\n</ul></li>\n<li>Since it's part of your assignment, it's not really your issue, but writing a struct to a file is implementation dependent.</li>\n<li>Your error checking could be more paranoid, but it's not strictly necessary\n<ul>\n<li>What happens if between the time you check for the existence of the file and the second time you try to open it, it's been deleted?</li>\n<li>Also, you might as well keep the files open when you can rather than reopening them</li>\n</ul></li>\n<li>If the last character of a string pulled through fgets isn't a new line, your buffer isn't big enough. Whether or not you want to handle that though... Well, it does make things a bit of a pain.</li>\n<li>When possible, avoid using actual type names in <code>sizeof</code>\n<ul>\n<li>For example, if you had something like <code>int* arr = malloc(sizeof(int) * numInts);</code> I'd write it as <code>int* arr = malloc(sizeof(*arr));</code></li>\n<li>It accomplishes the exact same thing, but if you change the type of <code>arr</code> later, your allocation won't break</li>\n<li>(Note: <code>sizeof</code> never actually evaluates its argument so you don't have to worry about that -- <code>arr</code> isn't actually dereferenced. Expressions just have their types deduced; they're not actually evaulated.)</li>\n<li>The reason I said this: <code>fwrite( &amp;accounts, sizeof(struct Accounts), 1, cfPtrDesitination );</code></li>\n<li>That could be: <code>fwrite( &amp;accounts, sizeof(accounts), 1, cfPtrDesitination );</code></li>\n<li>Not particularly useful here since the type is highly unlikely to change, but... good habit to have anyway :)</li>\n</ul></li>\n<li>Your <code>fwrite</code> call should probably have some error checking if you want to go the paranoid route</li>\n<li>100% opinion: I don't like your Hungarian-notation-esque variable names.\n<ul>\n<li><code>cfPtrSource</code> It's a pointer to a C file: my IDE also could've told me that.</li>\n</ul></li>\n<li>100% opinion: I tend to use avoid <code>NULL</code> and just check pointers as true or false <code>if (ptr)</code> instead of <code>if (ptr != NULL)</code>\n<ul>\n<li>Note: this one is highly opinion. I'm likely in the minority on this one. As Lundin noted in the comments, you get certain type safety with a NULL check that you cannot get with an implicit check. That is probably worth the 7 extra characters. A large part of this opinion comes down to me being lazy with arguably bad habits :).</li>\n</ul></li>\n<li>100% opinion: If you're going the Visual Studio route, I'd go with C++, not C.</li>\n</ul>\n\n<p><em>(Note: the ones that are just blatant opinion [or more particularly, opinion I'm too lazy to argue], have been marked, but really a lot of it is borderline opinion, so take it as you will.)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T13:12:53.060", "Id": "37322", "Score": "0", "body": "Nice review. Why do you say that the buffer in the `fgets` call is not big enough? Unless the entry in the file is more than 200 chars (which is possible and is not checked), it seems ok. Also, removing the \\n seems unnecessary - but checking it is there would allow him to protect against > 200 chars in the line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T22:49:19.427", "Id": "37378", "Score": "0", "body": "I have made the changes. No reason to justify or discuss the whys or why nots - everything was valid and I don't know enough otherwise. \nSomethings were done because the assignment requirements, or the instructor does it that way or thats how I got it to work\n\n\nBut thanks for all the tips, it definitely improves the overall code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T03:53:29.400", "Id": "37387", "Score": "0", "body": "@WilliamMorris I said that if the last character isn't a new line, then the buffer isn't big enough. Basically I was saying what you're saying. 200 characters might not be big enough. A simple way to check for that is `if (last char != '\\n' && !feof(f)) { /* buffer not big enough to hold entire line */ }`. (Then again, it's been a long time since I've written anything in C, so I may be remembering this incorrectly :p)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T00:17:42.810", "Id": "37577", "Score": "0", "body": "I agree with most of the points, but I must disagree with the first point. _typedef_ hides the information about the _real_ type of information. This is a really simple program, but if you have an huge program and you want it immediately understandable you should avoid _typedef_. I think that is much readable if you are explicit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T00:36:06.767", "Id": "37578", "Score": "0", "body": "@Federico That information is obvious as can be with a reasonable naming convention though (which I should have mentioned [`Account` for example]). You're right though, it's not very \"C\" to omit the struct. I'm one of those new-fangled C bastardizers though :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:19:08.600", "Id": "37597", "Score": "0", "body": "@Corbin I suspected that you are bastardized :P Anyway. The naming convention can be **struct_account** or **AccOUnt**. \n**struct account** is more readable and it self explains. In an open-source context, we cannot use a different convention for each program; the other programmers do not want (like) to learn your personal convention: lowCamelCase, CamelCase, something_t, UPPERCASE, mIDDLECASe, w1thnumb3r. It cause confusion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:59:50.710", "Id": "37606", "Score": "0", "body": "I agree with Corbin regarding the typedef, and I'm about as much old-school C programmer as they come. Whether to typedef structs or not is _coding style_. To use typedefs is more common than not. However, the (horrible, so-called) [Linux kernel coding style guide](https://www.kernel.org/doc/Documentation/CodingStyle) preaches to not use typedef, but provides a very weak rationale why. So this is a situation where there are two coding style camps and no consensus." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T10:00:50.743", "Id": "37607", "Score": "0", "body": "Likewise, using `sizeof(*arr)` instead of the actual type is also coding style and 100% opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T10:04:43.900", "Id": "37608", "Score": "0", "body": "Regarding the opinion to not check against NULL explicitly, there is _almost_ a consensus to always check for NULL as in the original code. For example, `if (ptr)` would be banned by MISRA-C, while `if (ptr==NULL)` would be recommended practice. The rationale is not only because the explicit check is easier to read, but also because you add type safety, in case you meant `if (*ptr)` but accidentally forgot the *." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:43:34.480", "Id": "37630", "Score": "0", "body": "@Federico Every code base involves learning a coding convention. Until The One Two Style Guide comes along, that's how it will be. Better yet, as there is very little hard evidence to support the superiority of any (reasonable) coding style, basically they all come down to personal convention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:49:35.037", "Id": "37631", "Score": "0", "body": "@Lundin There's no downside to sizeof(*arr) but there is a tangible (though small) benefit (and a relatively large benefit with statically sized arrays). And there's seems to be a consensus on it: http://stackoverflow.com/questions/373252/c-sizeof-with-a-type-or-variable. (Though of course a ~4 year old SO question barely matters.) I suspect we're just going to differ on this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:55:47.763", "Id": "37632", "Score": "0", "body": "@Lundin I've gotten into the \"compare to null or don't compare to null?\" more times than you'd think on CodeReview. The short thing: neither of us is going to convince the other. Actually, the ability to get a warning in the case you pointed out probably makes it worth the explicit `NULL` check.... But eh... Laziness :). (Nevertheless, I shall edit my answer to make it more clear that the `NULL` thing is *highly* opinionated on my part, and a rather rare opinion.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:01:19.000", "Id": "37635", "Score": "0", "body": "Though C++, a rather interestingly little mini debate is in the comments here: http://codereview.stackexchange.com/a/13062/7308" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:09:08.390", "Id": "37637", "Score": "0", "body": "@Corbin The closest thing to an universal C coding standard we have is MISRA-C. It is starting to gain acceptance even outside the branch of embedded systems, where it is already industry de facto. What's interesting is that MISRA is no coding _style_ guide, it only bans dangerous practice. Apparently MISRA considers `if(ptr)` _dangerous_ and not just bad style. Whether this is just their opinion or if they are backed up by actual, scientific research, I don't know. ->" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:12:31.147", "Id": "37638", "Score": "0", "body": "@Corbin Part of MISRA is based on Les Hatton's scientific population studies of bugs in real world applications, which are described in his book [Safer C](http://www.amazon.com/McGraw-Hill-International-Series-Software-Engineering/dp/0077076400) (which is quite a tough book to get through, it is more of a scientific publication than anything else). I suspect most of MISRA-C is not based on actual science though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:23:25.103", "Id": "37648", "Score": "0", "body": "@Lundin Everything is just code style. The code style aims is to improve readability and avoid errors. I think that a code style is not just \"use 4 space tab\" or banality like this.\n\nAbout *typedef*, I completely agree with the kernel coding style. If I read a portion of code of a big program for the first time, I do no want to waste my time to understand what is behind a typedef. If an apple is named 'apple' why call it 'something_round_and_red'. Avoiding typedef help the reader to understand and avoid you (programmer) to confuse about the real meaning of your custom type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:36:59.550", "Id": "37650", "Score": "0", "body": "@Corbin unfortunately you are right: \"they all come down to personal convention\". It is not a problem if you write code for yourself or for your company. But if your code is distributed, or you submit patch to an open-source project, you cannot apply your personal convention. If you work in the aerospace sector you must write *MISRA-C* code; if you submit Linux patches you must follow its rule. There are many standards, and I think that you must take the best from each of them to write beautiful code. It does not matter if you use 4/8 space tab,but in each code style there are important points" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:49:02.820", "Id": "37651", "Score": "0", "body": "@Corbin my very _very_ **very** personal opinion: it is right to avoid typedef like suggested in the Linux kernel code style. You save 6 char (struct), but someone else loses his time to understand it. _MISRA-C_ target is different and I understand that it can be important to define custom types" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:53:26.970", "Id": "37652", "Score": "0", "body": "@Federico Actually the main argument for typedef:ing structs is consistency. You don't write `auto signed long int` even though it is strictly speaking more correct than just `long`, now do you? Typedef:ing structs also make them behave consistently with C++, where the extra struct keyword is made reduntant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:57:32.060", "Id": "37653", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8079/discussion-between-federico-and-lundin)" } ], "meta_data": { "CommentCount": "20", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T09:10:24.383", "Id": "24194", "ParentId": "24182", "Score": "7" } } ]
{ "AcceptedAnswerId": "24194", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T03:09:33.163", "Id": "24182", "Score": "2", "Tags": [ "c" ], "Title": "Managing a user account" }
24182
<p>I am just learning how to do some multiprocessing with Python, and I would like to create a non-blocking chat application that can add/retrieve messages to/from a database. This is my somewhat primitive attempt (note: It is simplified for the purposes of this post); however, I would like to know how close/far off off the mark I am. Any comments, revisions, suggestions, etc. are greatly appreciated. </p> <p>Thank you!</p> <pre><code>import multiprocessing import Queue import time # Get all past messages def batch_messages(): # The messages list here will be attained via a db query messages = ["&gt;&gt; This is a message.", "&gt;&gt; Hello, how are you doing today?", "&gt;&gt; Really good!"] for m in messages: print m # Add messages to the DB def add_messages(q): # Retrieve from the queue message_to_add = q.get() # For testing purposes only; perfrom another DB query to add the message to the DB print "(Add to DB)" # Recieve new, inputted messages. def receive_new_message(q, new_message): # Add the new message to the queue: q.put(new_message) # Print the message to the screen print "&gt;&gt;", new_message if __name__ == "__main__": # Set up the queue q = multiprocessing.Queue() # Print the past messages batch_messages() while True: # Enter a new message input_message = raw_input("Type a message: ") # Set up the processes p_add = multiprocessing.Process(target=add_messages, args=(q,)) p_rec = multiprocessing.Process(target=receive_new_message, args=(q, input_message,)) # Start the processes p_rec.start() p_add.start() # Let the processes catch up before printing "Type a message: " again. (Shell purposes only) time.sleep(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:43:34.277", "Id": "37333", "Score": "0", "body": "That's quite odd that it works fine when I run it...I will look further into this. But, thank you for the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:26.577", "Id": "37335", "Score": "0", "body": "I can explicitly pass it to the functions that require it, and then I assume it will work for as well, correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:57.300", "Id": "37336", "Score": "0", "body": "Yes, you should pass `q` as a parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:58:10.620", "Id": "37338", "Score": "0", "body": "`q` is now passed to the functions. Thanks." } ]
[ { "body": "<ul>\n<li>Don't create a new process for every task. Put a loop in <code>add_messages</code>; <code>q.get</code> will wait for the next task in the queue.</li>\n<li><code>receive_new_message</code> is not doing anything useful in your example. Place <code>q.put(new_message)</code> right after <code>raw_input</code> instead.</li>\n</ul>\n\n<p>:</p>\n\n<pre><code>def add_messages(q): \n while True:\n # Retrieve from the queue\n message_to_add = q.get()\n print \"(Add to DB)\"\n\nif __name__ == \"__main__\":\n q = multiprocessing.Queue()\n p_add = multiprocessing.Process(target=add_messages, args=(q,))\n p_add.start()\n\n while True: \n input_message = raw_input(\"Type a message: \")\n\n # Add the new message to the queue:\n q.put(input_message)\n\n # Let the processes catch up before printing \"Type a message: \" again. (Shell purposes only)\n time.sleep(1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T17:38:24.597", "Id": "37415", "Score": "0", "body": "Thank you for the revision! I appreciate your help. On a side note, I included the `receive_new_message` process with the thought that I would need to output messages from the queue to users' screens, and that this process should be separate from the `add_messages` (to the db) process. Is this \"concern\" a necessary one? Or can the outputting to the screen be coupled with the database querying?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T09:11:20.743", "Id": "37441", "Score": "0", "body": "@JohnZ If you need the two subprocesses, you would use two queues. For example, `receive_new_message` might read from `q1`, do some processing and forward the results to `add_messages` via `q2`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T15:33:52.110", "Id": "37443", "Score": "0", "body": "Ahhh okay. That makes sense. Thank you for the feedback!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:29:27.990", "Id": "24213", "ParentId": "24187", "Score": "1" } } ]
{ "AcceptedAnswerId": "24213", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:56:02.460", "Id": "24187", "Score": "4", "Tags": [ "python" ], "Title": "Python multiprocessing messaging code" }
24187
<p>Pygame is free Python library released under the GPL License aimed at creating video games. It's build on top of <a href="/questions/tagged/sdl" class="post-tag" title="show questions tagged 'sdl'" rel="tag">sdl</a>, it's actively developed and hosted at <a href="https://bitbucket.org/pygame/pygame" rel="nofollow">BitBucket</a>.</p> <p>Pygame is highly portable and runs on nearly every platform and operating system.</p> <p>Useful links:</p> <ul> <li><a href="http://www.pygame.org" rel="nofollow">pygame.org</a> </li> <li><a href="https://bitbucket.org/pygame/pygame" rel="nofollow">source code/issue tracker</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:26:24.240", "Id": "24191", "Score": "0", "Tags": null, "Title": null }
24191
Pygame is a portable Python package for video games, built on SDL.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T08:26:24.240", "Id": "24192", "Score": "0", "Tags": null, "Title": null }
24192
<p>I'm trying to write efficient code for calculating the chain-length of each number.</p> <p>For example, <code>13 -&gt; 40 -&gt; 20 -&gt; 10 -&gt; 5 -&gt; 16 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1</code>. It took 13 iterations to get 13 down to 1, so <code>collatz(13)</code> = <code>10</code>.</p> <p>Here is my implementation:</p> <pre><code>def collatz(n, d={1:1}): if not n in d: d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1 return d[n] </code></pre> <p>It's quite efficient, but I'd like to know whether the same efficiency (or better) can be achieved by an iterative one.</p>
[]
[ { "body": "<p>Using the Python call stack to remember your state is very convenient and often results in shorter code, but it has a disadvantage:</p>\n\n<pre><code>&gt;&gt;&gt; collatz(5**38)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr24195.py\", line 3, in collatz\n d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1\n [... many lines omitted ...]\n File \"cr24195.py\", line 3, in collatz\n d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1\nRuntimeError: maximum recursion depth exceeded\n</code></pre>\n\n<p>You need to remember all the numbers you've visited along the way to your cache hit <em>somehow</em>. In your recursive implementation you remember them on the call stack. In an iterative implementation one would have to remember this stack of numbers in a list, perhaps like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def collatz2(n, d = {1: 1}):\n \"\"\"Return one more than the number of steps that it takes to reach 1\n starting from `n` by following the Collatz procedure.\n\n \"\"\"\n stack = []\n while n not in d:\n stack.append(n)\n n = n * 3 + 1 if n &amp; 1 else n // 2\n c = d[n]\n while stack:\n c += 1\n d[stack.pop()] = c\n return c\n</code></pre>\n\n<p>This is a bit verbose, and it's slower than your recursive version:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:map(collatz, xrange(1, 10**6)), number=1)\n2.7360708713531494\n&gt;&gt;&gt; timeit(lambda:map(collatz2, xrange(1, 10**6)), number=1)\n3.7696099281311035\n</code></pre>\n\n<p>But it's more robust:</p>\n\n<pre><code>&gt;&gt;&gt; collatz2(5**38)\n1002\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T11:40:33.847", "Id": "24198", "ParentId": "24195", "Score": "4" } } ]
{ "AcceptedAnswerId": "24198", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T09:14:06.903", "Id": "24195", "Score": "5", "Tags": [ "python", "optimization", "algorithm", "recursion", "memoization" ], "Title": "Iterative Collatz with memoization" }
24195
<p>I've created a CSV parser that tries to build a string table out of a CSV file. The goal is to handle CSV files as well as Excel.</p> <h2>Input CSV file:</h2> <blockquote> <pre class="lang-none prettyprint-override"><code>First field of first row,"This field is multiline but that's OK because it's enclosed in double qoutes, and this is an escaped "" double qoute" but this one "" is not "This is second field of second row, but it is not multiline because it doesn't start with an immediate double quote" </code></pre> </blockquote> <h2>What Excel shows:</h2> <p><img src="https://i.stack.imgur.com/JfZDu.png" alt="enter image description here"></p> <h2>My code:</h2> <pre class="lang-c++ prettyprint-override"><code>#include &lt;vector&gt; #include &lt;string&gt; // Returns a pointer to the start of the next field, or zero if this is the // last field in the CSV p is the start position of the field sep is the // separator used, i.e. comma or semicolon newline says whether the field ends // with a newline or with a comma const wchar_t* nextCsvField(const wchar_t *p, wchar_t sep, bool *newline, const wchar_t **escapedEnd) { *escapedEnd = 0; *newline = false; // Parse quoted sequences if ('"' == p[0]) { p++; while (1) { // Find next double-quote p = wcschr(p, L'"'); // Check for "", it is an escaped double-quote if (p[1] != '"') { *escapedEnd = p; break; } // If we don't find it or it's the last symbol // then this is the last field if (!p || !p[1]) return 0; // Skip the escaped double-quote p += 2; } } // Find next newline or comma. wchar_t newline_or_sep[4] = L"\n\r "; newline_or_sep[2] = sep; p = wcspbrk(p, newline_or_sep); // If no newline or separator, this is the last field. if (!p) return 0; // Check if we had newline. *newline = (p[0] == '\r' || p[0] == '\n'); // Handle "\r\n", otherwise just increment if (p[0] == '\r' &amp;&amp; p[1] == '\n') p += 2; else p++; return p; } typedef std::vector&lt;std::vector&lt;std::wstring&gt; &gt; StringTable; // Parses the CSV data and constructs a StringTable // from the fields in it. StringTable parseCsv(const wchar_t *csvData, wchar_t sep) { StringTable v; // Return immediately if the CSV data is empty. if (!csvData || !csvData[0]) return v; v.resize(1); // Here we CSV fields and fill the output StringTable. while (csvData) { // Call nextCsvField. bool newline; const wchar_t *escapedEnd; const wchar_t *next = nextCsvField(csvData, sep, &amp;newline, &amp;escapedEnd); // Add new field to the current row. v.back().resize(v.back().size() + 1); std::wstring &amp;field = v.back().back(); // If there is a part that is escaped with double-quotes, add it // (without the opening and closing double-quote, and also with any "" // escaped to ". After that csvData is set to the part immediately // after the closing double-quote, so anything after the closing // double-quote is added as well (but unescaped). if (escapedEnd) { for (const wchar_t *ii = csvData + 1; ii != escapedEnd; ii++) { field += *ii; if ('"' == ii[0] &amp;&amp; '"' == ii[1]) ii++; } csvData = escapedEnd + 1; } // If there was no escaped part, or the CSV is malformed, add anything // else "as is" (i.e. unescaped). Keep in mind that next might be NULL. if (next) field.append(csvData, next-1); else field += csvData; // If the field ends with a newline, add next row to the StringTable. if (newline) { if (field.empty()) v.back().pop_back(); v.resize(v.size() + 1); } // Set csvData to point to the start of the next field for the next // cycle. csvData = next; } // If the CSV ends with a newline, then there is an empty row added // (actually it's a row with a single empty string). We trim that empty // row here. if (v.back().empty() || (v.back().size() == 1 &amp;&amp; v.back().front().empty())) v.pop_back(); } </code></pre> <h2>What I'm interested in:</h2> <p>Whether my code handles all the corner cases, especially empty elements, lines, etc., and any mistakes I might have made.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:16:00.893", "Id": "37315", "Score": "0", "body": "Why did it add a `\"` after *quote*?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T13:54:48.627", "Id": "37324", "Score": "0", "body": "It seems Excel treats the rest of the field (after the closing double-quote and before the next comma/newline) as an unescaped part of the same field. This is a malformed CSV anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T17:25:31.747", "Id": "37447", "Score": "0", "body": "I may be a bit slow, but I'm not clear what you consider good data, what you consider malformed data that should be handled correctly and what you consider malformed data that can be handled incorrectly. Perhaps give some C string examples of each. Also, do you handle empty fields correctly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T19:58:13.477", "Id": "37451", "Score": "0", "body": "My idea is to handle it exactly as Excel does (even when it's malformed). That's why the screenshot from Excel, it shows how it treats malformed data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T01:34:27.947", "Id": "89525", "Score": "0", "body": "Which version of Excel are you testing against? Microsoft's understanding of CSV has changed a number of times through the years, even within the last decade." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T04:18:37.483", "Id": "89546", "Score": "0", "body": "@BobDalgleish Excel 2007 in my case." } ]
[ { "body": "<ul>\n<li><p>I'm not sure it's best to return <code>0</code> from <code>nextCsvField()</code>. Since the function is to return a pointer, consider returning <code>NULL</code> (or <code>nullptr</code> if you have C++11). This function also shouldn't return a <code>const</code> pointer if the return value (a valid <code>wchar_t</code>) will be modified.</p></li>\n<li><p>You're using a \"Yoda condition\" here:</p>\n\n<blockquote>\n<pre><code>if ('\"' == p[0])\n</code></pre>\n</blockquote>\n\n<p>This isn't too common, and it may still be prone to error. Either way, you should have your compiler warnings up high so that any accidental assignments in conditions will be reported.</p></li>\n<li><p>You should still use curly braces for single-line statements, as it could benefit maintenance.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-18T22:25:14.087", "Id": "57421", "ParentId": "24196", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:07:52.273", "Id": "24196", "Score": "6", "Tags": [ "c++", "parsing", "csv", "excel" ], "Title": "Correctly import CSV data, even when possibly malformed" }
24196
<p>Given a linked list, remove the nth node from the end of list and return its head.</p> <p>For example,</p> <blockquote> <p>Given linked list: 1->2->3->4->5, and n = 2.</p> <p>After removing the second node from the end, the linked list becomes 1->2->3->5.</p> <pre><code>ListNode *removeNthFromEnd(ListNode *head, int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if (head == NULL) { return NULL; } ListNode *pre, *cur; pre = cur = head; for (int i = 0; i &lt; n; ++i) { pre = pre-&gt;next; } while (pre != NULL &amp;&amp; pre-&gt;next != NULL) { cur = cur-&gt;next; pre = pre-&gt;next; } //mistake //if (cur == head) { // I use the above line to check if it's the first node to be deleted, // there is a problem for this case: list: 1-&gt;2, n : 1 if (pre == NULL) { ListNode *newHead = head-&gt;next; delete head; return newHead; } else { ListNode *tmp = cur-&gt;next; cur-&gt;next = tmp-&gt;next; delete tmp; return head; } } </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T03:16:24.553", "Id": "57564", "Score": "4", "body": "This question appears to be off-topic because it is not clear whether it's asking for code to be written; also the code being embedded in a block quote makes it looks like it's not the OP's code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T03:37:00.003", "Id": "57565", "Score": "1", "body": "@retailcoder: Based on the tag, I assume this was straight from the interviewer. But I cannot tell for sure, so I agree with your close reason." } ]
[ { "body": "<p>Your function fails if <code>n</code> is 0 or greater than the list size.</p>\n\n<p>Also, I prefer to see one variable defined per-line:</p>\n\n<pre><code>ListNode *pre = head;\nListNode *cur = head;\n</code></pre>\n\n<p>And the opening brace belongs in column 0 (I guess you don't agree, but there are - or were anyway - tools that rely on this).</p>\n\n<p>An alternative implementation might use a function to find the number of entries in the list and another to return a specified entry (size - n - 1, in this case). Then once you've checked that 0 &lt; n &lt;= size, the main function is simple - but no better than yours :-)</p>\n\n<p>BTW, <code>delete</code> is C++, not C</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-20T00:53:28.883", "Id": "42959", "Score": "1", "body": "If there are tools that rely on the code being formatted in non-K&R-style, then it's not the code that is wrong, it is the tools. Both *The C Programming Language* and *The C++ Programming Language* books use this style. Admittedly not for functions, but it's still perfectly valid C and C++. Which tools rely on the opening brace being in column 0?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T22:51:16.243", "Id": "24220", "ParentId": "24201", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T13:36:30.627", "Id": "24201", "Score": "1", "Tags": [ "c++", "interview-questions", "linked-list" ], "Title": "Remove Nth Node From End of List" }
24201
<p>In my VBA code, I am trying to generate a specific list of cell row positions.</p> <p>Basically, I first fill a collection with the entire list of row positions pertaining to a specific column:</p> <pre><code>Dim arrPos As New Collection .... For i = 3 To bottomRow arrPos.Add i Next i </code></pre> <p>Then I try to remove remove values from this collection if there's no problem at that specific row. </p> <pre><code>For h = matchRow To 3 Step -1 For g = arrPos.Count To 1 Step -1 If CLng(Worksheets(".....").Range("C" &amp; h).Value) = arrPos(g) Then arrPos.Remove (g) Exit For End If Next g Next h </code></pre> <p>Basically <code>Range("C" &amp; h).Value</code> is a column where the <code>=MATCH</code> function was used so there's a whole list row positions in that column. If the MATCH worked, then I can remove it from the collection. A similar type of loop is made use of further down the code for the rows where the MATCH came up false.</p> <p>The code gives the proper results but it can drag on at times (especially since row counts can get up to the 5000's) and even crash my puny laptop. As you can see, the method makes use of nested loops and I believe that significant results could be attained by re-factoring this portion. </p> <p>Does anyone have any suggestions? The question is basically requesting a more efficient way to identify the row positions that did not come up from a MATCH function: either because the value was slightly erroneous or just simply missing.</p>
[]
[ { "body": "<p>Doesn't MATCH return NA when there's not match? If that's the way you have it set up and you want the rows where there are errors, then it seems like you could simplify it by just checking for errors and putting them into a 'no good' array.</p>\n\n<pre><code>Sub FilterMatch()\n\n Dim vaMatch As Variant\n Dim vaNoGood As Variant\n Dim lBottomRow As Long\n Dim i As Long, lCnt As Long\n\n lBottomRow = 32\n\n 'Read in the range\n vaMatch = Range(\"c3\").Resize(lBottomRow - 2).Value\n 'Resize the array too big for now\n ReDim vaNoGood(1 To UBound(vaMatch, 1))\n\n For i = LBound(vaMatch, 1) To UBound(vaMatch, 1)\n 'MATCH returns NA if no good, so only care about errors\n If IsError(vaMatch(i, 1)) Then\n lCnt = lCnt + 1\n 'Save the row number of the error\n vaNoGood(lCnt) = i\n End If\n Next i\n\n 'Reduce array based on actual results\n ReDim Preserve vaNoGood(1 To lCnt)\n\n 'Print out the row numbers\n For i = LBound(vaNoGood) To UBound(vaNoGood)\n Debug.Print vaNoGood(i)\n Next i\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T01:06:03.960", "Id": "37384", "Score": "0", "body": "I wantt the missing positions too. As in even if match didn't produce n/a, the positions not returned as well" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:26:12.397", "Id": "24216", "ParentId": "24202", "Score": "3" } }, { "body": "<p>The answer is to instead use VBA object <code>Dictionary</code> accessible by adding the \"Microsoft Scripting Runtime\" As a reference in your project. I don't know the internal mechanics but the dicitonary object has a method to see if an object <code>.Exists</code> within it's collection. This is <strong>much</strong> faster than my nested looping through an ordinary <code>collection</code> object and seeing if a specific value is contained. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:30:05.490", "Id": "24347", "ParentId": "24202", "Score": "4" } } ]
{ "AcceptedAnswerId": "24347", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:29:23.723", "Id": "24202", "Score": "5", "Tags": [ "vba", "excel" ], "Title": "Removing from a collection in Excel VBA" }
24202
<p>I'm working on my first large CodeIgniter project (and one of my first MVC projects), and I want to get some feedback on the techniques I've used so far in one of my models:</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Model_programs extends SOA_Model{ function __construct(){ parent::__construct(); } /** * * Returns an array of all programs owned by a user. * * @param int $user_id User ID to query. * @return bool|array Array of user's programs or FALSE. */ function user_programs($user_id){ if(!is_numeric($user_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT programs.id, programs.name FROM programs INNER JOIN program_users ON program_users.program_id = programs.id WHERE program_users.user_id = :user_id"); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;execute(); $user_programs = $sth-&gt;fetchall(PDO::FETCH_ASSOC); if(!$user_programs) return FALSE; $return = array(); foreach($user_programs as $program){ $return[$program['id']] = $program['name']; } return $return; } /** * * Creates a new program owned by a user. * * @param int $user_id ID of user to own the program. * @param string $program_name Name of program to create, max 255 chars. Must be unique to the user. * @param string $program_description Description of program, max 2000 chars. * @param string $program_logo Location and filename of uploaded logo. * @return bool|int Program ID or FALSE. */ function create_program($user_id, $program_name, $program_description, $program_logo){ if(!is_numeric($user_id)) return FALSE; //Check if the user already owns a program of that name $sth = $this-&gt;dbh-&gt;prepare("SELECT programs.id FROM programs INNER JOIN program_users ON program_users.program_id = programs.id WHERE program_users.user_id = :user_id AND programs.name = :program_name"); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;bindParam(':program_name', $program_name); $sth-&gt;execute(); if($sth-&gt;fetch()) return FALSE; //Create a new record in the programs table $sth = $this-&gt;dbh-&gt;prepare("INSERT INTO programs (name, description, logo) VALUES (:name, :description, :logo)"); $sth-&gt;bindParam(':name', $program_name); $sth-&gt;bindParam(':description', $program_description); $sth-&gt;bindParam(':logo', $program_logo); if(!$sth-&gt;execute()) return FALSE; //Get the ID of the new program $program_id = $this-&gt;dbh-&gt;lastInsertId(); if(!$this-&gt;add_program_user($program_id, $user_id, 1)){ //Problem here $sth = $this-&gt;dbh-&gt;prepare("DELETE FROM programs WHERE program_id = :program_id"); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;execute(); return FALSE; } return (int)$program_id; } /** * Add a user to a program. If user already exists on * program, their user type will be updated. * * @param int $program_id ID of program to add user to. * @param int $user_id ID of user. * @param int $user_type_id ID of user type for user on program. * @return bool */ function add_program_user($program_id, $user_id, $user_type_id){ if(!is_numeric($program_id) || !is_numeric($user_id) || !is_numeric($user_type_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT * FROM program_users WHERE program_id = :program_id AND user_id = :user_id"); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;execute(); if($sth-&gt;fetch()){ //Update existing record in the program_users table $sth = $this-&gt;dbh-&gt;prepare("UPDATE program_users SET user_type = :user_type_id WHERE program_id = :program_id AND user_id = :user_id"); $sth-&gt;bindParam(':user_type_id', $user_type_id); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;bindParam(':user_id', $user_id); if(!$sth-&gt;execute()) return FALSE; }else{ //Create a new record in the program_users table $sth = $this-&gt;dbh-&gt;prepare("INSERT INTO program_users (program_id, user_id, user_type) VALUES (:program_id, :user_id, :user_type)"); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;bindParam(':user_type', $user_type_id); if(!$sth-&gt;execute()) return FALSE; } return TRUE; } /** * Remove specified user from program. * * @param int $program_id Program to remove user from. * @param int $user_id User to remove. * @return bool */ function remove_program_user($program_id, $user_id){ if(!is_numeric($program_id) || !is_numeric($user_id)) return FALSE; #$sth = $this-&gt;dbh-&gt;prepare("DELETE FROM program_users # WHERE program_id = :program_id # AND user_id = :user_id"); } /** * Gets program name from program ID. * * @param int $program_id ID of program to query. * @return bool|string Program name or FALSE. */ function program_name($program_id){ if(!is_numeric($program_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT name FROM programs WHERE id = :id"); $sth-&gt;bindParam(':id', $program_id); $sth-&gt;execute(); $program = $sth-&gt;fetch(); if(!$program) return FALSE; return $program['name']; } /** * Gets program ID from program name and user ID. * * @param string $program_name Name of program to look up. * @param int $user_id ID of user who owns the program. * @return bool|int ID of program owned by user. */ function program_id($program_name, $user_id){ if(!is_string($program_name) || !is_numeric($user_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT programs.id FROM programs INNER JOIN program_users ON program_users.program_id = programs.id WHERE programs.name = :program_name AND program_users.user_id = :user_id"); $sth-&gt;bindParam(':program_name', $program_name); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;execute(); $program = $sth-&gt;fetch(); if(!$program) return FALSE; return (int)$program['id']; } /** * * Get users associated with a program ID. * * @param int $program_id ID of program. * @return bool|array Array of user IDs. */ function program_users($program_id){ if(!is_numeric($program_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT user_id FROM program_users WHERE program_id = :program_id"); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;execute(); $program_users = $sth-&gt;fetchall(PDO::FETCH_ASSOC); return $program_users; } /** * @param int $program_id ID of program. * @param int $user_id ID of user. * @return bool|int ID of user type or FALSE if user does not exist * on program. */ function program_user_type($program_id, $user_id){ if(!is_int($program_id) || !is_numeric($user_id)) return FALSE; $sth = $this-&gt;dbh-&gt;prepare("SELECT user_type FROM program_users WHERE program_id = :program_id AND user_id = :user_id"); $sth-&gt;bindParam(':program_id', $program_id); $sth-&gt;bindParam(':user_id', $user_id); $sth-&gt;execute(); $program = $sth-&gt;fetch(); if(!$program) return FALSE; return (int)$program['user_type']; } } </code></pre> <p>This is still a work in progress so many things are subject to change, but overall am I utilizing MVC correctly (as far as you can tell from this code, at least)? I'm sure I'm doing a few things that I don't need to do, and possibly not doing some things that I should be doing?</p>
[]
[ { "body": "<p>Is there any specific reason that you don't use Active Record?</p>\n\n<p>For example:</p>\n\n<pre><code>$sth = $this-&gt;dbh-&gt;prepare(\"SELECT programs.id, programs.name\n FROM programs\n INNER JOIN program_users\n ON program_users.program_id = programs.id\n WHERE program_users.user_id = :user_id\");\n\n$sth-&gt;bindParam(':user_id', $user_id);\n$sth-&gt;execute();\n$user_programs = $sth-&gt;fetchall(PDO::FETCH_ASSOC);\n</code></pre>\n\n<p>This can be done like the following with AR, and it looks cleaner to me. This is probably personal preference.</p>\n\n<pre><code>$user_programs = $this-&gt;dbh-&gt;select('programs.id, programs.name')\n -&gt;from('programs')\n -&gt;join('program_users', 'programs.id = program_users.id', 'inner')\n -&gt;where('program_users.user_id', $user_id)\n -&gt;get()\n -&gt;result();\n</code></pre>\n\n<p>You can use <code>result_array()</code> as well if you want the results in array format.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T07:15:56.227", "Id": "37388", "Score": "1", "body": "I prefer PDO mainly because I have more experience with it, and I like to write actual SQL queries. Thanks for the input though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T02:48:54.527", "Id": "24232", "ParentId": "24205", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T15:21:07.237", "Id": "24205", "Score": "0", "Tags": [ "php", "mvc", "codeigniter" ], "Title": "CodeIgniter model" }
24205
<h3>Some background</h3> <p>This functions does some business logic before submitting a "add to cart" form</p> <h2>HTML</h2> <pre><code>&lt;form class="atcLoginRequired" method="get" action="/somePage"&gt; &lt;input type="hidden" value="someVal" name="nextpage"&gt; &lt;input name="ISODSCTX66WA_qty" type="text" value="1"&gt; &lt;input name="ISODSCTX77WA_qty" type="text" value="1"&gt; &lt;input type="Image" class="imageSubmit" src="ATCimage.jpg"&gt; &lt;/p&gt; </code></pre> <p></p> <h3>JavaScript</h3> <pre><code> var atcLoginRequired = $(".atcLoginRequired"); if (!atcLoginRequired.length) return; atcLoginRequired.on("submit", function(){ var jThis = $(this), nextPageInput = jThis.find("[name='nextpage']"), nextPageVal = nextPageInput.val(), skuValues = jThis.find("[name$='_qty']").map(function(){ var jThat = $(this); return (jThat.remove(), jThat.attr("name") + "=" + jThat.val() + "&amp;"); // the return statement actually executes the first expression, and "returns" the second one.. }).get().join(""); $(".imageSubmit").remove(); // to avoid having the x and y passed skuValues = skuValues.substring(0, skuValues.length - 1); nextPageInput.val(nextPageVal + "" + skuValues); }); </code></pre> <h3>The question</h3> <ul> <li>What can I do to make this it pass jsHint? </li> <li>What can I do to make this <strong>better</strong> in terms of <strong>readability</strong>, <strong>performance</strong> and <strong>extensibility</strong> ?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T18:02:17.367", "Id": "37490", "Score": "0", "body": "We prefix jQuery objects with `$`, for example, `$form` and `$input`." } ]
[ { "body": "<p><strong>Simple answer:</strong></p>\n\n<pre><code>var jThat = $(this).remove();\nreturn jThat.attr(\"name\") + \"=\" + jThat.val() + \"&amp;\"; \n</code></pre>\n\n<p>There's nothing wrong with calling <code>.remove()</code> right away; the element's still in memory so its attributes be still be accessed. As you said, the remove call is already executed in your code, before the rest.</p>\n\n<p><strong>Longer answer:</strong><br>\nDon't write your own query string by concatenating stuff with \"&amp;\" and \"=\". It's error-prone, a bother to deal with, and it also means you have to do the slice off the trailing \"&amp;\" later (which, incidentally, you can do with just <code>skuValues.slice(0, -1)</code>).</p>\n\n<p>jQuery has a <code>$.param()</code> function that's built for this sort of thing. Pass it an array of objects, each with <code>name</code> and a <code>value</code> property, and it'll make a properly encoded query string for you.</p>\n\n<pre><code>// no need to first store `$(\".atcLoginRequired\")` in a variable,\n// and then check its length. If nothing was found, jQuery will\n// just ignore the call to .on(). Same result as you checking, and\n// and returning if length is zero.\n\n$(\".atcLoginRequired\").on(\"submit\", function (event) {\n var form = $(this), // use a more descriptive name than \"jThis\"\n nextPageInput = form.find(\"[name='nextpage']\"),\n skuValues = form.find(\"[name$='_qty']\").map(function () {\n var input = $(this).remove(); // again, more descriptive\n // return an object fit for jQuery's param() function\n return {\n name: input.attr(\"name\"),\n value: input.val()\n };\n }).get();\n\n // add the nextPage stuff, if there is any\n if( nextPageInput.val() ) {\n skuValues.push({\n name: \"nextpage\",\n value: nextPageInput.val()\n });\n }\n nextPageInput.val( $.param(skuValues) );\n});\n</code></pre>\n\n<p>Overall, though, I'm wondering what the point is of stuffing a big query string into a hidden input. That's going against the grain. Why not send the inputs to the server as-is, and let it add a bunch of hidden inputs to the next page's form or something? Using an input to store other inputs seems like a kludge. </p>\n\n<hr>\n\n<blockquote>\n <p>What can I do to make this better in terms of readability, performance and extensibility ?</p>\n</blockquote>\n\n<p>For readability, see above. Less code, more descriptive variable names. You can find better names than mine - I just went for simple ones.</p>\n\n<p>Performance... well, there isn't a whole lot going on. It's not a complex algorithm. If you want performance, skip jQuery and go straight to the native DOM. Of course, that's a hassle to code, which is why jQuery is extremely useful. </p>\n\n<p>Extensibility: In what way exactly? This is, I presume, not a library in itself. It's the end-goal code. So extensibility is sort of moot. But if you want to add more on-submit functionality (like, say, form validation), the first order of business is to <em>not remove elements</em>. If you do that, the next piece of code will just find an empty form. Validation would be sort of pointless if it comes after this code, as it's not going to find anything but a hidden input with a big query string as its value. And if you need to validate that input, you'll need to parse that string, just to get back to the individual values again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T13:15:59.753", "Id": "37399", "Score": "0", "body": "Thanks so much! 2 main points i take out from this. 1. That i can call `remove()` and still access the attr's of that node. 2. The returning a obj and calling $.param(), (then there is the readability tips which is also great!) Wow, that was a very helpful review, thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:47:01.063", "Id": "24214", "ParentId": "24206", "Score": "4" } } ]
{ "AcceptedAnswerId": "24214", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T15:31:57.460", "Id": "24206", "Score": "1", "Tags": [ "javascript", "jquery", "html", "validation" ], "Title": "Refactor function that returns a comma Operator to pass jsHint" }
24206
<p>I'm new to jQuery and I've been messing about with this code, It works but I want to learn how to shorten the code by the eliminating unnecessary repeated code.</p> <p>Here is a link to <a href="http://jsfiddle.net/eSZFD/168/" rel="nofollow noreferrer">JSFiddle</a></p> <h1>HTML</h1> <pre><code>&lt;div id=&quot;div1&quot; style=&quot;display:none;&quot;&gt;one&lt;div id=&quot;divb&quot; class=&quot;upper&quot;&gt;close&lt;/div&gt;&lt;/div&gt; &lt;div id=&quot;div2&quot; style=&quot;display:none;&quot;&gt;two&lt;div id=&quot;divb&quot; class=&quot;upper&quot;&gt;close&lt;/div&gt;&lt;/div&gt; &lt;div id=&quot;div3&quot; style=&quot;display:none;&quot;&gt;three&lt;div id=&quot;divb&quot; class=&quot;upper&quot;&gt;close&lt;/div&gt;&lt;/div&gt; &lt;div id=&quot;div4&quot; style=&quot;display:none;&quot;&gt;four&lt;div id=&quot;divb&quot; class=&quot;upper&quot;&gt;close&lt;/div&gt;&lt;/div&gt; &lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;div class=&quot;buttons&quot;&gt; &lt;a class=&quot;button&quot; id=&quot;showdiv1&quot;&gt;Div 1&lt;/a&gt; &lt;a class=&quot;button&quot; id=&quot;showdiv2&quot;&gt;Div 2&lt;/a&gt; &lt;a class=&quot;button&quot; id=&quot;showdiv3&quot;&gt;Div 3&lt;/a&gt; &lt;a class=&quot;button&quot; id=&quot;showdiv4&quot;&gt;Div 4&lt;/a&gt; &lt;/div&gt; </code></pre> <h1>JQuery</h1> <pre><code>$(function() { $('#showdiv1').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp().delay(1000); $('#div1').slideDown('slow').delay(1000); }); $('.upper').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('#div1').slideUp('slow'); }); $('#showdiv2').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp().delay(1000); $('#div2').slideDown('slow').delay(1000); }); $('.upper').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('#div2').slideUp('slow'); }); $('#showdiv3').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp().delay(1000); $('#div3').slideDown('slow').delay(1000); }); $('.upper').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('#div3').slideUp('slow'); }); $('#showdiv4').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp().delay(1000); $('#div4').slideDown('slow').delay(1000); }); $('.upper').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('#div4').slideUp('slow'); }); }) </code></pre> <p>Ok, after much headache - I'm new to this sh#t. I've changed the code to this. All works fine. I would like someone that knows, to give me any tips for improvement, as I'm totally improvising here, thankyou.</p> <p>jquery</p> <pre><code>$(document).ready(function(){ $('a').click(function () { var divname= this.name; $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp().delay(1000); $(&quot;#&quot;+divname).slideDown('slow').delay(1000); }); $('.upper').click(function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); $('div[id^=div]').slideUp('slow'); }); }); </code></pre> <h1>More HTML</h1> <pre><code>&lt;body&gt; &lt;div id=&quot;div1&quot; style=&quot;display:none&quot;&gt; Hello World &lt;a class=&quot;upper&quot; id=&quot;div1&quot;&gt;close&lt;/a&gt; &lt;/div&gt; &lt;div id=&quot;div2&quot; style=&quot;display:none&quot;&gt; Test&lt;a class=&quot;upper&quot; id=&quot;div2&quot;&gt;close&lt;/a&gt; &lt;/div&gt; &lt;div id=&quot;div3&quot; style=&quot;display:none&quot;&gt; Another Test &lt;/div&gt; &lt;div id=&quot;div4&quot; style=&quot;display:none&quot;&gt; Final Test &lt;/div&gt; &lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt; &lt;div class=&quot;menu&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot; name=&quot;div1&quot; &gt;one&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; name=&quot;div2&quot; &gt;two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; name=&quot;div3&quot; &gt;three&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot; name=&quot;div4&quot; &gt;four&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T17:06:24.803", "Id": "37339", "Score": "4", "body": "Hi and welcome to Code Review. Please post your code in the question as well. Also make sure to check this out: http://codereview.stackexchange.com/faq" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:21:02.187", "Id": "37346", "Score": "0", "body": "@Yuck: You can't post people code for them. As this page gives away rights via collective comments. You have to ask them to post their own code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:52:51.833", "Id": "37358", "Score": "0", "body": "@Yuck: Obviously it was a well-intentioned edit but Loki's right, and [here are additional reasons why](http://meta.codereview.stackexchange.com/a/470)." } ]
[ { "body": "<p>Your newer code is much much better than the previous attempt. Some little fixes that I'd suggest are:</p>\n\n<ol>\n<li><p>Don't use the following</p>\n\n<pre><code>$('div[id^=div]').slideUp().delay(1000);\n</code></pre>\n\n<p>as it hides the <code>close</code> button inside the div. So, if I open <code>div1</code> and click the <code>div1</code> again, I can't see the <code>close</code> button there.</p></li>\n<li><p>Since you are continually using jQuery, I'd prefer to use <code>.attr()</code> method to fetch the name instead of</p>\n\n<pre><code>this.name;\n</code></pre>\n\n<p>that you have used inside your new code.</p></li>\n<li><p>You must not bind your <code>.click()</code> to the <code>a</code> tag. Instead you already have <code>class=\"button\"</code> assigned to them. Use it.</p></li>\n</ol>\n\n<p>Here is an updated <a href=\"http://jsfiddle.net/eSZFD/173/\" rel=\"nofollow\">fiddle link</a> that addresses the issues and fixes them.</p>\n\n<h2>jQuery Code</h2>\n\n<pre><code>$(function () {\n var newId = \"\";\n $('.button').click(function () {\n $('html, body').animate({\n scrollTop: 0\n }, 'slow');\n if (newId !== \"\") $('#' + newId).slideUp().delay(1000);\n newId = $(this).attr(\"name\");\n $('#' + newId).slideDown('slow').delay(1000);\n\n });\n $('.upper').click(function () {\n $('html, body').animate({\n scrollTop: 0\n }, 'slow');\n $(this).parent('div').slideUp('slow');\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T23:58:08.930", "Id": "37380", "Score": "1", "body": "I strongly disagree with number 2. Even though he is using jQuery, jQuery is a framework on top of JavaScript. Why take the effort to create a jQuery object and then call a far slower method to produce the EXACT same result when `this.name` is faster and more accessible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T23:59:18.550", "Id": "37381", "Score": "0", "body": "@Tyriar To maintain similarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T00:07:20.287", "Id": "37382", "Score": "0", "body": "The language being used is JavaScript though. I understand the importance of code consistency, but there is nothing wrong with using simple object properties when you're using jQuery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T00:08:49.497", "Id": "37383", "Score": "1", "body": "Yup, @Tyriar which is why I mentioned that **I'd prefer to use** as opposed to **you shouldn't**." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T23:09:43.160", "Id": "24222", "ParentId": "24207", "Score": "3" } }, { "body": "<p>View all my changes on this <a href=\"http://jsfiddle.net/BcTUR/\" rel=\"nofollow\">jsFiddle</a>.</p>\n\n<h2>HTML</h2>\n\n<ul>\n<li>Use the <em>self-closing</em> tag <code>&lt;br /&gt;</code> not the <em>closing</em> tag <code>&lt;/br&gt;</code>.</li>\n<li>Your close buttons (<code>.upper</code>) are doing a very similar function to your <code>&lt;a&gt;</code> tags below, the should both be <code>&lt;a&gt;</code> tags. The reason why I wouldn't make them <code>&lt;div&gt;</code>s is because you would need to manually add a <code>tab-index</code> to enable keyboard accessibility, links come with it.</li>\n<li>I'd use a HTML5 <code>data-</code> attribute instead of ID to specify the id of the div you're showing.</li>\n<li>No need to include an id on the close buttons.</li>\n<li><p>You can add a class to your 'sections' so they can be targeted together.</p>\n\n<pre><code>&lt;div id=\"div1\" class=\"section\"&gt;\n one\n &lt;a class=\"hide-div\"&gt;close&lt;/a&gt;\n&lt;/div&gt;\n&lt;div id=\"div2\" class=\"section\"&gt;\n two\n &lt;a class=\"hide-div\"&gt;close&lt;/a&gt;\n&lt;/div&gt;\n&lt;div id=\"div3\" class=\"section\"&gt;\n three\n &lt;a class=\"hide-div\" href=\"#\"&gt;close&lt;/a&gt;\n&lt;/div&gt;\n&lt;div id=\"div4\" class=\"section\"&gt;\n four\n &lt;a class=\"hide-div\" href=\"#\"&gt;close&lt;/a&gt;\n&lt;/div&gt;\n\n&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n\n&lt;div class=\"buttons\"&gt;\n &lt;a class=\"show-div\" data-div=\"div1\" href=\"#\"&gt;Div 1&lt;/a&gt;\n &lt;a class=\"show-div\" data-div=\"div2\" href=\"#\"&gt;Div 2&lt;/a&gt;\n &lt;a class=\"show-div\" data-div=\"div3\" href=\"#\"&gt;Div 3&lt;/a&gt;\n &lt;a class=\"show-div\" data-div=\"div4\" href=\"#\"&gt;Div 4&lt;/a&gt;\n&lt;/div&gt;\n</code></pre></li>\n</ul>\n\n<h2>CSS</h2>\n\n<ul>\n<li><p>Put the <code>display:none;</code> style into your CSS.</p>\n\n<pre><code>.section {\n height:600px;\n display:none;\n}\n\n.hide-div {\n display:block;\n}\n</code></pre></li>\n</ul>\n\n<h2>JavaScript</h2>\n\n<ul>\n<li>Target the <code>.button</code> class, not <code>a</code>. I would also rename <code>.button</code> to something a little more descriptive like <code>.show-div</code></li>\n<li>.upper isn't very descriptive, something like <code>.hide-div</code> would be better.</li>\n<li>You should only hide and delay the sections if there are any, this gives the user a weird second long pause if there are no sections visible. I've used the <code>.visible</code> class to aid with this.</li>\n<li><p>Pulled the hide sections code out because it's used in multiple places.</p>\n\n<pre><code>$(document).ready(function () {\n $('.show-div').click(function () {\n var divId = this.getAttribute('data-div');\n $('html, body').animate({\n scrollTop: 0\n }, 'slow');\n\n hideSections();\n\n $(\"#\" + divId)\n .slideDown('slow')\n .delay(1000)\n .addClass('visible');\n });\n\n $('.hide-div').click(function () {\n $('html, body').animate({\n scrollTop: 0\n }, 'slow');\n hideSections();\n });\n});\n\nfunction hideSections() {\n if ($('.visible').length &gt; 0) {\n $('.section')\n .slideUp()\n .delay(1000)\n .removeClass('visible');\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T08:44:44.553", "Id": "37390", "Score": "0", "body": "Thank you Tyriar and Back in a Flash, very helpful. Lots of great tips, I'm very pleased. May the learning curve continue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T08:54:03.793", "Id": "37392", "Score": "0", "body": "I can't upvote yet as I'm new, thanks again though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T02:05:11.063", "Id": "24229", "ParentId": "24207", "Score": "2" } } ]
{ "AcceptedAnswerId": "24229", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T15:46:38.437", "Id": "24207", "Score": "4", "Tags": [ "javascript", "jquery", "html", "animation" ], "Title": "Simple element slider animation tool" }
24207
<blockquote> <p>Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.</p> <p>The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.</p> </blockquote> <p>The following is my code, which has already been tested on a onlinejudge. Can someone help me give some comments for the code itself?</p> <pre><code>bool isValid(string s) { stack&lt;char&gt; s1; string::iterator it = s.begin(); map&lt;char, char&gt; x; x['('] = ')'; x['['] = ']'; x['{'] = '}'; for (; it!=s.end(); ++it) { if (!s1.empty()) { char c = s1.top(); if(x[c] == *it) { s1.pop(); } else { s1.push(*it); } } else { s1.push(*it); } } return s1.empty(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:45:18.897", "Id": "37348", "Score": "2", "body": "Instead of a stack you could use recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:53:30.663", "Id": "37376", "Score": "0", "body": "It seems your code validates `()))))` as correct? T." } ]
[ { "body": "<p>You use of objects without prefix them with <code>std::</code> is a bad sign.<br>\nI bet you used <code>using namespace std;</code> in the code. Please stop this habit.<br>\n<a href=\"https://stackoverflow.com/q/1452721/14065\">https://stackoverflow.com/q/1452721/14065</a></p>\n\n<p>When passing objects to functions prefer to pass by <code>const reference</code> to prevent unnecessary copies.</p>\n\n<pre><code>bool isValid(std::string const&amp; s) {\n // ^^^^^ ^^^^^^ \n</code></pre>\n\n<p>To prevent you accidentally modifying things try and use cost_itrerator when you need only read only accesses to a container:</p>\n\n<pre><code> std::string::const_iterator it = s.begin();\n</code></pre>\n\n<p>In C++11 you can use the new 'brace init' feature: </p>\n\n<pre><code>map&lt;char, char&gt; x;\nx['('] = ')';\nx['['] = ']';\nx['{'] = '}';\n\n//replace with:\n map&lt;char, char&gt; x = {{'(', ')'}, {'[',']'},{'{','}'}};\n</code></pre>\n\n<p>Also because this is a imutable you can make it <code>const</code> and <code>static</code>. The const will help prevent errors while the static is so you only create it once.</p>\n\n<pre><code>static map&lt;char, char&gt; const x = {{'(', ')'}, {'[',']'},{'{','}'}};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T22:07:48.550", "Id": "24219", "ParentId": "24208", "Score": "4" } }, { "body": "<p>Loki’s answer is good but I agree with Zoidberg’s comment and would completely reformulate this as a recursion. That way you can solve the problem in a more <em>declarative</em> way.</p>\n\n<p>The upshot: your code reads more like a formulation of the problem rather than a bunch of technical stuff, and is thus potentially easier to understand, although in this simple case the explicit stack is just fine.</p>\n\n<p>The idea of the algorithm can be summarised as follows:</p>\n\n<ul>\n<li>a string is correctly nested if it is empty; <em>or</em></li>\n<li>a string is correctly nested if\n<ul>\n<li>the next character is an expected group closing character <em>and</em></li>\n<li>the subsequent string is correctly nested; <em>or</em></li>\n</ul></li>\n<li>a string is correctly nested if\n<ul>\n<li>the next character is a group opening character <em>and</em></li>\n<li>the subsequent string is correct and closes the group <em>and</em></li>\n<li>the subsequent string <em>after that</em> is correctly nested.</li>\n</ul></li>\n</ul>\n\n<p>It makes sense to reformulate this slightly so that we <em>first</em> test whether the next character is expected (either an “end” character if no group is open, or an expected group closing character). If that isn’t the case we assume that a group is being opened and proceed accordingly.</p>\n\n<p>This can be translated line for line into C++:</p>\n\n<pre><code>match valid_group(char const* str, char expected = '\\0') {\n if (*str == expected)\n return {true, str + 1};\n\n if (*str == '\\0')\n return false;\n\n match result = valid_group(str + 1, closing_char(*str));\n\n if (not result.valid)\n return result;\n\n return valid_group(result.pos, expected);\n}\n</code></pre>\n\n<p>Here <code>match</code> is a type that holds whether the validation so far is successful, and at which position to resume validation; I’ve merely added an implicit constructor that allows us to write <code>return false;</code> rather than <code>return {false, str};</code>:</p>\n\n<pre><code>struct match {\n bool valid;\n char const* pos;\n\n match(bool valid, char const* pos = nullptr) : valid(valid), pos(pos) {}\n};\n</code></pre>\n\n<p>Oh yeah, and <code>closing_char</code> does just that:</p>\n\n<pre><code>char closing_char(char c) {\n switch (c) {\n case '(': return ')';\n case '[': return ']';\n case '{': return '}';\n default: return 'X';\n }\n}\n</code></pre>\n\n<p>… so obviously this function assumes that the input only contains valid braces and no other characters; in particular, <code>valid_group(\"}X\");</code> would return <code>true</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T15:40:22.873", "Id": "25307", "ParentId": "24208", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T16:18:23.887", "Id": "24208", "Score": "6", "Tags": [ "c++", "interview-questions", "stack" ], "Title": "Valid Parentheses" }
24208
<p>First, I want to say that this code works, but I want to make sure this is the right way of doing it. I am writing this for a SMS text API that loops through each phone number. I sometimes gets hung up on 1 number or just takes time. It roughly takes 6-8 sec per number. So I thought I would write something that would make it multitreaded. I wrote this to allow the number of threads at one time to go up depending on the workload.</p> <pre><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestTreading { class Program { static public BlockingCollection&lt;int&gt; Queue = new BlockingCollection&lt;int&gt;(); static public BlockingCollection&lt;int&gt; Finished = new BlockingCollection&lt;int&gt;(); static public BlockingCollection&lt;Thread&gt; Threads = new BlockingCollection&lt;Thread&gt;(); static public int QUCount = 0; static public int THCount = 0; static public int FNCount = 0; static void Main(string[] args) { BuildList(); DateTime StartTime = DateTime.Now; QUCount = Queue.Count; THCount = Threads.Count; FNCount = Finished.Count; while (QUCount &gt; 0) { THCount = Threads.Count; if (THCount &lt; 20) { Thread th1 = new Thread(LoopMethod); Threads.Add(th1); THCount = Threads.Count; th1.Start(); } } DateTime EndTime = DateTime.Now; Console.WriteLine(StartTime); Console.WriteLine(EndTime); Console.WriteLine(EndTime - StartTime); Console.ReadLine(); } static void LoopMethod() { int QueueItem = Queue.Take(); QUCount = Queue.Count; for (long i = 0; i &lt; 100000; i++) { long result = i / 2; } string Display = string.Format("ID:{0} Left In Queue:{1} Finished:{2} Threads Running:{3}", QueueItem, QUCount, FNCount, THCount); Console.WriteLine(Display); Thread.Sleep(10); Finished.Add(QueueItem); FNCount = Finished.Count; Thread CurTh = Thread.CurrentThread; Threads.TryTake(out CurTh); } static void BuildList() { for (long i = 0; i &lt; 5000; i++) { Random RandomNum = new Random(); int Num = RandomNum.Next(1, 2); Queue.Add(Num); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T22:08:24.433", "Id": "37375", "Score": "0", "body": "Which .NET version are you using? Can you show the SMS API (ideal solution should use asynchronous calls to SMS API)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T22:48:29.753", "Id": "37377", "Score": "0", "body": "@almaz Why? There is no need for offloading (since there is no GUI thread) and there also don't seem to be any scalability issues. So why do you say asynchronous calls would be ideal? Especially since they would make the code much more complicated in pre-C# 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T08:12:26.127", "Id": "37389", "Score": "0", "body": "@svick Because if SMS API exposes async calls then there is no need in creating additional threads." } ]
[ { "body": "<pre><code>static public BlockingCollection&lt;int&gt; Queue\nstatic public BlockingCollection&lt;int&gt; Finished\nstatic public BlockingCollection&lt;Thread&gt; Threads\nstatic public int QUCount\nstatic public int THCount\nstatic public int FNCount\n</code></pre>\n\n<p>There is no need to make any of these fields <code>public</code>. You shouldn't change the visibility from the default of <code>private</code> unless you have a reason to do it.</p>\n\n<pre><code>for (long i = 0; i &lt; 5000; i++)\n{\n Random RandomNum = new Random();\n int Num = RandomNum.Next(1, 2);\n Queue.Add(Num);\n}\n</code></pre>\n\n<p>This is a very complicated way to generate 5000 <code>1</code>s. If you actually want to generate random numbers, you can't create a new <code>Random</code> for each iteration, you should instead create it once before the loop and then just call <code>Next()</code> inside it. That's because <code>Random</code> is initialized by the current time by default, and the time as measured by .Net doesn't change that often. That means you would get runs of the same number, which is not random.</p>\n\n<pre><code>THCount = Threads.Count;\nFNCount = Finished.Count;\n</code></pre>\n\n<p>These lines don't do anything here, both collections are going to be empty at this point. In fact, the <code>Count</code> fields are completely useless, you should just use the <code>Count</code> property of each collection instead.</p>\n\n<pre><code>while (QUCount &gt; 0)\n{\n if (THCount &lt; 20)\n {\n Thread th1 = new Thread(LoopMethod);\n th1.Start();\n }\n}\n</code></pre>\n\n<p>This code doesn't make much sense. It's certainly possible that it will start all 20 threads even if there's just a single item in the queue, because you could create all of the threads before the first one starts.</p>\n\n<p>What's much worse is that it will keep on iterating while the other threads are working. This means a whole single core of your CPU will be fully busy, doing basically nothing.</p>\n\n<pre><code>Thread th1 = new Thread(LoopMethod);\n</code></pre>\n\n<p>Threads are relatively heavy-weight, you should usually create a new thread only for a long running operation. If you have thousands of operations, you shouldn't create thousands of threads. Instead, you should create just a few of them and have a loop inside each.</p>\n\n<pre><code>Threads.Add(th1);\n</code></pre>\n\n<p>There is no need to do this. You don't actually need a collection of threads, you just need to know their count. So you should use an <code>int</code> field for that, and increment that value in a thread-safe manner.</p>\n\n<pre><code>Thread CurTh = Thread.CurrentThread;\nThreads.TryTake(out CurTh);\n</code></pre>\n\n<p>This code looks like it's trying to take the current thread out of the collection. In fact, it does no such thing. Instead, it removes the first item from the collection (i.e. the oldest item that hasn't yet been removed from the collection) and assigns that to the <code>CurTh</code> variable. The <code>out</code> modifier means, among other things, that the parameter is used for output only and if it has some value before the method is called, it's going to be ignored.</p>\n\n<pre><code>int QUCount\nint THCount\nint FNCount\nThread th1\n</code></pre>\n\n<p>You shouldn't abbreviate your field and variable names like this. You should write their names in full, (e.g. <code>QueueCount</code> or <code>thread</code>), because code is read more often than it is written, so it makes sense to strive for code that is easy to read, not code that is easy to write. (And it doesn't even make much difference with autocompletion.)</p>\n\n<hr>\n\n<p>Usually, it's much better to use TPL for parallel processing, instead of manually using threads. Using <code>GetConsumingEnumerable()</code> and <code>Parallel.ForEach()</code> would make your code shorter, more readable and much more efficient. (CPU efficiency usually doesn't matter much for code like this, but you're wasting CPU a lot.)</p>\n\n<pre><code>class Program\n{\n static BlockingCollection&lt;int&gt; Queue = new BlockingCollection&lt;int&gt;();\n static BlockingCollection&lt;int&gt; Finished = new BlockingCollection&lt;int&gt;();\n\n static void Main()\n {\n BuildList();\n\n Parallel.ForEach(\n Queue.GetConsumingEnumerable(),\n new ParallelOptions { MaxDegreeOfParallelism = 20 },\n ProcessItem);\n }\n\n static void ProcessItem(int i)\n {\n int result = /* somehow calculate the result here */;\n Finished.Add(result);\n }\n}\n</code></pre>\n\n<p>(I have also removed your logging for brevity.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T00:54:21.243", "Id": "24226", "ParentId": "24211", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:34:58.997", "Id": "24211", "Score": "1", "Tags": [ "c#", "multithreading", ".net", "mobile" ], "Title": "Creating dynamic threads for a SMS text API" }
24211
<p>The code allows you to select an area from the left column and another area from the right column followed by clicking on the Choose button which sends the chosen areas to the server:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; body { overflow: hidden; } article.left { overflow: hidden; float: left; } article.left section { float: left; } section { border: 1px solid black; height: 6em; margin-right: 1em; width: 4em; } article.right section { border: 1px dashed black; } section.ice { transform:rotate(-90deg); -moz-transform:rotate(-90deg); -webkit-transform:rotate(-90deg); } article.right { float: right; } section.section-selected, section.right-selected { border-color: #EEE; } input.choose { display: none; } &lt;/style&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { $('article.left section').click(function() { var was_selected = $(this).hasClass('section-selected'); $('article.left section').removeClass('section-selected'); if (!was_selected) { $(this).addClass('section-selected'); } }); $('article.right section').click(function() { $(this).toggleClass('right-selected'); if ($('section.right-selected')) { $(this).children('input.choose').toggle(); } }); $('input.choose').click(function() { var section = $('section.section-selected'); if (section.length) { console.log(section.attr('section-id') + ' ' + $(this).attr('location-type')); console.log($(this).parents('article').attr('article-id')); } else { console.log('none selected'); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;article article-id="L" class="left"&gt; &lt;section section-id="A"&gt;A&lt;/section&gt; &lt;section section-id="B"&gt;B&lt;/section&gt; &lt;/article&gt; &lt;article article-id="R" class="right"&gt; &lt;section section-id="C"&gt;&lt;input type="button" class="choose" location-type="vertical" value="Choose" /&gt;&lt;/section&gt; &lt;section section-id="D" class="horizontal"&gt;&lt;input type="button" class="choose" location-type="horizontal" value="Choose" /&gt;&lt;/section&gt; &lt;/article&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's a link to the jsfiddle <a href="http://jsfiddle.net/95WvB/">http://jsfiddle.net/95WvB/</a>. The code is working fine but I am wondering if the above is what is considered as spaghetti code that so many of those js frameworks like ember or angular are trying to solve. Is it best to use one of those framework to refactor the above code or use backbone?</p> <p>This code is a sample of a much larger web application which repeats more or less of the same interactions between front and backend.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:59:30.610", "Id": "37361", "Score": "1", "body": "Why is your JavaScript, CSS and HTML all on the same file? Other than that, cache selector. I wouldn't use ember or angular for this sort of code since it is _very_ small compared to a real web \"application\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:02:09.130", "Id": "37364", "Score": "0", "body": "Just trying to make it simpler for people to test the code quickly, I separate the css and javascript in their own files in dev and production." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T20:46:56.573", "Id": "37665", "Score": "0", "body": "\"if ($('section.right-selected'))\" - does this work properly? Empty arrays evaluate to true in Javascript so I thought \"empty\" jQuery objects would as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T21:03:37.007", "Id": "37667", "Score": "0", "body": "$('section.right-selected') evaluates to [] which is false, you can test it in the chrome console. Not sure if other browsers give different output for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T12:45:28.250", "Id": "39568", "Score": "2", "body": "A) `$('section.right-selected')` doesn't evaluate to `[]`, it evaluates to a jQuery object. B) Both `[]` as well as *all* objects are considered `true` in JavaScript. If you want to know if `$('section.right-selected')` has selected anything, you *have to* use `if ($('section.right-selected').length > 0) {...` ." } ]
[ { "body": "<p>This bit needs refactoring. If you are writing a one time script or throw away code ,and you are absolutely certain it won't be more than throw away code, you needn't worry about refactoring.</p>\n\n<p>But since this is a part of a large application everything needs a name indicating what it is or does, making explicit as much as possible implicit structure etc..</p>\n\n<p>For example:</p>\n\n<pre><code> $('article.left section').click(function() {\n var was_selected = $(this).hasClass('section-selected');\n $('article.left section').removeClass('section-selected');\n if (!was_selected) {\n $(this).addClass('section-selected');\n }\n });\n</code></pre>\n\n<p>Can be changed to</p>\n\n<pre><code>function selectAtMostOne(selection, className) {\n selection.click(function() {\n var was_selected = $(this).hasClass(className);\n selection.removeClass(className);\n if (!was_selected) {\n $(this).addClass(className);\n }\n });\n}\nselectAtMostOne($('article.left section'), 'section-selected');\n</code></pre>\n\n<p>And if you are doing this <code>selectAtMostOnce</code> [or whatever it was supposed to do] multiple times, you can add it to jquery or do something else to make using it easier, as in: </p>\n\n<pre><code>$.fn.extend({\n selectAtMostOne: function(options) {\n var defaults = {\n selectedClass : 'selected'\n }\n var options = $.extend(defaults, options);\n\n var selection = this;\n return selection.click(function() {\n var was_selected = $(this).hasClass(options.selectedClass);\n selection.removeClass(options.selectedClass);\n if (!was_selected) {\n $(this).addClass(options.selectedClass);\n }\n });\n}\n});\n\n$('article.left section').selectAtMostOne({selectedClass : 'section-selected'});\n</code></pre>\n\n<p>As an additional benefit, this will remind you to use variables instead of copy-pasted string constants. If you mistype any variable, hopefully your IDE or static-analysis (jslint etc) will tell you that you are using a variable before declaring it, or will have undefined error; which will be easier to debug than the case of mistyped string constants.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T07:57:37.463", "Id": "24368", "ParentId": "24212", "Score": "1" } }, { "body": "<p>I would do it the following way:\nAs far as I got it, you want to select several Areas (e.g. something like Papersize and landscape or portrait format) and want to keep state of what selected so far.</p>\n\n<p>I did not refactor your whole code, but reengineer it a bit:</p>\n\n<pre><code>&lt;div id=\"container\"&gt; \n &lt;div class=\"left unselected\" id=\"a\"&gt;A&lt;/div&gt;\n &lt;div class=\"left unselected\" id=\"b\"&gt;B&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>For the sake of the example I limit my self to these two Areas. You could easily extrapolate to your needs.</p>\n\n<p>First I bound the forEach-function from the array with the following statement:</p>\n\n<pre><code>var forEach=Function.prototype.call.bind([].forEach);\n</code></pre>\n\n<p>After that I used an object to keep the state for me:</p>\n\n<pre><code>var selectedItems={\n a:false,\n b:false,\n c:false,\n d:false\n};\n</code></pre>\n\n<p>That's what you usually would do with something like a \"Model\"</p>\n\n<p>(cf. Backbone.Model.extend({}); in <a href=\"http://backbonejs.org/\" rel=\"nofollow\">http://backbonejs.org/</a>).</p>\n\n<p>But for this usecase, that simple object would do the trick.</p>\n\n<p>Next I would define a toggle function for each group (in my example only for \"left\"):</p>\n\n<pre><code>var toggleSelectionLeft=function(elem){\n target=$(elem.target);\n target.hasClass(\"selected\")?target.removeClass(\"selected\"):target.addClass(\"selected\"); \n var id=elem.target.id;\n selectedItems[id]=!selectedItems[id];\n};\n</code></pre>\n\n<p>This togglefunction handles the adaption of the css and sets the state of our object. Usually you would further decouple these tasks, in only triggering an \"elementSelected\" event, to which thwo functions would subcribe: (1) update the model and (2) adapt the CSS. These are two different tasks. For the sake of this simple example I left them together (So don't do this at home <em>g</em>).</p>\n\n<p>After all your behaviour is declared, you could go on, binding the \"click\" to the wanted behaviour:</p>\n\n<pre><code>forEach($(\".left\"), function(elem){\n $(elem).on(\"click\", toggleSelectionLeft);\n});\n</code></pre>\n\n<p>A working example is under: <a href=\"http://jsfiddle.net/Susv4/\" rel=\"nofollow\">http://jsfiddle.net/Susv4/</a>\nFor submitting values to the server you could easily evaluate our \"model\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T14:08:52.907", "Id": "26605", "ParentId": "24212", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:55:56.323", "Id": "24212", "Score": "6", "Tags": [ "javascript", "jquery", "html" ], "Title": "Is this spaghetti javascript code? How can it be refactored with a javascript library or framework?" }
24212
<p>I discovered that the existing menu in a web app I'm working on has an issue in Chrome, where the "Logged in as" section would jump off the menu bar down below. After looking through the code, I'm trying to rewrite it a bit so that it works more consistently.</p> <pre class="lang-html prettyprint-override"><code>&lt;div style="z-index: 22000; height: 25px; position: fixed; left: 0; top: 0; width: 100%; min-width: 960px;" class="HideMenuFromPrint"&gt; &lt;table style="width: 100%; height: 100%; font-family: Arial; font-size: small;" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;td style="width: 140px; height: 30px; background-color: #FFF; border-bottom-style: solid; border-bottom-width: thin; border-bottom-color: #bbb99d;"&gt; &lt;asp:Image ID="SiteLogoHeader" runat="server" CssClass="HeaderImagePaddingLeft" /&gt; &lt;/td&gt; &lt;td style="background-color: #FFF;"&gt; &lt;asp:Panel ID="pnlHeading" runat="server" Width="100%" Font-Size="Medium"&gt; &lt;table style="width: 100%; vertical-align: top;" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;td align="left"&gt; &lt;telerik:RadMenu ID="MasterPageMenu" runat="server" Height="20px" Style="top: 0px; left: 0px;" Width="100%" CssClass="RadMenuLevel" EnableRoundedCorners="True" OnItemDataBound="MasterPageMenu_ItemDataBound" OnClientItemClicking="onClicking" DataTextField="title" DataNavigateUrlField="url"&gt; &lt;DefaultGroupSettings OffsetX="11" OffsetY="2" /&gt; &lt;/telerik:RadMenu&gt; &lt;div style="position: absolute; right: -3px; top: 4px; width: auto; z-index: 24999; font-size: 8pt;"&gt; &lt;asp:Button runat="server" ID="LogoutButtonPrompt" Width="80" OnClick="LogoutButtonPrompt_Click" Text="" BackColor="Transparent" BorderColor="Transparent" CssClass="logOutBtnDefault" /&gt; &lt;div style="float: left; margin-top: 8px; text-align: right; padding-right: 20px;"&gt; Logged In As: &lt;asp:HyperLink ID="hlChangePassword" runat="server" NavigateUrl="~/Membership/ChangePassword.aspx" Font-Underline="false" Target="_self"&gt; &lt;asp:Label ID="Label1" runat="server"&gt;&lt;/asp:Label&gt;&lt;/asp:HyperLink&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/asp:Panel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>Original CSS:</p> <pre class="lang-css prettyprint-override"><code>.HeaderImagePaddingLeft { padding-left: 8px; } .RadMenuLevel { z-index: 22000; background-image: url('../Images/Nav_Background.png'); } </code></pre> <p>This was after my changes:</p> <pre class="lang-html prettyprint-override"><code> &lt;div id="MainMenu" class="HideMenuFromPrint"&gt; &lt;asp:Panel ID="pnlHeading" runat="server" Width="100%" Font-Size="8pt" Font-Names="Arial"&gt; &lt;ul id="MenuList"&gt; &lt;li style="display: block; float: left; padding-right: 25px; padding-left: 5px; background-color: #FFF;"&gt; &lt;asp:Image ID="SiteLogoHeader" runat="server" /&gt;&lt;/li&gt; &lt;li style="display: inline; position: absolute; right: -3px; padding: 2px; vertical-align: middle;"&gt; Logged In As: &lt;asp:HyperLink ID="hlChangePassword" runat="server" NavigateUrl="~/Membership/ChangePassword.aspx" Font-Underline="false" Target="_self"&gt; &lt;asp:Label ID="Label1" runat="server"&gt;&lt;/asp:Label&gt;&lt;/asp:HyperLink&gt; &lt;asp:Button runat="server" ID="LogoutButtonPrompt" OnClick="LogoutButtonPrompt_Click" Text="" BackColor="Transparent" BorderColor="Transparent" CssClass="logOutBtnDefault" /&gt; &lt;/li&gt; &lt;li style="display: inline; float: none; vertical-align: bottom;"&gt; &lt;telerik:RadMenu ID="MasterPageMenu" runat="server" EnableRoundedCorners="True" OnItemDataBound="MasterPageMenu_ItemDataBound" OnClientItemClicking="onClicking" DataTextField="title" DataNavigateUrlField="url" CssClass="RadMenuLevel" BorderStyle="None"&gt; &lt;DefaultGroupSettings OffsetX="11" OffsetY="2" /&gt; &lt;/telerik:RadMenu&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/asp:Panel&gt; &lt;/div&gt; </code></pre> <p>With the CSS:</p> <pre class="lang-css prettyprint-override"><code>#MainMenu { z-index: 22000; position: fixed; border-bottom-style: solid; min-width: 960px; display: block; background: transparent url('../Images/Nav_Background.png'); border-bottom-width: thin; border-bottom-color: #bbb99d; width: 100%; } #MenuList { float: left; list-style-type: none; } </code></pre> <p>The results were more or less what I was wanting (which is to say, not significantly different from the original and didn't have the problem in Chrome). Below is what it looks like in Firefox, before and after.</p> <p><img src="https://i.stack.imgur.com/8dO4N.png" alt="Before change"></p> <p><img src="https://i.stack.imgur.com/TAtSa.png" alt="After change"></p>
[]
[ { "body": "<p>You've done a pretty good job but there is still a lot of room for improvement. Some notes:</p>\n\n<ul>\n<li>It doesn't really make sense to use <code>&lt;ul&gt;</code> and <code>&lt;li&gt;</code> for the logo, menu and logged in text. Ideally they should each be in <code>&lt;div&gt;</code>s so they are more semantically correct; using a <code>&lt;ul&gt;</code> carries with it additional semantic meaning that it contains a list of similar items.</li>\n<li>Try to leverage classes or ids to target different elements.</li>\n<li>For border use the shorthand: <code>border: 1px solid #bbb99d;</code></li>\n<li>Make sure you include <code>AlternateText</code> for your logo so that screen readers can read the site/company name.</li>\n<li>Prefer CSS to WebForms styling like <code>Width=\"100%\"</code> and <code>Font-Underline=\"false\"</code>.</li>\n<li>It's generally bad to use <code>pt</code> for <code>font-size</code>, it's more difficult to make your site look nicer across a wide range of devices. Prefer <code>em</code> or <code>%</code>.</li>\n<li><code>Text=\"\"</code> on your <code>asp:Button</code> concerns me for accessibility reasons, unless you're setting the text in your code behind?</li>\n</ul>\n\n<p>I'll try my best to improve it but it may not be perfect as it's not a working example.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;div id=\"MainMenu\" class=\"HideMenuFromPrint\"&gt;\n &lt;asp:Panel ID=\"pnlHeading\" runat=\"server\" CssClass=\"menu-panel\"&gt;\n &lt;div id=\"logo\"&gt;\n &lt;asp:Image ID=\"SiteLogoHeader\" runat=\"server\" AlternateText=\"Site name\" /&gt;\n &lt;div&gt;\n &lt;div id=\"login\"&gt;\n Logged In As:\n &lt;asp:HyperLink ID=\"hlChangePassword\" runat=\"server\" NavigateUrl=\"~/Membership/ChangePassword.aspx\" \n Target=\"_self\"&gt;\n\n &lt;asp:Label ID=\"Label1\" runat=\"server\"&gt;&lt;/asp:Label&gt;\n &lt;/asp:HyperLink&gt;\n &lt;asp:Button runat=\"server\" ID=\"LogoutButtonPrompt\" OnClick=\"LogoutButtonPrompt_Click\"\n Text=\"\" CssClass=\"logOutBtnDefault\" /&gt;\n &lt;/div&gt;\n &lt;div id=\"menu\"&gt;\n &lt;telerik:RadMenu ID=\"MasterPageMenu\" runat=\"server\" EnableRoundedCorners=\"True\" \n OnItemDataBound=\"MasterPageMenu_ItemDataBound\" OnClientItemClicking=\"onClicking\" \n DataTextField=\"title\" DataNavigateUrlField=\"url\"\n CssClass=\"RadMenuLevel\"&gt;\n\n &lt;DefaultGroupSettings OffsetX=\"11\" OffsetY=\"2\" /&gt;\n &lt;/telerik:RadMenu&gt;\n &lt;/div&gt;\n &lt;/asp:Panel&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#MainMenu\n{\n z-index: 22000;\n position: fixed;\n border: 1px solid #bbb99d;\n min-width: 960px;\n display: block;\n background: transparent url('../Images/Nav_Background.png');\n width: 100%;\n}\n\n.menu-panel {\n width:100%;\n font-size:.9em;\n font-family:arial;\n}\n\n#logo {\n display: block;\n float: left; \n padding-right: 25px;\n padding-left: 5px;\n background-color: #FFF;\n}\n\n#login {\n display: inline;\n position: absolute;\n right: -3px;\n padding: 2px;\n vertical-align: middle;\n}\n\n#login a {\n text-decoration:none;\n}\n\n.logOutBtnDefault {\n border:0;\n background-color:transparent;\n}\n\n#menu {\n display: inline;\n float: none;\n vertical-align: bottom;\n}\n\n.RadMenuLevel {\n border:0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T03:32:01.580", "Id": "37516", "Score": "0", "body": "Thank you, I appreciate the suggestions. Until this particular assignment, it's been a long time since I've done any HTML markup, been trying to learn what's best practice as I go." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T04:31:26.740", "Id": "24270", "ParentId": "24215", "Score": "1" } } ]
{ "AcceptedAnswerId": "24270", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:03:39.357", "Id": "24215", "Score": "1", "Tags": [ "html", "asp.net", "css" ], "Title": "Changing master page's menu" }
24215
<p>I had an assignment some weeks ago that consisted of making a simple McCulloch-Pitts neural network. I ended up coding it in a pretty OO style (or the OO style I've been taught), and I felt that my implementation might have been a bit excessive for being a one-off assignment: could this perhaps been implemented in a simpler, less verbose way? Possibly forsaking modularity and such since it's not really a concern. I had never seen any Neural Network implementations in Java beforehand, so I didn't really know what was a reasonable approach for this kind of thing. </p> <p>This was implemented in Java - you were supposed to use C or C++, but I didn't know either of them so the teacher indulged me. It models a neural network with three input neurons, one output neuron and two layers of hidden neurons. The actual input-output specification is probably not important here, so I'll just explain the main class (NeuralNetwork.java); This class holds information about all neurons in the network and mediates all message passing between neurons: the neurons will in each fire one or more of their outgoing neurons in each timestep, based on the sum of the input of the ingoing neurons in the previous timestep. All of this message passing goes through the network: all the neurons don't know about each other or the network. </p> <p>So the crux of the problem is simply to coordinate neurons and whether or not they fire their synapses in each timestep, and to calculate the responses of the neurons that they fire "towards" (through the synapses). </p> <pre><code>package main; import java.util.HashMap; import java.util.LinkedList; public class NeuralNetwork { //for debugging int timestep = 0; HashMap&lt;String,InputNeuron&gt; inputNeurons; LinkedList&lt;Neuron&gt; internalNeurons; LinkedList&lt;OutputNeuron&gt; outputNeurons; public NeuralNetwork (HashMap&lt;String,InputNeuron&gt; inputNeurons, LinkedList&lt;Neuron&gt; internalNeurons, LinkedList&lt;OutputNeuron&gt; outputNeurons) { this.inputNeurons = inputNeurons; this.internalNeurons = internalNeurons; this.outputNeurons = outputNeurons; this.outputNeurons.get(0).getOutput(); } public int getNrTimestep() { return timestep; } public int[] timestep(LinkedList&lt;String&gt; inputs) { System.out.println("Network: timestep: " + timestep); for (String inp : inputs) { assert inputNeurons.get(inp) != null : "timestep was given a String as key for an InputNeuron that didn't exist"; inputNeurons.get(inp).fire(); } for (Neuron internal : internalNeurons) { internal.nextTimestep(); } for (Neuron outputNeuron : outputNeurons) { outputNeuron.nextTimestep(); } int[] output = new int[outputNeurons.size()]; int count = 0; for (OutputNeuron outputNeuron : outputNeurons) { output[count++] = outputNeuron.getOutput(); } timestep++; resetAll(); return output; } private void resetAll() { for (Neuron internal : internalNeurons) { internal.reset(); } for (Neuron outputNeuron : outputNeurons) { outputNeuron.reset(); } } } </code></pre>
[]
[ { "body": "<p>Since you didn't post the code of <code>Neuron</code>, <code>InputNeuron</code> and <code>OutputNeuron</code> so I just give some comments on the style.</p>\n\n<h3>Instance variables</h3>\n\n<pre><code>private HashMap&lt;String,InputNeuron&gt; inputNeurons;\nprivate LinkedList&lt;Neuron&gt; internalNeurons;\nprivate LinkedList&lt;OutputNeuron&gt; outputNeurons;\n</code></pre>\n\n<p>Instance variables should be kept <code>private</code> and expose via methods.</p>\n\n<p>Ps: I'm not sure here if you intended to let them <code>package-private</code> for other classess (e.g <code>Neuron</code>, etc) to access them directly.</p>\n\n<h3>Prefer reference to objects by their interfaces</h3>\n\n<p>It is considered a good practice to reference to objects by their interfaces rather than concrete implementation (if they have one). Here you are using the Collection Framework so it'd be better if you declared the instance variables via interfaces.</p>\n\n<pre><code>private Map&lt;String,InputNeuron&gt; inputNeurons;\nprivate List&lt;Neuron&gt; internalNeurons;\nprivate List&lt;OutputNeuron&gt; outputNeurons;\n</code></pre>\n\n<h3>Make defensive copies</h3>\n\n<p>The constructor of <code>NeuronNetwork</code> uses directly the arguments passed to it which could lead to some subtle bugs. It'd be better if you make a copy of those arguments.</p>\n\n<pre><code>public NeuralNetwork(Map&lt;String,InputNeuron&gt; inputNeurons, List&lt;Neuron&gt; internalNeurons,\n List&lt;OutputNeuron&gt; outputNeurons) {\n this.inputNeurons = new HashMap&lt;String, InputNeuron&gt;(inputNeurons);\n this.internalNeurons = new ArrayList&lt;Neuron&gt;(internalNeurons);\n this.outputNeurons = new ArrayList(outputNeurons);\n this.outputNeurons.get(0).getOutput(); // potential IndexOutOfBoundException\n}\n</code></pre>\n\n<p>The last line in the constructor could cause <code>IndexOutOfBoundException</code> if the <code>outputNeurons</code> is empty. I'm not sure the purpose of this line.</p>\n\n<h3>Avoid using array as return type if possible</h3>\n\n<p>The method <code>timeStep</code> returns an <code>int[]</code> which is an array. IMO this is not good since array is less convenience and doesn't provides much useful behaviors. Returning a <code>Collection</code> or a <code>List</code> would be a better choice.</p>\n\n<pre><code>public Collection&lt;Integer&gt; timestep(List&lt;String&gt; inputs) {\n System.out.println(\"Network: timestep: \" + timestep);\n\n for (String inp : inputs) {\n assert inputNeurons.get(inp) != null : \"timestep was given a String as key for an InputNeuron that didn't exist\";\n inputNeurons.get(inp).fire();\n }\n\n for (Neuron internal : internalNeurons) {\n internal.nextTimestep();\n }\n\n for (Neuron outputNeuron : outputNeurons) {\n outputNeuron.nextTimestep();\n }\n\n List&lt;Integer&gt; output = new ArrayList&lt;Integer&gt;(outputNeurons.size());\n for (OutputNeuron outputNeuron : outputNeurons) {\n output.add(outputNeuron.getOutput());\n }\n\n timestep++;\n resetAll();\n return output;\n}\n</code></pre>\n\n<h3>Misc</h3>\n\n<p>You could rename the method <code>getNrTimestep()</code> to <code>getTimestep()</code> for more elegant.</p>\n\n<p>That's it. Hope these could help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T19:20:41.433", "Id": "37828", "Score": "0", "body": "Thanks for the feedback. I didn't really get the benefit of making the defensive copies, though?\n\n\"Ps: I'm not sure here if you intended to let them package-private for other classess (e.g Neuron, etc) to access them directly.\"\n\nI intended them to be private, but forgot to do it. This class is not used by any of the other classes that model the neural network; it only uses the other classes (neurons)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T01:48:05.207", "Id": "37856", "Score": "0", "body": "Since `List` is mutable, if you use your arguments directly without making defensive copies, the client code which passes those arguments to `NeuronNetwork` can modify it directly just as exposing those field with `public`. You can read more about `Making defensive copies\" at [Java Journal](http://java-journal.blogspot.com/2011/01/defensive-copy-part-1-problem-and.html) or [Effective Java - Item 39](http://my.safaribooksonline.com/book/programming/java/9780137150021/methods/ch07lev1sec2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-12T02:07:06.520", "Id": "176592", "Score": "1", "body": "Returning `Collection` is wrong, as the order is relevant. The `output` is a vector in mathematical sense, so `List` may do. IMHO an array is best, as you never want it to grow or alike." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T08:02:53.857", "Id": "24494", "ParentId": "24218", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:50:59.650", "Id": "24218", "Score": "5", "Tags": [ "java", "machine-learning", "neural-network" ], "Title": "Simple Neural Network in Java" }
24218
<p>I just failed in a JavaScript test and I would really appreciate some comments of how I can improve so I can keep learning.</p> <p>The test was about making a form interactive, where the code should do things like changing to the next tab while showing not visible content, validate email, etc.</p> <p>I have received the following feedback to consider:</p> <p><code>[-]</code> caching (no jquery selector is cached)----<br> <code>[-]</code> performance optimization (nope, usage of jquery each instead of a native loop)---<br> <code>[-]</code> reusable code (hardly, as commented above)---<br> <code>[+]</code> clean code and good structure---</p> <p><code>[ ]</code> Extra points for applied design pattern</p> <hr> <pre><code>$("&lt;link rel='stylesheet' href='css/ui-lightness/jquery-ui-1.10.1.custom.css' type='text/css' media='screen' /&gt;").insertAfter("[type='text/css']"); // CSS de Jquery UI function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&amp;'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&amp;'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; function setTabOn(stepNumber) { stepNumber = parseInt(stepNumber); $("#step" + stepNumber + "_tab").addClass("on"); $("#step" + stepNumber + "_tab").click(function() { $(".step").hide(); $("#step" + stepNumber).show(); $("#steps a.active").removeClass("active"); }); } function nextStep(stepNumber) { stepNumber = parseInt(stepNumber) + 1; $(".step").hide(); $("ol#steps li a").removeClass("active"); $("#step" + stepNumber).show(); $("#step" + stepNumber + "_tab").addClass("active"); } $(document).ready(function() { $(".back").click(function() { var idBack = $(this).attr("id"); var idBack = idBack.match(/\d/) - 1; $(".step").hide(); $("#step" + idBack).show(); }); $("#step2_confirm_button").click(function() { $("#step2_confirm").dialog("destroy"); nextStep(2); setTabOn(2); }); $("#step2_cancel_button").click(function() { $("#step2_confirm").dialog("destroy"); }); $(".step").hide(); $("#step1").show(); $("#step1_tab").addClass("active"); $("#step2_confirm").hide(); $("#step1_next").click(function() { var flagFirstStepError = 0; var flagFirstStepEmpty = 0; var flagFirstStepEmail = 0; $("#step1_errors").html(""); $(".required").each(function() { if ($(this).val() == "") { flagFirstStepError = 1; return false } else { flagFirstStepEmpty = 1; } }); // end each if (flagFirstStepError == 1) { $("#step1_errors").append("We are sorry, but you need to enter all the required fields in order to proceed. The following information is missing: &lt;br /&gt;&lt;ol&gt;"); $(".required").each(function() { if ($(this).val() == "") { var labelId = $(this).attr("id"); var y = $("#step1 label[for=" + labelId + "]").html(); $("#step1_errors").append("&lt;li&gt;You must fill the " + y + " field&lt;/li&gt;"); } }); // end each $("#step1_errors").append("&lt;/ol&gt;"); } var userEmail = $("#email").val(); if (!isValidEmailAddress(userEmail)) { $("#step1_errors").append("&lt;p&gt; You must provide a valid email adress"); flagFirstStepEmail = 0; } else { flagFirstStepEmail = 1; } if (flagFirstStepEmail + flagFirstStepEmail == 2) { nextStep(1); setTabOn(1); } }); //end click $("#step2_next").click(function() { $("#confirm_list li").remove(); $("#share_list li label").find("input:checked").each(function() { var x = $(this).val(); $("#confirm_list").append("&lt;li&gt;" + x + "&lt;/li&gt;"); }); $("#step2_confirm").dialog(); }); }); </code></pre>
[]
[ { "body": "<p><strong>[-] caching (no jquery selector is cached)----</strong><br>\n<strong>Your code</strong>:</p>\n\n<pre><code>$(\"#step\" + stepNumber + \"_tab\").addClass(\"on\");\n$(\"#step\" + stepNumber + \"_tab\").click(function() { ...\n</code></pre>\n\n<p><strong>Revised</strong>:</p>\n\n<pre><code>var stepTab = $(\"#step\" + stepNumber + \"_tab\");\nstepTab.addClass(\"on\");\nstepTab.click(function() { ...\n</code></pre>\n\n<p>Storing the results of a selector will make sure you don't have to search the DOM for the \"#step\" + stepNumber + \"_tab\" element each time.</p>\n\n<p><strong>[-] performance optimization (nope, usage of jquery each instead of a native loop)---</strong><br>\n<strong>Original</strong>:</p>\n\n<pre><code>$(\".required\").each(function() { \n if ($(this).val() == \"\") {\n flagFirstStepError = 1;\n return false\n }\n else {\n flagFirstStepEmpty = 1;\n }\n\n});\n</code></pre>\n\n<p><strong>Revised</strong>:</p>\n\n<pre><code>var requiredElems = $(\".required\"), length = requireElems.length;\nfor(var i = 0; i &lt; length; i++){\n var requiredElem = $(requiredElems[i]); \n if (requiredElem.val() == \"\") {\n flagFirstStepError = 1;\n return false\n }\n else {\n flagFirstStepEmpty = 1;\n }\n}\n</code></pre>\n\n<p>The performance can be significantly slower using $.each because it needs to create a function and scope for each iteration where as the generic for loop has a lot less overhead and should be used in simple cases like this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T02:52:38.920", "Id": "24233", "ParentId": "24223", "Score": "1" } }, { "body": "<h2>Initial notes</h2>\n\n<ul>\n<li><p><strong>[-] caching (no jquery selector is cached)</strong></p>\n\n<p>You should be creating variables that store the elements you're selecting with jQuery. The reason for this is that when you call <code>$(\"#step\" + stepNumber + \"_tab\")</code> for example, jQuery will determine what type of selector it is (id), and them call <code>document.getElementById(\"step\" + stepNumber + \"_tab\")</code>. This is particularly important when you're selecting multiple elements.</p></li>\n<li><p><strong>[-] performance optimization (nope, usage of jquery each instead of a native loop)</strong></p>\n\n<p>So you used <code>$.each</code>, what is the problem with that? Well it is doing a tonne of other stuff just so you can have some nice convenient syntax. For systems you're trying to optimise you should probably stay away from it, prefer this:</p>\n\n<pre><code>var required = $(\".required\");\nfor (var i = 0; i &lt; required.length; i++) {\n // object is required[i]\n}\n</code></pre>\n\n<p>As you can see from <a href=\"http://jsperf.com/jquery-each-vs-for-loop/148\" rel=\"nofollow noreferrer\">this jsPeft</a>, a native <code>for</code> loop is much faster than <code>$.each</code>. You can see the source code for <code>each</code> at this <a href=\"https://stackoverflow.com/a/1883691/1156119\">StackOverflow post</a>.</p></li>\n<li><p><strong>[-] reusable code (hardly, as commented above)</strong></p>\n\n<p>The main issue here is that your document ready is a whopping 85 lines long. You should be splitting it up into logical groupings and placing it in functions. This is something that a lot of new programmers have trouble with and I never really understood until I saw a great example. Consider a function of 85 lines of code vs:</p>\n\n<pre><code>$(document).ready(function () {\n setupItemA();\n setupItemB();\n setupItemC();\n setupItemD();\n});\n</code></pre>\n\n<p>This is much more readable, modular and reusable.</p></li>\n<li><p><strong>[+] clean code and good structure</strong></p>\n\n<p>This ties in a lot with above point 'reusable code' in my opinion. I'm assume your teacher was marking this point on consistency, indentation, appropriate calls, etc. which it seems to do pretty well.</p></li>\n<li><p><strong>[] Extra points for applied design pattern</strong></p>\n\n<p>This would depend on what design patterns you have been learning in your course.</p></li>\n</ul>\n\n<h2>Code walkthrough</h2>\n\n<p>I'll now go through my implementation, line-by-line.</p>\n\n<pre><code>// Ideally this should go in your HTML page, I assume it wasn't an option though.\n$(\"&lt;link rel='stylesheet' href='css/ui-lightness/jquery-ui-1.10.1.custom.css' type='text/css' media='screen' /&gt;\").insertAfter(\"[type='text/css']\"); // CSS de Jquery UI\n\n// This regex wouldn't be acceptable in a lot of companies as it's huge and difficult\n// to read. A link to the source would be good in this situation.\nfunction isValidEmailAddress(emailAddress) {\n var pattern = new RegExp(/^((([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i);\n return pattern.test(emailAddress);\n};\n\n// If your spacing is more consistent, your code will look cleaner. More than one \n// line in a row can make code look messy.\n\nfunction setTabOn(stepNumber) {\n // This conversion is redundant, you're converting an int to an int and then using\n // it in a string. JavaScript does conversions like this implicitly anyhow\n //stepNumber = parseInt(stepNumber);\n\n // Caching\n var tab = $(\"#step\" + stepNumber + \"_tab\");\n tab.addClass(\"on\");\n tab.click(function() {\n $(\".step\").hide();\n $(\"#step\" + stepNumber).show();\n $(\"#steps a.active\").removeClass(\"active\");\n }); \n}\n\nfunction nextStep(stepNumber) {\n stepNumber = parseInt(stepNumber) + 1;\n $(\".step\").hide();\n // You don't need to include the ol in 'ol#steps', it makes your code more specific\n // and thus less reusable.\n $(\"#steps li a\").removeClass(\"active\");\n $(\"#step\" + stepNumber).show();\n $(\"#step\" + stepNumber + \"_tab\").addClass(\"active\");\n}\n\n$(document).ready(function() {\n // Your indentation went a little funny in your document ready\n\n $(\".back\").click(backClick);\n $(\"#step2_confirm_button\").click(step2Confirm);\n $(\"#step2_cancel_button\").click(step2Cancel);\n $(\"#step1_next\").click(step1NextClick);\n $(\"#step2_next\").click(step2NextClick);\n\n // Shuffled around in better order\n $(\".step\").hide();\n $(\"#step1\").show();\n $(\"#step1_tab\").addClass(\"active\");\n $(\"#step2_confirm\").hide();\n});\n\nfunction step2Confirm() {\n $(\"#step2_confirm\").dialog(\"destroy\");\n nextStep(2);\n setTabOn(2);\n}\n\nfunction step2Cancel() {\n $(\"#step2_confirm\").dialog(\"destroy\");\n}\n\nfunction backClick = function() {\n // You defined idBank twice here?\n //var idBack = $(this).attr(\"id\");\n //var idBack = idBack.match(/\\d/) - 1;\n // Use this.id instead of the jQuery alternative, it's much faster\n var idBack = this.id\n // I'm not sure what your regex was trying to do\n $(\".step\").hide();\n $(\"#step\" + idBack).show(); \n};\n\nfunction step1NextClick() { \n var flagFirstStepError = 0;\n var flagFirstStepEmpty = 0;\n var flagFirstStepEmail = 0;\n\n $(\"#step1_errors\").html(\"\");\n\n var required = $(\".required\");\n for (var i = 0; i &lt; required.length; i++) {\n if ($(this).val() == \"\") {\n flagFirstStepError = 1;\n // Missing semi-colon\n return false;\n // Place } else { all on same line\n } else {\n flagFirstStepEmpty = 1;\n }\n }\n\n if (flagFirstStepError == 1) {\n showError(this, required);\n }\n\n var userEmail = $(\"#email\").val();\n if (!isValidEmailAddress(userEmail)) {\n // Include a closing tag, address spelt wrong ;)\n $(\"#step1_errors\").append(\"&lt;p&gt;You must provide a valid email address&lt;/p&gt;\");\n flagFirstStepEmail = 0;\n } else {\n flagFirstStepEmail = 1;\n }\n\n // Never do an operation of the left-hand side of an if\n if (flagFirstStepEmail == 1 &amp;&amp; flagFirstStepEmail == 1) {\n nextStep(1);\n setTabOn(1);\n }\n}\n\nfunction showError(sender, required) {\n // Only append the string once, keep in a variable\n var message = \"We are sorry, but you need to enter all the required fields in order to proceed. The following information is missing: &lt;br /&gt;&lt;ol&gt;\";\n for (var i = 0; i &lt; required.length; i++) { \n if ($(sender).val() == \"\") {\n var y = $(\"#step1 label[for=\" + sender.id + \"]\").html();\n message += \"&lt;li&gt;You must fill the \" + y + \" field&lt;/li&gt;\";\n }\n }\n message += \"&lt;/ol&gt;\";\n $(\"#step1_errors\").append(message);\n}\n\n// I moved your events down here to reduce indentation, the size of document ready, and\n// improve readability\nfunction step2NextClick() { \n $(\"#confirm_list li\").remove();\n $(\"#share_list li label\").find(\"input:checked\").each(function() { \n var x = $(this).val(); \n $(\"#confirm_list\").append(\"&lt;li&gt;\" + x + \"&lt;/li&gt;\");\n });\n $(\"#step2_confirm\").dialog();\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T20:40:24.233", "Id": "37427", "Score": "0", "body": "Wow, your answer is realy detailed, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T09:43:21.780", "Id": "24240", "ParentId": "24223", "Score": "2" } }, { "body": "<p>This is an optimized version that I just made, if someone finds it useful</p>\n\n<pre><code>window.userProgress = 0;\nvar stepContent;\nvar stepTab; \nvar backButtons;\nvar nextButtons;\nvar step2Confirm;\n\n// CSS of Jquery UI\n$(\"&lt;link rel='stylesheet' href='css/ui-lightness/jquery-ui-1.10.1.custom.css' type='text/css' media='screen' /&gt;\").insertAfter(\"[type='text/css']\"); \n\n// Email validation\nfunction isValidEmailAddress(stepErrors) {\n var userEmail = $(\"#email\").val();\n var flagStepEmail = 0;\n\n var pattern = new RegExp(/^((([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&amp;'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i);\n\n if (!pattern.test(userEmail)) {\n var message = \"&lt;p&gt; You must provide a valid email address&lt;/p&gt;\"; \n printStepMessages(message, stepErrors);\n flagStepEmail = 1;\n } \n return flagStepEmail;\n};\n\n// Set into the variable \"userProgress\" the reached step by the user\nfunction changeUserProgress(button) {\n userProgress = parseInt(button.id.match(/\\d/)) + 1;\n}\n\n// Checks whether the user is allowed to move further\nfunction checkUserPermision(stepNumber) {\n if (isNaN(stepNumber)) {\n stepNumber = parseInt(stepNumber.id.match(/\\d/)) + 1;\n }\n if (stepNumber &lt;= userProgress ) {\n userMovement(stepNumber);\n }\n}\n\n// Hides and shows step content\nfunction userMovement(stepNumber) {\n var contentToShow;\n changeTab(stepNumber);\n stepContent.hide();\n for (var i = 0; i &lt; stepContent.length; i++) {\n contentToShow = stepContent[i];\n if(contentToShow.id == \"step\" + stepNumber) {\n contentToShow.style.display='block'; \n }\n }\n}\n\n// Sets the \"active\" and \"on\" classes on tabs\nfunction changeTab(stepNumber) {\n var stepTabNumber;\n stepTab.removeClass(\"active\");\n stepTab.removeClass(\"on\");\n for (var i = 0; i &lt; stepTab.length; i++) {\n var stepTabNumber = stepTab[i];\n var stepTabNumberId = stepTabNumber.id.match(/\\d/);\n if(stepTabNumberId == stepNumber) {\n stepTabNumber = $(stepTabNumber);\n stepTabNumber.addClass(\"active\"); \n }\n else if(stepTabNumberId &lt;= userProgress) {\n stepTabNumber = $(stepTabNumber);\n stepTabNumber.addClass(\"on\"); \n }\n } \n}\n\n// Shows messages to the user\nfunction printStepMessages(message, stepMessageContainer, messageIntro, requiredElements) {\n if(messageIntro === undefined) {\n messageIntro = '';\n }\n if(requiredElements === undefined) {\n requiredElements = '';\n }\n stepMessageContainer.prepend(messageIntro);\n stepMessageContainer.append(message);\n} \n\n// Checks if the required fields in Step 1 are filled and sets warning messages if not\nfunction firstTabCheck(requiredFirstStepElements, step1Errors) {\n var message = \"\";\n var fieldElement;\n var firstStepEmpty = 0;\n var messageIntro = \"We are sorry, but you need to enter all the required fields in order to proceed. The following information is missing: &lt;br /&gt;&lt;ol&gt;\";\n for (var i = 0; i &lt; requiredFirstStepElements.length; i++) {\n var requiredFirstStepElement = requiredFirstStepElements[i];\n if (requiredFirstStepElement.value == \"\") {\n fieldElement = $(\"#step1 label[for=\" + requiredFirstStepElement.id + \"]\").html();\n message += \"&lt;li&gt;You must fill the \" + fieldElement + \" field&lt;/li&gt;\";\n firstStepEmpty += 1;\n }\n }\n message += \"&lt;/ol&gt;\";\n if (firstStepEmpty &gt; 0) {\n printStepMessages(message, step1Errors, messageIntro, requiredFirstStepElements);\n } \n return firstStepEmpty;\n}\n\n// Sets message of confirmation for social networks \nfunction secondTabCheck(shareListLabel, socialConfirmList) {\n messaje = \"&lt;li&gt;\" + shareListLabel + \"&lt;/li&gt;\";\n printStepMessages(messaje, socialConfirmList);\n}\n\n$(document).ready(function() {\n\n stepContent = $(\".step\");\n stepTab = $(\"#steps\").find(\"a\"); \n backButtons = $(\".back\");\n nextButtons = $(\".next\");\n step2Confirm = $(\"#content #step2_confirm\");\n var requiredFirstStepElements = $(\".required\"); \n var socialConfirmList = $(\"#confirm_list\");\n var step1Errors = $(\"#step1_errors\");\n var shareListLabels = $(\"#share_list li label\");\n\n stepContent.hide();\n step2Confirm.hide();\n $(\"#content #step1\").show();\n $(\"#content #step1_tab\").addClass(\"active\");\n\n $(\"#step1_next\").click(function() { \n step1Errors.html(\"\");\n var firstStepEmpty = firstTabCheck(requiredFirstStepElements, step1Errors);\n var firstStepEmail = isValidEmailAddress(step1Errors);\n if (firstStepEmpty == 0 &amp;&amp; firstStepEmail == 0) {\n changeUserProgress(this);\n }\n }); \n\n $(\"#step2_next\").click(function() {\n var shareListLabel;\n if(userProgress &lt; 3) { \n $(\"#confirm_list li\").remove();\n var shareListLabelsCheck = shareListLabels.find(\"input:checked\"); \n for (var i = 0; i &lt; shareListLabelsCheck.length; i++) { \n shareListLabel = $(shareListLabelsCheck[i]).val();\n secondTabCheck(shareListLabel, socialConfirmList);\n } \n if(socialConfirmList.children().length &gt; 0) {\n step2Confirm.dialog();\n }\n else {\n changeUserProgress(this);\n }\n }\n });\n\n $(\"#step2_confirm_button\").click(function() {\n step2Confirm.dialog(\"destroy\");\n changeUserProgress(this);\n checkUserPermision(this);\n });\n\n $(\"#step2_cancel_button\").click(function() {\n step2Confirm.dialog(\"destroy\");\n });\n\n stepTab.click(function() { \n var idElement = parseInt(this.id.match(/\\d/)); \n checkUserPermision(idElement);\n });\n\n nextButtons.click(function() { \n var idElement = parseInt(this.id.match(/\\d/)) + 1; \n checkUserPermision(idElement);\n });\n\n backButtons.click(function() {\n var idElement = parseInt(this.id.match(/\\d/)) - 1;\n userMovement(idElement);\n });\n\n}); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T02:28:11.793", "Id": "24295", "ParentId": "24223", "Score": "0" } } ]
{ "AcceptedAnswerId": "24240", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T23:33:49.963", "Id": "24223", "Score": "0", "Tags": [ "javascript", "performance", "jquery", "form" ], "Title": "Support for an interactive form with multiple tabs" }
24223
<p>I'm sure code indentation is a basic requirement for correct development. I have checked out may pages to learn more and results of my coding are below.</p> <p>I like to share that here to receive opinions and suggestions.</p> <pre><code>&lt;?php include_once "../../config.php"; // Start if (!isset($_SESSION)) session_start(); $level = 2; if (!isset($_SESSION['user_id']) OR ($_SESSION['user_levell'] &gt; $req_level)) { header("Location: $url/dashboard.php?error=1"); exit; } // Load permissions $result = mysql_query(" SELECT conf FROM adm_users WHERE user_id=".$_SESSION['user_id'] ); $row = mysql_fetch_array($result, MYSQL_BOTH); $access = $row['acess']; if (($_SESSION['user_level'] != "1") &amp;&amp; ($access_config != "1")) { header("Location: index.php?error=1"); exit; } // End include_once "$url/includes/head.php"; include_once "$url/includes/menu.php"; // Load ser $result = mysql_query(" SELECT * FROM adm_ser WHERE ser_id='$ser_id' "); $row = mysql_fetch_array($result, MYSQL_BOTH); $ser_id = stripslashes($row['ser_id']); $ser_cod = stripslashes($row['ser_cod']); $ser_cd = stripslashes($row['ser_cnpj']); $ser_name = stripslashes($row['ser_name']); $ser_status_id = stripslashes($row['ser_status_id']); // Dropdown Ser Status $sql2 = mysql_query(" SELECT * FROM adm_ser_status WHERE status_id=".$ser_status_id ); while($row = mysql_fetch_array($sql2)) { $status_id_dropdown = $row['status_id']; $status_de_dropdown = $row['status_desc']; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T02:05:32.843", "Id": "37385", "Score": "0", "body": "There is no One True Coding Style. Decide on something and, most importantly, stick to it. (So far, everything look sensible, but I prefer to align the `=` of related assignments)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T23:25:48.383", "Id": "37430", "Score": "0", "body": "I think your coding style is ok, also bearing in mind what Jon said. However, if you are looking to set yourself a style to stick to, I suggest [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md), which is adopted by Zend, Symfony, Amazon to name a few" } ]
[ { "body": "<p>You don't need to indent your <code>$ser_</code> value assignments. Indentation should be left for within a class, method, loop, etc as you do for most of your other code. I notice that you separate your MySQL statement, which can be done, but on such a simple query, really isn't needed as the only purpose for doing that is to help readability when it is a complicated query. ^^</p>\n\n<p>On a side note, <code>mysql_</code> functions are <a href=\"http://www.php.net/manual/en/intro.mysql.php\" rel=\"nofollow\">deprecated now</a>, and you should switch to <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"nofollow\"><code>mysqli_</code></a> (or the MySQLi class), or (preferably) <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T01:59:49.160", "Id": "24228", "ParentId": "24227", "Score": "2" } }, { "body": "<p>In my opinion, it's highly recommend to use one one off \"official\" coding standars like</p>\n\n<ul>\n<li>Zend (<a href=\"http://framework.zend.com/manual/1.12/en/coding-standard.html\" rel=\"nofollow\">http://framework.zend.com/manual/1.12/en/coding-standard.html</a>)</li>\n<li>Pear (<a href=\"http://pear.php.net/manual/en/standards.php\" rel=\"nofollow\">http://pear.php.net/manual/en/standards.php</a>)</li>\n<li>PSR (<a href=\"https://github.com/php-fig/fig-standards/tree/master/accepted\" rel=\"nofollow\">https://github.com/php-fig/fig-standards/tree/master/accepted</a>)</li>\n</ul>\n\n<p>I highly recommend to use PSR-1, PSR-2.</p>\n\n<p>If you want to check what codding style \"errors\" you have - use php code sniffer:</p>\n\n<ul>\n<li><a href=\"http://pear.php.net/manual/en/package.php.php-codesniffer.php\" rel=\"nofollow\">http://pear.php.net/manual/en/package.php.php-codesniffer.php</a></li>\n<li><a href=\"http://jason.pureconcepts.net/2012/11/php-coding-standards/\" rel=\"nofollow\">http://jason.pureconcepts.net/2012/11/php-coding-standards/</a></li>\n<li>You even can integrate in your editor (if you use phpstorm <a href=\"http://blog.jetbrains.com/webide/2012/03/checking-your-code-with-php-code-sniffer-in-phpstorm-4-0/\" rel=\"nofollow\">http://blog.jetbrains.com/webide/2012/03/checking-your-code-with-php-code-sniffer-in-phpstorm-4-0/</a>) or example Sublime Text 2(<a href=\"http://www.soulbroken.co.uk/2012/02/php_codesniffer-plugin-for-sublime-text-2/\" rel=\"nofollow\">http://www.soulbroken.co.uk/2012/02/php_codesniffer-plugin-for-sublime-text-2/</a>)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T17:31:56.420", "Id": "37945", "Score": "0", "body": "agree. Adoption much better than invention." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T14:35:13.803", "Id": "24424", "ParentId": "24227", "Score": "1" } } ]
{ "AcceptedAnswerId": "24228", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T01:39:11.820", "Id": "24227", "Score": "1", "Tags": [ "php", "optimization" ], "Title": "Better code indentation" }
24227
<p>I needed to get the minimum and maximum date values from a query using the Sequel ORM in Ruby from my database. Sequel has a <code>range</code> method that returns a Range value. I'm having it return values from a timestamp field, so they're coming back as a range of Time objects.</p> <p>In order to split it into two variables using parallel assignment, I figured this was about as concise and succinct as I could get:</p> <pre><code>template_min_datestamp, template_max_datestamp = [Template.range(:created_at)].map{ |r| [r.min, r.max] } </code></pre> <p>I considered using:</p> <pre><code>template_min_datestamp, template_max_datestamp = Template.min(:created_at), Template.max(:created_at) </code></pre> <p>but that'd cause two hits to the database, which just makes my eye twitch.</p> <p>Simplifying it for the innocent, and factoring out the ORM calls, it'd look something like this in regular Ruby:</p> <pre><code>t1 = Time.parse('Jan 1, 2013 12:00:00 -700') t2 = Time.parse('Jan 31, 2013 12:00:00 -700') template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] } </code></pre> <p>It seems like there'd be a more direct way to break apart a range into two elements on one line using parallel assignment, but it's escaping me right now. </p> <p>Anyone got some enlightenment to share?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T05:07:41.263", "Id": "37431", "Score": "1", "body": "`template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] }[0]` this works, but I'm not sure if it is what you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T09:47:58.573", "Id": "37527", "Score": "0", "body": "@YuriyGolobokov: yup, that's also what I understood. But then again, although `map` + `first` works, it seems a very non-declarative workaround of the abstraction as/into/chain/..." } ]
[ { "body": "<p>If I understood your question correctly, you need a <code>let</code>-abstraction, for example <a href=\"https://stackoverflow.com/questions/12848967/\">Object#as</a> (or whatever name you like for it, it seems to have dozens). I'd write:</p>\n\n<pre><code># this goes in your core_ext module.\nclass Object\n def as\n yield self\n end\nend\n\nt1 = Time.parse('Jan 1, 2013 12:00:00 -700')\nt2 = Time.parse('Jan 31, 2013 12:00:00 -700')\nmin_datestamp, max_datestamp = (t1..t2).as { |r| [r.min, r.max] }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:02:35.473", "Id": "37405", "Score": "0", "body": "Well, yeah, but that's taken one line of code to seven and hasn't really simplified anything, it's just blurred what is happening. I'm going to go poke at the `*` operator with `..` and see if there's some undiscovered magic there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:06:59.193", "Id": "37406", "Score": "0", "body": "`Object#as` is a generic method, an abstraction that you won't write there. As I see it this effectively reduces the code to one quite descriptive line: `min_datestamp, max_datestamp = (t1..t2).as { |r| [r.min, r.max] }`. If vanilla Ruby does not provide an abstraction you need, you write it. \"blurred what is happening\". This is a archetypical let-block used in lots of languages (and used by many Ruby developers), nothing fancy. Or maybe I didn't understand your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:51:29.530", "Id": "37412", "Score": "0", "body": "I don't think we're on the same page. I edited the question. Hopefully it'll be more clear. I'm trying to avoid making dual DB requests, and make use of the `min` and `max` ends of the range that's returned, without resorting to embedding the range inside `[]` and using `map`. I can't decide if that's a skanky hack, or a brilliant use of `map`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T09:56:15.253", "Id": "24242", "ParentId": "24231", "Score": "0" } }, { "body": "<p><strong>Update</strong></p>\n\n<p>@steenslag points out the <code>minmax</code> builtin. No monkey patching necessary.</p>\n\n<pre><code>template_min_datestamp, template_max_datestamp = Template.range(:created_at).minmax\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T22:47:28.423", "Id": "38006", "Score": "2", "body": "`(2..6).minmax #=>[2, 6]` is plain Ruby." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T01:53:21.333", "Id": "24452", "ParentId": "24231", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T02:30:37.333", "Id": "24231", "Score": "1", "Tags": [ "ruby" ], "Title": "Splitting a range into min and max?" }
24231
<p><a href="http://pastebin.com/wMK0USKx" rel="nofollow">Here's a simple Python Flask app</a>. It uses the Wikidot API to transfer pages between two wikis. I'd like to hear your input on the best way to refactor this code. Here are a couple of questions I have in addition to any criticisms you may have:</p> <p><code>get_lines()</code>: there are two places in here where exceptions can be thrown. I want to be able to catch them independently to be able to give better feedback (see how <code>flash()</code> is used).</p> <p>However, now you have two types of returns for this function (and, in my opinion, that's not very Pythonic): you have a None type if there was an error and a variable if there wasn't. How should the exceptions be best handled here: at the call site or in the function?</p> <pre><code>def get_lines(admin): try: data = admin.pages.get_one({'site': ADMIN_SITE, 'page': SOURCE_PAGE})['content'] except: flash('Error: unable to fetch the production-wiki page with mappings') return data = data.splitlines() try: idx = data.index(SEPERATOR) data = data[idx+1:] except: flash('Error: malformed page mapping') return return data </code></pre> <p>What's the best way to abstract <code>update_pictures</code> and <code>update_wiki</code>? They're 90% the same logic.</p> <pre><code>def update_pictures(): try: admin, prod = get_proxies() except: flash('Error: Unable to initialize XMLRPC connections') return data = get_lines(admin) if not data: return for idx, line in enumerate(data): if line.count('|') != 3: continue admin_page_url, admin_file_url, prod_page_url = line.split('|') if not admin_page_url: flash('Line {0}: Error: no admin page url'.format(idx)) return if not admin_file_url: flash('Line {0}: Error: no admin file url'.format(idx)) return if not prod_page_url: flash('Line {0}: Error: no prod page url'.format(idx)) return try: file_ = admin.files.get_one(ADMIN_SITE, admin_page_url, admin_file_url) except: flash('Line {0]: Error: unable to fetch file {1}/{2}'.format(idx, admin_page_url, admin_file_url)) return kwargs = {'site': PROD_SITE, 'page': prod_page_url, 'file': admin_file_url, 'content': file_['content'], 'revision_comment': 'Updated by wiki_copy script'} if file_['comment']: kwargs['comment'] = admin_page_content['comment'] try: prod.files.save_one(kwargs) except: flash('Line {0}: Error: unable to save page {1}/{2}-&gt;{3}/{2}'.format(idx, admin_page_url, admin_file_url, prod_page_url)) return flash('Line {0}: Successful copy: {1}/{2}-&gt;{3}/{2}'.format(idx, admin_page_url, admin_file_url, prod_page_url)) def update_wiki(): try: admin, prod = get_proxies() except: flash('Error: Unable to initialize XMLRPC connections') return data = get_lines(admin) if not data: return for idx, line in enumerate(data): if line.count('|') != 1: continue admin_page_url, prod_page_url = line.split('|') if not admin_page_url: flash('Line {0}: Error: no admin page url'.format(idx)) return if not prod_page_url: flash('Line {0}: Error: no prod page url'.format(idx)) return try: admin_page_content = admin.pages.get_one({'site': ADMIN_SITE, 'page': admin_page_url}) except: flash('Line {0]: Error: unable to fetch page {1}'.format(idx, admin_page_url)) return kwargs = {'site': PROD_SITE, 'page': prod_page_url, 'revision_comment': 'Updated by wiki_copy script'} title = admin_page_content['title'] if not title: title = prod_page_url kwargs['title'] = title content = admin_page_content['content'] if not content: flash('Line {0}: Error: page {1} has no content'.format(idx, admin_page_url)) return kwargs['content'] = content if admin_page_content['tags']: kwargs['tags'] = admin_page_content['tags'] try: prod.pages.save_one(kwargs) except: flash('Line {0}: Error: unable to save page {1}-&gt;{2}'.format(idx, admin_page_url, prod_page_url)) return flash('Line {0}: Successful copy: {1}-&gt;{2}'.format(idx, admin_page_url, prod_page_url)) return </code></pre> <p>I do understand that the best way to do the I/O is to do just about anything anything other than have it block the main thread and the Flask request. However, this is just a quick script (hence the use of Flask). The reason why there are two paths (one for pages, one for file attachments) is because I want to reduce the chance of timeouts.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T01:50:38.707", "Id": "39234", "Score": "0", "body": "Under what kinds of circumstances will these errors happen?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T06:50:38.343", "Id": "39244", "Score": "0", "body": "Looking at this code again I think I understand the best way to handle errors - have get_lines re-throw inside of the exception handler instead of return. This lets you flash() on the inside and handle errors in a single way at the call site." } ]
[ { "body": "<p>The only one thing which looks dangerous<br>\nWith this:</p>\n\n<pre>\nexcept:\n</pre>\n\n<p>This means you will handle all the exceptions. That is wrong.<br>\nYou are supposed to handle only those exceptions which you expect.</p>\n\n<pre>\nexcept MyExpectedException, OtherExpectedException:\n</pre>\n\n<p>If you get unexpected exception, script has to raise this exception and crash.<br>\nThis will save your time on debugging.<br>\nI see you have logs, but I recommend you to avoid such situations. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T08:18:23.357", "Id": "37471", "Score": "0", "body": "I think the departure from the usual style of exception handling is justified here for UI reasons. If an unexpected exception happens the user will get a 500 error. With this they'll at least get an error which gives line context, keeps the program running and is at least somewhat helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T14:36:10.760", "Id": "37481", "Score": "0", "body": "Please at least try store the raise messages in any log file. This really will help in debugging and protecting. Because you will never know what type of error appeared, maybe crack in system? http://wiki.python.org/moin/HandlingExceptions" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T00:08:38.460", "Id": "24266", "ParentId": "24241", "Score": "0" } }, { "body": "<pre><code>def get_lines(admin):\n try:\n data = admin.pages.get_one({'site': ADMIN_SITE, 'page': SOURCE_PAGE})['content']\n except:\n flash('Error: unable to fetch the production-wiki page with mappings')\n return\n</code></pre>\n\n<p>You should definitely throw an exception rather than <code>flash</code> here. My approach is to define a <code>UserError</code> exception. When those are caught they are displayed to the user, other exceptions aren't. You also shouldn't catch all exceptions here. That'll make it really difficult to figure out what's going on if there is an exception here. Just catch the one exception you actually are interested in. Also, make the error message better. Have it include the SOURCE_PAGE and ADMIN_SITE. The point is to make it easy for the user to fix the problem from the error.</p>\n\n<pre><code> data = data.splitlines()\n try:\n idx = data.index(SEPERATOR)\n data = data[idx+1:]\n except:\n flash('Error: malformed page mapping')\n return\n</code></pre>\n\n<p>Make this error message better. Say that it couldn't find the expected SEPERATOR, not simply malformed page mapping</p>\n\n<pre><code> return data\n\n\ndef update_pictures():\n try:\n admin, prod = get_proxies()\n except:\n flash('Error: Unable to initialize XMLRPC connections')\n return\n</code></pre>\n\n<p><code>get_proxies</code> should be the one raising the exception here.</p>\n\n<pre><code> data = get_lines(admin)\n if not data:\n return\n for idx, line in enumerate(data):\n if line.count('|') != 3:\n continue\n</code></pre>\n\n<p>Shouldn't that be 2? thing1|thing2|thing3 -- 2 |'s</p>\n\n<pre><code> admin_page_url, admin_file_url, prod_page_url = line.split('|')\n\n\n if not admin_page_url:\n flash('Line {0}: Error: no admin page url'.format(idx))\n return\n if not admin_file_url:\n flash('Line {0}: Error: no admin file url'.format(idx))\n return\n if not prod_page_url:\n flash('Line {0}: Error: no prod page url'.format(idx))\n return\n</code></pre>\n\n<p>Do those checks really help you? Presumably blank urls will fail in the next step anyways.</p>\n\n<pre><code> try:\n file_ = admin.files.get_one(ADMIN_SITE, admin_page_url, admin_file_url)\n except:\n flash('Line {0]: Error: unable to fetch file {1}/{2}'.format(idx, admin_page_url, admin_file_url))\n return\n</code></pre>\n\n<p>You've got a typo {0] instead of {0}. M</p>\n\n<pre><code> kwargs = {'site': PROD_SITE,\n 'page': prod_page_url,\n 'file': admin_file_url,\n 'content': file_['content'],\n 'revision_comment': 'Updated by wiki_copy script'}\n\n if file_['comment']:\n kwargs['comment'] = admin_page_content['comment']\n</code></pre>\n\n<p>kwargs usually refers to the ** arguments from a function.</p>\n\n<pre><code> try:\n prod.files.save_one(kwargs)\n except:\n flash('Line {0}: Error: unable to save page {1}/{2}-&gt;{3}/{2}'.format(idx, admin_page_url, admin_file_url, prod_page_url))\n return\n</code></pre>\n\n<p>Again, don't generically catch things and ignore them. In general, its a bad idea to give feedback when unexpected errors occour. It might give an attack information they shouldn't have. </p>\n\n<pre><code> flash('Line {0}: Successful copy: {1}/{2}-&gt;{3}/{2}'.format(idx, admin_page_url, admin_file_url, prod_page_url))\n</code></pre>\n\n<p>As for refactoring, I'd define a function like:</p>\n\n<pre><code>def extract_urls(admin, number):\n for idx, line in get_lines(admin):\n if line.count('|') == number:\n yield idx, + line.split('|')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:21:43.240", "Id": "25336", "ParentId": "24241", "Score": "2" } } ]
{ "AcceptedAnswerId": "25336", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T09:55:36.937", "Id": "24241", "Score": "2", "Tags": [ "python", "flask" ], "Title": "Simple Python Flash app using Wikidot API to transfer pages between two wikis" }
24241
<p>I am currently trying to teach myself some programming. I have started to work with Python by doing <a href="https://www.hackerrank.com/challenges/string-similarity" rel="nofollow">this challenge</a>.</p> <p>For each test case, I need to find the sum of the self-similarities of a string with each of its suffixes. For example, given the string <code>ababaa</code>, the self-similarity scores are</p> <ul> <li>6 (because <code>ababaa</code> = <code>ababaa</code>)</li> <li>0 (because <code>ababaa</code> ≠ <code>babaa</code>)</li> <li>3 (because <code>ababaa</code> and <code>abaa</code> share three initial characters)</li> <li>0 (because <code>ababaa</code> ≠ <code>baa</code>)</li> <li>1 (because <code>ababaa</code> and <code>aa</code> share one initial character)</li> <li>1 (because <code>ababaa</code> and <code>a</code> share one initial character)</li> </ul> <p>… for a total score of 11.</p> <p>When I test run it works out fine, however when I run this code with longer strings it takes too long time to run, so the site shuts down the program. Each input string consists of up to 100000 lowercase characters.</p> <p>Is this because this code make unnecessary loops? Or what else might the problem be here? </p> <pre><code># Solution.py for https://www.hackerrank.com/challenges/string-similarity import sys for line in sys.stdin: if line.islower(): line = line[:-1] # line will be compared to suffix line_length = len(line) points = 0 for s in xrange(0,line_length): suffix = line[s:] suffix_length = len(suffix) count = 1 while count &lt; suffix_length+1: if line.startswith(suffix[:1]): # if line and first character of suffix mach if line.startswith(suffix[:suffix_length]): points += len(suffix[:suffix_length]) break else: if line.startswith(suffix[:count+1]): count += 1 elif line.startswith(suffix[:count]): points += len(suffix[:count]) break else: break print points </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:05:08.987", "Id": "49229", "Score": "2", "body": "Try studying z-algorithm. This question is a very very simple modification of the z-array you get as part of the z-algorithm. See this <http://codeforces.com/blog/entry/3107> for the tutorial or youtube video tutorials <http://www.youtube.com/watch?v=MFK0WYeVEag>" } ]
[ { "body": "<p>It is slow because you use slow algorithm (\"too many loops\"). This problem might be a bit hard for beginner. If you want to solve it anyway, be sure to search for tutorials on string algorithms (try to look at <a href=\"http://en.wikipedia.org/wiki/Aho-Corasick\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Aho-Corasick</a> and change it a bit). Maybe dynamic programming will help you with this or other problems.</p>\n\n<p>PS I hope you understand nobody here can not spoil the solution. Have fun with programming.</p>\n\n<hr>\n\n<p>You could always try another problems:</p>\n\n<p>Timus one of the best: <a href=\"http://acm.timus.ru/problemset.aspx\" rel=\"nofollow\">http://acm.timus.ru/problemset.aspx</a></p>\n\n<p>Project Euler if you like mathematics: <a href=\"http://projecteuler.net/\" rel=\"nofollow\">http://projecteuler.net/</a></p>\n\n<p>(Please feel free to edit and add some more.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T13:07:48.370", "Id": "24249", "ParentId": "24246", "Score": "4" } }, { "body": "<p>You have far too many <code>if line.startswith(something)</code> checks inside the <code>while</code> loop -- you are checking the same characters many times. The <code>while</code> loop counts characters, so you only need to compare one pair of characters on each iteration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T13:06:52.370", "Id": "24417", "ParentId": "24246", "Score": "1" } }, { "body": "<p>As @Janne-Karila has said there are too many <code>startswith</code>s. Your <code>suffix[:1]</code> could be replaced by <code>suffix[0]</code> and <code>suffix[:suffix_length]</code> is simply the same as <code>suffix</code>.</p>\n\n<p>If you design the loops right you only need to compare one character at a time, and there is no call to use <code>startswith</code> at all. This also greatly simplifies the code.</p>\n\n<pre><code>def string_sim():\n n = int(sys.stdin.readline())\n for _ in range(n):\n line = sys.stdin.readline().strip()\n points = len(line)\n for s in xrange(1, len(line)):\n for count in xrange(len(line) - s):\n if line[count] != line[s + count]:\n break\n points += 1\n print points\nstring_sim()\n</code></pre>\n\n<p>This will give a slight speed boost, but as others have pointed out, you need a wholly better algorithm to pass all the tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T20:14:59.303", "Id": "30930", "ParentId": "24246", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T11:33:51.017", "Id": "24246", "Score": "6", "Tags": [ "python", "algorithm", "strings", "time-limit-exceeded" ], "Title": "Hackers Ranking String Similarity" }
24246
<p>As a free-time activity in order to learn some Lisp I had to implement depth first directed graph search. Due to large graph size (800K nodes, 5M arcs) recursion-based approach I could devise didn't work. </p> <p>Below is my stack-based implementation that I would like to improve in terms of readability if nothing else. Any comments on style, use of Lisp idioms, code smell are welcome.</p> <pre><code>(defun depth-first-search (adjacency-array visit-function &amp;optional (init-function nil init-function-supplied-p)) (let* ((num-nodes (array-dimension adjacency-array 0)) (init most-negative-fixnum) (nodes-seen (make-array num-nodes :element-type 'fixnum :initial-element init)) (results (make-array num-nodes :element-type 'fixnum :initial-element init))) (labels ((visited-p (node) (not (eql init (aref results (1- node))))) (seen-p (node) (not (eql init (aref nodes-seen (1- node))))) (mark-seen (node) (setf (aref nodes-seen (1- node)) 1)) (mark-visited (node) (setf (aref results (1- node)) (funcall visit-function))) (visit (node) (unless (visited-p node) (when init-function-supplied-p (funcall init-function node)) (mark-seen node) (loop with stack = (list node) until (null stack) for head = (first stack) for tails = (aref adjacency-array (1- head)) for fresh-tails = (unless (visited-p head) (loop for tail in tails unless (or (visited-p tail) (seen-p tail)) collect tail)) do (if fresh-tails (progn (mapcar #'mark-seen fresh-tails) (setq stack (append fresh-tails stack))) (progn (pop stack) (unless (visited-p head) (mark-visited head)))))))) (loop for node from 1 to num-nodes unless (or (null node) (visited-p node)) do (visit node) finally (return results))))) </code></pre> <p>Some details:</p> <ul> <li><code>adjacency-array</code> for a graph <code>1-&gt;2;1-&gt;3;3-&gt;1</code> would be <code>#((2 3) nil (1))</code>.</li> <li><code>visit-function</code> returns a "visited" value for a node.</li> <li><code>init-function</code> makes necessary actions when new subgraph search starts.</li> </ul>
[]
[ { "body": "<p>If-else functionality is build-it into <code>loop</code> (no way). </p>\n\n<p>This fragment inside the loop can be rewritten:</p>\n\n<pre><code>do (if fresh-tails \n (progn\n (mapcar #'mark-seen fresh-tails)\n (setq stack (append fresh-tails stack)))\n (progn\n (pop stack)\n (unless (visited-p head) (mark-visited head))))\n</code></pre>\n\n<p>Using <code>loop</code>'s <code>if-else</code>:</p>\n\n<pre><code>if fresh-tails do\n (mapcar #'mark-seen fresh-tails)\n (setq stack (append fresh-tails stack)) \nelse do\n (pop stack)\n (unless (visited-p head) (mark-visited head))\n</code></pre>\n\n<p>Less clutter, however requires manual formatting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T10:51:36.793", "Id": "24333", "ParentId": "24247", "Score": "0" } }, { "body": "<p>This usage of <code>LOOP</code> is not supported by ANSI Common Lisp. You can't have an <code>UNTIL</code> clause (only in a <em>main clause</em> in <code>LOOP</code> syntax) before a <code>FOR</code> clause (a <em>variable clause</em>).</p>\n\n<p>See: <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_loop.htm\" rel=\"nofollow\">Macro LOOP</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T11:17:34.470", "Id": "24899", "ParentId": "24247", "Score": "1" } } ]
{ "AcceptedAnswerId": "24333", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T11:39:41.110", "Id": "24247", "Score": "1", "Tags": [ "lisp", "common-lisp", "graph" ], "Title": "Improving readability of non-recursive depth first search function in Lisp" }
24247
<p>Is this a good approach for a BayeuxClient class?</p> <p>Reading cometd reference book, Chapter 6 Java Libraries, I created this BayeuxClient class.</p> <p>As a newbie to cometd, I would like to know if this class has any flaws:</p> <pre><code>import java.util.*; import java.net.URL; import org.cometd.client.BayeuxClient; import org.eclipse.jetty.client.HttpClient; public class CometD_Client extends BayeuxClient { private URL BayeuxServer_URL; private HttpClient JettyHttpClient; private Map&lt;String, Object&gt; TransportOptions; private ClientTransport C_Transport; private ClientSession C_Session; private boolean HandIsShaken£ = false; private final ClientSessionChannel.MessageListener MyChannelListener; public CometD_Client(URL BayeuxServer_URL) { this.BayeuxServer_URL = BayeuxServer_URL; // Create (and eventually set up) Jetty's HttpClient; JettyHttpClient = new HttpClient(); JettyHttpClient.start(); // Prepare the transport; TransportOptions = new HashMap&lt;String, Object&gt;(); ClientTransport C_Transport = LongPollingTransport.create(TransportOptions, JettyHttpClient ); C_Session = new BayeuxClient(URL, C_Transport); C_Session.handshake(); HandIsShaken£ = C_Session.waitFor(1000, BayeuxClient.State.CONNECTED); if(HandIsShaken£) { // TO DO: Output that the handshake had succeed; } else { // TO DO: Output that the handshake had failed; } MyChannelListener = new AChannelListener(); C_Session.getChannel(Channel.META_HANDSHAKE).addListener ( new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel ThisMetaChanel, Message msg) { // TO DO: Output msg to check it out; C_Session.getChannel("/myBroadcast/myChannel").subscribe ( new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel ThisMetaChanel, Message msg) { // TO DO: Handle the received messages to this chaned; } } ); } } ); } public boolean GetIfHandIsShaken£() { return HandIsShaken£; } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>I have no idea how to type the last character on my keyboard which makes modification harder:</p>\n\n<blockquote>\n<pre><code>public boolean GetIfHandIsShaken£()\n</code></pre>\n</blockquote>\n\n<p>It's better to use only ASCII letters.</p></li>\n<li><p>See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em> and <a href=\"http://docs.oracle.com/javase/specs/\" rel=\"nofollow\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a>:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n \n <p>[...]</p>\n \n <p>Names of fields that are not final should be in mixed \n case with a lowercase first letter and the first letters of \n subsequent words capitalized.</p>\n</blockquote>\n\n<p><code>CometD_Client</code> could have a more descriptive classname too. Every CometD client could have been called <code>CometdClient</code>. Why is it special? Try to put that into the name.</p></li>\n<li><blockquote>\n<pre><code>TransportOptions = new HashMap&lt;String, Object&gt;();\n</code></pre>\n</blockquote>\n\n<p>This could be in the same line as the declaration:</p>\n\n<pre><code>private Map&lt;String, Object&gt; transportOptions = new HashMap&lt;String, Object&gt;();\n</code></pre></li>\n<li><p><code>HttpClient</code> has a <code>stop()</code> method. I suppose you should call it somewhere.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-08T05:42:01.743", "Id": "43774", "ParentId": "24248", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T12:52:53.870", "Id": "24248", "Score": "1", "Tags": [ "java", "design-patterns" ], "Title": "Is this a good approach for a BayeuxClient class?" }
24248
<p>I've recently re-written a Python script I use to run a couple of lightweight blogs. Looking over the horrible code I'd written before, I decided to rewrite it using object-oriented concepts. I wanted to submit it to get feedback, best practices, and other areas I should look at. This is my first script that uses any object oriented ideas. </p> <pre><code>import markdown import jinja2 import re import datetime import time import glob import cgi class Article: def __init__(self, local_dir, local_file): local_file = local_file.replace('/','') self.local_file_name = local_file with open(local_dir + '/' + local_file) as f: self.lines = f.readlines() self.file_text = ''.join(self.lines[4:]) def text(self): return self.file_text def title(self): title = self.get_metadata(self.lines[0]) return title def html_filename(self): html_filename = re.sub('.txt','.html',self.local_file_name) return html_filename def date_text(self): date_text = self.get_metadata(self.lines[2]) return date_text def date_datetime(self): date_txt = self.date_text() date_obj = datetime.datetime.strptime(date_txt, '%d %B %Y') return date_obj def date_rss(self): date = time.strptime(self.date_text(), '%d %B %Y') rss_date = time.strftime('%a, %d %b %Y 06:%M:%S +0000', date) return rss_date def summary(self): summary = re.sub('&lt;[^&lt;]+?&gt;','', self.html())[0:200] summary = re.sub('\n',' ',summary) return summary def html(self): md = markdown.Markdown() converted_text = md.convert(self.file_text).encode('utf-8') return converted_text def get_metadata(self,line): element = re.sub('\n|Author: |Date: |Title: ','',line) element = cgi.escape(element).strip() return element class FileList: def __init__(self, dir, ignore_list): self.textfiles = glob.glob(dir+"/*.txt") for ignored_file in ignore_list: self.textfiles.remove(dir+ignored_file) def files(self): return self.textfiles class Site: def load_articles(self, dir, ignore_list): file_list = FileList(dir, ignore_list) articles = [] for file in file_list.files(): article = Article(dir, file.replace(dir,'')) articles.append({ 'title': article.title(), 'datetime': article.date_datetime(), 'text': article.text(), 'summary': article.summary(), 'html': article.html(), 'date_text': article.date_text(), 'html_filename': article.html_filename(), 'date_rss': article.date_rss() },) articles = sorted(articles, key=lambda k: k['datetime'], reverse=True) return articles def build_from_template(self, data, template, output_file, dir): with open(template) as f: template = jinja2.Template(f.read()) with open(dir + '/' + output_file,'w') as i: i.write(template.render(data = data)) return True def build_site(self, params): dir = params['DIR'] template_dir = params['TEMPLATE_DIR'] index_template = template_dir + '/index_template.html' archive_template = template_dir + '/archive_template.html' rss_template = template_dir + '/rss_template.xml' article_template = template_dir + '/article_template.html' index_output = '/index.html' archive_output = '/archive.html' rss_output = '/index.xml' site = Site() articles = site.load_articles(dir, params['IGNORE_LIST']) for article in articles: output = article['html_filename'] site.build_from_template(article, article_template, output, dir) site.build_from_template(articles, index_template, index_output, dir) site.build_from_template(articles, archive_template, archive_output, dir) site.build_from_template(articles, rss_template, rss_output, dir) return True </code></pre> <p>Here's the script that executes the code above to actually build a site:</p> <pre><code>#!/usr/local/bin/python import pueblo PARAMS = { 'DIR': '/dir/to/your/html/files/', # no final slash 'TEMPLATE_DIR': '/dir/to/store/your/templates', # no final slash 'IGNORE_LIST': ['ignorethis.txt'] } print "Content-type: text/html\n\n" site = pueblo.Site() site.build_site(PARAMS) print "&lt;html&gt;&lt;head&gt;&lt;title&gt;Site Rebuilt&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Site Rebuilt&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;" </code></pre> <p>Finally, here's an example Jinja2 template:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;title&gt;yoursite.com&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;meta name="viewport" content="user-scalable=yes, width=device-width" /&gt; &lt;link href="./index.xml" rel="alternate" type="application/rss+xml" /&gt; &lt;h1&gt;yoursite.com&lt;/h1&gt; &lt;p class="site_description"&gt;your description&lt;/p&gt; &lt;ul class="navbar"&gt; &lt;li class="navitem"&gt;&lt;a href="your_about_page.html"&gt;about&lt;/a&gt;&lt;/li&gt; &lt;li class="navitem"&gt;&lt;a href="./archive.html"&gt;archive&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/div&gt; &lt;div class="article_list"&gt; {% for i in range(30) %} &lt;h2&gt;&lt;a href="{{ data[i].html_filename }}"&gt;{{ data[i].title }}&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;{{ data[i].date_text }}: {{ data[i].summary }} &lt;a href="{{ data[i].html_filename }}"&gt;...&lt;/a&gt;&lt;/p&gt; {% endfor %} &lt;h2&gt;&lt;a href="archive.html"&gt;View All Articles&lt;/a&gt;&lt;/h2&gt; </code></pre>
[]
[ { "body": "<p>Overall your design looks good to me. A couple of relatively minor things to note: </p>\n\n<p><strong>Use new-style classes</strong><br>\nIn Python 2.x you should make sure your classes inherit from <code>object</code>. Such classes are known as new-style classes. (In Python 3.x all classes are new-style classes.) New-style classes offer: </p>\n\n<ul>\n<li>support for the built-in function <code>super()</code> to refer to the base class (or other parent class) without hard-coding; more info: <a href=\"http://rhettinger.wordpress.com/2011/05/26/super-considered-super/\" rel=\"nofollow\">http://rhettinger.wordpress.com/2011/05/26/super-considered-super/</a></li>\n<li>improved method resolution order (MRO); more info: <a href=\"http://python-history.blogspot.com/2010/06/method-resolution-order.html\" rel=\"nofollow\">http://python-history.blogspot.com/2010/06/method-resolution-order.html</a></li>\n<li>support for descriptors: methods that behave like attributes; more info: <a href=\"http://docs.python.org/2/reference/datamodel.html#invoking-descriptors\" rel=\"nofollow\">http://docs.python.org/2/reference/datamodel.html#invoking-descriptors</a></li>\n</ul>\n\n<p><strong>Use the standard-library to make your code more portable</strong><br>\nWhen building up paths you may do so in a cross-platform way by using <code>os.path.join</code>. This is just one example, but there are other places in your code where you can use this: </p>\n\n<pre><code>import os\nfile_path = os.path.join( local_dir, local_file )\nwith open(file_path) as f:\n ...\n</code></pre>\n\n<p><strong>Miscellaneous</strong><br>\nThere is a comment which doesn't agree with the code.</p>\n\n<pre><code>'DIR': '/dir/to/your/html/files/', # no final slash\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:00:22.700", "Id": "37537", "Score": "0", "body": "Is this a simple matter of doing something like \"class article(object):\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:29:30.233", "Id": "37542", "Score": "0", "body": "Yes exactly: `class Article(object):`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T15:50:31.260", "Id": "24253", "ParentId": "24250", "Score": "4" } }, { "body": "<p>There's nothing wrong with <a href=\"https://stackoverflow.com/questions/8297723/oop-getter-setter-methods\">directly accessing class attributes</a> in Python, so you could cut out some complexity by doing all your metadata-related calculation once in <code>__init__</code>:</p>\n\n<pre><code>class Article:\n def __init__(self, local_dir, local_file):\n ...\n # I'd actually lose get_metadata() completely, and do its list parsing here as well.\n self.title = self.get_metadata(self.lines[0])\n self.html_filename = re.sub('.txt','.html',self.local_file_name) \n # etc.\n</code></pre>\n\n<p>If the attribute is something that's likely to need some manipulation each time you need it, you can use properties as well.</p>\n\n<p>Also, as a general note, you don't really need to assign your return values to a variable before returning them. You can easily do</p>\n\n<pre><code>def title(self):\n return self.get_metadata(self.lines[0]) \n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>def title(self):\n title = self.get_metadata(self.lines[0])\n return title\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T19:09:44.320", "Id": "24257", "ParentId": "24250", "Score": "1" } }, { "body": "<pre><code>import markdown\nimport jinja2\nimport re\nimport datetime\nimport time\nimport glob\nimport cgi\n\nclass Article:\n def __init__(self, local_dir, local_file):\n</code></pre>\n\n<p>It would make more sense to pass in the complete path, and then use <code>os.path.dirname</code> and <code>os.path.basename</code> to extract the parts if you need them.</p>\n\n<pre><code> local_file = local_file.replace('/','')\n</code></pre>\n\n<p>Don't use replace to eliminate items in your string if you know where they are. Use <code>.lstrip()</code> or <code>.rstrip()</code> to remove from the beginning or end. Furthermore, don't use string manipulation on filepaths at all. Use <code>os.path</code> functions</p>\n\n<pre><code> self.local_file_name = local_file\n</code></pre>\n\n<p>Don't store things in local variables and then store them on the object. Just store them directly on the object.</p>\n\n<pre><code> with open(local_dir + '/' + local_file) as f:\n self.lines = f.readlines()\n self.file_text = ''.join(self.lines[4:]) \n\n def text(self):\n return self.file_text\n</code></pre>\n\n<p>Rather then define functions like this, just store it as <code>.text</code> and fetch it directly.</p>\n\n<pre><code> def title(self):\n title = self.get_metadata(self.lines[0])\n return title\n\n def html_filename(self):\n html_filename = re.sub('.txt','.html',self.local_file_name)\n return html_filename\n</code></pre>\n\n<p>Don't use regular expressions when a simple string function will do the same. In this case <code>.</code> means something special and so this probably doesn't work exactly like you think. </p>\n\n<pre><code> def date_text(self):\n date_text = self.get_metadata(self.lines[2])\n return date_text\n\n def date_datetime(self):\n date_txt = self.date_text()\n date_obj = datetime.datetime.strptime(date_txt, '%d %B %Y')\n return date_obj\n\n def date_rss(self):\n date = time.strptime(self.date_text(), '%d %B %Y')\n rss_date = time.strftime('%a, %d %b %Y 06:%M:%S +0000', date)\n return rss_date\n</code></pre>\n\n<p>Generally, it doesn't make sense to have an object provide its data in multiple formats like this. Just provide access to the datetime object. Your caller can use the <code>strftime/strptime</code> methods to get the format they want. It doesn't make any sense for this object to be concerned with the formats other objects want.</p>\n\n<pre><code> def summary(self):\n summary = re.sub('&lt;[^&lt;]+?&gt;','', self.html())[0:200]\n</code></pre>\n\n<p>We use +? instead of *?</p>\n\n<pre><code> summary = re.sub('\\n',' ',summary)\n return summary\n\n\n\n def html(self):\n md = markdown.Markdown()\n converted_text = md.convert(self.file_text).encode('utf-8')\n return converted_text\n</code></pre>\n\n<p>I'd suggest for all these, that you extract the data in the constructor, and store it on local attributes.</p>\n\n<pre><code> def get_metadata(self,line):\n element = re.sub('\\n|Author: |Date: |Title: ','',line)\n</code></pre>\n\n<p>This ignores the actual information saying what the line is. That bothers me. I think it'd better to follow those pieces of information.</p>\n\n<pre><code> element = cgi.escape(element).strip()\n return element\n\nclass FileList:\n def __init__(self, dir, ignore_list):\n self.textfiles = glob.glob(dir+\"/*.txt\")\n for ignored_file in ignore_list:\n self.textfiles.remove(dir+ignored_file)\n\n def files(self):\n return self.textfiles\n</code></pre>\n\n<p>Again, no need in python to define getters, just access the attributes. The whole thing actually would be better as a function return the list of files.</p>\n\n<pre><code>class Site:\n def load_articles(self, dir, ignore_list):\n file_list = FileList(dir, ignore_list)\n articles = []\n for file in file_list.files():\n article = Article(dir, file.replace(dir,''))\n articles.append({\n 'title': article.title(),\n 'datetime': article.date_datetime(),\n 'text': article.text(),\n 'summary': article.summary(),\n 'html': article.html(), \n 'date_text': article.date_text(),\n 'html_filename': article.html_filename(),\n 'date_rss': article.date_rss()\n },)\n</code></pre>\n\n<p>Don't copy your article over into a dictionary. That completely defeats the point of having object. Make a list of articles and have Jinja extract the fields.</p>\n\n<pre><code> articles = sorted(articles, key=lambda k: k['datetime'], reverse=True)\n</code></pre>\n\n<p>Why not do an inplace sort?</p>\n\n<pre><code> return articles\n\n def build_from_template(self, data, template, output_file, dir):\n with open(template) as f:\n template = jinja2.Template(f.read())\n with open(dir + '/' + output_file,'w') as i:\n i.write(template.render(data = data))\n return True\n\n def build_site(self, params):\n dir = params['DIR']\n template_dir = params['TEMPLATE_DIR']\n index_template = template_dir + '/index_template.html'\n archive_template = template_dir + '/archive_template.html'\n rss_template = template_dir + '/rss_template.xml'\n article_template = template_dir + '/article_template.html'\n index_output = '/index.html'\n archive_output = '/archive.html'\n rss_output = '/index.xml' \n site = Site()\n</code></pre>\n\n<p>You already have a site object, why are you creating another one?</p>\n\n<pre><code> articles = site.load_articles(dir, params['IGNORE_LIST']) \n for article in articles:\n output = article['html_filename']\n site.build_from_template(article, article_template, output, dir)\n site.build_from_template(articles, index_template, index_output, dir)\n site.build_from_template(articles, archive_template, archive_output, dir)\n site.build_from_template(articles, rss_template, rss_output, dir) \n</code></pre>\n\n<p>You repeat the same thing for the index/archive/rss without any substational code differences. Have a list of <code>[\"archive\",\"rss\",index\"]</code> and do everything related to those in a loop.</p>\n\n<pre><code> return True\n</code></pre>\n\n<p>Serves no purpuse. You don't need a return value unless you are answering a question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T15:32:04.287", "Id": "37442", "Score": "0", "body": "Thank you very much for this, Winston. Can you describe the in-place sort? I'm not exactly sure how that would work when I don't have a list of articles somewhere ordered by the datetime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T15:45:50.377", "Id": "37444", "Score": "0", "body": "@MikeShea, use the `.sort()` method instead of the `sorted()` function. Its somewhat more efficient if you don't need to keep the original list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T16:59:36.727", "Id": "37446", "Score": "0", "body": "Thanks! I just updated it with articles.sort(key=lambda k: k.datetime, reverse=True) instead of articles = sorted(articles, blah). A big help!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T21:32:27.450", "Id": "24261", "ParentId": "24250", "Score": "4" } } ]
{ "AcceptedAnswerId": "24261", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T13:23:49.300", "Id": "24250", "Score": "3", "Tags": [ "python", "object-oriented" ], "Title": "Small blogging script" }
24250
<p>I'm a PHP novice and so looking for some advice on a PHP function I have created to use within a WordPress installation.</p> <p>As you can see from the code below, it runs when one of the admin's press 'Publish' on a pending post.</p> <p>It takes a Zip file that has been uploaded by a user via Gravity Forms, then unzips <em>ONLY</em> .mp3 extensions. Re-zips and moves all the files to a new folder in our Amazon S3 directory.</p> <p>The code is pieced together from my limited knowledge and some help along the way with questions on here.</p> <p>So, here's what I ended up with:</p> <pre><code>add_action('pending_to_publish', 'unzip_to_s3'); function unzip_to_s3() { global $post; global $wpdb; // Only run function if post is portfolio post type if ('portfolio' == $post-&gt;post_type) { // Set temp path $temp_path = '../wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/tmp/'; // Get filename from Zip file $file = get_post_meta($post-&gt;ID, 'file_url', true); $zip_file = basename($file); // Create full Zip file path $zip_file_path = $temp_path.$zip_file; // Generate unique name for temp sub_folder for unzipped files $temp_unzip_folder = uniqid('temp_TMS_', true); // Create full temp sub_folder path $temp_unzip_path = $temp_path.$temp_unzip_folder; // Make the new temp sub_folder for unzipped files if (!mkdir($temp_unzip_path, 0755, true)) { die('Error: Could not create path: '.$temp_unzip_path); } // Unzip files to temp unzip folder, ignoring anything that is not a .mp3 extension $zip = new ZipArchive(); $filename = $zip_file_path; if ($zip-&gt;open($filename)!==TRUE) { exit("cannot open &lt;$filename&gt;\n"); } for ($i=0; $i&lt;$zip-&gt;numFiles;$i++) { $info = $zip-&gt;statIndex($i); $file = pathinfo($info['name']); if(strtolower($file['extension']) == "mp3") { file_put_contents($temp_unzip_path.'/'.basename($info['name']), $zip-&gt;getFromIndex($i)); } else { $zip-&gt;deleteIndex($i); } } $zip-&gt;close(); // Re-zip the unzipped mp3's and store new zip file in temp folder created earlier $temp_unzip_path = $temp_unzip_path.'/'; $zip = new ZipArchive(); $dirArray = array(); $new_zip_file = $temp_unzip_path.$zip_file; $new = $zip-&gt;open($new_zip_file, ZIPARCHIVE::CREATE); if ($new === true) { $handle = opendir($temp_unzip_path); while (false !== ($entry = readdir($handle))) { if(!in_array($entry,array('.','..'))) { $dirArray[] = $entry; $zip-&gt;addFile($temp_unzip_path.$entry,$entry); } } closedir($handle); } else { echo 'Failed to create Zip'; } $zip-&gt;close(); // Set Media bucket dir $bucket_path = '../wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/mixtape2/'; // Generate unique name for sub_bucket $sub_bucket = uniqid('TMS_', true); // Create full sub_bucket path $sub_bucket_path = $bucket_path.$sub_bucket; // Make the new sub_bucket if (!mkdir($sub_bucket_path, 0755, true)) { die('Error: Could not create path: '.$sub_bucket_path); } // Move mp3's to new sub_bucket // Get array of all source files $files = scandir($temp_unzip_path); // Identify directories $source = $temp_unzip_path; $destination = $sub_bucket_path.'/'; // Cycle through all source files foreach ($files as $file) { if (in_array($file, array(".",".."))) continue; // if move files is successful delete the original temp folder if (rename($source.$file, $destination.$file)) { rmdir($temp_unzip_path); } } // Delete original Zip file unlink($temp_path.$zip_file); // Update Custom field for new Zip file location update_post_meta($post-&gt;ID, 'file_url', 'http://themixtapesite.com/wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/mixtape2/'.$sub_bucket.'/'.$zip_file); } } </code></pre> <p>Whilst this function does work, we're dealing with large files and so it does take a while to process.</p> <p>What is happening is when the admin presses publish it triggers this function but the page just sits there until it's finished this function and then will continue. This function can take up to around 5 minutes to run.</p> <p>I'm looking to optimise this function (in terms of code) but also see if there's a way I can run this in the background so that the admin can carry on with other things and not have to sit there waiting around.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:14:46.733", "Id": "37400", "Score": "1", "body": "If you're going to delete files from the original zip file that are not mp3s, why bother to create a new one? You already have the one you want after the first loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:55:57.847", "Id": "37402", "Score": "0", "body": "My logic behind that was to protect against zipbombs. If the unzip function is only looking at file extensions then it wouldn't see folder structures etc. so, i unzip all the mp3's. then rezip them knowing i have a clean zip file with no additional folder structures etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T15:20:53.340", "Id": "37403", "Score": "0", "body": "I don't really see any optimizations but I can point out a problem with your first loop.. Whenever you delete anything inside a loop, you need to rewind your loop by 1 so that you don't skip over the next in line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T15:32:45.270", "Id": "37404", "Score": "0", "body": "@Sosukodo Forgive me, but i'm not sure how to do that? My knowledge of loops is very limited unfortunately.. do you have a url to somewhere i can read up on what you've mentioned please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:26:58.757", "Id": "37407", "Score": "0", "body": "Just echo the file name in that loop on a test zip to see what happens after deleteIndex is called.. deleteIndex may just use unset so you may not have anything to worry about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:29:19.453", "Id": "37408", "Score": "0", "body": "Also, for optimization, have you figured out which chunk of code is taking the longest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:31:09.307", "Id": "37409", "Score": "0", "body": "I don't know how far you want to take this but you could use [XDebug](http://xdebug.org/docs/profiler) or something similar." } ]
[ { "body": "<p>I'm not going to touch on how to improve the speed of the zip operation because it's always going to be a bottleneck no matter how much optimization you do. Instead you should focus on how to improve the experience for the end user so that they don't have to wait for the operation to complete. There are a couple of ways to do this with PHP like <a href=\"http://php.net/manual/en/function.pcntl-fork.php\" rel=\"nofollow noreferrer\">pcntl_fork</a>, Server-Sent Events, or simply disconnecting the script from the user.</p>\n\n<p>Forking is a bit overkill. Server-sent events would be neat to keep the client informed of progress, but it will only do that if your site is designed as a single page app (or the user doesn't leave the page). I think disconnecting the user is your best bet as it's the easiest one to accomplish. All you need to do is buffer your output to the user and set a header that tells the client the size of the content you're sending. Then tell PHP to keep running after client disconnect and you're all done.</p>\n\n<p>Check out this <a href=\"https://stackoverflow.com/questions/3833013/continue-php-execution-after-sending-http-response\">stackoverflow answer by povilasp</a> for a great simple example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-18T16:37:28.257", "Id": "120428", "ParentId": "24251", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:01:14.857", "Id": "24251", "Score": "4", "Tags": [ "php", "optimization", "beginner" ], "Title": "Unzip and move function" }
24251
<p>I wrote a simple Python snake game which is about 250 lines of code. Can someone give me some advice on how I can refactor/make it better?</p> <p><strong>game.py</strong></p> <pre><code># game.py - 3/22/2013 import pygame, sys, os from pygame.locals import * from classes import * def main(): pygame.init() pygame.display.set_caption('PyGame Snake') window = pygame.display.set_mode((480, 480)) screen = pygame.display.get_surface() clock = pygame.time.Clock() font = pygame.font.Font('freesansbold.ttf', 20) game = SnakeGame(window, screen, clock, font) while game.run(pygame.event.get()): pass pygame.quit() sys.exit() if __name__ == '__main__': main() </code></pre> <p><strong>classes.py</strong></p> <pre><code>#classes.py - 3/22/2013 import pygame, random from pygame.locals import * # Gams speed STARTING_FPS = 4 FPS_INCREMENT_FREQUENCY = 80 # Direction constants DIRECTION_UP = 1 DIRECTON_DOWN = 2 DIRECTION_LEFT = 3 DIRECTION_RIGHT = 4 # World size WORLD_SIZE_X = 20 WORLD_SIZE_Y = 20 # Snake and food attributes SNAKE_START_LENGTH = 4 SNAKE_COLOR = (0, 255, 0) FOOD_COLOR = (255, 0, 0) # Snake class class Snake: # Initializes a Snake object def __init__(self, x, y, startLength): self.startLength = startLength self.startX = x self.startY = y self.reset() # Resets snake back to its original state def reset(self): self.pieces = [] self.direction = 1 for n in range(0, self.startLength): self.pieces.append((self.startX, self.startY + n)) # Changes the direction of the snake def changeDirection(self, direction): # Moving in the opposite direction of current movement is not allowed if self.direction == 1 and direction == 2: return if self.direction == 2 and direction == 1: return if self.direction == 3 and direction == 4: return if self.direction == 4 and direction == 3: return self.direction = direction # Returns the head piece of the snake def getHead(self): return self.pieces[0] # Returns the tail piece of the snake def getTail(self): return self.pieces[len(self.pieces) - 1] # Updates snake by moving blocks in direction of movement def update(self): (headX, headY) = self.getHead() head = () # Create new piece that is the new head of the snake if self.direction == 1: head = (headX, headY - 1) elif self.direction == 2: head = (headX, headY + 1) elif self.direction == 3: head = (headX - 1, headY) elif self.direction == 4: head = (headX + 1, headY) # Remove tail of the snake and add a new head self.pieces.insert(0, head) self.pieces.pop() # Adds a new piece to the end of the snake def grow(self): (tx, ty) = self.getTail() piece = () if self.direction == 1: piece = (tx, ty + 1) elif self.direction == 2: piece = (tx, ty - 1) elif self.direction == 3: piece = (tx + 1, ty) elif self.direction == 4: piece = (tx - 1, ty) self.pieces.append(piece) # Are two pieces of the snake occupying the same block? def collidesWithSelf(self): """ # Because of the way new pieces are added when the snake grows, eating a # new food block could cause the snake to die if it's in a certain position. # So instead of checking if any of the spots have two pieces at once, the new # algorithm only checks if the position of the head piece contains more than one block. for p in self.pieces: if len(self.pieces) - len([c for c in self.pieces if c != p]) &gt; 1: return True return False """ return len([p for p in self.pieces if p == self.getHead()]) &gt; 1 # SnakeGame class class SnakeGame: # Initializes SnakeGame object with pre-initialized objects and configuration settings def __init__(self, window, screen, clock, font): self.window = window self.screen = screen self.clock = clock self.font = font self.fps = STARTING_FPS self.ticks = 0 self.playing = True self.score = 0 self.nextDirection = DIRECTION_UP self.sizeX = WORLD_SIZE_X self.sizeY = WORLD_SIZE_Y self.food = [] self.snake = Snake(WORLD_SIZE_X / 2, WORLD_SIZE_Y / 2, SNAKE_START_LENGTH) self.addFood() # Adds a new piece of food to a random block def addFood(self): fx = None fy = None while fx is None or fy is None or (fx, fy) in self.food: fx = random.randint(1, self.sizeX) fy = random.randint(1, self.sizeY) self.food.append((fx, fy)) # Handles input from keyboard def input(self, events): for e in events: if e.type == QUIT: return False elif e.type == KEYUP: if e.key == K_w: self.nextDirection = 1 elif e.key == K_s: self.nextDirection = 2 elif e.key == K_a: self.nextDirection = 3 elif e.key == K_d: self.nextDirection = 4 elif e.key == K_SPACE and not self.playing: self.reset() return True # Update gamestate -- update snake and check for death def update(self): self.snake.changeDirection(self.nextDirection) self.snake.update() # If snake hits a food block, then consume the food, add new food and grow the snake for food in self.food: if self.snake.getHead() == food: self.food.remove(food) self.addFood() self.snake.grow() self.score += len(self.snake.pieces) * 50 # If snake collides with self or the screen boundaries, then game over (hx, hy) = self.snake.getHead() if self.snake.collidesWithSelf() or hx &lt; 1 or hy &lt; 1 or hx &gt; self.sizeX or hy &gt; self.sizeY: self.playing = False # Resets the game def reset(self): self.playing = True self.nextDirection = DIRECTION_UP self.fps = STARTING_FPS self.score = 0 self.snake.reset() # Draws snake and food objects to the screen def draw(self): self.screen.fill((45, 45, 45)) (width, height) = self.window.get_size() blockWidth = int(width / self.sizeX) blockHeight = int(height / self.sizeY) # Draw pieces of snake for (px, py) in self.snake.pieces: pygame.draw.rect(self.screen, SNAKE_COLOR, (blockWidth * (px-1), blockHeight * (py-1), blockWidth, blockHeight)) # Draw food objects for (fx, fy) in self.food: pygame.draw.rect(self.screen, FOOD_COLOR, (blockWidth * (fx-1), blockHeight * (fy-1), blockWidth, blockHeight)) pygame.display.flip() # Draws the death message to the screen def drawDeath(self): self.screen.fill((255, 0, 0)) self.screen.blit(self.font.render("Game over! Press Space to start a new game", 1, (255, 255, 255)), (20, 150)) self.screen.blit(self.font.render("Your score is: %d" % self.score, 1, (255, 255, 255)), (140, 180)) pygame.display.flip() # Run the main game loop def run(self, events): if not self.input(events): return False if self.playing: self.update() self.draw() else: self.drawDeath() self.clock.tick(self.fps) self.ticks += 1 if self.ticks % FPS_INCREMENT_FREQUENCY == 0: self.fps += 1 return True </code></pre>
[]
[ { "body": "<h3>1. Introduction</h3>\n\n<p>This is not bad overall, considering that this is your first program written with PyGame. I've made many comments below, but don't take the length of this answer to heart: there are always many things to say about a piece of code of this length.</p>\n\n<h3>2. Game design issues</h3>\n\n<ol>\n<li><p>The game could do with some instructions. I had to look at the source code to see that I need to use WASD for movement. Alternatively, you might allow the player to use the arrow keys too (these are natural keys the player might try).</p></li>\n<li><p>You use FPS (the number of frames per second) to control the speed of the snake. This design decision commits you to processing everything in the game at the same frequency as the snake moves. The concepts <em>frames per second</em> and <em>speed of the snake in moves per second</em> are distinct, so it's good practice to separate them.</p>\n\n<p>At the moment there's nothing in the game other than the snake, so you get away with this. But as soon as you add other game elements that need to animate at different speeds, you'll run up against this difficulty. Better to get this right while things are still simple.</p>\n\n<p>See section 5 for one way to solve this problem.</p></li>\n<li><p>New pieces of food can be created in positions occupied by the snake!</p></li>\n<li><p>The food position is not reset when a new game starts. (This can cause the snake to be overlap the food at the start of the game.)</p></li>\n<li><p>The score doesn't get drawn during the game.</p></li>\n</ol>\n\n<h3>3. Major comments</h3>\n\n<ol>\n<li><p>The docstring for <code>collidesWithSelf</code> reads like this:</p>\n\n<pre><code>\"\"\"\n# Because of the way new pieces are added when the snake grows, eating a\n# new food block could cause the snake to die if it's in a certain position. \n# So instead of checking if any of the spots have two pieces at once, the new\n# algorithm only checks if the position of the head piece contains more than one block.\n\nfor p in self.pieces:\n if len(self.pieces) - len([c for c in self.pieces if c != p]) &gt; 1: return True\nreturn False\n\"\"\"\n</code></pre>\n\n<p>This is not appropriate content for a docstring. The purpose of a docstring is to explain the interface of a method to a programmer who is trying to use it. But here you have some notes to yourself about the history of this function and why it is implemented like it is. These notes properly belong in a comment.</p>\n\n<p>The reason you have been having problems in this function is that the growth of the snake is not right. In the <code>grow()</code> method you grow a new tail segment in the opposite direction to the snake's current movement. But this can cause the snake to self-intersect.</p>\n\n<p>The usual way that \"snake\" games work is that when the snake eats some food, it does not grow a new tail segment immediately. Instead, it waits until the next time it moves and grows a new tail segment in the position where its old tail used to be. This is easily implemented by incrementing a counter each time the snake eats food:</p>\n\n<pre><code>def grow(self):\n self.growth_pending += 1\n</code></pre>\n\n<p>and then decrementing the counter instead of deleting the tail segment:</p>\n\n<pre><code>if self.growth_pending &gt; 0:\n self.growth_pending -= 1\nelse:\n # Remove tail\n self.pieces.pop()\n</code></pre>\n\n<p>This avoids self-intersection, and so this would allow you to implement the collision operation using your original approach. But you might consider this simpler approach:</p>\n\n<pre><code>it = iter(self.pieces)\nhead = next(it)\nreturn head in it\n</code></pre></li>\n<li><p>You represent directions by numbers between 1 and 4. It is hard to remember which direction is which, so it would be easy to make a mistake and treat 1 as \"up\" in one part of the code but \"down\" in another. You'd be much less likely to make this mistake if you used the names <code>DIRECTION_UP</code> and so on. You went to all the trouble to create these names: why not use them?</p>\n\n<p>(But see 3.4 below for a better suggestion.)</p></li>\n<li><p>The code below looks dodgy because there is no <code>else:</code> on the end of the series of tests.</p>\n\n<pre><code>head = ()\nif self.direction == 1: head = (headX, headY - 1)\nelif self.direction == 2: head = (headX, headY + 1)\nelif self.direction == 3: head = (headX - 1, headY)\nelif self.direction == 4: head = (headX + 1, headY)\n</code></pre>\n\n<p>A programmer reading this would want to know what happens if <code>self.direction</code> is not in the range 1 to 4. Of course, you hope that you have designed the program so that this can't happen. So you might make this crystal clear by rewriting this code like this:</p>\n\n<pre><code>if self.direction == DIRECTION_UP: head = (headX, headY - 1)\nelif self.direction == DIRECTION_DOWN: head = (headX, headY + 1)\nelif self.direction == DIRECTION_LEFT: head = (headX - 1, headY)\nelif self.direction == DIRECTION_RIGHT: head = (headX + 1, headY)\nelse: raise RuntimeError(\"Bad direction: {}\".format(self.direction))\n</code></pre>\n\n<p>(But see 3.4 below for a better suggestion.)</p></li>\n<li><p>Instead of representing a direction with a number from 1 to 4 (which it's hard to remember which is which), why not use a pair (<em>δx</em>, <em>δy</em>)? For example, you could write:</p>\n\n<pre><code>DIRECTION_UP = 0, -1\nDIRECTION_DOWN = 0, 1\nDIRECTION_LEFT = -1, 0\nDIRECTION_RIGHT = 1, 0\n</code></pre>\n\n<p>This would save you a bunch of <code>if ... elif ...</code> tests. For example you could rewrite the code I gave above like this:</p>\n\n<pre><code>old_head = self.getHead()\nnew_head = old_head[0] + self.direction[0], old_head[1] + self.direction[1]\n</code></pre></li>\n<li><p>Similarly, instead of having a bunch of <code>if .. elif ...</code> tests for the input:</p>\n\n<pre><code>if e.key == K_w: self.nextDirection = 1\nelif e.key == K_s: self.nextDirection = 2\nelif e.key == K_a: self.nextDirection = 3\nelif e.key == K_d: self.nextDirection = 4\n</code></pre>\n\n<p>you could have a lookup table that maps key to direction:</p>\n\n<pre><code># Input mapping\nKEY_DIRECTION = {\n K_w: DIRECTION_UP, K_UP: DIRECTION_UP, \n K_s: DIRECTION_DOWN, K_DOWN: DIRECTION_DOWN, \n K_a: DIRECTION_LEFT, K_LEFT: DIRECTION_LEFT, \n K_d: DIRECTION_RIGHT, K_RIGHT: DIRECTION_RIGHT,\n}\n</code></pre>\n\n<p>and then the test becomes:</p>\n\n<pre><code>if e.key in KEY_DIRECTION:\n self.next_direction = KEY_DIRECTION[e.key]\n</code></pre></li>\n<li><p>You check for collision with the edges of the playing area like this:</p>\n\n<pre><code>(hx, hy) = self.snake.getHead()\nif hx &lt; 1 or hy &lt; 1 or hx &gt; self.sizeX or hy &gt; self.sizeY:\n</code></pre>\n\n<p>but PyGame defines a <a href=\"http://www.pygame.org/docs/ref/rect.html\"><code>Rect</code> class</a> with a <a href=\"http://www.pygame.org/docs/ref/rect.html#Rect.collidepoint\"><code>collidepoint</code> method</a>, so you could set up the rectangle like this in <code>SnakeGame.__init__</code>:</p>\n\n<pre><code>self.world = Rect(1, 1, 21, 21)\n</code></pre>\n\n<p>and then test for collision like this:</p>\n\n<pre><code>if not self.world.collidepoint(self.snake.getHead()):\n</code></pre></li>\n<li><p>You number your coordinates starting at 1. This causes you some difficulty. For example, you have to subtract 1 from each of your coordinates before passing them to <code>pygame.draw.rect</code>. If your coordinates started at 0 you wouldn't have to do this.</p></li>\n<li><p>A lot of your code deals with positions or vectors represented by a pair (<em>x</em>, <em>y</em>). This means that each time you process a position, you have to break it down into its <em>x</em> and <em>y</em> coordinates, process the coordinates, and then reassemble the results into a new pair. For example:</p>\n\n<pre><code>(headX, headY) = self.getHead()\nif self.direction == 1: head = (headX, headY - 1)\n</code></pre>\n\n<p>You could simplify this code by making a class to represent positions and vectors. Sadly, PyGame does not come with such a class, but you can easily find many implementations on the web, or just write one yourself:</p>\n\n<pre><code>class Vector(tuple):\n def __add__(self, other): return Vector(v + w for v, w in zip(self, other))\n</code></pre>\n\n<p>now you can write:</p>\n\n<pre><code>new_head = self.getHead() + self.direction\n</code></pre>\n\n<p>and make many other simplifications. (See section 5 for more methods on the <code>Vector</code> class.)</p></li>\n</ol>\n\n<h3>4. Minor comments</h3>\n\n<ol>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>) says that method names should \"Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability\". So you should consider renaming <code>collidesWithSelf</code> as <code>collides_with_self</code> and so on. (You're not obliged to follow PEP8 but it makes it easier for other Python programmers to read your code.)</p></li>\n<li><p>The organization of the code into the files <code>game.py</code> and <code>classes.py</code> doesn't seem to be motivated by any principle, and the vague name <code>classes.py</code> confirms this. For a small game like this, I don't think there's anything to be lost by putting all the code in one file. (And if it grows to the point where you want to split it, the obvious thing to do would be to put the <code>Snake</code> class in its own module.)</p></li>\n<li><p>It's not clear to me what you gain from separating your game initialization code into <code>main</code> and <code>SnakeGame.__init__</code>. Why not put all the initialization into the latter?</p></li>\n<li><p>You don't need <code>sys.exit()</code> at the end of <code>main</code>: Python quits automatically when it finishes running your program. Adding this line just makes it hard to test your program from the interactive interpreter, because when you quit from the game, it exits the interactive interpreter too.</p></li>\n<li><p>You have unnecessary parentheses in many places. A line like:</p>\n\n<pre><code>(headX, headY) = self.getHead()\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>headX, headY = self.getHead()\n</code></pre>\n\n<p>since comma binds more tighly than assignment in Python. \"<a href=\"http://drj11.wordpress.com/2008/10/02/c-return-and-parentheses/\">Program as if you know the language</a>\"!</p></li>\n<li><p><code>DIRECTON_DOWN</code> is misspelled. (Is this why you don't use it?)</p></li>\n<li><p>You represent the snake using a <a href=\"http://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29\">queue</a> of positions, which is a good approach. However, you implement your queue using a Python list. The trouble here is that Python lists are efficient at adding and removing elements at the end, but not at the beginning. In particular the operation</p>\n\n<pre><code>self.pieces.insert(0, head)\n</code></pre>\n\n<p>takes time proportional to the length of <code>self.pieces</code>. (You can consult the <a href=\"http://wiki.python.org/moin/TimeComplexity\">TimeComplexity page</a> on the Python wiki to see the time complexity of operations on built-in Python data structures.) This isn't a big deal here, since the snake never gets very long, but it's worth getting into practice at thinking about the complexity of your algorithms.</p>\n\n<p>For an efficient queue implementation, use <a href=\"http://docs.python.org/2/library/collections.html#collections.deque\"><code>collections.deque</code></a>.</p></li>\n<li><p>The line:</p>\n\n<pre><code>return self.pieces[len(self.pieces) - 1]\n</code></pre>\n\n<p>can be rewritten:</p>\n\n<pre><code>return self.pieces[-1]\n</code></pre>\n\n<p>Since negative list indexes count backwards from the end of the list.</p></li>\n<li><p>Instead of doing division and coercing the result to an integer:</p>\n\n<pre><code>int(width / self.sizeX)\n</code></pre>\n\n<p>use Python's <em>floor division</em> operation:</p>\n\n<pre><code>width // self.sizeX\n</code></pre></li>\n</ol>\n\n<h3>5. Revised code</h3>\n\n<p>This code addresses the comments above and includes some more improvements for you to discover.</p>\n\n<pre><code>from collections import deque\nimport pygame\nfrom random import randrange\nimport sys\nfrom pygame.locals import *\n\nclass Vector(tuple):\n \"\"\"A tuple that supports some vector operations.\n\n &gt;&gt;&gt; v, w = Vector((1, 2)), Vector((3, 4))\n &gt;&gt;&gt; v + w, w - v, v * 10, 100 * v, -v\n ((4, 6), (2, 2), (10, 20), (100, 200), (-1, -2))\n \"\"\"\n def __add__(self, other): return Vector(v + w for v, w in zip(self, other))\n def __radd__(self, other): return Vector(w + v for v, w in zip(self, other))\n def __sub__(self, other): return Vector(v - w for v, w in zip(self, other))\n def __rsub__(self, other): return Vector(w - v for v, w in zip(self, other))\n def __mul__(self, s): return Vector(v * s for v in self)\n def __rmul__(self, s): return Vector(v * s for v in self)\n def __neg__(self): return -1 * self\n\nFPS = 60 # Game frames per second\nSEGMENT_SCORE = 50 # Score per segment\n\nSNAKE_SPEED_INITIAL = 4.0 # Initial snake speed (squares per second)\nSNAKE_SPEED_INCREMENT = 0.25 # Snake speeds up this much each time it grows\nSNAKE_START_LENGTH = 4 # Initial snake length in segments\n\nWORLD_SIZE = Vector((20, 20)) # World size, in blocks\nBLOCK_SIZE = 24 # Block size, in pixels\n\nBACKGROUND_COLOR = 45, 45, 45\nSNAKE_COLOR = 0, 255, 0\nFOOD_COLOR = 255, 0, 0\nDEATH_COLOR = 255, 0, 0\nTEXT_COLOR = 255, 255, 255\n\nDIRECTION_UP = Vector(( 0, -1))\nDIRECTION_DOWN = Vector(( 0, 1))\nDIRECTION_LEFT = Vector((-1, 0))\nDIRECTION_RIGHT = Vector(( 1, 0))\nDIRECTION_DR = DIRECTION_DOWN + DIRECTION_RIGHT\n\n# Map from PyGame key event to the corresponding direction.\nKEY_DIRECTION = {\n K_w: DIRECTION_UP, K_UP: DIRECTION_UP, \n K_s: DIRECTION_DOWN, K_DOWN: DIRECTION_DOWN, \n K_a: DIRECTION_LEFT, K_LEFT: DIRECTION_LEFT, \n K_d: DIRECTION_RIGHT, K_RIGHT: DIRECTION_RIGHT,\n}\n\nclass Snake(object):\n def __init__(self, start, start_length):\n self.speed = SNAKE_SPEED_INITIAL # Speed in squares per second.\n self.timer = 1.0 / self.speed # Time remaining to next movement.\n self.growth_pending = 0 # Number of segments still to grow.\n self.direction = DIRECTION_UP # Current movement direction.\n self.segments = deque([start - self.direction * i\n for i in xrange(start_length)])\n\n def __iter__(self):\n return iter(self.segments)\n\n def __len__(self):\n return len(self.segments)\n\n def change_direction(self, direction):\n \"\"\"Update the direction of the snake.\"\"\"\n # Moving in the opposite direction of current movement is not allowed.\n if self.direction != -direction:\n self.direction = direction\n\n def head(self):\n \"\"\"Return the position of the snake's head.\"\"\"\n return self.segments[0]\n\n def update(self, dt, direction):\n \"\"\"Update the snake by dt seconds and possibly set direction.\"\"\"\n self.timer -= dt\n if self.timer &gt; 0:\n # Nothing to do yet.\n return\n # Moving in the opposite direction of current movement is not allowed.\n if self.direction != -direction:\n self.direction = direction\n self.timer += 1 / self.speed\n # Add a new head.\n self.segments.appendleft(self.head() + self.direction)\n if self.growth_pending &gt; 0:\n self.growth_pending -= 1\n else:\n # Remove tail.\n self.segments.pop()\n\n def grow(self):\n \"\"\"Grow snake by one segment and speed up.\"\"\"\n self.growth_pending += 1\n self.speed += SNAKE_SPEED_INCREMENT\n\n def self_intersecting(self):\n \"\"\"Is the snake currently self-intersecting?\"\"\"\n it = iter(self)\n head = next(it)\n return head in it\n\nclass SnakeGame(object):\n def __init__(self):\n pygame.display.set_caption('PyGame Snake')\n self.block_size = BLOCK_SIZE\n self.window = pygame.display.set_mode(WORLD_SIZE * self.block_size)\n self.screen = pygame.display.get_surface()\n self.clock = pygame.time.Clock()\n self.font = pygame.font.Font('freesansbold.ttf', 20)\n self.world = Rect((0, 0), WORLD_SIZE)\n self.reset()\n\n def reset(self):\n \"\"\"Start a new game.\"\"\"\n self.playing = True\n self.next_direction = DIRECTION_UP\n self.score = 0\n self.snake = Snake(self.world.center, SNAKE_START_LENGTH)\n self.food = set()\n self.add_food()\n\n def add_food(self):\n \"\"\"Ensure that there is at least one piece of food.\n (And, with small probability, more than one.)\n \"\"\"\n while not (self.food and randrange(4)):\n food = Vector(map(randrange, self.world.bottomright))\n if food not in self.food and food not in self.snake:\n self.food.add(food)\n\n def input(self, e):\n \"\"\"Process keyboard event e.\"\"\"\n if e.key in KEY_DIRECTION:\n self.next_direction = KEY_DIRECTION[e.key]\n elif e.key == K_SPACE and not self.playing:\n self.reset()\n\n def update(self, dt):\n \"\"\"Update the game by dt seconds.\"\"\"\n self.snake.update(dt, self.next_direction)\n\n # If snake hits a food block, then consume the food, add new\n # food and grow the snake.\n head = self.snake.head()\n if head in self.food:\n self.food.remove(head)\n self.add_food()\n self.snake.grow()\n self.score += len(self.snake) * SEGMENT_SCORE\n\n # If snake collides with self or the screen boundaries, then\n # it's game over.\n if self.snake.self_intersecting() or not self.world.collidepoint(self.snake.head()):\n self.playing = False\n\n def block(self, p):\n \"\"\"Return the screen rectangle corresponding to the position p.\"\"\"\n return Rect(p * self.block_size, DIRECTION_DR * self.block_size)\n\n def draw_text(self, text, p):\n \"\"\"Draw text at position p.\"\"\"\n self.screen.blit(self.font.render(text, 1, TEXT_COLOR), p)\n\n def draw(self):\n \"\"\"Draw game (while playing).\"\"\"\n self.screen.fill(BACKGROUND_COLOR)\n for p in self.snake:\n pygame.draw.rect(self.screen, SNAKE_COLOR, self.block(p))\n for f in self.food:\n pygame.draw.rect(self.screen, FOOD_COLOR, self.block(f))\n self.draw_text(\"Score: {}\".format(self.score), (20, 20))\n\n def draw_death(self):\n \"\"\"Draw game (after game over).\"\"\"\n self.screen.fill(DEATH_COLOR)\n self.draw_text(\"Game over! Press Space to start a new game\", (20, 150))\n self.draw_text(\"Your score is: {}\".format(self.score), (140, 180))\n\n def play(self):\n \"\"\"Play game until the QUIT event is received.\"\"\"\n while True:\n dt = self.clock.tick(FPS) / 1000.0 # convert to seconds\n for e in pygame.event.get():\n if e.type == QUIT:\n return\n elif e.type == KEYUP:\n self.input(e)\n if self.playing: \n self.update(dt)\n self.draw()\n else:\n self.draw_death()\n pygame.display.flip()\n\ndef main():\n pygame.init()\n SnakeGame().play()\n pygame.quit()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-11T12:40:51.457", "Id": "114207", "Score": "0", "body": "hi thank you, this code is very useful. However I wonder how to implement no world boundaries so when the snake exit the world it comes back at the opposite side. if not self.world.collidepoint(self.snake.head()): #reposition snake here. Any help would be very welcome because I don't know anything about vectors :-(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-11T14:37:33.633", "Id": "114245", "Score": "0", "body": "@kasperTaeymans: That would make a good question for Stack Overflow, if you made your best attempt first, and then asked them for help with fixing your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-12T13:48:33.337", "Id": "114496", "Score": "0", "body": "Hi Gareth, thank you for the reply! I will ask it on stackoverflow when I have time. I'm buzzy on a different part of my project now. I'll post a link here in the comments when the question + attempt is online. It might be useful for other interested readers. Also I'll link back to this code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-17T13:17:22.023", "Id": "115376", "Score": "0", "body": "I've asked a question related to the no boundaries option on stackoverflow. Here is the link to that question: http://stackoverflow.com/questions/25891680/dissable-boundaries-in-a-python-snake-game" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T16:18:27.567", "Id": "24282", "ParentId": "24267", "Score": "28" } } ]
{ "AcceptedAnswerId": "24282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T01:26:43.553", "Id": "24267", "Score": "26", "Tags": [ "python", "array", "pygame", "snake-game" ], "Title": "Snake game using PyGame" }
24267
<p>I'm making a GUI system in Python for game development with PyGame. Right now I have a button that changes colors when you hover and click on it. My question is, is this code well designed or can it be improved?</p> <p><strong>game.py</strong></p> <pre><code>import sys, pygame from pygame.locals import * from gui import * def input(events): for e in events: if e.type == QUIT: pygame.quit() sys.exit() pygame.init() pygame.display.set_caption("GUI Demo") window = pygame.display.set_mode((640, 480)) screen = pygame.display.get_surface() clock = pygame.time.Clock() font = pygame.font.Font(None, 32) button = Button("btn_1", "Hello World", 50, 50, 200, 120) button.decorate((255, 0, 0), (0, 255, 0), (0, 0, 255)) while True: screen.fill((120, 40, 200)) input(pygame.event.get()) button.update(pygame.mouse.get_pos(), pygame.mouse.get_pressed()) button.draw(screen) pygame.display.flip() </code></pre> <p><strong>gui.py</strong></p> <pre><code># Mini-GUI demo import pygame BUTTON_NORMAL = 0 BUTTON_HOVER = 1 BUTTON_ACTIVE = 2 class Surface: def __init__(self, x, y, w, h, color): self.x = x self.y = y self.w = w self.h = h self.color = color def collides(self, surface): return self.y &lt; surface.top + surface.height and self.y + self.h &gt; surface.top and self.x &lt; surface.left + surface.width and self.x + self.w &gt; surface.left def getCoords(self): return (self.x, self.y) def draw(self, surface): pass class GUIElement(Surface): def __init__(self, id, x, y, w, h, color): super(GUIElement, self).__init__(x, y, w, h, color) self.id = id class Textbox(GUIElement): def __init__(self, id, x, y, w, h, color): super(Textbox, self).__init__(id, x, y, w, h, color) self.data = "" # TODO: update and draw class Button(GUIElement): def __init__(self, id, text, x, y, w, h): super(Button, self).__init__(id, x, y, w, h, None) self.text = text self.font = pygame.font.Font(None, 32) self.state = BUTTON_NORMAL self.normalColor = None self.hoverColor = None self.activeColor = None def decorate(self, normalColor, hoverColor, activeColor): self.normalColor = normalColor self.hoverColor = hoverColor self.activeColor = activeColor self.color = self.normalColor def update(self, mouseCoords, mousePressed): (up, down, middle) = mousePressed if len(mouseCoords) &lt; 4: mouseCoords = pygame.Rect(mouseCoords[0], mouseCoords[1], 1, 1) if not self.collides(mouseCoords): self.state = BUTTON_NORMAL self.color = self.normalColor return if up: self.state = BUTTON_ACTIVE self.color = self.activeColor else: self.state = BUTTON_HOVER self.color = self.hoverColor def draw(self, surface): pygame.draw.rect(surface, self.color, pygame.Rect(self.x, self.y, self.w, self.h)) surface.blit(self.font.render(self.text, 1, (255, 255, 255)), self.getCoords()) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T22:30:07.090", "Id": "37456", "Score": "0", "body": "The comment \"TODO: update and draw\" suggests that this code might not be ready for review yet. It's best for you to fix all the problems you know about before submitting it for review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T23:55:20.793", "Id": "37461", "Score": "0", "body": "That's just for the textbox element. The button is complete so far." } ]
[ { "body": "<ol>\n<li><p>There are no docstrings. What is the purpose of each of your classes and methods, and how am I supposed to call them?</p></li>\n<li><p>If you click outside the button, and then slide the pointer over the button, it becomes active. Normal GUI buttons require the initial click to be <em>on</em> the button in order to be able to activate it.</p></li>\n<li><p>The class name <code>Surface</code> runs the risk of confusion with <a href=\"http://www.pygame.org/docs/ref/surface.html\" rel=\"nofollow\"><code>pygame.Surface</code></a>. Or in some applications, of shadowing it.</p></li>\n<li><p>The <code>GUIElement</code> class is a <code>Surface</code> with an <code>id</code>. But none of the code uses the <code>id</code>, so this class is useless. (No doubt you have some purpose in mind, but what is it?)</p></li>\n<li><p>Calling <code>sys.exit()</code> makes it awkward to test your program from the interactive interpreter.</p></li>\n<li><p>If you care about portability to Python 2, you should make <code>Surface</code> inherit from <code>object</code> so that it is a new-style class. On the other hand, if you don't care about portability to Python 2, just call <code>super()</code> instead of <code>super(GUIElement, self)</code> or whatever.</p></li>\n<li><p><code>Surface</code> takes arguments <code>x, y, w, h</code>. Why not use a <a href=\"http://www.pygame.org/docs/ref/rect.html\" rel=\"nofollow\"><code>pygame.Rect</code></a>? Then you could just call <a href=\"http://www.pygame.org/docs/ref/rect.html#Rect.colliderect\" rel=\"nofollow\"><code>Rect.colliderect</code></a> instead of writing your own version.</p></li>\n<li><p><code>Surface.draw</code> does nothing. Is this because <code>Surface</code> is an abstract base class? If so, you should use <a href=\"http://docs.python.org/3/library/abc.html#abc.ABCMeta\" rel=\"nofollow\"><code>metaclass = ABCMeta</code></a> and decorate the <code>draw</code> method with <a href=\"http://docs.python.org/3/library/abc.html#abc.abstractmethod\" rel=\"nofollow\"><code>@abstractmethod</code></a> to make this clear.</p></li>\n<li><p>In order to create a coloured button, you have to create the <code>Button</code> object and then call its <code>decorate</code> method to set its colours. Why not allow the caller to set the colours when they create the button? (Via optional keyword arguments.) Similarly for the font.</p></li>\n<li><p>Since you can deduce a button's <code>color</code> from its <code>state</code>, you don't need a separate <code>color</code> attribute (or do you?). By having two attributes you run the risk of them getting out of sync. Why not have a map from state to colour?</p></li>\n<li><p><code>up, down, middle</code> are misleading variable names: the values returned by <a href=\"http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed\" rel=\"nofollow\"><code>pygame.mouse.get_pressed()</code></a> are actually the state of the three mouse buttons. Use names like <code>button1, button2, button3</code>.</p></li>\n<li><p><a href=\"http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pos\" rel=\"nofollow\"><code>pygame.mouse.get_pos()</code></a> returns the mouse coordinates (<em>x</em>, <em>y</em>) so it's not clear why you write <code>if len(mouseCoords) &lt; 4</code>. Won't this always be true? And why do you need to make a rectangle here anyway?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:00:33.463", "Id": "24304", "ParentId": "24268", "Score": "4" } } ]
{ "AcceptedAnswerId": "24304", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T01:32:25.240", "Id": "24268", "Score": "4", "Tags": [ "python", "gui", "pygame" ], "Title": "GUI system in PyGame" }
24268
<pre><code>function dep_tree(graph,node,prev_deps){ return uniq(flatten(graph[node].map(function(child_node){ if (contains(prev_deps,child_node)) throw "Circular reference between "+child_node+" and "+node; return dep_tree(graph,child_node,prev_deps ? prev_deps.concat(node) : [node]) })).concat(node)); }; </code></pre> <ul> <li><code>graph</code> is an object such as <code>{a:[],b:["a"],c:[],d:["b","c"]}</code>, that links a file, ex: <code>"d"</code> to it's dependencies <code>"b" "c"</code>. </li> <li><code>file</code> is the the node to search.</li> <li><code>prev_deps</code> is internal, to keep track of visited nodes</li> </ul> <p>The function returns the full dependency tree of that node. For example, <code>dep_tree(that_obj_above,"d") = ["b","c","a"]</code>. Is this code correct, overall? Is it correctly checking for circular dependencies? Is there a name for what I'm doing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:43:15.297", "Id": "37433", "Score": "1", "body": "`uniq`, `flatten` are imported from `underscore.js`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:51:52.310", "Id": "37436", "Score": "0", "body": "@JanDvorak Yes, I forgot to mention, sorry. Do I know you? That name sounds familiar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:52:58.900", "Id": "37437", "Score": "0", "body": "[We have met before](http://codereview.stackexchange.com/a/23905/22489)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:53:14.347", "Id": "37438", "Score": "0", "body": "@JanDvorak Oh sure you're the guy who made my fuzzy_match faster than assembly, thanks for that! Actually that was your only answer...!? Why!?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:55:57.710", "Id": "37439", "Score": "0", "body": "I don't come often to CR. I know I should." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T08:56:17.350", "Id": "37440", "Score": "0", "body": "Also see my own solution to that problem: http://stackoverflow.com/questions/13303040/javascript-dependency-list/13303185#13303185" } ]
[ { "body": "<p>Not a lot of code to review,</p>\n\n<ul>\n<li>To reduce confusion, I would use <code>_.uniq()</code> rather than point straight to <code>uniq()</code></li>\n<li>lowerCamelCase is preferred, <code>child_node</code> -> <code>childNode</code></li>\n<li><code>dep_tree</code> is unfortunate, I like <code>recursiveDependencies</code> better</li>\n<li><p>I would have set <code>prev_deps = prev_deps || [];</code> prior to return, it would make your recursive call less golfic:</p>\n\n<pre><code>return dep_tree(graph,child_node, prev_deps.concat(node) ) \n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:58:03.793", "Id": "44197", "ParentId": "24273", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T07:52:40.260", "Id": "24273", "Score": "2", "Tags": [ "javascript", "algorithm", "functional-programming", "graph" ], "Title": "Is this code for getting the dependency tree of a file correct?" }
24273
<p>I've written a circular buffer with multithreaded write and single read ability:</p> <pre><code>public class RingBuffer&lt;E&gt; extends AbstractList&lt;E&gt; implements RandomAccess { class Pointer { int p = 0; public int getPointer(){ return this.p; } public void increasePointer(int p) { this.p = p; } } private final int n; private final List&lt;E&gt; rb; private int size = 0; private Pointer ptr_w = new Pointer(); private Pointer ptr_r = new Pointer(); public RingBuffer(int n) { this.n = n + 1; this.rb = new ArrayList&lt;E&gt;(Collections.nCopies(this.n, (E) null)); } public int size() { return this.size; } private int wrap(int i) { int m = i % this.n; return (m &lt; 0) ? m += this.n : m; } @Override public E get(int i) { return (this.size == 0) ? null : this.rb.get(i); } @Override public E remove(int i) { E e = this.get(this.ptr_r.getPointer()); if(e != null) { this.rb.set(this.ptr_r.getPointer(), null); setPointer(false, this.ptr_r); } System.out.println("Read: " + this.ptr_r.getPointer() + " " + size()); return e; } @Override public synchronized boolean add(E e) { if (size() == this.n - 1) throw new IllegalStateException("Cannot add element. Ringbuffer is filled."); this.rb.set(this.ptr_w.getPointer(), e); setPointer(true, this.ptr_w); System.out.println("Write: " + this.ptr_w.getPointer() + " " + size()); return true; } private synchronized void setPointer(boolean a, Pointer ptr) { this.size = (a) ? this.size + 1 : this.size - 1; ptr.increasePointer(wrap(ptr.getPointer() + 1)); } } </code></pre> <p>I would like to know what I could improve and what you think about the code. I'm new to multithreading and would love to get some feedback.</p>
[]
[ { "body": "<p>I highly recommend <a href=\"http://rads.stackoverflow.com/amzn/click/0321349601\" rel=\"nofollow\"><em>Java Concurrency in Practice</em></a> by Brian Goetz et al. This will give you a solid foundation for building multi-threaded Java applications.</p>\n\n<p>The biggest problem with <code>RingBuffer</code> is that it is <em>not</em> thread-safe. You must synchronize all read and write operations to be certain to see the latest values for fields. This doesn't mean you have to lock the structure the entire time.</p>\n\n<p>This is explained far better in the book than I can here. The short of it is that without synchronization via memory barriers, the JVM is free to cache values read in one thread and miss writes happening in another.</p>\n\n<ol>\n<li><strong>Thread A</strong> calls <code>get</code> and sees that the buffer is empty.</li>\n<li><strong>Thread B</strong> calls <code>add</code> which updates the pointer.</li>\n<li><strong>Thread A</strong> calls <code>get</code> again, but without a memory barrier the cached pointer value tells it that the queue is still empty.</li>\n</ol>\n\n<p>You'll need to add synchronization to guard any access of the pointers and size. Sometimes you can merely add <code>synchronized</code> to the method, but this usually hurts performance. You want to shrink your synchronized blocks to the bare minimum; prefer using <code>synchronized (&lt;lock&gt;)</code> blocks over synchronized methods.</p>\n\n<p>Here are some other suggestions unrelated to concurrency:</p>\n\n<ol>\n<li><p><code>RingBuffer</code> composes an <code>ArrayList</code> so it should not extend <code>AbstractList</code> itself. It shouldn't even implement the basic <code>List</code> interface nor <code>RandomAccess</code> because it doesn't truly support the <code>get</code> operation. It should implement <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html\" rel=\"nofollow\"><code>Queue</code></a> instead.</p></li>\n<li><p>As written, <code>get</code> allows reading outside the buffer. Are you sure you want to support this? See (1) above.</p></li>\n<li><p>You don't need a class to hold an integer pointer given that it is internal to <code>RingBuffer</code>. A simple <code>int</code> is sufficient.</p></li>\n<li><p>The modulo operator <code>%</code> should handle negative values already (test this!) so <code>wrap</code> could be simplified.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T19:22:51.593", "Id": "37492", "Score": "0", "body": "I knew that I should shrink the synchronized blocks to the bare of minimum. Therefore I added the `setPointer(boolean a, Pointer ptr)` function which is synchronized. Read and write use this function to get the position and set the size, in my opinion the threads are synchronised. I’m wrong? Yea, your right with the `get` I will have a look at the implement. Thanks for your hints." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T19:58:48.317", "Id": "37494", "Score": "0", "body": "Assuming you had a similar synchronized `getPointer` method to fix the stale read problem I addressed above, you still have concurrency issues. For exampe, in `remove` you read the element at the pointer but increment the pointer in a separate operation. Another thread could read the same element before the first had a chance to increment the pointer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T19:04:42.650", "Id": "37560", "Score": "0", "body": "Thanks again. If I put the `set` function from `rb` into `setPointer(boolean a, Pointer ptr)` I’m fine? Or is there a better way? I created the Pointer class. cause with this I’m able to set the read and write pointer in the function with out distinguish which pointer I pass. A simple `int` would be passed as value not as reference, so I don’t know which pointer was passed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T21:27:48.060", "Id": "37568", "Score": "0", "body": "No, that is not sufficient. See this explanation of the [race condition](http://stackoverflow.com/questions/11262322/please-explain-the-race-condition-in-this-put-if-absent-idiom)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T17:51:53.140", "Id": "24314", "ParentId": "24275", "Score": "4" } } ]
{ "AcceptedAnswerId": "24314", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T09:06:52.367", "Id": "24275", "Score": "7", "Tags": [ "java", "multithreading", "circular-list" ], "Title": "Multi threaded circular buffer" }
24275
<p>I read about how markov-chains were handy at creating text-generators and wanted to give it a try in python. </p> <p>I'm not sure if this is the proper way to make a markov-chain. I've left comments in the code. Any feedback would be appreciated.</p> <pre><code>import random def Markov(text_file): with open(text_file) as f: # provide a text-file to parse data = f.read() data = [i for i in data.split(' ') if i != ''] # create a list of all words data = [i.lower() for i in data if i.isalpha()] # i've been removing punctuation markov = {i:[] for i in data} # i create a dict with the words as keys and empty lists as values pos = 0 while pos &lt; len(data) - 1: # add a word to the word-key's list if it immediately follows that word markov[data[pos]].append(data[pos+1]) pos += 1 new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])} # create another dict for the seed to match up with length_sentence = random.randint(15, 20) # create a random length for a sentence stopping point seed = random.randint(0, len(new) - 1) # randomly pick a starting point sentence_data = [new[start_index]] # use that word as the first word and starting point current_word = new[start_index] while len(sentence_data) &lt; length_sentence: next_index = random.randint(0, len(markov[current_word]) - 1) # randomly pick a word from the last words list. next_word = markov[current_word][next_index] sentence_data.append(next_word) current_word = next_word return ' '.join([i for i in sentence_data]) </code></pre>
[]
[ { "body": "<pre><code>import random\n\ndef Markov(text_file):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores. I'd also probably have this function take a string as input rather then a filename. That way this function doesn't make assumptions about where the data is coming from</p>\n\n<pre><code> with open(text_file) as f: # provide a text-file to parse\n data = f.read()\n</code></pre>\n\n<p>data is a bit too generic. I'd call it text.</p>\n\n<pre><code> data = [i for i in data.split(' ') if i != ''] # create a list of all words \n data = [i.lower() for i in data if i.isalpha()] # i've been removing punctuation\n</code></pre>\n\n<p>Since ''.isalpha() == False, you could easily combine these two lines</p>\n\n<pre><code> markov = {i:[] for i in data} # i create a dict with the words as keys and empty lists as values\n\n pos = 0\n while pos &lt; len(data) - 1: # add a word to the word-key's list if it immediately follows that word\n markov[data[pos]].append(data[pos+1])\n pos += 1\n</code></pre>\n\n<p>Whenever possible, avoid iterating over indexes. In this case I'd use</p>\n\n<pre><code> for before, after in zip(data, data[1:]):\n markov[before] += after\n</code></pre>\n\n<p>I think that's much clearer.</p>\n\n<pre><code> new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])} # create another dict for the seed to match up with \n</code></pre>\n\n<p><code>[i for i in markov]</code> can be written <code>list(markov)</code> and it produces a copy of the markov list. But there is no reason to making a copy here, so just pass markov directly.</p>\n\n<p><code>zip(range(len(x)), x)</code> can be written as <code>enumerate(x)</code> </p>\n\n<p><code>{k:v for k,v in x}</code> is the same as <code>dict(x)</code> </p>\n\n<p>So that whole line can be written as</p>\n\n<pre><code> new = dict(enumerate(markov))\n</code></pre>\n\n<p>But that's a strange construct to build. Since you are indexing with numbers, it'd make more sense to have a list. An equivalent list would be</p>\n\n<pre><code> new = markov.keys()\n</code></pre>\n\n<p>Which gives you a list of the keys</p>\n\n<pre><code> length_sentence = random.randint(15, 20) # create a random length for a sentence stopping point\n\n seed = random.randint(0, len(new) - 1) # randomly pick a starting point\n</code></pre>\n\n<p>Python has a function random.randrange such that random.randrange(x) = random.randint(0, x -1) It good to use that when selecting from a range of indexes like this</p>\n\n<pre><code> sentence_data = [new[start_index]] # use that word as the first word and starting point\n current_word = new[start_index]\n</code></pre>\n\n<p>To select a random item from a list, use <code>random.choice</code>, so in this case I'd use</p>\n\n<pre><code> current_word = random.choice(markov.keys())\n\n\n\n while len(sentence_data) &lt; length_sentence:\n</code></pre>\n\n<p>Since you know how many iterations you'll need I'd use a for loop here.</p>\n\n<pre><code> next_index = random.randint(0, len(markov[current_word]) - 1) # randomly pick a word from the last words list.\n next_word = markov[current_word][next_index]\n</code></pre>\n\n<p>Instead do <code>next_word = random.choice(markov[current_word])</code></p>\n\n<pre><code> sentence_data.append(next_word)\n current_word = next_word\n\n return ' '.join([i for i in sentence_data])\n</code></pre>\n\n<p>Again, no reason to be doing this <code>i for i</code> dance. Just use <code>' '.join(sentence_data)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:02:20.130", "Id": "37448", "Score": "0", "body": "thanks for taking the time to respond. Your markups will be very helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-02T11:59:47.910", "Id": "167891", "Score": "0", "body": "It's a bit difficult to figure out which comment belongs to which code snippet (above or below?). Also sometimes I think you wanted to have two separate code snippets, but they were merged because there was no text in between." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T17:08:12.697", "Id": "24284", "ParentId": "24276", "Score": "7" } } ]
{ "AcceptedAnswerId": "24284", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T11:57:42.617", "Id": "24276", "Score": "11", "Tags": [ "python", "algorithm", "markov-chain" ], "Title": "Implementation of a Markov Chain" }
24276
<p>This is a simple attempt by me to test whether two words are anagrams or not:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #define CH_LEN 15 #define N 26 int main(void) { char track_letters[N] = {0}; char first_word[CH_LEN]; char sec_word[CH_LEN]; printf("Enter first word: "); int i; for(i = 0; i &lt; CH_LEN; i++) { first_word[i] = getchar(); if(first_word[i] == '\n') break; if(!isalpha(first_word[i])) --i; track_letters[(tolower(first_word[i]) - 'a')]++; } printf("Enter second word: "); for(i = 0; i &lt; CH_LEN; i++) { sec_word[i] = getchar(); if(sec_word[i] == '\n') break; if(!isalpha(sec_word[i])) --i; track_letters[(tolower(sec_word[i]) - 'a')]--; } for(i = 0; i &lt; CH_LEN; i++) { if(track_letters[i] != 0) { printf("The words are not anagrams"); return 0; } } printf("The words are anagrams"); return 0; } </code></pre> <p>You can use any method of C (structure, pointers, functions etc.).</p>
[]
[ { "body": "<p>You limit yourself to anagrams of 15 letters.</p>\n\n<pre><code>#define CH_LEN 15\nchar first_word[CH_LEN];\nchar sec_word[CH_LEN];\n</code></pre>\n\n<p>But you don't actually use words after they are input.<br>\nYou can fix the limitation (and a potentially serious bug) by not using the concept of a line. Just read characters.</p>\n\n<p>In the code just read characters:</p>\n\n<pre><code>char nextInput = getchar();\n</code></pre>\n\n<p>No all alphabets are 26 letters.</p>\n\n<pre><code>#define N 26\n</code></pre>\n\n<p>I would have done this for clarity to show that you are looking at a-z:</p>\n\n<pre><code>#define N ('z' - 'a' + 1)\n</code></pre>\n\n<p>Also N is not that descriptive. Personally I would have preferred a global static variable.</p>\n\n<pre><code>static const AlphabetSize = ('z' - 'a' + 1);\n</code></pre>\n\n<p>You basically repeat the same piece of code twice. This violates the DRY principle. Remove this code into a function and call the function passing parameters for the differences.</p>\n\n<pre><code> int i;\n for(i = 0; i &lt; CH_LEN; i++) {\n first_word[i] = getchar();\n if(first_word[i] == '\\n')\n break;\n if(!isalpha(first_word[i]))\n --i;\n\n track_letters[(tolower(first_word[i]) - 'a')]++;\n\n\n }\n printf(\"Enter second word: \");\n for(i = 0; i &lt; CH_LEN; i++) {\n sec_word[i] = getchar();\n if(sec_word[i] == '\\n')\n break;\n if(!isalpha(sec_word[i]))\n --i;\n track_letters[(tolower(sec_word[i]) - 'a')]--;\n\n }\n</code></pre>\n\n<p>I would write like this:</p>\n\n<pre><code> ProcessesAnagram(track_letters, +1); // Reads first Line\n ProcessesAnagram(track_letters, -1); // Reads second line\n</code></pre>\n\n<p>Since we are not longer bound by a word size. I would change the loop to check for the end of line (or end of input)).</p>\n\n<pre><code> void ProcessesAnagram(int* track_letters, int increment)\n {\n int nextLetter = getchar();\n for(;nextLetter != EOF &amp;&amp; nextLetter != '\\n'; nextLetter = getchar())\n {\n if(!isalpha(nextLetter)\n { continue; // If not a letter just start the next iteration\n }\n\n // Note: increment is +1 first anagram\n // increment is -1 second anagram (so they will cancel out)\n track_letters[(tolower(nextLetter) - 'a')] += increment; \n }\n }\n</code></pre>\n\n<p>There is a bug here</p>\n\n<p>You are using the wrong size: <code>CH_LEN</code> is the size of the words. But the track_letters array has a size of <code>N</code>.</p>\n\n<pre><code> for(i = 0; i &lt; CH_LEN; i++) {\n if(track_letters[i] != 0) {\n printf(\"The words are not anagrams\");\n return 0;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T21:08:45.763", "Id": "37452", "Score": "0", "body": "In a non-26-char alphabet, the extra chars are not going to be between 'a' and 'z', are they? Also, the `continue` is not really necessary; just reverse the condition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T21:17:01.783", "Id": "37453", "Score": "0", "body": "@WilliamMorris: Both good points. But I don't mind the continue. In my opinion (and this is totally depended on context and how your team feels so can be very variable) I think the error test and continue helps show state that are not being considered thus makes the code more readable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T16:04:53.830", "Id": "24281", "ParentId": "24278", "Score": "3" } }, { "body": "<p>Adding to what Loki said, I would have taken the two words from the command line and I would split the checking code into a separate function:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n int track_letters[N] = {0};\n if (argc != 3) {\n fprintf(stderr, \"Usage: %s word1 word2\\n\", argv[0]);\n } else {\n processes_anagram(track_letters, argv[1], 1);\n processes_anagram(track_letters, argv[2], -1);\n check_letters(track_letters);\n }\n return 0;\n}\n</code></pre>\n\n<p>Also add a \\n onto the printf strings</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T21:28:15.650", "Id": "24290", "ParentId": "24278", "Score": "0" } } ]
{ "AcceptedAnswerId": "24281", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T13:35:48.560", "Id": "24278", "Score": "1", "Tags": [ "c", "strings" ], "Title": "Comparing two anagrams in C" }
24278
<p>I am working on <a href="http://thehotdeal.net/clients/1/chris/re/phase3/" rel="nofollow">this website</a> currently.</p> <p>If you resize the window to less than 650px then the main menu is replaced by a button which when pressed triggers a left fly-out menu similar to the Facebook uses on the mobile website.</p> <p>When viewed on a computer the menu works very well, but on mobile devices the performance is not so good and the slide-in effect is not smooth. I need help with the performance. </p> <pre><code>&lt;!-- Mobile Nav.. the navigation items are generated dynamically using jQuery --&gt; &lt;div id="mobNav" style="background: url(images/top_bg.jpg) repeat; background-size: 100%; position:absolute; left:-200px; width:200px; height:100%;"&gt; &lt;/div&gt; &lt;!-- This is just a wrapper for the rest of the page content --&gt; &lt;div id="shift"&gt; content Goes Here &lt;/div&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>jQuery(document).ready(function($) { var mobNav = $("#mobNav"), mainNav = $("#mainnav"), top = $("#top"), shift = $("#shift"); // add navigation items to mobile nav mobNav.html(mainNav.html()); $(window).on("scroll", function() { if($(window).scrollTop() &gt; 300){ top.fadeIn(); } else{ top.fadeOut(); } if(parseInt(mobNav.css("left"), 10) == 0){ // if is visible then hide mobNav.css("left", -mobNav.outerWidth()); shift.css("margin-left", "0"); } }); $(window).on("resize", function() { if(parseInt(mobNav.css("left"), 10) == 0){ // if is visible then hide mobNav.css("left", -mobNav.outerWidth()); shift.css("margin-left", "0"); } }); // button that triggers mobile nav visibility $("#mob_nav_trigger").click(function(e) { e.preventDefault(); var winWidth = $(window).width(), docHeight = $(document).height(); mobNav.css("minHeight", docHeight).addClass("visible_now").animate({ left: parseInt(mobNav.css('left'),10) == 0 ? -mobNav.outerWidth() : 0 }); shift.animate({ marginLeft: parseInt(shift.css('margin-left'),10) == 200 ? 0 : 200 }).css("minWidth", winWidth); }); }); </code></pre> <p>Of course I'll be refactoring the code and take some code which is repeating and convert it into a function like:</p> <pre><code> if(parseInt(mobNav.css("left"), 10) == 0){ // if is visible then hide mobNav.css("left", -mobNav.outerWidth()); shift.css("margin-left", "0"); } </code></pre>
[]
[ { "body": "<h2>Notes</h2>\n<p>I gave it a shot, there isn't really much that I felt could be improved upon though. I'm sure performance would be better if you were using CSS3 transitions (the implementation certainly would be nicer &lt;3 CSS3) but I assume you wanted better browser coverage.</p>\n<ul>\n<li><p>Ideally put your CSS in a separate file to keep your markup clean.</p>\n</li>\n<li><p>I put a function around your code so that the symbols can be properly minified.</p>\n</li>\n<li><p>I introduced a <code>menuVisible</code> variable which will be <code>false</code> if the menu is not showing and not in transition. The reason I did this was to simplify the conditions on scroll, resize and button click events that run every time.</p>\n</li>\n<li><p>Fluent syntax for <code>$(window)</code> when hooking up events, saves converting <code>window</code> into a <code>jQuery</code> object twice.</p>\n</li>\n<li><p>Refactored a little so the functions are better split up and to clean up document ready.</p>\n</li>\n<li><p>Something I noticed when playing with your menu from the link you gave, it's actually not very smooth at all on my desktop if the menu is transitioning at the same time as your slideshow. I suggest you halt the animation on your slideshow when the button is pressed, that will probably make the biggest difference to how smooth the page is.</p>\n<p>Alternatively you could disable the slideshow all together or remove the animation when it's in the mobile media query, scrolling may suffer as a result of the slideshow animation as well.</p>\n</li>\n</ul>\n<h2>Code</h2>\n<h3>HTML</h3>\n<pre><code>&lt;div id=&quot;mobNav&quot;&gt;&lt;/div&gt;\n\n&lt;div id=&quot;shift&quot;&gt;\n content Goes Here\n&lt;/div&gt;\n</code></pre>\n<h3>CSS</h3>\n<pre><code>#mobNav {\n background: url(images/top_bg.jpg) repeat;\n background-size: 100%;\n position:absolute;\n left:-200px;\n width:200px;\n height:100%;\n}\n</code></pre>\n<h3>JS</h3>\n<pre><code>(function ($, window, document) {\n var mobNav, mainNav, top, shift;\n var menuVisible = false;\n \n $(document).ready(function($) {\n mobNav = $(&quot;#mobNav&quot;);\n mainNav = $(&quot;#mainnav&quot;);\n top = $(&quot;#top&quot;);\n shift = $(&quot;#shift&quot;);\n \n mobNav.html(mainNav.html());\n \n $(window).on(&quot;scroll&quot;, scroll);\n .on(&quot;resize&quot;, hideMenu);\n $(&quot;#mob_nav_trigger&quot;).click(function(e) {\n e.preventDefault();\n showMenu();\n });\n });\n \n function scroll() {\n if ($(window).scrollTop() &gt; 300)\n top.fadeIn();\n else\n top.fadeOut();\n hideMenu();\n }\n \n function showMenu() {\n var winWidth = $(window).width(),\n docHeight = $(document).height();\n mobNav.css(&quot;minHeight&quot;, docHeight)\n .addClass(&quot;visible_now&quot;)\n .animate({ \n left: menuVisible ? -mobNav.outerWidth() : 0 }, \n function () { \n if (menuVisible) \n menuVisible = false;\n });\n shift.css(&quot;minWidth&quot;, winWidth)\n .animate({ marginLeft: menuVisible ? 0 : 200 });\n if (!menuVisible)\n menuVisible = true;\n }\n \n function hideMenu() {\n if (menuVisible) {\n mobNav.css(&quot;left&quot;, -mobNav.outerWidth());\n shift.css(&quot;margin-left&quot;, &quot;0&quot;);\n menuVisible = false;\n }\n }\n})($, window, document);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:58:35.020", "Id": "37450", "Score": "0", "body": "@tyiar thank you so much for your time.. really appreciate it. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T17:13:32.950", "Id": "24285", "ParentId": "24279", "Score": "2" } } ]
{ "AcceptedAnswerId": "24285", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T13:57:35.030", "Id": "24279", "Score": "0", "Tags": [ "javascript", "performance", "jquery", "mobile" ], "Title": "Responsive left fly-out menu" }
24279
<p>I've started with developing BMP format reader in C#. This tool might read all data from binary BMP file and represents all data from it (from the header, the pixel data etc).</p> <p>I have started and have done only first 14 bytes reading (header) and getting the pixel data from 24 bit BMP file. Of course there would be a lot of work, but I'd like to know if I'm developing this correctly.</p> <p>Please, review <a href="http://ideone.com/4ZxyAJ" rel="nofollow">my code</a>:</p> <pre><code>using System; using System.IO; using System.Text; class BMPDataInfo { enum BMPHeaderTypes { BM, // Windows family BA, // OS/2 struct bitmap array CI, // OS/2 struct color icon CP, // OS/2 const color pointer IC, // OS/2 struct icon PT, // OS/2 pointer Invalid, // if two bytes from loaded file don't equal to any values of all BMP possible formats }; byte[] fileData; Encoding fileEncoding; BMPFileInfo fileInfo; class BMPFileInfo { internal Encoding currentEncoding; internal BMPHeaderTypes currentBMPType; internal uint currentFileSize; internal int reservedFirst; internal int reservedSecond; internal int tablePixelStartAddress; internal int[] tablePixel; } public BMPDataInfo() { fileInfo = new BMPFileInfo(); } internal byte[] ReadFile(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open); fileData = new byte[fs.Length]; fs.Read(fileData, 0, fileData.Length); fs.Close(); using (var fileStreamReader = new StreamReader(fileName, true)) { fileEncoding = fileStreamReader.CurrentEncoding; } switch (fileEncoding.BodyName) { case "utf-8": fileInfo.currentEncoding = Encoding.UTF8; break; case "us-ascii": fileInfo.currentEncoding = Encoding.ASCII; break; } return fileData; } internal void BMPGetHeader() { #region Initializing the array size of 14 bytes for the BMP header byte[] headerBMP = new byte[14]; for (int i = 0; i &lt; headerBMP.Length; i++) { headerBMP[i] = fileData[i]; } #endregion #region Getting first TWO bytes to check the type of BMP file format fileInfo.currentBMPType = BMPCheckHeaderType(ref headerBMP[0], ref headerBMP[1]); #endregion #region Getting file size from BMP header, NOT from the `Length` property of stream byte[] fileSizeHeaderInfo = new byte[4]; // needed fix for the correct byte shift (data[i] = i &lt;&lt; shiftValue) for (int i = 2, j = 0; j &lt; fileSizeHeaderInfo.Length; i++, j++) { fileSizeHeaderInfo[j] = fileData[i]; } fileInfo.currentFileSize = BMPGetFileSize(ref fileSizeHeaderInfo); #endregion #region Getting reserved fields from BMP header byte[] fileReservedInfo = new byte[4]; for (int i = 6, j = 0; j &lt; fileReservedInfo.Length; i++, j++) { fileReservedInfo[j] = fileData[i]; } int[] reservedResult = BMPGetReservedFromHeader(ref fileReservedInfo); fileInfo.reservedFirst = reservedResult[0]; fileInfo.reservedSecond = reservedResult[1]; #endregion #region Getting the starting address, of the byte where the bitmap image data (pixel array) can be found byte[] filePixelArrayAddress = new byte[4]; for (int i = 10, j = 0; j &lt; filePixelArrayAddress.Length; i++, j++) { filePixelArrayAddress[j] = fileData[i]; } fileInfo.tablePixelStartAddress = BMPGetStartAddress(ref filePixelArrayAddress); #endregion #region Reading the pixel table of the current BMP // needed to be refactored, because the test BMP file has 24 bit depth color, so: 1 pixel/3 bytes fileInfo.tablePixel = new int[fileData.Length - fileInfo.tablePixelStartAddress]; int[] bufferTable = new int[3]; for (int i = fileInfo.tablePixelStartAddress, j = 0, k = 0; i &lt; fileInfo.tablePixel.Length; i++, k++) { if (k &gt; 2) { int tmpValue = 0; for (int z = 0; z &lt; k; z++) { tmpValue += bufferTable[z]; } fileInfo.tablePixel[j] = tmpValue; k = 0; j++; i++; } bufferTable[k] = fileData[i]; } #endregion } BMPHeaderTypes BMPCheckHeaderType(ref byte firstValue, ref byte secondValue) { if (firstValue == 0x42 &amp;&amp; secondValue == 0x4d) { return BMPHeaderTypes.BM; } return BMPHeaderTypes.Invalid; } uint BMPGetFileSize(ref byte[] headerPart) { uint fileSize = (uint)fileData[5] &lt;&lt; 24 | (uint)fileData[4] &lt;&lt; 16 | (uint)fileData[3] &lt;&lt; 8 | (uint)fileData[2]; return fileSize; } int[] BMPGetReservedFromHeader(ref byte[] headerPart) { int reservedFirst = headerPart[0] + headerPart[1]; int reservedSecond = headerPart[2] + headerPart[3]; int[] resultReserved = new int[2]; resultReserved[0] = reservedFirst; resultReserved[1] = reservedSecond; return resultReserved; } int BMPGetStartAddress(ref byte[] headerPart) { int resultStartAddress = 0; for (int i = 0; i &lt; headerPart.Length; i++) { resultStartAddress += headerPart[i]; } return resultStartAddress; } } class App { const string fileName = @"\1.bmp"; static void Main() { try { BMPDataInfo objDataInfo = new BMPDataInfo(); objDataInfo.ReadFile(fileName); objDataInfo.BMPGetHeader(); } catch (Exception exc) { Console.WriteLine(exc); } } } </code></pre>
[]
[ { "body": "<p>Instead of marking pieces of functionality within your BMPGetHeader() method with regions. I would suggest turning each region into a private method. The code will be much easier to read and refactor once this is done. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:47:38.820", "Id": "37449", "Score": "0", "body": "there would be too much similar function with the `foreach` block, it the function `BMPGetHeader()` will consists of many similar small functions, wouldn't be? I suppose I could be wrong, please tell me the exact reasons to cut this function into few small, which will be to similar?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T22:16:28.877", "Id": "37455", "Score": "4", "body": "@OlegOrlov How is having several methods that are too similar any worse than having `#region`s in the same method that are similar?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T07:02:20.907", "Id": "98979", "Score": "0", "body": "I think #regions are one of the best *smell*-indicators around (function to long, not-single responsible, ...) - remove them whereever you can" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:31:10.813", "Id": "24287", "ParentId": "24286", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:15:45.717", "Id": "24286", "Score": "1", "Tags": [ "c#", "image" ], "Title": "BMP file reader" }
24286
<p>After creating a similar program in C++, I've decided to try to write it in x86 assembly language (the type of assembly I was taught in college).</p> <p>I'd like to receive feedback regarding syntax and clarity. The macros used here were provided by my college, so I don't think that's a concern.</p> <pre><code>%include "macros.s" .DATA num_lbl: DB "&gt; Numbers (2): ", 0 gcd_lbl: DB "*** GCD: ", 0 lcm_lbl: DB "*** LCM: ", 0 num1: DD 0 num2: DD 0 num1_cpy: DD 0 num2_cpy: DD 0 gcd: DD 0 lcm: DD 0 .CODE .STARTUP xor EAX, EAX xor EBX, EBX xor ECX, ECX xor EDX, EDX xor EDI, EDI xor ESI, ESI main: nwln nwln PutStr num_lbl nwln nwln GetLInt [num1] GetLInt [num2] mov EAX, [num1] mov [num1_cpy], EAX mov EBX, [num2] mov [num2_cpy], EBX call calc_euclidean call calc_lcm nwln PutStr gcd_lbl PutLInt [gcd] nwln PutStr lcm_lbl PutLInt [lcm] nwln .EXIT calc_euclidean: mov EAX, [num2] cmp EAX, 0 jne chk_swap mov EAX, [num1] mov [gcd], EAX ret calc_lcm: mov EAX, [num1_cpy] mov EDX, [num2_cpy] mul EDX mov EDI, EAX xor EBX, EBX mov EDX, EDI shr EDX, 16 mov EAX, EDI mov BX, [gcd] div BX mov SI, AX mov [lcm], SI ret chk_swap: mov EAX, [num1] mov EBX, [num2] cmp EAX, EBX jl swap after_check: jmp loop swap: mov EAX, [num1] mov EBX, [num2] ; temp mov ECX, [num2] ; num2 = num1 ; num1 = temp mov EBX, EAX mov EAX, ECX mov [num1], EAX mov [num2], EBX jmp after_check loop: mov EDX, [num1] shr EDX, 16 mov EAX, [num1] mov BX, [num2] div BX mov EDI, [num1] mov ESI, [num2] mov EDI, ESI mov [num1], EDI mov [num2], EDX jmp calc_euclidean </code></pre>
[]
[ { "body": "<p>1) In a language like C or C++, you wouldn't do something like this:</p>\n\n<pre><code>foo (1,2);\nx = bar (2.5);\n</code></pre>\n\n<p>It makes it harder to read the code because the function name makes no sense without its parameters. The same is true for assembly. Basically, this:</p>\n\n<pre><code>xor EAX, EAX\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>xor EAX, EAX\n</code></pre>\n\n<hr>\n\n<p>2) In a language like C or C++, you wouldn't do something like this:</p>\n\n<pre><code>b = a * 5 + 2298;\nc = b / 9;\n</code></pre>\n\n<p>Instead, you might do this:</p>\n\n<pre><code>kelvin_x9 = fahrenheit * 5 + 2298;\nkelvin = kelvin_x9 / 9;\n</code></pre>\n\n<p>In assembly, because you can't give registers descriptive names (in the same way that you can give variables descriptive names in higher level languages) and because often you do things that are semantically wrong (e.g. using shifts when you mean multiplication, using LEA when you're not loading an effective address, etc) it's <strong>extremely important for code maintainability to use comments</strong>. Basically this:</p>\n\n<pre><code>calc_lcm:\n mov EAX, [num1_cpy]\n mov EDX, [num2_cpy]\n mul EDX\n\n mov EDI, EAX\n\n xor EBX, EBX\n\n mov EDX, EDI\n shr EDX, 16\n mov EAX, EDI\n mov BX, [gcd]\n div BX\n\n mov SI, AX\n mov [lcm], SI\n\n ret\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>calc_lcm:\n mov EAX, [num1_cpy] ;eax = number1\n mov EDX, [num2_cpy] ;edx = number2\n mul EDX ;edx:eax = number1 * number2\n\n mov EDI, EAX ;edi = number1 * number2, high 32-bits of number discarded\n\n xor EBX, EBX\n\n mov EDX, EDI ;edx = number1 * number2\n shr EDX, 16 ;edx = number1 * number2 / 65536, dx:ax = number1 * number2\n mov EAX, EDI ;eax = number1 * number2, (can be deleted as EAX already contained this value)\n mov BX, [gcd] ;bx = GCD\n div BX ;ax = number1 * number2 / GCD, dx = number1 * number2 % GCD\n\n mov SI, AX ;si = number1 * number2 / GCD\n mov [lcm], SI\n ret\n</code></pre>\n\n<p>For assembly there's only 2 types of bugs - comments that don't describe sane logic, and code that doesn't do what the comments say it should. This allows you to debug the code effectively and drastically reduces the chance of missing mistakes (in addition to the hopefully obvious massive improvement in code readability).</p>\n\n<hr>\n\n<p>3) In a language like C or C++, you would create lots of bugs caused by things like integer overflows because the language doesn't provide a sane/easy way to detect these bugs. In assembly you should not create lots of bugs caused by things like integer overflows because you can easily test for overflows.</p>\n\n<p>For example, this:</p>\n\n<pre><code>calc_lcm:\n mov EAX, [num1_cpy] ;eax = number1\n mov EDX, [num2_cpy] ;edx = number2\n mul EDX ;edx:eax = number1 * number2\n\n mov EDI, EAX ;edi = number1 * number2, high 32-bits of number discarded\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>calc_lcm:\n mov EAX, [num1_cpy] ;eax = number1\n mov EDX, [num2_cpy] ;edx = number2\n mul EDX ;edx:eax = number1 * number2\n\n test EDX, EDX ;Will the result fit in 32 bits?\n jne .overflow ; no, error\n mov EDI, EAX ;edi = number1 * number2\n</code></pre>\n\n<p><em>Note: A better idea would be to do \"movzx ebx,word [GCD]\" and \"div ebx\" to divide EDX:EAX by the GCD instead of pointlessly converting the 64-bit value you had in EDX:EAX into a 32-bit value in DX:AX.</em></p>\n\n<hr>\n\n<p>4) A compiler will check if (e.g.) functions are being called with the correct number of parameters, and will make sure that various registers are saved/restored, etc where necessary. In assembly there is none of that; so you have to do it manually, so you have to be able to do it manually. To be able to do it manually you need to document routines properly. For example, this:</p>\n\n<pre><code>calc_lcm:\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>;Calculate Lowest Common Multiple\n;\n;Input:\n; [num1_cpy] Some number\n; [num2_cpy] Some other number\n; [GCD] The GCD\n;\n;Output:\n; [lcm] The result\n;\n;Trashed:\n; eax, edx, ebx, esi, edi\n\ncalc_lcm:\n</code></pre>\n\n<p>Normally, you'd pass parameters in registers and return parameters in registers to avoid wasting time on loading/storing where avoidable. For example, the entire \"calc_lcm\" code might be:</p>\n\n<pre><code>;Calculate Lowest Common Multiple\n;\n;Input:\n; eax Some number\n; edx Some other number\n; ebx The GCD\n;\n;Output:\n; eax The result\n;\n;Trashed:\n; edx\n\ncalc_lcm:\n mul EDX ;edx:eax = number1 * number2\n div EBX ;eax = (number1 * number2) / GCD, edx = (number1 * number2) % GCD\n ret\n</code></pre>\n\n<hr>\n\n<p>5) If you're writing assembly you should write assembly; and not attempt to obfuscate the code by inventing your own language that makes it difficult read the code and impossible to effectively optimise the code.</p>\n\n<p>For example, this code:</p>\n\n<pre><code> nwln\n nwln\n PutStr num_lbl\n nwln\n nwln\n GetLInt [num1]\n GetLInt [num2]\n</code></pre>\n\n<p>Is 100% meaningless gibberish.</p>\n\n<p>I don't know what this code should be (and am completely unable to see ways of optimising it that would have been obvious if it was assembly) because I have no idea what any of these macros do. I can't tell which registers get trashed, I can't see which pushes/pops/moves are redundant. I might be able to assume that it'd be safe to delete the first 2 <code>nwln</code> lines and change the string to <code>num_lbl: DB \"\\n\\n&gt; Numbers (2): \", 0</code> but then that could introduce all sorts of bugs because I didn't bother with the hassle of finding and reading the macros that may do more (or less) than whatever I've assumed they might do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:42:27.287", "Id": "37546", "Score": "0", "body": "A lot of great stuff. Thanks! I'll report back if I have additional questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:57:54.600", "Id": "37559", "Score": "0", "body": "Yes, `nwln` prints a newline, and I don't think there's another way around that. `PutStr` prints a string and `GetLInt` prompts for a 32-bit value, in case you didn't figure that out. Also, I'm unable to use `.overflow` (further above) since it's considered undefined. There may be more code I need to add for that, if I still need it. I'll post my updated code right now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T23:00:51.953", "Id": "37573", "Score": "0", "body": "For assembly there's no optimiser and you are responsible for optimising yourself. I can almost guarantee that a bunch of \"failed to optimise\" problems are hidden by those macros. The `.overflow` in my example is a label that you'd need to create - if there's a problem the CPU jumps to `.overflow` where the error handling code would be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T23:20:56.510", "Id": "37574", "Score": "0", "body": "For instance, I could just have the program terminate if it reaches that point? I'm not sure what an appropriate error message could say, if one is preferred." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T23:37:08.753", "Id": "37575", "Score": "0", "body": "Better yet, could you please link me to some relevant documentation regarding division and integer overflow? I've had trouble finding any information for my specific assembly language (all topics, not just this), and I don't have my book with me." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:17:49.527", "Id": "24350", "ParentId": "24288", "Score": "12" } }, { "body": "<h1>Comments</h1>\n\n<p>@Brendan has explained why comments in assembly are very important. I want to show an alternate style of commenting for assembly language which I feel has certain advantages.</p>\n\n<p>The usual way to comment assembly is to use a comment on the right side of every line. I'll use this snippet from @Brandan's answer as an example. By the way, Brandan's comments are quite good; I am not picking on his examples.</p>\n\n<pre><code> mov EAX, [num1_cpy] ;eax = number1\n mov EDX, [num2_cpy] ;edx = number2\n mul EDX ;edx:eax = number1 * number2\n</code></pre>\n\n<p>This is a good practice, and as it is a commone one, the reader of your code will be comfortable with it. There are, however, a few small disadvantages to this style:</p>\n\n<ul>\n<li>Long comments, when needed, are slightly awkward.</li>\n<li>It is natural, in this style, to tell <em>what</em> each instruction is doing, when what is more needed is to tell <em>why</em> each instruction is doing something. With discipline, you can avoid that trap, as Brandan does, but I see much assembly code that falls prey to it. I believe that the comment-per-line style subtly encourages it.</li>\n</ul>\n\n<p>To avoid these disadvantages, I prefer, in many cases, to comment the code in chunks, like this:</p>\n\n<pre><code> ; edx:eax = number1 * number2\n mov EAX, [num1_cpy]\n mov EDX, [num2_cpy]\n mul EDX\n ; overflow if result doesn't fit in 32 bits\n test EDX, EDX\n jne .overflow\n</code></pre>\n\n<h1>Indentation</h1>\n\n<p>The varying levels of indentation are very confusing. If they are an accident of cut-and-paste, then never mind. If they are a result of using tabs in your source, then I would recommend to not use tabs. If, however, you are attempting to convey information by varying the indentation, I have to admit that I didn't understand what the indentation was trying to convey. I would recommend using only one level of indentation.</p>\n\n<h1>Flow of control</h1>\n\n<p>The flow of control is what we used to call \"spaghetti code.\" Here I've taken your code and removed everything but flow control:</p>\n\n<pre><code> ...\nmain:\n ...\n call calc_euclidean\n call calc_lcm\n ...\n .EXIT\n\ncalc_euclidean:\n ...\n jne chk_swap\n ...\n ret\n\ncalc_lcm:\n ...\n ret\n\nchk_swap:\n ...\n jl swap\n\nafter_check:\n jmp loop\n\nswap:\n ...\n jmp after_check\n\nloop:\n ...\n jmp calc_euclidean\n</code></pre>\n\n<p><code>main</code> is simple. It calls two subroutines, then returns. No problem here.</p>\n\n<p>It appears that the remaining code is all a part of <code>calc_euclidean</code>, <em>except</em> for <code>calc_lcm</code>. <code>calc_lcm</code> is a standalone subroutine, so what's it doing inside <code>calc_euclidean</code>? We'll move calc_lcm to the end.</p>\n\n<p>At the end of <code>swap</code>, there's a jump to <code>after_check</code>, which immediately jumps to <code>loop</code>, the section which follows <code>swap</code>. The jump to <code>after_check</code> can be removed, as well as the labe <code>after_check</code>.</p>\n\n<p>Now there's this sequence:</p>\n\n<pre><code>chk_swap:\n ...\n jl swap\n\nafter_check:\n jmp loop\n\nswap:\n</code></pre>\n\n<p>With the label <code>after_check</code> removed, this can be replaced with:</p>\n\n<pre><code>chk_swap:\n ...\n jnl loop\n</code></pre>\n\n<p>Here's the new, simpler flow control:</p>\n\n<pre><code> ...\nmain:\n ...\n call calc_euclidean\n call calc_lcm\n ... \n .EXIT\n\ncalc_euclidean:\n ...\n jne chk_swap\n ...\n ret\nchk_swap:\n ...\n jnl loop\n ...\nloop:\n ...\n jmp calc_euclidean\n\ncalc_lcm:\n ...\n ret\n</code></pre>\n\n<p>I think there could be more improvement possible; I will leave that as an exercise for the reader.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T17:16:39.543", "Id": "66537", "Score": "0", "body": "Unfortunately, I cannot test this right now since I cannot get the `make` utility working, but this still looks very good. I never thought of looking out for spaghetti code in this language, so thanks for pointing it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:07:50.240", "Id": "66576", "Score": "0", "body": "@Jamal, I'm glad you found this helpful. Thank you for the fun question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:21:15.367", "Id": "66577", "Score": "1", "body": "Since your commenting suggestions seem a bit more useful and because you've pointed out the spaghetti code (big flow and readability problem), I'm going to accept this answer. It was a tough decision as these are great answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:30:18.757", "Id": "66578", "Score": "0", "body": "@Jamal - I agree, Bredan's answer is very good. I've had a code review where each answer was good enough to deserve the checkmark, so I understand your pain." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T14:30:37.707", "Id": "39654", "ParentId": "24288", "Score": "8" } } ]
{ "AcceptedAnswerId": "39654", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T19:23:59.387", "Id": "24288", "Score": "18", "Tags": [ "mathematics", "assembly" ], "Title": "GCD/LCM calculator in x86 NASM assembly" }
24288
<p>Here's some code... please, be brutal</p> <pre><code>function twisty (elem, container) { elem = $('.some-elem'); container = $('.container').hide(); var spots = elem.text().replace(' ', '').split(''); for(var i = 0; i &lt; 300; i++) { $('&lt;span/&gt;', { 'class': 'spot '+ i, text: spots[Math.ceil(Math.random() * spots.length-1)] , css: { fontSize: Math.ceil(Math.random() * 50), left: Math.ceil(Math.random() * 1000), top: Math.ceil(Math.random() * 30), bottom: Math.ceil(Math.random() * 50), opacity: Math.random() / 3, color: 'rgb('+ Math.ceil(Math.random() * 70) + ',' + Math.ceil(Math.random() * 70) + ',' + Math.ceil(Math.random() * 70) + ')', transform: 'rotate(' + Math.ceil(Math.random() * 360) + 'deg)' } }).appendTo(container.fadeIn(800)); } } jQuery(document).ready(function($) { twisty(); $('.some-elem').on('click', function(){ $('.container').hide(); $('span.spot').remove(); twisty(); }); </code></pre> <p>});</p> <p>Here's the html</p> <pre><code>&lt;div class=&quot;content&quot;&gt; &lt;h2 class=&quot;some-elem&quot;&gt;hello world&lt;div class=&quot;container&quot;&gt;&lt;/div&gt;&lt;/h2&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/laserface/NaDG5/11/embedded/result/" rel="nofollow noreferrer">Here's a link to the fiddle output</a></p> <p>Probably not the most useful piece of code, but some things I'm trying to learn are:</p> <ul> <li>How to extend native javascript objects (so how could i minimize the excessive use of calling Math.random)</li> <li>How to make my code as clean and as portable as possible</li> <li>How to animate stuff</li> <li>How to do all of the above without using jQuery</li> <li>How to extend jQuery</li> </ul> <p>But mostly, I'm looking for feedback :]</p> <p>edit: fixed so it actually fades in</p> <p>(updated link to include some css, cause the transform prop wasn't working)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T03:04:46.083", "Id": "37463", "Score": "0", "body": "Lol, it's changed quite a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T03:06:30.113", "Id": "37464", "Score": "0", "body": "yea, well, i'm new to jsfiddle, so needed to adjust it to be how it was locally. but i'm done now, i promise." } ]
[ { "body": "<h2>Notes</h2>\n\n<p>I had a go at converting it to native JavaScript, was fun :P Pretty nifty bit of code. Here are my notes:</p>\n\n<ul>\n<li>I pulled <code>Math.ceil(Math.random() * x))</code> out into a function <code>randomInt(x)</code>, I recommend against extending native JavaScript objects. They tend to be difficult problems to debug, just create a new function instead.</li>\n<li><p>I would probably prefer to have <code>.container</code> outside of <code>.some-elem</code> or programmatically generated. I didn't make this change though. The main issue with having it inside .some-elem next to the text is that when you attempt to fill <code>spots</code> in JS you need to get rid of the <code>.container</code> markup from <code>.innerHTML</code> as it comes out like this:</p>\n\n<pre><code>hello world&lt;div class=\"container\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Which leads to a bit of ugly code to extract everything before the <code>'&lt;'</code>:</p>\n\n<pre><code>var spots = [].splice.call(elem.innerHTML, 0, elem.innerHTML.indexOf('&lt;'));\n</code></pre></li>\n<li><p>You can add the <code>speak: none;</code> to <code>.container</code> so <a href=\"https://stackoverflow.com/a/672161/1156119\">screen readers don't read</a> \"hello world lakmsdlkaslkadsadfas...\".</p></li>\n<li><p>You can extend jQuery like so:</p>\n\n<pre><code>$.fn.customFunction = function () {\n console.log(this);\n}\n\n$('.some-elem').customFunction();\n</code></pre></li>\n<li><p>I've used CSS3 transitions in place of <code>$.fadeIn()</code>, browser support isn't quite as good (looking at you IE), but the implementation is worth it in my opinion. Especially when most people wouldn't even notice like this super subtle fade in.</p></li>\n<li><p>I'm not so sure about adding a number as a class name, I don't think it's legal to have class names start with a number.</p></li>\n<li><p>Your indentation when you were applying everything to the <code>&lt;span&gt;</code> was a little ugly :P</p></li>\n<li><p>Overall it was a pretty decent and clean jQuery implementation.</p></li>\n</ul>\n\n<h2>Code</h2>\n\n<p><a href=\"http://jsfiddle.net/Tyriar/UsAe8/3/\" rel=\"nofollow noreferrer\">jsFiddle</a></p>\n\n<h3>HTML</h3>\n\n<pre><code>&lt;div class=\"content\"&gt;\n &lt;h2 class=\"some-elem\"&gt;hello world&lt;div class=\"container\"&gt;&lt;/div&gt;&lt;/h2&gt; \n&lt;/div&gt;\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>body { background: black; font-family: consolas;}\n\ndiv.content {\n background: white;\n opacity: 0.9;\n min-height: 1000px;\n width: 960px;\n margin: auto;\n color: black;\n padding: 10px;\n list-style: none;\n position: relative;\n}\n\n\ndiv.content &gt; .some-elem {\n text-shadow: 1px 1px 6px rgba(0, 0, 0, 1), 0px -1px 2px rgba(0, 0, 0, 1);\n border-bottom: 7px solid #41919B;\n border-top: 7px solid #41919B;\n border-right: 1px solid #BDBDBD;\n border-left: 1px solid #BDBDBD;\n padding-bottom: 7px;\n box-shadow: 0px 11px 17px 1px rgba(0, 0, 0, 0.5), inset 0px 0px 0px 1px rgba(0, 0, 0, 0.6);\n border-radius: 5px 5px 5px 5px;\n text-align: center;\n color: black;\n width: 960px;\n overflow: hidden;\n position: relative;\n letter-spacing: 11px;\n line-height: 60px;\n cursor: pointer;\n}\ndiv.content &gt; .some-elem:hover {\n color: #fff;\n text-shadow: 1px 1px 6px rgba(0, 0, 0, 1), 0px -1px 2px rgba(0, 0, 0, 1);\n}\n\nspan.spot {\n position: absolute;\n top: 0px;\n z-index: -1;\n text-shadow: none;\n box-shadow: none;\n}\n\n.container {\n opacity:0;\n -webkit-transition:opacity .8s ease;\n -moz-transition:opacity .8s ease;\n transition:opacity .8s ease;\n speak: none;\n}\n\n.container.show {\n opacity:1;\n}\n</code></pre>\n\n<h3>JS</h3>\n\n<pre><code>function twisty(elemClass, containerClass) {\n var elem = document.getElementsByClassName('some-elem')[0];\n var container = elem.getElementsByClassName('container')[0];\n var spots = [].splice.call(elem.innerHTML, 0, elem.innerHTML.indexOf('&lt;'));\n\n for (var i = 0; i &lt; 300; i++) {\n var span = document.createElement('span');\n var color = 'rgb('+ randomInt(70) + ',' +\n randomInt(70) + ',' +\n randomInt(70) + ')';\n var transform = 'rotate(' + randomInt(360) + 'deg)';\n\n span.innerHTML = spots[randomInt(spots.length - 1)];\n span.className = 'spot '+ i;\n span.style.fontSize = randomInt(50) + 'px';\n span.style.left = randomInt(1000) + 'px';\n span.style.top = randomInt(30) + 'px';\n span.style.bottom = randomInt(50) + 'px';\n span.style.opacity = Math.random() / 3;\n span.style.color = color;\n span.style.webkitTransform = transform;\n span.style.mozTransform = transform;\n span.style.transform = transform;\n container.appendChild(span);\n }\n\n container.classList.add('show');\n}\ntwisty();\n\ndocument.getElementsByClassName('some-elem')[0].onclick = function () {\n var container = document.getElementsByClassName('container')[0];\n container.classList.remove('show');\n while (container.hasChildNodes()) {\n container.removeChild(container.lastChild);\n }\n twisty();\n};\n\nfunction randomInt(max) {\n return Math.ceil(Math.random() * max);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T04:18:02.060", "Id": "37465", "Score": "0", "body": "thanks for all the tips. Definitely cleaner with the randomInt function. here's a question i have though... when I try to run this without jsFiddle, it doesn't work. I know it has to do with using either document.onload or onready, but since I'm so used to using jQuery $(document).ready(), I have no idea what the correct way is to implement that using vanilla javascript. (also, I got tired of correcting the indentation from jsFiddle). your version has given me a good amount of stuff I didn't already know... so muchos gracias!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T04:20:12.093", "Id": "37466", "Score": "0", "body": "You can either put it at the end of the page just before `</body>` or throw it all in `window.onload = function () { /**/ }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T04:31:42.287", "Id": "37467", "Score": "0", "body": "when i use window.onload or document.onready, i get an error \"Cannot call method 'appendChild' of undefined\", when i use document.onload, it fails silently. not a huge deal.. i can try and figure that bit out. i want to try and keep the script in a separate document if possible" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T04:36:46.900", "Id": "37468", "Score": "0", "body": "You can look at the markup that jsFiddle has produced, I turned jQuery off in this one and it has everything in `window.onload=function(){}` inside `<head>` http://jsfiddle.net/Tyriar/Y9msP/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T03:39:11.310", "Id": "24297", "ParentId": "24292", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T01:56:09.453", "Id": "24292", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Here is a function I wrote that, with the help of jQuery, will randomize a bunch of properties" }
24292
<p>I have created a jQuery slider for my personal website and I wanted to get some feedback on how it looks and if there are things I can do to make it better.</p> <p>You can see the live demo here: <a href="http://www.nickmeagher.com" rel="nofollow">http://www.nickmeagher.com</a></p> <p>And here is the code:</p> <pre class="lang-javascript prettyprint-override"><code> var sliderWidth = 0, marginLeft = 0, containerWidth = 1040, slideSpeed = 600, slideDuration = 6000, autoSlide = 0; // (0) = off (1) = on function slide_right() { if ( (sliderWidth - Math.abs(marginLeft)) &gt; containerWidth ) { $('.portfolio-inner-wrapper').stop().animate({ 'margin-left': '+=-' + containerWidth }, slideSpeed, function() { marginLeft += -containerWidth; }); } else { $('.portfolio-inner-wrapper').stop().animate({ 'margin-left': '0px' }, slideSpeed, function() { marginLeft = 0; }); } } function slide_left() { if ( (sliderWidth - Math.abs(marginLeft)) &lt; containerWidth ) { $('.portfolio-inner-wrapper').animate({ 'margin-left': '+=+' + containerWidth }, slideSpeed, function() { marginLeft += containerWidth; }); } else { $('.portfolio-inner-wrapper').animate({ 'margin-left': '0' }, slideSpeed, function() { marginLeft = 0; }); } } // Iterate through each container to calculate width $('.work-container').each(function() { sliderWidth += $(this).outerWidth( true ); }); // Set width of inner wrapper $('.portfolio-inner-wrapper').css('width', sliderWidth); $('a.next').click(function() { slide_right(); }); $('a.prev').click(function() { slide_left(); }); if (autoSlide == 1) { setInterval(function() { slide_right(); }, slideDuration); } </code></pre>
[]
[ { "body": "<p>Here are some general things you should be doing differently. These suggestions don't change the functionality of your slider, and are suggestions you can apply to your future projects.</p>\n\n<p>First and most important</p>\n\n<pre><code>var wrapper = $('.portfolio-inner-wrapper');\n//As a rule of thumb, if you use a selector more than once, you should cache it.\n //Now use 'wrapper' everywhere you used $('portfilo...') instead.\n //Cache it outside if you want to use it in other functions as well.\n//Ex:\nwrapper.css('width', sliderWidth);\n</code></pre>\n\n<p>Next:</p>\n\n<pre><code>if (autoSlide) { //Don't need == 1. Zero is a falsy value.\n setInterval(function() {\n slide_right();\n }, slideDuration); //You don't need setInterval either. jQuery has a built in queue.\n}\n</code></pre>\n\n<p>When you have multiple 'animate' calls, jQuery puts them in a queue to execute them one by one. This goes for the rest of your slider as well.</p>\n\n<p>Save function calls. Do it like this:</p>\n\n<pre><code>$('a.next').on('click', function() {\n if ( (sliderWidth - Math.abs(marginLeft)) &gt; containerWidth ) {\n wrapper.stop().animate({\n 'margin-left': '+=-' + containerWidth\n }, slideSpeed, function() {\n marginLeft += -containerWidth;\n });\n } else {\n wrapper.stop().animate({\n 'margin-left': '0' //Zero doesn't need a unit of measure (ie. px, em, %, etc)\n }, slideSpeed, function() {\n marginLeft = 0;\n });\n }\n});\n</code></pre>\n\n<p>When you use the <code>.click()</code> method, jQuery calls the <code>.on()</code> method. Then if you still call another function inside that, that's three function calls that could be spared if you simply used this:</p>\n\n<pre><code>$('a').on('click', function() {\n do.stuff\n});\n</code></pre>\n\n<p>Finally, I'll be happy to answer any other questions you might have.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T21:08:38.490", "Id": "37567", "Score": "0", "body": "Very good feedback! I didn't know jQuery had a built in queue instead of setInterval? What is it called?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:09:07.440", "Id": "37622", "Score": "0", "body": "The queue is built in and is automatically used with `.animate()`. If you want to alter the order or play with the queue in general use the `.queue()` method." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:29:42.680", "Id": "24321", "ParentId": "24293", "Score": "1" } } ]
{ "AcceptedAnswerId": "24321", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T01:56:46.837", "Id": "24293", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "A review of my jQuery Slider" }
24293
<p>I believe with everyone's help on Stack Overflow, I got my code safe guarded from SQL injection. I'm trying to confirm that is correct, just in case I misinterpreted the help and advice I received.</p> <pre><code>&lt;?php $username = "xxxx"; $password = "xxxx"; ?&gt; &lt;font size="+3" face="Verdana"&gt;xxxx&lt;/font&gt; &lt;br&gt;&lt;br&gt; &lt;form name="form" action="xxxx.php" method="get"&gt; &lt;input type="text" name="q" size="60" /&gt; &lt;input type="submit" name="Submit" value="Search"&gt; &lt;/form&gt; &lt;table&gt; &lt;? $var = $_GET['q']; try { $conn = new PDO('mysql:host=localhost;dbname=xxxx', $username, $password); $stmt = $conn-&gt;prepare("SELECT * FROM xxxx WHERE xxxx LIKE :search"); $stmt-&gt;execute(array(':search' =&gt; '%'.$var.'%')); $result = $stmt-&gt;fetchAll(); if ( count($result) ) { foreach($result as $row) { echo "&lt;tr&gt;&lt;td align=center width=100&gt;" . $row['xxxx'] . "&lt;/td&gt;&lt;td align=center width=100&gt;" . $row['xxxx'] . "&lt;/td&gt;&lt;td align=center width=100&gt;" . $row['xxxx'] . "&lt;/td&gt;&lt;td align=center width=100&gt;" . $row['xxxx'] . "&lt;/td&gt;&lt;td align=center width=100&gt;&lt;img src=http://www.xxx.com/" . $row['image'] . " height=50&gt;" . "&lt;/td&gt;&lt;td align=left width=500&gt;http://www.xxx.com/" . $row['image'] . "&lt;/a&gt; &lt;/td&gt;&lt;td align=center valign=middle width=100&gt; &lt;form action=xxx.php method=POST&gt; &lt;input type=hidden value=" . $row['id'] . " name=edit&gt; &lt;input type=image src=http://www.xxx.com/images/edit.png height=30&gt; &lt;/form&gt; &lt;/td&gt;&lt;td align=center valign=middle width=100&gt; &lt;form action=xxx.php method=POST&gt; &lt;input type=hidden value=" . $row['id'] . " name=delete&gt; &lt;input type=image src=http://www.xxx.com/images/delete.png height=30&gt; &lt;/form&gt; &lt;/td&gt;&lt;/tr&gt;"; } } else { echo "No results found."; } } catch(PDOException $e) { echo 'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;/table&gt; </code></pre>
[]
[ { "body": "<p>You can use PHP to output the page to your own for <code>action=\"xxxx.php\"</code> in the form tag.</p>\n\n<pre><code>action=\"&lt;?= htmlentities($_SERVER['PHP_SELF']); ?&gt;\"\n</code></pre>\n\n<p>It looks like a lot to type, but it'll help if you might decide to change file name later. Other than that, I don't see any other cause of concern. You might want to think about using <code>fetchAll</code> too. It might slow down your page generation because it takes up a lot of memory to store the entire result into a single array. You can use a <code>while</code> loop too, as follows:</p>\n\n<pre><code>$stmt-&gt;execute(array(':search' =&gt; '%'.$var.'%'));\nwhile( $row = $stmt-&gt;fetch() ) {\n</code></pre>\n\n<p>This way, if no result was found, nothing will output to the page. And it'll be considerably faster than <strong><code>fetchAll</code></strong> request.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T05:38:28.060", "Id": "37469", "Score": "0", "body": "Thanks. I updated my code with the information you posted here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T14:10:35.327", "Id": "37480", "Score": "1", "body": "the `$_SERVER['PHP_SELF']` is not really needed. You can also leave it empty or use `#`. I would not recommend to use `$_SERVER['PHP_SELF']`, because that can be a security issue (you solved it here, but that makes the code much harder than it needs to be)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T05:15:23.940", "Id": "24298", "ParentId": "24296", "Score": "1" } }, { "body": "<ul>\n<li>You should <em>not</em> mix PHP logic and HTML. All logic should be placed on top of the document and HTML (+ some minor PHP loops/<code>echo</code>s/<code>if</code>s) below it;</li>\n<li><code>$var = $_GET['q'];</code> is unneeded and you loose memory;</li>\n<li>never use the shorttag (<code>&lt;?</code>);</li>\n<li><p>You forgot to set the errormode for PDO, that means it doesn't throw exceptions. To set it, use <a href=\"http://php.net/pdo.setattribute\"><code>PDO::setAttribute</code></a>:</p>\n\n<pre><code>$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n</code></pre></li>\n<li>I do not recommend to use <code>*</code> in your queries. The query will be faster and easier to use if you specify which columns you want;</li>\n<li><p>You should specify the fetch style of <code>PDOStatement::fetchAll</code>. Otherwise it defaults to <code>PDO::FETCH_BOTH</code>, which means your array get to big and your script slower. You can specify it with a parameter in the function:</p>\n\n<pre><code>$stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n</code></pre>\n\n<p>Or specify it for the <code>PDOstatement</code>:</p>\n\n<pre><code>$stmt-&gt;setFetchMode(PDO::FETCH_ASSOC);\n</code></pre></li>\n<li>A small tip: Indent your code within each block with a tab or 4 spaces, that makes your code much easier to read. Also, choose a coding standard and use it everywhere. Consistent scripts are a pleasure to write, read and use!</li>\n</ul>\n\n<p>Some none PDO/PHP things:</p>\n\n<ul>\n<li>The <code>&lt;font&gt;</code> element is outdated. You should do this with CSS;</li>\n<li>You should not use inline CSS (like <code>style=</code>, <code>align=</code>, <code>width=</code>), put it in a CSS stylesheet instead;</li>\n<li>When you are using 2 <code>&lt;br&gt;</code> next to eachother, you almost always know you do something wrong and you should take a look at how to solve it with CSS margins/paddings.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:21:18.157", "Id": "37554", "Score": "0", "body": "What if I NEED to select every column in the database when displaying results? Should I still type them out manually rather than using *? I kind of understand what you are saying about mixing PHP logic & HTML but do you have a good example of why not to do this or just something that shows where I'm going wrong? I believe you are saying the form should be at the end of the page not the top. But is using <table> before and after the output ok? I was unable to put it in the foreach loop unless I want a new table every time. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:31:20.747", "Id": "37555", "Score": "0", "body": "1) Yes, even if you need all columns I recommend to type them out. It's more readable, you know your column names so you know which data you get back, otherwise you need to go to PmA to see how you database look like and go back to use it in your scripts. And it's faster most of the times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:32:43.660", "Id": "37557", "Score": "0", "body": "2) It's about Seperation of Scripts. You shouldn't mix 2 languages. And you avoid errors like 'Headers already sent'. 3) In your HTML, you can use some PHP echo's, loops, ect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T17:04:09.007", "Id": "84528", "Score": "1", "body": "it's also a go idea to list out the columns you want, in the case that columns are added to the table, you may not want those columns and the extra columns could break your query, whereas identifying the columns should keep the long term use of the query to it's longest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T17:43:01.543", "Id": "84540", "Score": "0", "body": "Out of curiosity, what's wrong with the `<?=?>` short tag? I understand that not all servers have it enabled, but assuming you have control over your servers is there another drawback?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T21:31:48.227", "Id": "84598", "Score": "0", "body": "@MatthewJohnson there is nothing wrong with the `<?= ?>` *shortcut* tag. However, the question used the `<?` as the PHP open tag, which is wrong." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T14:21:41.280", "Id": "24307", "ParentId": "24296", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T03:39:07.473", "Id": "24296", "Score": "3", "Tags": [ "php", "mysql", "pdo", "sql-injection" ], "Title": "Confirming safety of SQL injection" }
24296
<p>I need to remove the fractional part of a <code>BigDecimal</code> value when its scale has a value of zero. For example,</p> <pre><code>BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>It would assign <code>12.00</code>. I want it to assign only <code>12</code> to <code>value</code> in such cases.</p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign <code>12</code>,</p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign <code>12</code>.</p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign<code>12.01</code></p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.99").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign <code>12.99</code>.</p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.999").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign<code>13</code></p> <hr> <pre><code>BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP); </code></pre> <p>should assign <code>12.35</code> and alike.</p> <hr> <p>I have this question on <a href="https://stackoverflow.com/q/15590624/1391249">StackOverflow</a>.</p> <p>For this to be so, I'm doing the following.</p> <pre><code>String text="123.008"; BigDecimal bigDecimal=new BigDecimal(text); if(bigDecimal.scale()&gt;2) { bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP); } if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0) { bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP); } System.out.println("bigDecimal = "+bigDecimal); </code></pre> <p>It's just as an example. Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T17:23:38.370", "Id": "37552", "Score": "0", "body": "Besides the content, a +1 for providing the tests. Makes it much easier to get an understanding of the desired functionality" } ]
[ { "body": "<blockquote>\n <p>Is there a better way to do this?</p>\n</blockquote>\n\n<p>Yes, <code>stripTrailingZeros()</code>.</p>\n\n<p>To check your tests:</p>\n\n<pre><code>public static void main(final String[] args) {\n check(truncate(\"12.000000\"), \"12\");\n check(truncate(\"12.0001\"), \"12\");\n check(truncate(\"12.0051\"), \"12.01\");\n check(truncate(\"12.99\"), \"12.99\");\n check(truncate(\"12.999\"), \"13\");\n check(truncate(\"12.3456\"), \"12.35\");\n System.out.println(\"if we see this message without exceptions, everything is ok\");\n}\n\nprivate static BigDecimal truncate(final String text) {\n BigDecimal bigDecimal = new BigDecimal(text);\n if (bigDecimal.scale() &gt; 2)\n bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);\n return bigDecimal.stripTrailingZeros();\n}\n\nprivate static void check(final BigDecimal bigDecimal, final String string) {\n if (!bigDecimal.toString().equals(string))\n throw new IllegalStateException(\"not equal: \" + bigDecimal + \" and \" + string);\n\n}\n</code></pre>\n\n<p>output:</p>\n\n<blockquote>\n <p>if we see this message without exceptions, everything is ok</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T05:01:47.373", "Id": "37584", "Score": "0", "body": "Good to know a precise, concise and recommended way. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-11T21:08:17.403", "Id": "400438", "Score": "1", "body": "Be careful with this. `10.00` becomes `1E+1`, not `10`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-14T14:14:48.003", "Id": "405252", "Score": "0", "body": "@stickfigure and how do I make it `10.00` and not `1E+1` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-14T18:50:04.793", "Id": "405289", "Score": "0", "body": "Depends on what you want to do? I wanted prettier USD amounts, so I ended up manipulating the toString version (ie `cost.endsWith(\".00\") ? cost.substring(0, cost.length() - 3) : cost`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-02T16:35:08.210", "Id": "442425", "Score": "0", "body": "The proposed solutions passes the given tests. For the new case of `10.00`: The result is technically correct, only the printing may be inconvenient. The printing can be changed with `DecimalFormat`. Depending on the specification, `new DecimalFormat(\"0.00\")` may be suitable." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T23:58:25.130", "Id": "24325", "ParentId": "24299", "Score": "8" } } ]
{ "AcceptedAnswerId": "24325", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T07:02:46.900", "Id": "24299", "Score": "3", "Tags": [ "java" ], "Title": "Is this the way of truncating the fractional part of a BigDecimal when its scale is zero in Java?" }
24299
<p>Can you please try my algorithm and give comments or feedback about it?</p> <pre><code>package md52; import java.io.*; //input outputs import static java.lang.Math.*; //for math purposes /** * * JesseePogi */ public class Md52 { public static String input; public static void main(String[] args) { //start timer (for algo speed testing) long start = System.currentTimeMillis(); //input BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Enter the text here: "); input = bf.readLine(); } catch(IOException err) { System.out.println("Read Error!"); } //initialize digest int h0 = 0x67452301; int h1 = 0xefcdab89; int h2 = 0x98badcfe; int h3 = 0x10325476; //Initialize hash for chunk int a = h0; int b = h1; int c = h2; int d = h3; int f = 0, g = 0; //initialize shift rotation int r[] = {7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22, 5, 9,14,20,5, 9,14,20,5, 9,14,20,5, 9,14,20, 4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23, 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21}; //initialize constant k int k[] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; //long formula for k (didn't use because of unwanted results when casting as int) /* double k[] = new double[64]; for (int i = 0; i &lt; 64; i++) { k[i] = floor(abs(sin(i+1)) * pow(2,32)); System.out.println(k[i]); } */ //store original input String origInput = input; //leftrotate13 the original input (by character) for(int i = 0; i &lt; 13; ++i) { origInput = origInput.substring(1,origInput.length()) +""+ origInput.charAt(0); } //sum all the values of origInput for salting byte[] bytesTemp1 = origInput.getBytes(); int sum = 0; for (int i : bytesTemp1) sum += i; //convert to bit (input) byte[] bytesTemp = input.getBytes(); StringBuilder binaryTemp = new StringBuilder(); for (byte byt : bytesTemp) { int val = byt; for (int i = 0; i &lt; 8; i++) { binaryTemp.append((val &amp; 128) == 0 ? 0 : 1); val &lt;&lt;= 1; } } String origInput_bits = binaryTemp.toString(); //for padding purposes if (origInput_bits.length() &lt; 64) { origInput_bits = origInput_bits + "1"; for (int i = origInput_bits.length(); i&lt;64; i++) { origInput_bits = origInput_bits + "0"; } } //padding 1 and 0s' binaryTemp.append("1"); for(int i = binaryTemp.length(); i%512!=448; i++) { binaryTemp.append("0"); } //pad additional 64bits to get 512bits (from end to end until it reach the middle part) String pad1_address0 = origInput_bits.substring(0,8); String pad2_addressEnd = origInput_bits.substring(origInput_bits.length()-8,origInput_bits.length()); String pad3_address1 = origInput_bits.substring(8,16); String pad4_addressEnd1 = origInput_bits.substring(origInput_bits.length()-16,origInput_bits.length()-8); String pad5_address2 = origInput_bits.substring(16,24); String pad6_addressEnd2 = origInput_bits.substring(origInput_bits.length()-24,origInput_bits.length()-16); String pad7_address3 = origInput_bits.substring(24,32); String pad8_addressEnd3 = origInput_bits.substring(origInput_bits.length()-32,origInput_bits.length()-24); String origInput_bits64 = pad1_address0+""+pad2_addressEnd+""+pad3_address1+""+pad4_addressEnd1+""+pad5_address2+""+pad6_addressEnd2+""+pad7_address3+""+pad8_addressEnd3; binaryTemp.append(origInput_bits64); //sixteen 32bit chunks in string wTemp[] String wTemp[] = new String[16]; int x = 0; for (int i = 0; i &lt; 16; i++) { wTemp[i] = binaryTemp.substring(x,x+=32); wTemp[i] = wTemp[i].toString(); } //string wTemp[] to byte[] data byte[] data1 = new byte[64]; int y = 0; int count = 0; for(int i = 0; i &lt; 16; ++i) { while (count &lt; 64) { if(i&lt;=3) { if(i&gt;=0) { data1[count]= (byte) Integer.parseInt(wTemp[i].substring(y,y+=8),2); if (y==32){y = 0; ++count; break;} } } if(i&lt;=7) { if(i&gt;=4) { data1[count]= (byte) Integer.parseInt(wTemp[i].substring(y,y+=8),2); if (y==32){y = 0; ++count; break;} } } if(i&lt;=11) { if(i&gt;=8) { data1[count]= (byte) Integer.parseInt(wTemp[i].substring(y,y+=8),2); if (y==32){y = 0; ++count; break;} } } if(i&lt;=15) { if(i&gt;=12) { data1[count]= (byte) Integer.parseInt(wTemp[i].substring(y,y+=8),2); if (y==32){y = 0; ++count; break;} } } ++count; } } /* data1[0] = (byte) Integer.parseInt(wTemp[0].substring(0,8), 2); data1[1] = (byte) Integer.parseInt(wTemp[0].substring(8,16), 2); data1[2] = (byte) Integer.parseInt(wTemp[0].substring(16,24), 2); data1[3] = (byte) Integer.parseInt(wTemp[0].substring(24,32), 2); data1[4] = (byte) Integer.parseInt(wTemp[1].substring(0,8), 2); data1[5] = (byte) Integer.parseInt(wTemp[1].substring(8,16), 2); data1[6] = (byte) Integer.parseInt(wTemp[1].substring(16,24), 2); data1[7] = (byte) Integer.parseInt(wTemp[1].substring(24,32), 2); data1[8] = (byte) Integer.parseInt(wTemp[2].substring(0,8), 2); data1[9] = (byte) Integer.parseInt(wTemp[2].substring(8,16), 2); data1[10] = (byte) Integer.parseInt(wTemp[2].substring(16,24), 2); data1[11] = (byte) Integer.parseInt(wTemp[2].substring(24,32), 2); data1[12] = (byte) Integer.parseInt(wTemp[3].substring(0,8), 2); data1[13] = (byte) Integer.parseInt(wTemp[3].substring(8,16), 2); data1[14] = (byte) Integer.parseInt(wTemp[3].substring(16,24), 2); data1[15] = (byte) Integer.parseInt(wTemp[3].substring(24,32), 2); data1[16] = (byte) Integer.parseInt(wTemp[4].substring(0,8), 2); data1[17] = (byte) Integer.parseInt(wTemp[4].substring(8,16), 2); data1[18] = (byte) Integer.parseInt(wTemp[4].substring(16,24), 2); data1[19] = (byte) Integer.parseInt(wTemp[4].substring(24,32), 2); data1[20] = (byte) Integer.parseInt(wTemp[5].substring(0,8), 2); data1[21] = (byte) Integer.parseInt(wTemp[5].substring(8,16), 2); data1[22] = (byte) Integer.parseInt(wTemp[5].substring(16,24), 2); data1[23] = (byte) Integer.parseInt(wTemp[5].substring(24,32), 2); data1[24] = (byte) Integer.parseInt(wTemp[6].substring(0,8), 2); data1[25] = (byte) Integer.parseInt(wTemp[6].substring(8,16), 2); data1[26] = (byte) Integer.parseInt(wTemp[6].substring(16,24), 2); data1[27] = (byte) Integer.parseInt(wTemp[6].substring(24,32), 2); data1[28] = (byte) Integer.parseInt(wTemp[7].substring(0,8), 2); data1[29] = (byte) Integer.parseInt(wTemp[7].substring(8,16), 2); data1[30] = (byte) Integer.parseInt(wTemp[7].substring(16,24), 2); data1[31] = (byte) Integer.parseInt(wTemp[7].substring(24,32), 2); data1[32] = (byte) Integer.parseInt(wTemp[8].substring(0,8), 2); data1[33] = (byte) Integer.parseInt(wTemp[8].substring(8,16), 2); data1[34] = (byte) Integer.parseInt(wTemp[8].substring(16,24), 2); data1[35] = (byte) Integer.parseInt(wTemp[8].substring(24,32), 2); data1[36] = (byte) Integer.parseInt(wTemp[9].substring(0,8), 2); data1[37] = (byte) Integer.parseInt(wTemp[9].substring(8,16), 2); data1[38] = (byte) Integer.parseInt(wTemp[9].substring(16,24), 2); data1[39] = (byte) Integer.parseInt(wTemp[9].substring(24,32), 2); data1[40] = (byte) Integer.parseInt(wTemp[10].substring(0,8), 2); data1[41] = (byte) Integer.parseInt(wTemp[10].substring(8,16), 2); data1[42] = (byte) Integer.parseInt(wTemp[10].substring(16,24), 2); data1[43] = (byte) Integer.parseInt(wTemp[10].substring(24,32), 2); data1[44] = (byte) Integer.parseInt(wTemp[11].substring(0,8), 2); data1[45] = (byte) Integer.parseInt(wTemp[11].substring(8,16), 2); data1[46] = (byte) Integer.parseInt(wTemp[11].substring(16,24), 2); data1[47] = (byte) Integer.parseInt(wTemp[11].substring(24,32), 2); data1[48] = (byte) Integer.parseInt(wTemp[12].substring(0,8), 2); data1[49] = (byte) Integer.parseInt(wTemp[12].substring(8,16), 2); data1[50] = (byte) Integer.parseInt(wTemp[12].substring(16,24), 2); data1[51] = (byte) Integer.parseInt(wTemp[12].substring(24,32), 2); data1[52] = (byte) Integer.parseInt(wTemp[13].substring(0,8), 2); data1[53] = (byte) Integer.parseInt(wTemp[13].substring(8,16), 2); data1[54] = (byte) Integer.parseInt(wTemp[13].substring(16,24), 2); data1[55] = (byte) Integer.parseInt(wTemp[13].substring(24,32), 2); data1[56] = (byte) Integer.parseInt(wTemp[14].substring(0,8), 2); data1[57] = (byte) Integer.parseInt(wTemp[14].substring(8,16), 2); data1[58] = (byte) Integer.parseInt(wTemp[14].substring(16,24), 2); data1[59] = (byte) Integer.parseInt(wTemp[14].substring(24,32), 2); data1[60] = (byte) Integer.parseInt(wTemp[15].substring(0,8), 2); data1[61] = (byte) Integer.parseInt(wTemp[15].substring(8,16), 2); data1[62] = (byte) Integer.parseInt(wTemp[15].substring(16,24), 2); data1[63] = (byte) Integer.parseInt(wTemp[15].substring(24,32), 2); */ //byte[] data to real int w[] (concatenation) int[] w = new int[16]; int count2 = 0; for(int i = 0; i &lt; 16; ++i) { w[i] = (((int)data1[count2++])) | (((int)data1[count2++]) &lt;&lt; 8) | (((int)data1[count2++]) &lt;&lt; 16) | (((int)data1[count2++]) &lt;&lt; 24); } //main loop for(int i = 0; i &lt;= 63; i++) { if (i &lt;= 15) { if (i &gt;= 0) { f = (b &amp; c) | ((~b) &amp; d); g = i; } } if (i &lt;= 31) { if (i &gt;= 16) { f = (d &amp; b) | ((~d) &amp; c); g = (5*i + 1) % 16; } } if (i &lt;= 47) { if (i &gt;= 32) { f = (b ^ c ^ d); g = (3*i + 5) % 16; } } if (i &lt;= 63) { if (i &gt;= 48) { f = c ^ (b | (~d)); g = (7*i) % 16; } } int temp = d; d = c; c = b; b = b + Integer.rotateLeft((a + f + k[i] + w[g]), r[i]); a = temp; } //Add this chunk's hash to result so far h0 = h0 + a; h1 = h1 + b; h2 = h2 + c; h3 = h3 + d + sum; //sum is salted //Show the final result System.out.println("Hash Code: "+Integer.toHexString(h0)+Integer.toHexString(h1)+Integer.toHexString(h2)+Integer.toHexString(h3)); //end timer long end = System.currentTimeMillis(); long diff = end - start; System.out.println("\nAlgorithm Speed (ms): " + diff); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T23:42:51.370", "Id": "37507", "Score": "6", "body": "What is the purpose of this? Should this be an implementation of md5? Or is it something else?" } ]
[ { "body": "<p>One thing is that you should always specify an encoding when calling <code>String.getBytes</code>, since otherwise the result depends too much on the execution environment. I didn't look through the rest of the code, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T05:18:36.973", "Id": "59014", "Score": "2", "body": "There should never have been any Strings in the first place; MD5 should work on byte arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T21:14:26.413", "Id": "59142", "Score": "0", "body": "Or maybe on UTF-8 encoded strings in NFC. But then consistently." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T03:30:09.080", "Id": "36104", "ParentId": "24300", "Score": "2" } }, { "body": "<p>A few notes:</p>\n\n<hr>\n\n<p>There is no need to comment <code>import</code> statements. Although I want to say thank you, I've never actually seen anyone do that before. But really, don't do it.</p>\n\n<hr>\n\n<p>Commented-out code is dead code. Dead code should be removed. If you are afraid of deleting code, you probably don't know about source control management. Look into learning how to work with SCM tools such as git.</p>\n\n<hr>\n\n<p>Variable names should be meaningful and reveal the semantics in order to make the code read like a story or at least a manual. Names like <code>a</code>, <code>b</code>, <code>c</code>, … are meaningless and only make understanding (and therefore maintaining) the code harder.</p>\n\n<hr>\n\n<p>Your code contains many <em>magic numbers</em>, i.e. numbers that appear in the code without obviously revealing their meaning. Convert them into constants to improve both readability and maintainability.</p>\n\n<hr>\n\n<p>Avoid enumerating variable names such as <code>byteTemp</code> and then <code>byteTemp1</code>. Again, variable names should represent semantics. They should not represent their type either (we will know that by reading their declaration).</p>\n\n<p>Ask yourself: If you only saw the name <code>byteTemp</code>, what would you <em>really</em> know about it? Maybe that it (probably) has to do with bytes, but you would know nothing about what this variable represents in the context.</p>\n\n<hr>\n\n<p>The common Java standard is camelCase, not snake_case. So variables should be named <code>someVariable</code>, not <code>some_variable</code>.</p>\n\n<hr>\n\n<p>Your method is (way, way) too long. Break every individual piece into its own method. Maybe even break it down into separate classes if necessary. A good method does one thing, yours does dozens of things and makes it pretty much impossible to keep track of what is going on as there is no abstraction supporting this.</p>\n\n<hr>\n\n<p>Instead of printing the result, your method (which won't be a <code>main</code> method anyway) should <code>return</code> the result. Leave it up to the caller to decide what they want to do with the result.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-23T04:53:03.873", "Id": "96171", "Score": "0", "body": "I doubt that there's much that can be done about the magic numbers. They aren't supposed to make logical sense. It's just how the algorithm works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-23T05:18:45.007", "Id": "96173", "Score": "0", "body": "Maybe, but it'd still be good to have constants for them because it makes code more maintainable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T17:08:11.557", "Id": "107064", "Score": "0", "body": "Variables within cryptographic primitives often have no intuitive meaning. An implementation should use the names used in the specification which may well be `a`,..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T17:10:45.737", "Id": "107065", "Score": "0", "body": "Concerning magic numbers the only thing I'd do is turn `h0`...`h3`, `r`, `k` into static fields instead of including them in the main method. There is little else you can do with these." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-22T20:50:05.120", "Id": "54973", "ParentId": "24300", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T07:32:58.203", "Id": "24300", "Score": "4", "Tags": [ "java", "algorithm", "cryptography" ], "Title": "New MD5 algorithm" }
24300
<p>This is my first program written in C++. I chose to make this public in order to receive suggestions on further improvements and to know if I'm using any "forbidden" code.</p> <p>I'm asking because I initially put a lot of <code>goto</code>s in the program, but later found out that using <code>goto</code> was "evil." Therefore, after a lot of trial and error, I removed them all and replaced them with a couple of <code>do</code>-<code>while</code> loops. I must say using <code>do</code>-<code>while</code> makes the final code much easier to read.</p> <p>Please let me know if you still see any "forbidden" code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main () { string name, favfood, age, y_n_decision; do { cout &lt;&lt; "welcome to my program in c++" &lt;&lt; endl; cout &lt;&lt; "Please enter your name" &lt;&lt; endl; getline (cin, name); cout &lt;&lt; "enter your favourite food" &lt;&lt; endl; getline (cin, favfood); cout &lt;&lt; "awesome! " &lt;&lt; favfood &lt;&lt; " is my favourite food too" &lt;&lt; endl; cout &lt;&lt; "enter your age" &lt;&lt; endl; getline (cin, age); cout &lt;&lt; " so your name is " &lt;&lt; name &lt;&lt; " and your fav food is " &lt;&lt; favfood &lt;&lt; " and your age is " &lt;&lt; age &lt;&lt; endl; cout &lt;&lt; "please press Y to restart, or Q to quit" &lt;&lt; endl; do { getline (cin, y_n_decision); if (y_n_decision == "q") { cout &lt;&lt; "quitting now" &lt;&lt; endl; return 0; } else if (y_n_decision == "y") { cout &lt;&lt; "nice! you typed y. Exiting current loop and returning to int main() aka the beginning." &lt;&lt; endl; break; } else { cout &lt;&lt; "you didn't type either y or q. YOU MUST PRESS Y OR Q OR I WILL PROMPT U FOREVER!!" &lt;&lt; endl; } } while (y_n_decision == "y" || "n"); } while (y_n_decision == "y" || "n"); return 0; } </code></pre> <p><strong>EDITED:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using std::cout; using std::endl; using std::string; using std::cin; int main () { string name, favfood, age; string y_n_decision; while (y_n_decision != "y" || y_n_decision != "q") { cout &lt;&lt; "welcome to my program in c++" &lt;&lt; endl; cout &lt;&lt; "Please enter your name" &lt;&lt; endl; getline (cin, name); cout &lt;&lt; "enter your favourite food" &lt;&lt; endl; getline (cin, favfood); cout &lt;&lt; "awesome! " &lt;&lt; favfood &lt;&lt; " is my favourite food too" &lt;&lt; endl; cout &lt;&lt; "enter your age" &lt;&lt; endl; getline (cin, age); cout &lt;&lt; " so your name is " &lt;&lt; name &lt;&lt; " and your fav food is " &lt;&lt; favfood &lt;&lt; " and your age is " &lt;&lt; age &lt;&lt; endl; cout &lt;&lt; "please press y to restart, or q to quit" &lt;&lt; endl; while (y_n_decision != "y" || y_n_decision != "q") { getline (cin, y_n_decision); if (y_n_decision == "q") { cout &lt;&lt; "quitting now" &lt;&lt; endl; return 0; } else if (y_n_decision == "y") { cout &lt;&lt; "nice! you typed y. Exiting current loop and returning to int main() aka the beginning." &lt;&lt; endl; break; } else { cout &lt;&lt; "you didn't type either y or q. YOU MUST PRESS y OR q OR I WILL PROMPT U FOREVER!!" &lt;&lt; endl; } } } return 0; } </code></pre>
[]
[ { "body": "<p>Armond, the main thing you should do is to learn about functions. Putting everything in <code>main</code> is not practicable beyond very small programs. And nested loops are generally a bad idea too. So for example you might extract the content of the first loop into a function and extract the second loop into another function.</p>\n\n<p>So you would get something like:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n do {\n user_interaction();\n } while (user_says_exit() == false);\n return 0;\n}\n</code></pre>\n\n<p>Also note that <code>while (true) {...}</code> is more commonly used than <code>do {... } while (true);</code> although <code>do{} while()</code> loops clearly have their uses.</p>\n\n<p><hr>\n<strong>EDIT</strong></p>\n\n<p>To be honest, I like the edited version less than the original. You are now testing the <code>y_n_decision</code> as the condition in both loops. And you are relying on the variable having been default-initialized. Moreover the loops are now <code>while</code> instead of <code>do-while</code> and are arguably more wrong now than they were before. A <code>while (true)</code> loop is preferable to your original <code>do ... while (true)</code> because the condition (true) is immediately visible at the top of the loop. But the new loops using <code>while (condition)</code> rely upon the initial value of the condition - and in your case you have to force that to be false by using an initializer that is not y/q. This is at best inelegant.</p>\n\n<p>Here is how I might have coded what you are doing:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;ctype.h&gt;\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nstatic bool user_says_exit(void)\n{\n std::string decision;\n do {\n cout &lt;&lt; \"Please press y to restart, or q to quit\" &lt;&lt; endl;\n getline(cin, decision);\n } while (decision != \"y\" &amp;&amp; decision != \"q\");\n return (decision != \"y\");\n}\n\nstatic void user_interaction(void)\n{\n std::string age;\n std::string favfood;\n std::string name;\n cout &lt;&lt; \"Welcome to my program in c++\" &lt;&lt; endl;\n cout &lt;&lt; \"Please enter your name\" &lt;&lt; endl;\n getline (cin, name);\n cout &lt;&lt; \"Enter your favourite food\" &lt;&lt; endl;\n getline (cin, favfood);\n cout &lt;&lt; \"Awesome! \" &lt;&lt; favfood &lt;&lt; \" is my favourite food too\" &lt;&lt; endl;\n cout &lt;&lt; \"Enter your age\" &lt;&lt; endl;\n getline (cin, age);\n cout &lt;&lt; \"So your name is \" &lt;&lt; name &lt;&lt; \", your fav food is \"\n &lt;&lt; favfood &lt;&lt; \" and your age is \" &lt;&lt; age &lt;&lt; endl;\n}\n\nint main(int argc, char **argv)\n{\n do {\n user_interaction();\n } while (user_says_exit() == false);\n cout &lt;&lt; \"Quitting now\" &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:43:10.343", "Id": "37500", "Score": "1", "body": "`while (!user_says_exit());` would be more idiomatic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T21:19:42.427", "Id": "37503", "Score": "0", "body": "Thank you so much @William Morris for your kind suggestions. Yes I can already see how complicated it would get with everything kept in 'main' once the app grows bigger. Thank you Josay I have duly noted both William's and your suggestions and replaced all do-whiles with whiles only. I reposted the updated code above. Really appreciate your input. As for functions, yes William that does make sense, specially when you want to create a very large number of statements and conditions. I definitely need to 'functionize' the whole app!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T19:58:29.320", "Id": "24318", "ParentId": "24301", "Score": "5" } }, { "body": "<p><strong>Style</strong></p>\n\n<ul>\n<li>Make sure that your code is consistent in the style. Choose whether you put the opening brace on the next line or on the current line and stick to it.</li>\n</ul>\n\n<p><strong>User interface</strong></p>\n\n<ul>\n<li>If you expect 'y' or 'q' from the user, don't ask him to press 'Y' or 'Q'.</li>\n<li>In your case, this is probably more some debug logs than a proper user interface but as a rule, you probably should bother the user with implementation details in your user interface (\"current loop\", \"int main()\").</li>\n</ul>\n\n<p><strong>Code organisation</strong></p>\n\n<ul>\n<li>Define your variables in the smallest possible scope.</li>\n<li>You shouldn't do <code>using namespace std</code>. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c\">SO question about this</a> </li>\n</ul>\n\n<p><strong>Code flow</strong></p>\n\n<ul>\n<li>At the moment, your code is checking <code>y_n_decision != \"y\" || y_n_decision != \"q\"</code> in different places. In order to see when it is true, let's try to see when it is actually false. This happens when the two sides or the <code>||</code> are false which is when <code>y_n_decision</code> is both \"y\" and \"q\". This cannot happen thus the condition is always true and not really useful. You can get rid of your checks making the code easier to read. (You should also take that chance to move the declaration of y_n_decision to the inside of the inner while now that we don't need it anywhere else anymore).</li>\n</ul>\n\n<p>(To be honest, before diving into the code, I thought it would be a bit harder to clean the whole thing but once this obviously-useless checks are removed, everything is already much clearer).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T21:52:24.007", "Id": "37504", "Score": "0", "body": "Josay, thank you so much for these valuable suggestions. I now need to go through your suggestions one by one and implement them in the code. I'll repost the modified code and let you know asap :) Thanks. As for bothering the user with implementation details, yes you're right on lol. It was left there just for debugging purposes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T19:58:46.863", "Id": "24319", "ParentId": "24301", "Score": "4" } } ]
{ "AcceptedAnswerId": "24318", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T09:48:31.060", "Id": "24301", "Score": "3", "Tags": [ "c++", "beginner" ], "Title": "\"Favorite food\" program" }
24301
<p>I am making a Python program with what I learned so far where the user enters two IPs that represents the start and end of the range of IPs to be scanned, then saves the wanted IP in a text file.</p> <pre><code> #ip range and scanning import socket import sys ok=[] def ipscan(start2,port): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: s.connect((start2,port)) print start2 ,'--&gt;port %s is Open'%port ok.append(start2) except: print start2 ,'--&gt;port %s is Closed ! '%port def iprange(start,end): while end&gt;start: start[3]+=1 ipscan('.'.join(map(str,start)),p) for i in (3,2,1,0): if start[i]==255: start[i-1]+=1 start[i]=0 #--------------------------------------------# sta=map(int,raw_input('From : ').split('.')) fin=map(int,raw_input('to : ').split('.')) p=input('Port to scan : ') iprange(sta,fin) print '-----------end--------------' of=open('Output.txt','w') for ip in ok: of.writelines(ip+'\n') of.close() </code></pre> <p>It seems to be working but I need to be sure, and wanted to know if I can make it any faster, or if there is a better way.</p>
[]
[ { "body": "<p>Your naming convention doesnt aid legability. e.g, rename <code>p</code> to <code>port</code>.</p>\n\n<p>Don't do carte blanche exception handling. Be more specific, e.g.:</p>\n\n<pre><code>try:\n ...\nexcept (ValueError, KeyError)\n ...\n</code></pre>\n\n<p>You are also a miser with your spaces. White space is important for legibility.</p>\n\n<p>explicit is better than implicit so replace <code>ipscan('.'.join(map(str,start)),p)</code> with <code>ipscan(start2='.'.join(map(str,start)), port=p)</code></p>\n\n<p>Consider replacing <code>while end&gt;start</code> with <code>while end &gt;= start</code> as it allows scanning of a single IP address..</p>\n\n<p>I cans see how the ordering of 3,2,1,0 is important so replace</p>\n\n<pre><code>for i in (3,2,1,0):\n if start[i]==255:\n start[i-1]+=1 #what if \n start[i]=0\n</code></pre>\n\n<p>with</p>\n\n<pre><code>for i, val in enumerate(start):\n if val == 255:\n start[i] = 0\n start[i-1] += 1\n</code></pre>\n\n<p>Also, what if item at index 0 == 255? that will cause <code>start[i-1] += 1</code> to raise an Index Error.</p>\n\n<p>Also, it is not clear why that transformation is being done, so some documentation will be great. Future you will thank present you for it too. Just simply <code>#this does x because of y</code> can suffice.</p>\n\n<p>replace</p>\n\n<pre><code>of=open('Output.txt','w')\nfor ip in ok:\n of.writelines(ip+'\\n')\nof.close()\n</code></pre>\n\n<p>with context and join</p>\n\n<pre><code>with open('Output.txt','w') as of:\n of.write('\\n'.join(ok))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T13:06:56.117", "Id": "24337", "ParentId": "24302", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T10:47:24.030", "Id": "24302", "Score": "2", "Tags": [ "python", "socket" ], "Title": "Port-scanning with two IPs" }
24302
<p>Is it possible to reduce this long nested for loops and if conditions to increase its readability and to optimize it for future reference. </p> <p>While writing code for my scheduling app, I ended up with a method as shown below. Really, I have a data structure like <a href="http://pastie.org/7097616" rel="nofollow">this</a>. Here, I checks - Is there any stages (Inside LCycle) which using same Tool at same time and If its found so, another method <code>LCycleTimeShift</code> is called to make a rearrangment. </p> <p>But I want to check whether the new arrangement is adaptable and the for loop counter is reset so that it will check the new arrangment again. I think this is not the better way to write the code for better readabilty. A little research on the topic found that Enumerators can help me in this. But I don't know how can I accomplish this with the following code. </p> <pre><code>public List&lt;LCycle&gt; ToolArrangment(List&lt;LCycle&gt; TimeLineInit) { for (int i = 0; i &lt; TimeLineInit.Count; i++)//Each LIfeCycles In TimeLine { for (int j = 0; j &lt; TimeLineInit[i].Stage.Count; j++)//Each Stages inTimeLine { for (int k = 0; k &lt; i; k++)//Each L esvd =ifeCycles Upto Current LifeCycle { for (int l = 0; l &lt; TimeLineInit[k].Stage.Count; l++)//Each Stages of (LifeCycle upto current LifeCycle) { for (int m = 0; m &lt; TimeLineInit[i].Stage[j].ToolList.Count; m++)//each tools in stage of timelkine { for (int n = 0; n &lt; TimeLineInit[k].Stage[l].ToolList.Count;n++ )// Each tools In that stage (for loop outer of outer) { if (TimeLineInit[i].Stage[j].ToolList[m].ToolName == TimeLineInit[k].Stage[l].ToolList[n].ToolName)//If both tools are same (satidfying above for loop conditions) { if (IsTimeOverLaps(TimeLineInit[i].Stage[j].StageSpan, TimeLineInit[k].Stage[l].StageSpan)) {//tool using at same time. Stage ReplaceStage = TimeLineInit[i].Stage[j].DeepCopy();//Taking Copy of stage Span to make time shift Double TimeDifference=(ReplaceStage.StageSpan.ToTime-ReplaceStage.StageSpan.FromTime).TotalMinutes;//Calculating required time shift ReplaceStage.StageSpan.FromTime=TimeLineInit[k].Stage[l].StageSpan.ToTime;//FromTime changed accordingly ReplaceStage.StageSpan.ToTime=ReplaceStage.StageSpan.ToTime.AddMinutes(TimeDifference);//To Time Changed accordingly LCycleTimeShift(TimeLineInit[i], ReplaceStage);//passing refernce j = 0; k = 0; l = 0; m = 0; n = 0;//Counter Reset to validate the new arrangment } } } } } } } } return TimeLineInit; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T11:45:00.153", "Id": "37472", "Score": "0", "body": "o.0 do you really need that many `for` loops?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:08:26.843", "Id": "37473", "Score": "0", "body": "Does it matter which of 2 overlapping stages actually gets rescheduled, or you're allowed to change any of them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:11:42.327", "Id": "37474", "Score": "0", "body": "yes I need @Tyriar" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:13:12.397", "Id": "37475", "Score": "0", "body": "@almaz the later one only rescheduled" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:44:45.337", "Id": "37476", "Score": "0", "body": "You should consider using `foreach` instead of `for` for collections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T12:49:03.607", "Id": "37477", "Score": "0", "body": "And that counter reset is a terrible thing to do. Especially since I think it won't work the way you expect. (It won't start looping from the topmost `for`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T13:15:47.870", "Id": "37478", "Score": "0", "body": "@svick you meant it won't start from 0. or not at all" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T01:28:49.153", "Id": "37515", "Score": "2", "body": "That's some serious for loop nesting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T08:42:09.823", "Id": "37520", "Score": "0", "body": "Have to rethink this. How would prof oaks do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T08:49:29.483", "Id": "37521", "Score": "0", "body": "@SmartLemon Thats what me too wanted to know. But everyone pointing wats bad in this code not how to fix" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T08:52:05.057", "Id": "37522", "Score": "0", "body": "When resetting the values at the bottom you are creating an infinite loop inside the last loop. Unless you have done something to get around this..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T08:55:46.547", "Id": "37523", "Score": "0", "body": "@SmartLemon But it won't run infinity. Another method called in between will really fix it. But what should I do if I don't know how much time the for loop executes. I want to `LCycleTimeShift` until the list get optimized" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T09:04:59.873", "Id": "37525", "Score": "3", "body": "This smells like feature envy (http://c2.com/cgi/wiki?FeatureEnvySmell) and it's breaking the Law of Demeter (http://c2.com/cgi/wiki?LawOfDemeter). Clean it up, move logic into respective classes. The inner logic most definately belongs in Stage or Tool, and some of the fors probably belong in LCycle. The code you pasted should read something like foreach(var cycle in TimeLineInit) cycle.MakeTimeShifts();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T09:16:45.123", "Id": "37526", "Score": "0", "body": "@Lars-Erik But why always foreach gets more preference. Most of the advices was about foreach" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T11:30:12.550", "Id": "37530", "Score": "0", "body": "I agree with @Lars-Erik. You would need two for loops, though. \nI also believe these `List<LCycle> TimeLineInit` is in some aggregate root [That is, whatever object owns this list]. And this method method belongs there. \nAnd call it like so :`aggregateRoot.MakeTimeShifts()`.\n\nMethod signature is very telling. Receiving, modifying elements and returning a collection...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:22:29.673", "Id": "37610", "Score": "0", "body": "@Subin use whichever loop suits you, but move each indentation to its respective responsible class." } ]
[ { "body": "<p>This does not reduce nesting per se, but it reduces clutter for all loop variables that are not really used:</p>\n\n<pre><code>public List&lt;LCycle&gt; ToolArrangment(List&lt;LCycle&gt; TimeLineInit)\n{\n for (int i = 0; i &lt; TimeLineInit.Count; i++) //Each LIfeCycles In TimeLine\n {\n stages:\n for (int k = 0; k &lt; i; k++) //Each LifeCycles Upto Current LifeCycle\n foreach (var stageA in TimeLineInit[i].Stage)\n foreach (var stageB in TimeLineInit[k].Stage)\n foreach (var toolA in stageA.ToolList)\n foreach (var toolB in stageB.ToolList)\n {\n if ( //If both tools are same (satidfying above for loop conditions)\n toolA.ToolName == toolB.ToolName\n //tool using at same time.\n &amp;&amp; IsTimeOverLaps(stageA.StageSpan, stageB.StageSpan))\n {\n Stage ReplaceStage = stageA.DeepCopy(); //Taking Copy of stage Span to make time shift\n Double TimeDifference = (ReplaceStage.StageSpan.ToTime - ReplaceStage.StageSpan.FromTime).TotalMinutes;\n //Calculating required time shift\n ReplaceStage.StageSpan.FromTime = stageB.StageSpan.ToTime; //FromTime changed accordingly\n ReplaceStage.StageSpan.ToTime = ReplaceStage.StageSpan.ToTime.AddMinutes(TimeDifference); //To Time Changed accordingly\n LCycleTimeShift(TimeLineInit[i], ReplaceStage); //passing refernce\n\n goto stages;\n }\n }\n }\n\n return TimeLineInit;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T10:18:19.537", "Id": "37528", "Score": "1", "body": "http://xkcd.com/292/ ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T10:28:08.867", "Id": "37529", "Score": "0", "body": "@GCATNM: Yeah, but that's a rare specimen of a good `goto`. Seriously it's _the_ reason it's left in the language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:18:07.567", "Id": "37532", "Score": "0", "body": "foreach is recommended for better readabilty! rite?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:31:48.413", "Id": "37534", "Score": "2", "body": "@SubinJacob: Yes, IMHO `foreach` yields code that's a lot more readable. Consider `item` vs. `MyWordlyNamedCollectionsCollection[k].Items[i]`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T10:08:16.893", "Id": "24332", "ParentId": "24303", "Score": "2" } }, { "body": "<p>First, having this many nested loops indicates that your algorithm could have really bad time complexity. And with the way you're resetting the indexes, I'm not even sure your code is guaranteed to complete. There may be a more efficient algorithm to do what you want, but I'm not going to try to find that.</p>\n\n<p>Second, the <code>i</code>, <code>j</code>, <code>k</code> naming convention for loop variables is okay if you have two or maybe three nested loops. But with six levels, it makes your code much less readable (and more error-prone). You should consider using locals with reasonable names instead of expressions like <code>TimeLineInit[i].Stage[j].ToolList[m]</code>. Or even better, <code>foreach</code> loops, which basically do the same with less code.</p>\n\n<p>Third, I think the code you're using for resetting is wrong. For example, when <code>i = 0</code> and you reset the loop variables, you end up running the innermost loop with <code>i = 0</code> and <code>k = 0</code>, which should never happen (since the invariant is <code>k &lt; i</code>).</p>\n\n<p>Fourth, I think that a method that takes something as a parameter, modifies it and then returns it is a code smell. One exception would be a fluent interface, but that doesn't seem to be your case, since the method is not an extension method.</p>\n\n<p>Fifth, you should use normal .Net naming conventions (e.g. <code>camelCase</code> for local variables, instead of <code>PascalCase</code>).</p>\n\n<p>Sixth, you should do all your time calculations in <code>TimeSpan</code>s, instead of <code>double</code>s representing minutes, because it's simpler.</p>\n\n<p>Seventh, I think you could make your code more readable using LINQ.</p>\n\n<p>The whole code would look something like:</p>\n\n<pre><code>public void ToolArrangment(List&lt;LCycle&gt; timeLineInit)\n{\n foreach (var lifeCycle1 in timeLineInit)\n {\n bool repeat;\n do\n {\n repeat = false;\n\n var stages = (from stage1 in lifeCycle1.Stage\n from lifeCycle2 in timeLineInit.TakeWhile(lc2 =&gt; lc2 != lifeCycle1)\n from stage2 in lifeCycle2.Stage\n from tool1 in stage1.ToolList\n from tool2 in stage2.ToolList\n where tool1.ToolName == tool2.ToolName\n where IsTimeOverLaps(stage1.StageSpan, stage2.StageSpan)\n select new { stage1, stage2 })\n .FirstOrDefault();\n\n if (stages != null)\n {\n var replaceStage = stages.stage1.DeepCopy();\n var timeDifference = replaceStage.StageSpan.ToTime - replaceStage.StageSpan.FromTime;\n replaceStage.StageSpan.FromTime = stages.stage2.StageSpan.ToTime;\n replaceStage.StageSpan.ToTime = replaceStage.StageSpan.ToTime + timeDifference;\n LCycleTimeShift(lifeCycle1, replaceStage);\n repeat = true;\n }\n } while (repeat);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I gave it some thought and I think a much more efficient algorithm to do the same is not that difficult. You would have a hash table indexed by <code>ToolName</code> and for each tool, you would keep a list of all known stages that use it. You would walk though all tools in all stages in all timelines and add them to the list of stages for that tool. If you couldn't do that because of an overlap, you would move the stage, just like you do right now (if I understand your code correctly).</p>\n\n<p>I haven't though out all the details, but I think something like this should work and be much faster than your solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T05:34:14.733", "Id": "37587", "Score": "0", "body": "What the meaning of `.FirstOrDefault();`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T05:37:48.770", "Id": "37588", "Score": "0", "body": "I didn't understand the fourth statement. Were you speaking about `LCycleTimeShift`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:26:25.740", "Id": "37599", "Score": "0", "body": "@SubinJacob You always want to take the first pair of stages that fulfills the conditions, modify the structure accordingly and then start from the beginning. `FirstOrDefault()` is there to get that first pair. If there is no matching pair, it will return `null`, which lets it exist the `do`-`while` cycle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:27:46.450", "Id": "37600", "Score": "0", "body": "@SubinJacob No, I was speaking about `ToolArrangment()`. It takes the whole list as a parameter, modifies some objects inside it and then returns it. That's a pattern that doesn't make much sense, I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:55:02.953", "Id": "37601", "Score": "0", "body": "But why that pattern doesn't make sense? passing a large data structure is not recommended? why? (I think, you were asking to send only the object that needed for rearrangement)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:07:03.857", "Id": "37611", "Score": "0", "body": "@SubinJacob That's not it. It's that there is no reason to return it, since the caller already has the structure. So you should make the `ToolArrangment()` method `void`-returning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:51:10.080", "Id": "37613", "Score": "0", "body": "but only if a reference type, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:53:32.623", "Id": "37614", "Score": "0", "body": "Once I was advised its better to use value types since it could enhance readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:16:36.507", "Id": "37640", "Score": "0", "body": "@SubinJacob Yeah, but almost all mutable types in .Net are reference types. And custom value types should be used only very rarely, I'm not sure how would they enhance readability." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T21:59:24.700", "Id": "24359", "ParentId": "24303", "Score": "5" } } ]
{ "AcceptedAnswerId": "24359", "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T10:55:24.270", "Id": "24303", "Score": "3", "Tags": [ "c#", "design-patterns" ], "Title": "Reduce nested for loops and if statements using Iterator Blocks?" }
24303
<p>I've been teaching myself a bit of web design and development over the past month or so, coming from an CG/VFX background with no prior experience so it's been a bit alien to me to say the least.</p> <p>I found the excellent Javascript is Sexy guide and have been going through it, but today was project time. I must admit I felt kinda stumped. I thought I was getting a good handle on it but then when the hand-holding stops, it gets a bit overwhwelming.</p> <p>Anyway, I've done the 'quiz' assignment, but I have no idea if this is good or terrible, or on the right track.</p> <p><a href="http://jsfiddle.net/TeeJayEllis/3q8fs/" rel="nofollow">http://jsfiddle.net/TeeJayEllis/3q8fs/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var totalScore = 0; var questionNumber = 0; var allQuestions = [{ question: "Who is Prime Minister of the United Kingdom?", choices: ["Tony Blair", "Gordon Brown", "Winston Churchill", "David Cameron"], correctAnswer: "David Cameron" }, { question: "What is the capital city of Spain?", choices: ["Barcelona", "London", "Madrid", "Lisbon"], correctAnswer: "Madrid" }, { question: "How many strings does a guitar have?", choices: ["Three", "Four", "Five", "Six"], correctAnswer: "Six" }, { question: "What year did MTV launch?", choices: ["1980", "1992", "1981", "1979"], correctAnswer: "1981" } ]; var correctGuess = function(i) { totalScore += 1; questionNumber ++; $('#questionDiv').fadeOut("slow"); $('#mainContent').empty(); $('#mainContent').append('&lt;div id="answerDiv"&gt;&lt;/div&gt;'); $('#answerDiv').append('&lt;h1&gt;Correct!&lt;h1&gt;'); $('#answerDiv').append('&lt;h2&gt;Total Score: ' + totalScore + '&lt;/h2&gt;' ); $('#answerDiv').fadeIn("slow"); if (totalScore &lt; 4) { $('#answerDiv').append('&lt;button id="nextButton"&gt;Next Question&lt;/button&gt;'); $('#nextButton').click(function() {question(questionNumber);}) } else { $('#answerDiv').append('&lt;h1&gt;Congratulations, you Win!'); $('#answerDiv').append('&lt;button id="restartButton"&gt;Play Again&lt;/button&gt;'); $('#restartButton').click(function() { questionNumber = 0; totalScore = 0; question(questionNumber);}) } }; var incorrectGuess = function(i) { totalScore = 0; questionNumber = 0; $('#questionDiv').fadeOut("slow"); $('#mainContent').empty(); $('#mainContent').append('&lt;div id="answerDiv"&gt;&lt;/div&gt;'); $('#answerDiv').append('&lt;h1&gt;Wrong!&lt;h1&gt;'); $('#answerDiv').fadeIn("slow"); $('#answerDiv').append('&lt;button id="restartButton"&gt;Restart&lt;/button&gt;'); $('#restartButton').click(function() {question(questionNumber);}) }; var question = function(i) { $('#questionDiv').fadeOut("slow"); $('#mainContent').empty(); $('#mainContent').append('&lt;div id="questionDiv"&gt;&lt;/div&gt;'); $('#questionDiv').append('&lt;h1&gt;Question ' + (i + 1) + '&lt;h1&gt;'); $('#questionDiv').append('&lt;h2&gt;' + allQuestions[i].question + '&lt;/h2&gt;'); $('#questionDiv').append('&lt;input type="radio" name="questionChoices" value="' + allQuestions[i].choices[0] + '" checked="yes"&gt;' + allQuestions[i].choices[0] + '&lt;/input&gt;'); $('#questionDiv').append('&lt;input type="radio" name="questionChoices" value="' + allQuestions[i].choices[1] + '"&gt;' + allQuestions[i].choices[1] + '&lt;/input&gt;'); $('#questionDiv').append('&lt;input type="radio" name="questionChoices" value="' + allQuestions[i].choices[2] + '"&gt;' + allQuestions[i].choices[2] + '&lt;/input&gt;'); $('#questionDiv').append('&lt;input type="radio" name="questionChoices" value="' + allQuestions[i].choices[3] + '"&gt;' + allQuestions[i].choices[3] + '&lt;/input&gt;'); $('#questionDiv').append('&lt;button id="submitButton"&gt;Submit&lt;/button&gt;'); $('#questionDiv').fadeIn("slow"); $('#submitButton').click(function() { if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer &amp;&amp; i &lt; 4) { correctGuess(); } else { incorrectGuess(); } }) }; question(questionNumber);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#mainContent { margin-top: 50px; padding-top: 100px; width: 600px; height: 300px; border: 5px black solid; margin-left: auto; margin-right: auto; text-align: center; } button { display: block; margin-left: auto; margin-right: auto; margin-top: 10px; } #questionDiv { display: none; } #answerDiv { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="mainContent"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T14:57:01.413", "Id": "37482", "Score": "0", "body": "There is something one should understand when programming in client-side javascript: the DOM is slow. Awfully slow. Very very slow. You have to use the DOM the least possible times. 2 times is too much. And I'm serious, the horrible performance of the DOM is noticeable." } ]
[ { "body": "<p>Overall, it's ok.</p>\n\n<p>Several points though:</p>\n\n<ul>\n<li><strong>The DOM is slow.</strong> Really. Calling it ten times when it's possible to do it only once is awful.</li>\n<li>To follow this, cache your selectors. <code>$</code> is a function returning an object. And you're calling it every time you use <code>$(arg)</code>.</li>\n<li>Be consistent. Why do you use these two forms? <code>totalScore += 1; questionNumber ++;</code>. They're doing exactly the same, yet you use two different ways to do the same thing.</li>\n<li>Why don't you declare your functions with the simple form? <code>function correctGuess()</code>... Your form doesn't change much in your case, but hoisting could hurt you later.</li>\n<li>Don't do one-liners. <code>$('#nextButton').click(function() {question(questionNumber);})</code> is impossible to read.</li>\n<li>Why are you having an <code>i</code> argument to <code>correctGuess</code> and <code>incorrectGuess</code>? You're not using it at all.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:12:52.010", "Id": "37495", "Score": "0", "body": "Thanks, Florian.\n\nI didn't even know using the DOM so much was frowned upon! Complete beginner!\n\nSo, what is a more appropriate alternative? I was just going by the assignment from the guide I was using which suggests generating a dynamic quiz with either JQuery or JavaScript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:22:45.557", "Id": "37496", "Score": "0", "body": "@TomEllis Well, in your example, it's better to create a single string that you concatenate. This way, you have only one interaction with the DOM (when you'll `html(str)`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:34:42.420", "Id": "37497", "Score": "0", "body": "Some reading on the `.append()` method you might want to check out: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:01:55.827", "Id": "37531", "Score": "0", "body": "@TomEllis the DOM is not frowned upon. It's essential! But it's also well known that it's very slow, and must thus be handled specifically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:24:23.130", "Id": "37538", "Score": "0", "body": "Ok thanks guys. I still don't really get it, I'm not even sure how to use the concatenation as you suggested.\n\nI think I'll hit the books a bit more!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T15:03:23.957", "Id": "24309", "ParentId": "24308", "Score": "5" } }, { "body": "<p>One thing you should always consider is \"namespacing\" your code (basically putting all of your code into one object), or \"hiding\" it in an an anonymous function. This helps keeping the global namespace clean, which becomes relevant when you have other people's JavaScript in your page.</p>\n\n<p>Regarding the DOM mentioned by the others: You should anyway keep the \"separation of concerns\" in mind and instead of building the HTML in your script (which is slow), put as much of the HTML into the, well, HTML as possible. Example:</p>\n\n<pre><code>&lt;div id=\"questionDiv\"&gt;\n &lt;h1&gt;Question &lt;span&gt;&lt;/span&gt;&lt;h1&gt;\n &lt;h2&gt;&lt;/h2&gt;\n &lt;input type=\"radio\" value=\"\" checked id=\"answer1\"&gt;&lt;label for=\"answer1\"&gt;&lt;/label&gt;\n &lt;input type=\"radio\" value=\"\" id=\"answer2\"&gt;&lt;label for=\"answer2\"&gt;&lt;/label&gt;\n &lt;input type=\"radio\" value=\"\" id=\"answer3\"&gt;&lt;label for=\"answer3\"&gt;&lt;/label&gt;\n &lt;input type=\"radio\" value=\"\" id=\"answer4\"&gt;&lt;label for=\"answer4\"&gt;&lt;/label&gt;\n &lt;button type=\"button\"&gt;Submit&lt;/button&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And in the JavaScript:</p>\n\n<pre><code>var questionDiv = $('#questionDiv');\nquestionDiv.find('h1 &gt; span').text(i + 1);\nquestionDiv.find('h2').text(allQuestions[i].question);\nquestionDiv.find('input[type=radio]').each(function(index) {\n var choice = allQuestions[i].choices[index];\n $(this).val(choice).next('label').text(choice);\n});\n</code></pre>\n\n<p>You can do simularly with the right and wrong answer divs. </p>\n\n<p>Also if you do this keep in mind you'll only need to assign the event handlers once and not for each question.</p>\n\n<p>BTW, you are generating invalid HTML. There is not such thing as a closing <code>&lt;/input&gt;</code> tag. Use a label as I did.</p>\n\n<p>Also <code>checked=\"yes\"</code> is wrong too. It's either <code>checked=\"checked\"</code> or just <code>checked</code>.</p>\n\n<p>Finally don't forget <code>type=\"button\"</code> on the button, or it will be a real submit button that submits to the server.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T20:18:18.810", "Id": "37662", "Score": "0", "body": "In xhtml you are expected to close input tags, e.g. `<input type=\"radio\" value=\"\" id=\"answer2\" />`. I think html 5 is flexible, you can self close or not - you are right about never using `</input>` though!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:41:31.760", "Id": "24348", "ParentId": "24308", "Score": "1" } }, { "body": "<p>I've worked on you're code yo provide you with an actual code example. I've re-done most of the code to show you and I've explained it all with comments. Here's the link to the <a href=\"http://jsfiddle.net/3q8fs/3/\" rel=\"nofollow\">Fiddle</a> and I'll be happy to answer any questions you might have.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>var totalScore = 0, //You only need to say 'var' once. If you want to declare more, just use a ',' between each one.\n questionNumber = 0,\n allQuestions = [{\n question: \"Who is Prime Minister of the United Kingdom?\",\n choices: [\"Tony Blair\", \"Gordon Brown\", \"Winston Churchill\", \"David Cameron\"],\n correctAnswer: \"David Cameron\"\n },\n {\n question: \"What is the capital city of Spain?\",\n choices: [\"Barcelona\", \"London\", \"Madrid\", \"Lisbon\"],\n correctAnswer: \"Madrid\"\n },\n {\n question: \"How many strings does a guitar have?\",\n choices: [\"Three\", \"Four\", \"Five\", \"Six\"],\n correctAnswer: \"Six\"\n },\n {\n question: \"What year did MTV launch?\",\n choices: [\"1980\", \"1992\", \"1981\", \"1979\"],\n correctAnswer: \"1981\"\n }\n];\n\n//As a rule of thumb, if you use a selection more than once you should cahce it. Like this:\nvar mainContent = $('#mainContent'); //Now we replace all the $('#mainContent') with a simple 'mainContent' reference.\n\nfunction correctGuess (i) { //Name your functions the easy way.\n totalScore ++; //+=1 is the same thing as ++\n questionNumber ++;\n\n var updatePage = ['&lt;div id=\"answerDiv\"&gt;' +\n '&lt;h1&gt;Correct!&lt;h1&gt;' +\n '&lt;h2&gt;Total Score: ' + totalScore + '&lt;/h2&gt;&lt;/div&gt;'\n ], // This is how you concatenate. We join all the items we want to put in first, then call a single append.\n whereToPut = updatePage[0].length -6; //We want to put it at the end of the text, but before the &lt;/div&gt;\n\n if(totalScore &lt; 4){\n var whatToPut = '&lt;button id=\"nextButton\"&gt;Next Question&lt;/button&gt;';\n\n\n //Here we place the nextQuestion variable intro the updatePage variable at the end just before the closing div\n updatePage = [updatePage.slice(0, whereToPut), whatToPut, updatePage.slice(whereToPut)].join('');\n\n $('#mainContent').html(updatePage); //You don't need to empty out the div every time, just replace what is there using .html().\n //Notice how we use it only once.\n\n $('#nextButton').on('click', function() { //Using this .on() method, you save a function call because .click() calls the .on(), so you might as well jump straight there.\n question(questionNumber); //Don't do one liner functions\n });\n } else {\n //Same thing as before\n var whatToPut = '&lt;h1&gt;Congratulations, you Win!&lt;/h1&gt;&lt;button id=\"restartButton\"&gt;Play Again&lt;/button&gt;';\n\n updatePage = [updatePage.slice(0, whereToPut), whatToPut, updatePage.slice(whereToPut)].join('');\n\n $('#mainContent').html(updatePage);\n\n $('#restartButton').on('click', function() {\n questionNumber = 0;\n totalScore = 0;\n question(questionNumber);\n });\n }\n\n $('#answerDiv').fadeIn(\"slow\");\n};\n\nfunction incorrectGuess(i) {\n //Same as before, concatenate and append a single time.\n totalScore = 0;\n questionNumber = 0;\n\n $('#questionDiv').fadeOut(\"slow\");\n\n var updatePage = ['&lt;div id=\"answerDiv\"&gt;&lt;/div&gt;' +\n '&lt;h1&gt;Wrong!&lt;h1&gt;' +\n '&lt;button id=\"restartButton\"&gt;Restart&lt;/button&gt;'\n ];\n\n $('#mainContent').html(updatePage);\n $('#answerDiv').fadeIn(\"slow\");\n\n $('#restartButton').on('click', function() {\n question(questionNumber);\n });\n};\n\nfunction question(i) {\n $('#questionDiv').fadeOut(\"slow\");\n mainContent.html('&lt;div id=\"questionDiv\"&gt;' +\n '&lt;h1&gt;Question ' + (i + 1) + '&lt;h1&gt;' +\n '&lt;h2&gt;' + allQuestions[i].question + '&lt;/h2&gt;' +\n '&lt;input type=\"radio\" name=\"questionChoices\" value=\"' + allQuestions[i].choices[0] + '\" checked=\"yes\"&gt;' + allQuestions[i].choices[0] + '&lt;/input&gt;' +\n '&lt;input type=\"radio\" name=\"questionChoices\" value=\"' + allQuestions[i].choices[1] + '\"&gt;' + allQuestions[i].choices[1] + '&lt;/input&gt;' +\n '&lt;input type=\"radio\" name=\"questionChoices\" value=\"' + allQuestions[i].choices[2] + '\"&gt;' + allQuestions[i].choices[2] + '&lt;/input&gt;' +\n '&lt;input type=\"radio\" name=\"questionChoices\" value=\"' + allQuestions[i].choices[3] + '\"&gt;' + allQuestions[i].choices[3] + '&lt;/input&gt;' +\n '&lt;button id=\"submitButton\"&gt;Submit&lt;/button&gt;' +\n '&lt;/div&gt;'\n );\n $('#questionDiv').fadeIn(\"slow\");\n\n $('#submitButton').on('click', function() {\n if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer &amp;&amp; i &lt; 4) {\n correctGuess();\n } else {\n incorrectGuess();\n }\n });\n};\n\nquestion(questionNumber);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T17:02:36.033", "Id": "24352", "ParentId": "24308", "Score": "1" } } ]
{ "AcceptedAnswerId": "24352", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T14:36:03.427", "Id": "24308", "Score": "4", "Tags": [ "javascript", "beginner", "jquery", "quiz" ], "Title": "Beginner's quiz with jQuery" }
24308
<p>This page (<a href="http://bl.ocks.org/byrongibson/5232838" rel="nofollow">full source &amp; demo</a>) displays a 2-channel horizontal <a href="http://bl.ocks.org/mbostock/4060954" rel="nofollow">d3.js Streamgraph</a> that takes realtime mouse coordinates as data inputs for the graph.</p> <p>However, it tends to gradually use up an increasing amount of memory until there's none left, both on Chrome and Firefox (on Ubuntu 12.04 x64). Data is being collected but not released, yet the arrays that hold the incoming mouse coord data are being popped for every push, and I'm missing where the problem is occuring.</p> <p>I'm working on profiling it, but wondering if any JS experts can eyeball it and see it. The only dependencies are JQuery and D3.js v3.</p> <pre><code>&lt;body&gt; &lt;div id="chart"&gt;&lt;/div&gt; &lt;script&gt; var l = 2; // number of stream channels (layers) var n = 100; // number of samples per layer var random = d3.random.normal(0, .2); var a = []; var b = []; /* Normalize mouse coords to a 0:1 range for d3. */ var denom = { x: $(window).width(), y: $(window).height() }; var currentMouseCoord = { x: 1, y: 1 }; /* While mouse is moving over the streamgraph iframe, replace data stream with realtime normalized mouse coords */ $(document).mousemove(function(e) { currentMouseCoord.x = e.pageX/denom.x; currentMouseCoord.y = e.pageY/denom.y; }).mouseover(); /* When mouse leaves the streamgraph iframe, reset data stream to constant 1 */ $(document).mouseout(function(e) { currentMouseCoord.x = 1; currentMouseCoord.y = 1; }).mouseout(); function stream_layers(l, m, o) { return d3.range(l).map(function(d,i) { if (i == 0) { for (idx = 0; idx &lt; m; idx++) a[idx] = currentMouseCoord.x; return a.map(stream_index); } else if (i ==1) { for (idx = 0; idx &lt; m; idx++) b[idx] = currentMouseCoord.y; return b.map(stream_index); } }); } function update_layers(l, m, o) { return d3.range(l).map(function(d,i) { if (i == 0) { a[m] = currentMouseCoord.x; return a.map(stream_index); } else if (i == 1) { b[m] = currentMouseCoord.y; return b.map(stream_index); } }); } function stream_index(d, i) { return {x: i, y: Math.max(0, d)}; } var data0 = d3.layout.stack().offset("wiggle")(stream_layers(l,n,0)); var data1 = d3.layout.stack().offset("wiggle")(stream_layers(l,n,0)); //var color = d3.interpolateRgb("#aad", "#556"); var color = d3.interpolateRgb("#f30", "#fdb"); var w = $(window).width(); var h = 150; var mx = n - 1; var my = d3.max(data0.concat(data1), function(d) { return d3.max(d, function(d) { return d.y0 + d.y; }); }); var area = d3.svg.area() .x(function(d) { return d.x * w / mx; }) .y0(function(d) { return h - d.y0 * h / my; }) .y1(function(d) { return h - (d.y + d.y0) * h / my; }); var vis = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); vis.selectAll("path") .data(data0) .enter().append("path") .style("fill", function() { return color(Math.random()); }) .attr("d", area); function transition() { a.push(.01 + .01*Math.random()); b.push(.01 + .01*Math.random()); data0 = d3.layout.stack().offset("wiggle")(update_layers(l,n,0)); vis.selectAll("path").data(data0).attr("d", area).attr("transform", null).transition().duration(40).ease("linear").attr("transform", "translate(" + -w/n + ")").each("end", function (d,i) { if (i==0) transition();}); a.shift(); b.shift(); } $(document).ready(transition()); &lt;/script&gt; </code></pre> <p></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T20:43:46.333", "Id": "37501", "Score": "1", "body": "You use `$(window)` and `$(document)` quite a bit, so you might want to wrap with an IIFE and pass `document` and `window` into to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T18:58:44.990", "Id": "62344", "Score": "1", "body": "I profiled your code on Chrome, your memory usage is stable, everything gets properly de-allocated. I suspect the problem is in WebGL, do you have up to date video drivers ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-22T04:07:58.977", "Id": "63043", "Score": "0", "body": "Thanks, I was using a computer with an i3 with integrated gpu only, so that was probably the problem. Much appreciated!" } ]
[ { "body": "<p>I am happy your problem is solved. All in all, your code looks solid, my review is mostly nitpicking:</p>\n\n<ul>\n<li><p>I am all for spartan coding, but you have far too many 1 and 2 character variables, you ought to use more meaningful variables.</p></li>\n<li><p>Try to have 1 <code>var</code> block at the top. More specifically, you declare <code>data0</code> after declaring the function <code>stream_layers</code>, there is no need for that.</p></li>\n<li><p>Please use lowerCamelCase coding, so <code>update_layers</code> -> <code>updateLayers</code></p></li>\n<li><p>There is no need to call <code>.mouseover();</code> after setting the listener, especially since you also call <code>.mouseout();</code> afterwards for which there is also no need as you already set <code>x</code> and <code>y</code> to 1 with <code>var currentMouseCoord = { x: 1, y: 1 };</code></p></li>\n<li><p>You can drop curly braces after loops, please don't drop newlines.</p></li>\n<li><p><code>vis.selectAll(\"path\").data(data0).attr....</code> in <code>transition()</code> really should be broken out into multiple lines.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T21:52:12.410", "Id": "64477", "Score": "0", "body": "Thanks, I'll make a pass on the production version incorporating your suggestions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-26T15:23:23.583", "Id": "38119", "ParentId": "24313", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T17:43:15.287", "Id": "24313", "Score": "4", "Tags": [ "javascript", "jquery", "memory-management", "d3.js" ], "Title": "d3.js realtime streamgraph memory usage" }
24313
<p>How well does this code limit security problems when uploading images to the server?</p> <pre><code>&lt;?php $filename = $_FILE['inputfile']['name']; $upload_path = 'images/'; //extract extension $ext = strtolower(substr($filename, strrpos($filename, '.') + 1)); // return mime type ala mimetype extension $finfo = finfo_open(FILEINFO_MIME_TYPE); //get MIME type of the given file $mime = finfo_file($finfo, $filename); //close finfo finfo_close($finfo); if (is_uploaded_file($_FILES['inputfile']['tmp_name'])) { //first check: file extension and mime type if(!in_array($ext, array('jpeg', 'jpg', 'gif', 'png')) &amp;&amp; !in_array($mime, array('image/jpeg', 'image/gif', 'image/png')) ){ die("Error1: Invalid Image type"); } //create image according to MIME type //first: JPEG and JPG if($ext == 'jpeg' || $ext == 'jpg'){ //move_uploaded_file ignored because no need to use it $im = @imagecreatefromjpeg($_FILE['inputfile']['tmp_name']); if($im){ $createimage = imagejpeg($im, $upload_path.$_FILE['inputfile']['name']); if(!$createimage){ die("Error3: Can't create image!"); } //last check $filecontent = file_get_contents($upload_path.$_FILE['inputfile']['name']); //clean the file from any php code //changed while(preg_match('#&lt;\?php|\?&gt;|&lt;\?#i', $filecontent)){ $filecontent = str_replace(array("&lt;?php", "&lt;?", "?&gt;"), "", $filecontent); } $handle = fopen($upload_path.$_FILE['inputfile']['name'], "wb"); fwrite($handle, $filecontent); fclose($handle); } else{ die("Error2: Invalid Image Detected"); } } } ?&gt; </code></pre> <p>Edit:</p> <pre><code> while(preg_match('#&lt;\?php|\?&gt;|&lt;\?#i', $filecontent)){ $filecontent = str_replace(array("&lt;?php", "&lt;?", "?&gt;"), "", $filecontent); } </code></pre>
[]
[ { "body": "<p>The whitelist of file extensions is a pretty good way to keep it secure. There are a couple other things you can do to safeguard from someone uploading different file types though.</p>\n\n<ol>\n<li><p>Add an .htaccess file that disables PHP files in the upload directory. This should protect from anyone injecting PHP code into an image.</p>\n\n<pre><code>&lt;IfModule mod_php5.c&gt;\nphp_flag engine off\n&lt;/IfModule&gt;\n</code></pre></li>\n<li><p>Use the <code>getimagesize()</code> function to verify there is a size before doing something. <code>getimagesize()</code> will return false if it doesn't have a size. For example:</p>\n\n<pre><code>if (getimagesize($image) === false) {\n die('This is an invalid file.');\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:25:47.847", "Id": "37533", "Score": "1", "body": "The `.htaccess` entry only prevents execution when directly accessing the image in the upload folder, but it doesn't prevent execution if the image is included via LFI." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T01:44:46.980", "Id": "24328", "ParentId": "24317", "Score": "1" } }, { "body": "<p>This is a bad example of correcting user input:</p>\n\n<pre><code>$filecontent = str_replace(array(\"&lt;?php\", \"&lt;?\", \"?&gt;\"), \"\", $filecontent);\n</code></pre>\n\n<p>I could still upload an image with the following comment in it:</p>\n\n<pre><code>&lt;?&lt;?phpphp echo \"this code gets executed\"; ??&gt;&gt;\n</code></pre>\n\n<p>because after your <code>str_replace</code> the comment would be</p>\n\n<pre><code>&lt;?php echo \"this code gets executed\"; ?&gt;\n</code></pre>\n\n<p>Instead of correcting user input, you should simply search for these strings reject and the image if it contains <code>&lt;?</code>. Why should you save the image anyway if you suspect an hacker attack? ;-)</p>\n\n<p><strong>Edit</strong>: This would be better</p>\n\n<pre><code>// test for opening php tags\n// including asp-style opening tags (http://www.php.net/manual/en/ini.core.php#ini.asp-tags)\nif(strpos($filecontent, \"&lt;?\") !== false || strpos($filecontent, \"&lt;%\") !== false) {\n // stop upload\n}\n</code></pre>\n\n<p><strong>Edit</strong>:\nAnd one other thing I forgot to mention. <strong>Never use the original filename of the upload without validating it!</strong></p>\n\n<p>Because you could receive a request like this:</p>\n\n<pre><code>POST /upload.php HTTP/1.1\nHost: localhost\nContent-Length: 318\nContent-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L\n\n------WebKitFormBoundaryePkpFF7tjBAqx29L\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"../hello.jpg\"\nContent-Type: image/jpeg\n\n&lt;?php echo \"evil code\"; ?&gt;\n------WebKitFormBoundaryePkpFF7tjBAqx29L\n</code></pre>\n\n<p>And the \"image\" file gets saved in the directory above.</p>\n\n<p>Better generate your own file names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:30:38.503", "Id": "24335", "ParentId": "24317", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T19:01:29.540", "Id": "24317", "Score": "1", "Tags": [ "php", "security", "php5", "file-system" ], "Title": "Securing an Image Upload Script" }
24317
<p>My postfix program essentially allows the user two input options to calculate a postfix equation:</p> <ul> <li>Confirmations after each input (after an input, the user is ask for another number, operator, or final result)</li> <li>No confirmation after each input (user is only asked for a number of inputs (values and operators), and the final result is shown after the loop)</li> </ul> <p>My original attempt at this program used the first option because I had trouble getting my program to tell the difference between a value and an operator (both are treated as ASCII values, which is normal). However, I used a better method (the second option) after learning about <code>atoi()</code>. Alongside these two functions, another function does all of the calculations for both functions.</p> <p>How could this program be improved for clarity and effectiveness? Should I even bother offering both options, even just for comparison's sake? I'm also not sure how much input validation I should provide, if it's really necessary.</p> <p><strong>NOTE</strong>: The <code>IntStack</code> class was written by an instructor of mine, and I'm just using it for simplicity and learning. As it is part of my own written code, I'm including it here so that my code's meaning is not lost. As it's not my own code, <strong><em>please do not review it</em></strong>. Only review my own code.</p> <p><strong>Postfix.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include "IntStack.h" using std::cout; using std::cin; int noConfirmationExecution(); int confirmationExecution(); void calcOperation(IntStack&amp;, char); int main() { int executionType; int calcTotal; cout &lt;&lt; "&gt;&gt;&gt; Execution Type:\n\n"; cout &lt;&lt; "(1) Values entered all at once (with no confirmations)\n"; cout &lt;&lt; "(2) Values entered one at a time (with confirmations)\n\n"; cin &gt;&gt; executionType; if (executionType == 1) calcTotal = noConfirmationExecution(); else if (executionType == 2) calcTotal = confirmationExecution(); cout &lt;&lt; "\n\n*** Total: " &lt;&lt; calcTotal &lt;&lt; "\n\n\n"; system("PAUSE"); return 0; } int noConfirmationExecution() { IntStack stack(20); char item = ' '; cout &lt;&lt; "\n&gt;&gt; Items ('s' to stop):\n\n"; cin &gt;&gt; item; while (item != 's') { int i = atoi(&amp;item); if (item != '+' &amp;&amp; item != '-' &amp;&amp; item != '*' &amp;&amp; item != '/') stack.push(i); else if (item == '+' || item == '-' || item == '*' || item == '/') calcOperation(stack, item); cin &gt;&gt; item; } int total; stack.pop(total); return total; } int confirmationExecution() { IntStack stack(20); int number; char _continue = 'Y'; char anotherNumber; char anotherOperator; cout &lt;&lt; "\n&gt; Number: "; cin &gt;&gt; number; stack.push(number); do { do { anotherNumber = 'n'; cout &lt;&lt; "\n&gt; Number: "; cin &gt;&gt; number; stack.push(number); cout &lt;&lt; "\n- Another Number (y/n)? "; cin &gt;&gt; anotherNumber; } while (anotherNumber != 'n'); do { anotherOperator = 'n'; char _operator; cout &lt;&lt; "\n&gt;&gt; Operator: "; cin &gt;&gt; _operator; calcOperation(stack, _operator); cout &lt;&lt; "\n- Another Operator (y/n)? "; cin &gt;&gt; anotherOperator; } while (anotherOperator != 'n'); cout &lt;&lt; "\n- Continue (y/n)? "; cin &gt;&gt; _continue; } while (_continue != 'n'); int total; stack.pop(total); return total; } void calcOperation(IntStack &amp;stack, char _operator) { int num1, num2; stack.pop(num2); stack.pop(num1); if (_operator == '+') stack.push(num1 + num2); else if (_operator == '-') stack.push(num1 - num2); else if (_operator == '*') stack.push(num1 * num2); else if (_operator == '/') stack.push(num1 / num2); } </code></pre> <hr> <p><strong>IntStack.h</strong></p> <blockquote> <pre><code>#ifndef INTSTACK_H #define INTSTACK_H class IntStack { private: int *stackArray; int stackSize; int top; public: IntStack(int); IntStack(const IntStack &amp;); ~IntStack(); void push(int); void pop(int &amp;); bool isFull() const; bool isEmpty() const; }; #endif </code></pre> </blockquote> <p><strong>IntStack.cpp</strong></p> <blockquote> <pre><code>#include &lt;iostream&gt; #include "IntStack.h" using namespace std; IntStack::IntStack(int size) { stackSize = size; stackArray = new int[size]; top = -1; } IntStack::IntStack(const IntStack &amp;obj) { // Create the stack array. if (obj.stackSize &gt; 0) stackArray = new int[obj.stackSize]; else stackArray = NULL; // Copy the stackSize attribute. stackSize = obj.stackSize; // Copy the stack contents. for (int count = 0; count &lt; stackSize; count++) stackArray[count] = obj.stackArray[count]; // Set the top of the stack. top = obj.top; } IntStack::~IntStack() {delete [] stackArray;} void IntStack::push(int num) { if (isFull()) { cout &lt;&lt; "The stack is full.\n"; } else { top++; stackArray[top] = num; } } void IntStack::pop(int &amp;num) { if (isEmpty()) { cout &lt;&lt; "The stack is empty.\n"; } else { num = stackArray[top]; top--; } } bool IntStack::isFull() const { bool status; if (top == stackSize - 1) status = true; else status = false; return status; } bool IntStack::isEmpty() const { bool status; if (top == -1) status = true; else status = false; return status; } </code></pre> </blockquote>
[]
[ { "body": "<p>Sure if you have too:</p>\n\n<pre><code>using std::cout;\nusing std::cin;\n</code></pre>\n\n<p>But are you really saving that much.</p>\n\n<p>Even forward declaration of functions, its nice to have the name of the parameters. It helps in understanding the context in which the function will be called.</p>\n\n<pre><code>void calcOperation(IntStack&amp;, char);\n</code></pre>\n\n<p>I leave the parameter names off when they are not used (so usually this only happens in overridden virtual functions).</p>\n\n<p>What happens if the user enters not one or two?<br>\nPersonally I would make this a command line flag. Under normal conditions just run without validation. With the command line flag '-h' it means a human is working interactively and thus will confirm values.</p>\n\n<p>Very platform specific:</p>\n\n<pre><code> system(\"PAUSE\");\n</code></pre>\n\n<p>There is no real need for this. In a terminal the application quitting is not a problem. In an IDE you just have to set a configuration option to stop the window closing. So you really should not need to bother with this.</p>\n\n<p>Personally I only return a value from main() if there is an option of failing.</p>\n\n<pre><code> return 0;\n</code></pre>\n\n<p>If the application always succeeds then no return is an indication that it will always work and thus no need to check for errors (note: in C++ main() is special and the compiler inserts <code>return 0</code> if it does not exist).</p>\n\n<p>Since you use the same stack in both situations. Why not declare it in main() and pass it in. Then if you need to modify it you only have one place to change (not two as in the current implementation).</p>\n\n<pre><code> IntStack stack(20);\n</code></pre>\n\n<p>Since <code>item</code> is a char. Any numbers can only be single digit. So using atoi() seems a waste. But it is also wrong. Because atoi() expects a <code>'\\0'</code> terminated C-String (you have not provided this you need a second character set to <code>'\\0'</code></p>\n\n<pre><code> cin &gt;&gt; item;\n\n while (item != 's')\n {\n int i = atoi(&amp;item);\n</code></pre>\n\n<p>To make this work you need:</p>\n\n<pre><code> cin &gt;&gt; item;\n while (item != 's)\n {\n int i = item - '0';\n</code></pre>\n\n<p>But to make it work with multi-characer numbers I think I would use std::string</p>\n\n<pre><code> std::string word;\n std::cin &gt;&gt; word;\n while (item != \"s\")\n {\n try\n {\n int i = boost::lexical_cast&lt;int&gt;(word);\n stack.push(i);\n }\n catch(...)\n {\n // handle + - * / here as they are not numbers;\n }\n</code></pre>\n\n<p>If you can't use boost then the same affect can be achieved with std::stringstream and a little more work.</p>\n\n<p>Your <code>while</code> loop looks like a <code>for(;;)</code> loop. So why not use it:</p>\n\n<pre><code> cin &gt;&gt; item;\n while(item != 's')\n {\n // STUFF\n cin &gt;&gt; item;\n }\n\n // I would write like this:\n for(cin &gt;&gt; item; item != 's'; cin &gt;&gt; item)\n {\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T01:15:26.540", "Id": "37512", "Score": "0", "body": "I primary use Visual C++, so I do need `system(\"PAUSE\")`. I am aware that it doesn't work on other platforms (I've coded C++ on Linux before). I was always told that I don't need to put variable names in prototypes, but I can do that anyway. I can also leave out `return 0` from now on, in those cases you've mentioned. I have also put the stack initialization in `main()`. I was unaware of the alternate syntax for `cin` (at the bottom), and I'll keep that in mind. I love learning about alternate syntax forms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T01:18:13.443", "Id": "37513", "Score": "0", "body": "I may need some additional help with the input (where you mentioned boost and `stringstream`). I apparently cannot use boost, but I can use `stringstream`. I just need to figure out how to use it with numbers and operators (going back to `atoi`, which I mentioned before)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T03:04:04.770", "Id": "37952", "Score": "0", "body": "@JamalA: See third answer below." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T00:54:40.530", "Id": "24326", "ParentId": "24324", "Score": "2" } }, { "body": "<p>Convert string to any type:</p>\n\n<pre><code>template&lt;typename ResultType&gt;\nResultType lexical_cast(std::string const&amp; input, bool useAll = true)\n{\n std::stringstream inputstream(input);\n ResultType result;\n\n // Try and convert.\n // A failed conversion results in an exception.\n if (!inputstream &gt;&gt; result)\n { throw std::runtime_error(\"Failed to convert\");\n }\n\n char x;\n if (useAll &amp;&amp; inputstream &gt;&gt; x)\n {\n // If the above operations worked.\n // This means that there was more data in the input string\n // that was not used in the conversion to ResultType\n // \n // Say the input string was 5.2\n // If you convert this to int then the `result` is 5\n // but you have left \".2\" on the input stream this may be a problem.\n // So this is a test for non white space characters left on the input.\n\n throw std::runtime_error(\"Not all data used in conversion\");\n }\n\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>int x = lexical_cast&lt;int&gt;(\"5\");\nfloat y = lexical_cast&lt;float&gt;(\"5.678\");\n\nint x = lexical_cast&lt;int&gt;(\"5.2\", false); // false shows you don't\n // care about left over data.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T03:55:04.163", "Id": "37954", "Score": "0", "body": "If you want it to work with just ints. Then remove the line `template<typename ResultType>` and replace all occurences of `ResultType` with `int`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T03:55:48.713", "Id": "37955", "Score": "0", "body": "Okay, I'll try that. Please take a look at the updated code in case there are other problems. I apologize for this request becoming off-topic for this site. It doesn't seem necessary to duplicate it on Stack Overflow, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T18:14:47.507", "Id": "37989", "Score": "0", "body": "Okay, I found the problem. The `pop()` function in MyStack had a bug, but I fixed it. I tested the program after that, and everything worked. My original stringstream was correct as well, allowing me to use multi-digit numbers. I'll change that line in the code and finally put this case to a close." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T03:02:55.140", "Id": "24583", "ParentId": "24324", "Score": "2" } }, { "body": "<p>Here are what I think. </p>\n\n<ul>\n<li>Don't use system(\"PAUSE\"), you can easily implement this functionality. It might works fine on Windows system, but will not work on Mac, and Linux. </li>\n<li>When the stack is full, your program returned an incorrect result. If you have learned about exception handling, this is a good opportunity to use it. Instead of print out an error message, raise an exception and let the caller (<em>calcTotal</em>) handle it.</li>\n<li>In general, you should spell out an identifier (function name, variable name, …) instead of abbreviate it. For example <em>convertedNumber</em> is better than <em>convItem</em>.</li>\n<li>More about <em>convItem</em>: please name your identifier to reflect its role. I suggest using the name <em>operand</em> instead of <em>convItem</em>. Similarly, <em>operand1</em>, <em>operand2</em> are better than <em>num1</em>, <em>num2</em>, respectively.</li>\n<li>Use of blank lines: you should use blank lines to stragically organize your code (to separate out units such as functions, logical block of codes, …) However, too many blank lines make the code hard to follow due to the constant need of scrolling.</li>\n<li>Avoid using hard-coded constants such as \"+\", you should use constants with descriptive names such as OPERATOR_ADD, OPERATOR_SUBTRACT…</li>\n<li>Right now, your code assumes the items are just numbers, four operators and ignore any invalid tokens such as <em>sin</em>, <em>cos</em>, … It is better to flag them as errors than to ignore them.</li>\n<li><p>Keep in mind that using <code>std::istringstream</code> to convert a string to int is not robust: Try the following:</p>\n\n<pre><code>std::string buffer = \"Hello\";\nint portNumber = -1;\nstd::istringstream(buffer) &gt;&gt; portNumber; // failed, portNumber still = -1\n</code></pre></li>\n</ul>\n\n<h3>Update: About system(\"PAUSE\")</h3>\n\n<p>It seems the purpose of the pause command is to prevent Visual Studio from closing down the console. If that is the case, take a look at this <a href=\"https://stackoverflow.com/questions/1775865/visual-studio-console-app-prevent-window-from-closing\">stackoverflow discussion</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T19:53:52.340", "Id": "37995", "Score": "0", "body": "I only use `system(\"PAUSE\")` when I'm on Windows. I do remember to take out when I put it on another OS. As for everything else, I'll make the necessary changes and post them again later. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T23:03:34.367", "Id": "38007", "Score": "0", "body": "Post updated. I have kept system(\"PAUSE\") because it's just a hassle to find a better solution for it on Windows. The program has passed all of my testing, except -1 cannot be used for calculations (it's currently used for the error-handling). Is there an alternative, or do I just have to deal with one number (any number) being an invalid input?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T19:46:22.587", "Id": "24606", "ParentId": "24324", "Score": "1" } } ]
{ "AcceptedAnswerId": "24326", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T22:41:38.577", "Id": "24324", "Score": "3", "Tags": [ "c++", "stack", "math-expression-eval" ], "Title": "Calculating postfix notation using two forms of input" }
24324
<p>Im trying to get better at writing jQuery plugins. Was hoping to get some feedback on my notes, but also just about the general architechture and implenmentation of this pattern (dont even know this one is called :P)</p> <p>jsFiddle: <a href="http://jsfiddle.net/gajwp/4/" rel="nofollow">http://jsfiddle.net/gajwp/4/</a> Click the input fields! (No need to comment on positioning or stylnig, it looks better on my site)</p> <p>Project use jQuery 1.4.2 (so no .on() event handling :( )</p> <p>Notes:</p> <ul> <li>Should be DRY, short, fast, beautiful and all that :)</li> <li>Havent fully wrapped my head around the constructor/prototype thing. For instance, why am I creating the $bubble in the constructor and not in the prototype init() method? I hoping its because then its the same $bubble that is used throughout.</li> <li>I feel like there is a better way to build the bubble content. It must be possible to pass the plugin an object with the information. Tips welcome.</li> <li>In the template I used there was stuff like 'this._name = pluginName' in the constructor. What does the underscore mean, and what are the use for it?</li> <li>How is the event bindings? Was a bit confused about it because of the functionality. Popup should pop on fucus, and hide on blur. But not hide if focusing on a new field. Also if you click the popup or the "More..." link, it should also stay open - and close again if you click outside it.</li> </ul> <p>Plugin code (same as in fiddle):</p> <pre><code>;(function ($, window, document, undefined) { "use strict"; var pluginName = 'formHelper', $input, o, $bubble, stopBlurEvent, key, defaults = { position: "left", dataObject: { Default: { info: '&lt;p class="info"&gt;Default info&lt;/p&gt;&lt;a href="#" class="help-more"&gt;More...&lt;/a&gt;', extended: '&lt;p class="help-extended"&gt;Default extended...&lt;/p&gt;' }, Email: { info: '&lt;p class="info"&gt;Email info&lt;/p&gt;&lt;a href="#" class="help-more"&gt;More...&lt;/a&gt;', extended: '&lt;p class="help-extended"&gt;Email extended...&lt;/p&gt;' }, Name: { info: '&lt;p class="info"&gt;Name info&lt;/p&gt;&lt;a href="#" class="help-more"&gt;More...&lt;/a&gt;', extended: '&lt;p class="help-extended"&gt;Name extended...&lt;/p&gt;' } } }; function FormHelper(element, options) { var that = this; $input = $(element); o = $.extend({}, defaults, options); $bubble = $('&lt;div class="help-bubble" /&gt;').bind({ 'mouseenter': function() { stopBlurEvent = true; }, 'mouseleave': function() { stopBlurEvent = false; }, 'mousedown': function(e) { e.stopImmediatePropagation(); $('html').not(this).bind('click', function() { that.hideBubble(); }); } }).delegate('.help-more', 'click', function(e) { e.preventDefault(); e.stopPropagation(); that.toggleExtendedInfo(); }); this.init(); } FormHelper.prototype = { showBubble: function(input) { var $currentInput = $(input); key = (o.dataObject.hasOwnProperty($currentInput.attr('id'))) ? $currentInput.attr('id') : 'Default'; var bubbleContent = '&lt;h4&gt;' + $currentInput.attr('title') + '&lt;/h4&gt;' + o.dataObject[key].info; $bubble.html(bubbleContent).insertBefore($currentInput).fadeIn(); stopBlurEvent = false; }, hideBubble: function() { if (!stopBlurEvent) { $bubble.fadeOut('fast', function() { $(this).detach(); $('html').unbind('click'); }); } }, toggleExtendedInfo: function() { var $moreLink = $('.help-more', $bubble); if ($moreLink.hasClass('open')) { $moreLink.removeClass('open'); $('.help-extended', $bubble).slideUp('fast', function() { $(this).remove(); }); } else { $moreLink.addClass('open'); $(o.dataObject[key].extended).appendTo($bubble).slideDown(); } }, init: function() { var that = this; $input.bind({ 'focus': function() { that.showBubble(this); }, 'blur': function(e) { if (stopBlurEvent) { e.preventDefault(); } else { that.hideBubble(); } }, 'mousedown': function() { stopBlurEvent = true; } }); } }; $.fn[pluginName] = function(options) { return this.each(function() { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new FormHelper(this, options)); } }); }; })(jQuery, window, document); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T06:53:49.177", "Id": "37591", "Score": "0", "body": "I actually had the semicolon in ealier, but removed it because jslint diddnt like it. But your suggestion made me look it up at read about it, so now I understand WHY its a good idea to put it there :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T06:56:56.877", "Id": "37592", "Score": "0", "body": "The click binding on everything but the bubble, doesnt seem effective to me either. But couldnt find another way to know when the user clicks outside the bubble. Any ideas?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T07:01:29.193", "Id": "37594", "Score": "0", "body": "You're absolutely right about the init just calling another function. Refactored the code in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:02:26.727", "Id": "37636", "Score": "0", "body": "I've added to my answer according to your comments." } ]
[ { "body": "<p>It was fun going over your code. I haven't played with 1.4 for a while. Well here are some suggestions:</p>\n\n<ul>\n<li>Place a semicolon before your IIFE as a precaution against statements without a separator. Putting a semicolon before the function prevents the function from becoming an argument. This can happen when you minify and concat JS files.</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>(function(){...foo...})()(function(){...bar...})() //No separator :/\n(function(){...foo...})();(function(){...bar...})() //But you smart feller put in a semicolon\n</code></pre>\n\n<ul>\n<li>You bind a click to everything except the $bubble? Doesn't that seem a bit excessive?</li>\n</ul>\n\n<p>Right here:</p>\n\n<pre><code>$('html').not(this).bind('click', function() { \n that.hideBubble();\n});\n</code></pre>\n\n<ul>\n<li>About prototypes, it can be difficult to grasp at first, but keep at it, you'll have an \"Aha!\" moment soon enough where it will all become clear. My suggestion is read and read and practice. Here are some reading materials on the subject I would recommend:</li>\n</ul>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/ff852808.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/magazine/ff852808.aspx</a>\n- <a href=\"http://ejohn.org/apps/learn/#64\" rel=\"nofollow\">http://ejohn.org/apps/learn/#64</a></p>\n\n<ul>\n<li><p>For your plugin's data I would suggest <a href=\"http://handlebarsjs.com/\" rel=\"nofollow\">Handlebars.js</a>. It's an awesome templating engine that works with Mustache, so if you've used that before this one should be easy.</p></li>\n<li><p>There's a library called Underscore.js which provides functional programming support. But I think the <code>_name</code> you're referring to is simply a naming convention and does not carry any meaning to Javascript.</p></li>\n<li><p>Your entire <code>init:</code> function is there to simply call another function? Are you planning on putting more in there? If not I would suggest just going straight to binding.</p></li>\n<li><p>You use <code>$(input)</code> several times. You should cache that selector like you do elsewhere.</p></li>\n<li><p>This is just my nit-pickyness but I don't like single line functions. I just think they're harder to read. But don't lose any sleep over that.</p></li>\n</ul>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>If you really want to bind a click event to everything except <code>$bubble</code>, you can do it (jQuery 1.4 friendly) like this:</p>\n\n<pre><code>$(document).bind('click', function (e) {\n // Do whatever you want; the event that'd fire if the \"special\" element has been clicked on has been cancelled.\n});\n\n$('.help-bubble').bind('click', function(e) {\n e.stopPropagation();\n});\n</code></pre>\n\n<p>Now, what I would suggest you do instead is create a div outside of your main stack to handle this. Imagine an absolutely positioned div behind most of the page, and you only bind the event once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T07:08:33.087", "Id": "37596", "Score": "0", "body": "Nice, I'm commenting my question instead of your answer :P Sorry, and please see above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:46:58.067", "Id": "24341", "ParentId": "24334", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:27:00.713", "Id": "24334", "Score": "2", "Tags": [ "javascript", "jquery", "optimization", "plugin" ], "Title": "Optimizing my jQuery form popup plugin" }
24334
<p>According to instructions and sample code from <a href="http://msdn.microsoft.com/en-us/magazine/jj863137.aspx" rel="nofollow noreferrer">MSDN Magazine</a> and comments from post here <a href="https://stackoverflow.com/questions/15530143/deteminant-of-nn-matrix">determinant of n x n</a>...</p> <p>I changed code to be like this:</p> <pre><code>using System; internal class MatrixDecompositionProgram { private static void Main(string[] args) { float[,] m = MatrixCreate(4, 4); m[0, 0] = 3.0f; m[0, 1] = 7.0f; m[0, 2] = 2.0f; m[0, 3] = 5.0f; m[1, 0] = 1.0f; m[1, 1] = 8.0f; m[1, 2] = 4.0f; m[1, 3] = 2.0f; m[2, 0] = 2.0f; m[2, 1] = 1.0f; m[2, 2] = 9.0f; m[2, 3] = 3.0f; m[3, 0] = 5.0f; m[3, 1] = 4.0f; m[3, 2] = 7.0f; m[3, 3] = 1.0f; int[] perm; int toggle; float[,] luMatrix = MatrixDecompose(m, out perm, out toggle); float[,] lower = ExtractLower(luMatrix); float[,] upper = ExtractUpper(luMatrix); float det = MatrixDeterminant(m); Console.WriteLine("Determinant of m computed via decomposition = " + det.ToString("F1")); } // -------------------------------------------------------------------------------------------------------------- private static float[,] MatrixCreate(int rows, int cols) { // allocates/creates a matrix initialized to all 0.0. assume rows and cols &gt; 0 // do error checking here float[,] result = new float[rows, cols]; return result; } // -------------------------------------------------------------------------------------------------------------- private static float[,] MatrixDecompose(float[,] matrix, out int[] perm, out int toggle) { // Doolittle LUP decomposition with partial pivoting. // rerturns: result is L (with 1s on diagonal) and U; perm holds row permutations; toggle is +1 or -1 (even or odd) int rows = matrix.GetLength(0); int cols = matrix.GetLength(1); //Check if matrix is square if (rows != cols) throw new Exception("Attempt to MatrixDecompose a non-square mattrix"); float[,] result = MatrixDuplicate(matrix); // make a copy of the input matrix perm = new int[rows]; // set up row permutation result for (int i = 0; i &lt; rows; ++i) { perm[i] = i; } // i are rows counter toggle = 1; // toggle tracks row swaps. +1 -&gt; even, -1 -&gt; odd. used by MatrixDeterminant for (int j = 0; j &lt; rows - 1; ++j) // each column, j is counter for coulmns { float colMax = Math.Abs(result[j, j]); // find largest value in col j int pRow = j; for (int i = j + 1; i &lt; rows; ++i) { if (result[i, j] &gt; colMax) { colMax = result[i, j]; pRow = i; } } if (pRow != j) // if largest value not on pivot, swap rows { float[] rowPtr = new float[result.GetLength(1)]; //in order to preserve value of j new variable k for counter is declared //rowPtr[] is a 1D array that contains all the elements on a single row of the matrix //there has to be a loop over the columns to transfer the values //from the 2D array to the 1D rowPtr array. //----tranfer 2D array to 1D array BEGIN for (int k = 0; k &lt; result.GetLength(1); k++) { rowPtr[k] = result[pRow, k]; } for (int k = 0; k &lt; result.GetLength(1); k++) { result[pRow, k] = result[j, k]; } for (int k = 0; k &lt; result.GetLength(1); k++) { result[j, k] = rowPtr[k]; } //----tranfer 2D array to 1D array END int tmp = perm[pRow]; // and swap perm info perm[pRow] = perm[j]; perm[j] = tmp; toggle = -toggle; // adjust the row-swap toggle } if (Math.Abs(result[j, j]) &lt; 1.0E-20) // if diagonal after swap is zero . . . return null; // consider a throw for (int i = j + 1; i &lt; rows; ++i) { result[i, j] /= result[j, j]; for (int k = j + 1; k &lt; rows; ++k) { result[i, k] -= result[i, j] * result[j, k]; } } } // main j column loop return result; } // MatrixDecompose // -------------------------------------------------------------------------------------------------------------- private static float MatrixDeterminant(float[,] matrix) { int[] perm; int toggle; float[,] lum = MatrixDecompose(matrix, out perm, out toggle); if (lum == null) throw new Exception("Unable to compute MatrixDeterminant"); float result = toggle; for (int i = 0; i &lt; lum.GetLength(0); ++i) result *= lum[i, i]; return result; } // -------------------------------------------------------------------------------------------------------------- private static float[,] MatrixDuplicate(float[,] matrix) { // allocates/creates a duplicate of a matrix. assumes matrix is not null. float[,] result = MatrixCreate(matrix.GetLength(0), matrix.GetLength(1)); for (int i = 0; i &lt; matrix.GetLength(0); ++i) // copy the values for (int j = 0; j &lt; matrix.GetLength(1); ++j) result[i, j] = matrix[i, j]; return result; } // -------------------------------------------------------------------------------------------------------------- private static float[,] ExtractLower(float[,] matrix) { // lower part of a Doolittle decomposition (1.0s on diagonal, 0.0s in upper) int rows = matrix.GetLength(0); int cols = matrix.GetLength(1); float[,] result = MatrixCreate(rows, cols); for (int i = 0; i &lt; rows; ++i) { for (int j = 0; j &lt; cols; ++j) { if (i == j) result[i, j] = 1.0f; else if (i &gt; j) result[i, j] = matrix[i, j]; } } return result; } // -------------------------------------------------------------------------------------------------------------- private static float[,] ExtractUpper(float[,] matrix) { // upper part of a Doolittle decomposition (0.0s in the strictly lower part) int rows = matrix.GetLength(0); int cols = matrix.GetLength(1); float[,] result = MatrixCreate(rows, cols); for (int i = 0; i &lt; rows; ++i) { for (int j = 0; j &lt; cols; ++j) { if (i &lt;= j) result[i, j] = matrix[i, j]; } } return result; } } </code></pre> <p>Any comments or ideas on how to improve this code (especially this part):</p> <pre><code> //----tranfer 2D array to 1D array BEGIN for (int k = 0; k &lt; result.GetLength(1); k++) { rowPtr[k] = result[pRow, k]; } for (int k = 0; k &lt; result.GetLength(1); k++) { result[pRow, k] = result[j, k]; } for (int k = 0; k &lt; result.GetLength(1); k++) { result[j, k] = rowPtr[k]; } //----tranfer 2D array to 1D array END </code></pre> <p>...are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-26T17:30:24.850", "Id": "267212", "Score": "0", "body": "This code not can detriment matrix 4*4 ={0012,0051,6790,0795}" } ]
[ { "body": "<p>Optimizing for performance and readability you may want to avoid the 3 executions of the same loop:</p>\n\n<pre><code>for (int k = 0; k &lt; result.GetLength(1); k++){\n var swapTemp = result[pRow, k];\n result[pRow, k] = result[j, k]\n result[j, k] = swapTemp;\n}\n</code></pre>\n\n<p>You may also want to loop backwards (try it and see if it works out better for you):</p>\n\n<pre><code>for (int k = result.GetLength(1)-1; k &gt;= 0; k--)\n</code></pre>\n\n<p>And finally, something a little non-intuitive. Use double over float for accuracy and speed in .NET as your floats are probably converted to double anyway. CLR via C# covers this quirk but again, test it out as things may have changed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:40:41.433", "Id": "37558", "Score": "0", "body": "OK, I will try that. FLOAT is requested in much bigger complete program, this determinant calculation is just a part of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T22:42:17.117", "Id": "37569", "Score": "0", "body": "Why do you suggest looping backwards? I really doubt doing that would be more efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:12:52.833", "Id": "37639", "Score": "0", "body": "@svick I haven't tested it all around (so give it a try and see) but some list structures will have the Count property for example re-evaluated each iteration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T23:31:41.517", "Id": "37671", "Score": "0", "body": "@Dandy I think that would be an argument for caching that value in a local variable before the loop, not for looping backwards. That way, it's clear what are you doing and why. In any case, doing that would be a micro-optimization, which: 1. should not be done in normal code 2. should be supported by measuring the specific case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T16:49:39.743", "Id": "37781", "Score": "0", "body": "@svick Yeah, optimizing the iteration of that loop does reduce readability but what is \"normal code?\" Perhaps this is a special case and it may be beneficial to try or maybe not. It is my opinion which I am sharing that sometimes micro-optimization is OK and in some situations is desirable. I feel this swap is a great place for it especially if it is applied to many small matrices. Also forgot to mention that in addition to reducing evaluations of list count it may be possible for the JIT to remove range checking by changing the iteration." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T18:04:41.530", "Id": "24354", "ParentId": "24336", "Score": "2" } }, { "body": "<p><strong>Unused functions</strong></p>\n\n<p>Removing these 3 lines does not affect the final result.</p>\n\n<pre><code>float[,] luMatrix = MatrixDecompose(m, out perm, out toggle);\n\nfloat[,] lower = ExtractLower(luMatrix);\nfloat[,] upper = ExtractUpper(luMatrix);\n</code></pre>\n\n<p><strong>Comments</strong></p>\n\n<p>I don't really see the point in <code>// -----------------------------</code> on top of your methods. You can just type <code>///</code> which automatically propose a neat documentation, per example, in the MatrixCreate function : </p>\n\n<pre><code> /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n /// &lt;param name=\"rows\"&gt;&lt;/param&gt;\n /// &lt;param name=\"cols\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static float[,] MatrixCreate(int rows, int cols)\n</code></pre>\n\n<p><strong>Hardcoded values</strong></p>\n\n<p>They are usually a bad idea (what happens if, per example, you use this value somewhere else, and decide to change it someday?):</p>\n\n<pre><code> if (Math.Abs(result[j, j]) &lt; 1.0E-20) // if diagonal after swap is zero . . .\n return null; // consider a throw\n</code></pre>\n\n<p>Another option would be to have a <code>threshold</code> or <code>tolerance</code> value in your class.</p>\n\n<p><strong>Multiple accesses inside the same loop</strong></p>\n\n<p>Here you have to access <code>result[i, j]</code> every time in the second loop. This harms performance and makes this second loop unclear.</p>\n\n<pre><code>for (int i = j + 1; i &lt; rows; ++i)\n {\n result[i, j] /= result[j, j];\n for (int k = j + 1; k &lt; rows; ++k)\n {\n result[i, k] -= result[i, j] * result[j, k];\n }\n }\n</code></pre>\n\n<p>Could be written:</p>\n\n<pre><code>for (int i = j + 1; i &lt; rows; ++i)\n {\n result[i, j] /= result[j, j];\n double intermediateMultiplier = result[i, j];\n for (int k = j + 1; k &lt; rows; ++k)\n {\n result[i, k] -= intermediateMultiplier * result[j, k];\n }\n }\n</code></pre>\n\n<p><strong>Function naming</strong></p>\n\n<p><code>ExtractLower</code> and <code>ExtractUpper</code> are kind of misguiding, I would expect that <code>ExtractLower(x)=ExtractUpper(Transpose(x))</code>, but this is not the case as each function treats the diagonal in a different manner.</p>\n\n<p>In order to improve readability, I would write a <code>Transpose</code> method and a <code>SetDiagonalValuesTo(float[,] matrix, double value)</code></p>\n\n<pre><code>private static float[,] Transpose(float[,] matrix)\n{\n int rows = matrix.GetLength(0); int cols = matrix.GetLength(1);\n float[,] result = MatrixCreate(rows, cols);\n for (int i = 0; i &lt; rows; ++i)\n {\n for (int j = 0; j &lt; cols; ++j)\n {\n result[i, j] = matrix[j, i];\n }\n }\n return result;\n}\n\nprivate static float[,] ExtractLower(float[,] matrix)\n{\n return ExtractUpper(Transpose(matrix));\n}\n\nprivate static float[,] SetDiag(float[,] matrix, float diagonalValue)\n{\n int rows = matrix.GetLength(0);\n float[,] result = MatrixCreate(rows, rows);\n for (int i = 0; i &lt; rows; ++i)\n {\n result[i, i] = diagonalValue;\n }\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-27T09:22:30.587", "Id": "142576", "ParentId": "24336", "Score": "1" } } ]
{ "AcceptedAnswerId": "24354", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:50:23.997", "Id": "24336", "Score": "4", "Tags": [ "c#", "matrix" ], "Title": "Calculating n x n determinant" }
24336
<p>I am trying to write an efficient loop for rendering a jQuery Mobile listview. Is this the most efficient loop? I append elements 100 at a time to try and allow the user to see progress without blocking the UI. This currently still needs work.</p> <p>I also use a blend of html strings and jQuery DOM objects. I'm not sure about the performance cost.</p> <p>What are your thoughts? Assume <code>items</code> could be an array of 600/700 items.</p> <pre><code>/** * Renders the passed in list items into a JQM listview. * @param items {Array{Objects}} - An array of key/value objects */ function renderSourceItems(items) { var content = $page.find(".content"); if (!items) { content.html('&lt;p&gt;No Data Found&lt;/p&gt;'); } else { var column, value, list, markup = ""; column = _.keys(items[0])[0]; // The key is the database column content.empty(); $('&lt;ul/&gt;', { "data-role" : "listview", "data-filter": "true", "data-theme" : "c" }).appendTo(content).listview(); list = content.find('ul'); for (var i = 0; i &lt; items.length; i++) { value = items[i][column]; markup += '&lt;li&gt;&lt;a href="#apage" data-column="' + column +'" data-value="' + value +'"&gt;' + (value || "[No Value]") + '&lt;/a&gt;&lt;/li&gt;'; if (i % 100 === 0) { list.append(markup).listview("refresh"); markup = ""; } } // refresh triggers the page to adjust its sizes, // otherwise long lists can force the footer navbar to the bottom of the list intead of the screen bottom. list.append(markup).listview("refresh"); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>If you have a reasonably or entirely fixed template, use something like <a href=\"http://handlebarsjs.com/\" rel=\"nofollow noreferrer\">HandlebarsJS</a> to make a template that you populate. </p></li>\n<li><p>Now about performance, I would suggest you make a <a href=\"http://jsperf.com/\" rel=\"nofollow noreferrer\">jsPerf</a> test for your specific case and try out the different options to see which is fastest since the right answer is really different for each case. Here's an interesting answer to a question about passing HTML strings:\n<a href=\"https://stackoverflow.com/questions/3015335/jquery-html-vs-append\">https://stackoverflow.com/questions/3015335/jquery-html-vs-append</a></p></li>\n<li><p>A big no no for me is putting an append in a loop. It's going to be much better if you do a loop and cache the things to append into a variable, then do a single append with that. DOM manipulations carry some of the highest costs to performance. If you check out this article you can see the tests with arrays and performance costs first hand: <a href=\"http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly\" rel=\"nofollow noreferrer\">http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly</a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:07:59.560", "Id": "37540", "Score": "0", "body": "Thanks, I originally had the append outside the loop and rendered the whole list as a markup string but with lists of 700 items the UI seems to be blocked for ages (couple of seconds)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:12:26.080", "Id": "37541", "Score": "0", "body": "Yeah if you check out that last article you can see their tests and it's something like 9-10x faster to have it outside. They included some string concatenation improvements there too, which might help reduce those \"ages\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T22:19:48.657", "Id": "81089", "Score": "0", "body": "@CrimsonChin a couple os seconds to append 700 items on a mobile device browser does not sound that bad to me" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:04:51.597", "Id": "24343", "ParentId": "24338", "Score": "0" } }, { "body": "<pre><code>//elements that don 't change should be declared in a scope that doesn't \n //get executed all the time to avoid redundant opearation\nvar content = $(\".content\", $page);\n\nfunction renderSourceItems(items) {\n\n //JS normally pulls up variable declarations, even when declared\n //anywhere. To avoid readability issues, it's best you declare\n //them up here\n var column, list;\n\n //the \"return early\" or \"blacklist\" method returns if any anomalies\n //are found earlier in the code. That way, you don't use nested ifs\n if (!items) {\n content.html('&lt;p&gt; No Data Found &lt;/p&gt;');\n return;\n }\n\n //down here, it's assumed that items does exist and has content\n\n column = _.keys(items[0])[0];\n content.empty();\n\n //depending on the browser, DOM strings vs jQuery DOM vary in\n //performance. Since it varies, I'd rather improve readability\n //by using one of them that's more readable, where in my case\n //it's jQuery DOM building\n list = $('&lt;ul/&gt;', {\n \"data-role\": \"listview\",\n \"data-filter\": \"true\",\n \"data-theme\": \"c\"\n });\n\n\n //our recursive function using setTimeout to avoid freezing UI\n (function looper(i) {\n\n var value, item;\n\n if (!(i % 100)) {\n value = items[i][column];\n\n //each item gets built using our readable method\n //here we make a list item and append to it a link with\n //the given data\n item = $('&lt;li/&gt;').appendTo(list);\n $('&lt;a/&gt;', {\n 'href': '#apage ',\n 'data - column ': column,\n 'data - value ': value\n }).text(value || ' [No Value]').appendTo(item);\n\n }\n\n setTimeout(function () {\n if (++i &lt; items.length) {\n //when not yet the last item, repeat\n looper(i);\n } else {\n //else we end\n\n //now you notice that we only append the list to the DOM down here\n //why not append it beforehand? The issue is DOM access - it's slow!\n //we take advantage of jQuery using DOM fragments, DOM elements that\n //are not in the DOM and just operate off-DOM. We only append\n //to the DOM after everything is completed, thus minimizing\n //DOM access from items.length times to just 1\n list.appendTo(content).listview(\"refresh\");\n }\n }, 200);\n\n //start with index 0\n }(0));\n\n\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:40:33.453", "Id": "37543", "Score": "0", "body": "nice answer, one thing the for loop has to append all the li items I just put the \"break\" in as a chance to update the ui so the user knows the site hasnt frozen" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:55:06.157", "Id": "37549", "Score": "0", "body": "@CrimsonChin you could do a recursive `setTimeout`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:22:58.100", "Id": "37598", "Score": "0", "body": "I might, i don't want do multiple appends are considerably slower but they would give the user better visual feedback" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:21:07.140", "Id": "24346", "ParentId": "24338", "Score": "2" } } ]
{ "AcceptedAnswerId": "24346", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:35:19.183", "Id": "24338", "Score": "0", "Tags": [ "javascript", "jquery", "dom", "jquery-mobile" ], "Title": "Render Large jQuery Mobile Listview" }
24338
<p>I am new to Haskell and, coming from a OO/procedural programming background, I want to make sure my code follows the <em>functional</em> way of doing things. I built this short module to test if a given string is a palindrome (same backwards and forwards, case-sensitive) and I am simply wondering if this is the most "Haskell" way to do it. Any criticism is greatly appreciated.</p> <pre><code>module PalindromeTest (isPalindrome) where isPalindrome :: String -&gt; Bool isPalindrome w | nChars &lt;= 1 = nChars == 1 | nChars == 2 = firstElem == lastElem | firstElem /= lastElem = False | firstElem == lastElem = isPalindrome (take (nChars - 2) (tail w)) where firstElem = head w lastElem = last w nChars = length w </code></pre>
[]
[ { "body": "<p>I would just write</p>\n\n<pre><code>isPalindrome w = w == reverse w\n</code></pre>\n\n<p>Short, and very easy to understand! And in this case it's also a lot more efficient, but that's another story...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:38:05.130", "Id": "37545", "Score": "2", "body": "I totally agree with this answer. One of the cool things of functional programming is that it makes it easier to reason at a higher abstraction level making the program much more compact and easy tu understand" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-11T09:25:09.013", "Id": "139798", "Score": "2", "body": "Could you point me towards an explanation as to how this produces the most efficient answer? As a procedural programmer, I can see where @mjgpy3 was coming from, so as I'm also trying to learn haskell atm, I'd like to really understand how the compiler performs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:19:06.133", "Id": "24345", "ParentId": "24340", "Score": "19" } }, { "body": "<p>@yatima2975 is dead right, there's a much easier way to do this as he has shown.</p>\n\n<p>I'm going to write an answer though just because there's a couple things you're doing which you should be corrected of early as being the wrong approach in haskell.</p>\n\n<pre><code> | nChars &lt;= 1 = nChars == 1\n | nChars == 2 = firstElem == lastElem\n</code></pre>\n\n<p>In both these cases you're using a guard statement to check the length of an array, in haskell it's much more idiomatic to use matching to create cases for specific lengths, like so:</p>\n\n<pre><code>isPalindrome [] = False\nisPalindrome [a] = True\nisPalindrome [a,b] = a == b\n</code></pre>\n\n<p>Also:</p>\n\n<pre><code> | firstElem == lastElem = isPalindrome (take (nChars - 2) (tail w))\n</code></pre>\n\n<p>Here you're doing math on the length, when all you need is the init and the tail, also this is your last case so you can simplify it using otherwise. But you don't even need to use a guard statement here because it's an and operation.</p>\n\n<pre><code>isPalindrome w = (head w == last w) &amp;&amp; isPalindrome middle\n where middle = (init . tail) w\n</code></pre>\n\n<p>Learn your head/last/init/tail functions and get used to remember to use those. They work like so:</p>\n\n<pre><code> Head=1\n |\n | __________Tail=[2,3,4,5]\n ||\n [1,2,3,4,5]\n[1,2,3,4]=Init________||\n |\n |\n 5=Last\n</code></pre>\n\n<p>All of that said, the <em>correct</em> way to do this is the implementation detailed by yatima.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T02:44:35.590", "Id": "126413", "Score": "1", "body": "My favorite method of remembering head, tail, init, last: http://s3.amazonaws.com/lyah/listmonster.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T02:45:38.943", "Id": "126414", "Score": "0", "body": "@cdated yeah that's what I was basically drawing above, I still picture that in my head :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T02:46:42.010", "Id": "126415", "Score": "0", "body": "Is there a reason to do `(init . tail) w` instead of `init $ tail w`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T02:55:52.760", "Id": "126416", "Score": "1", "body": "@cdated not to my knowledge, just as a rule I favor composition over application, I suppose that may be a bit of style? Possibly just something I've inadvertently learned from reading others code. I *feel* like it's conventional to use composition over application where you can, if for no other reason than the precedence of `$` can mix you up if you're not careful" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T01:29:18.427", "Id": "24404", "ParentId": "24340", "Score": "11" } } ]
{ "AcceptedAnswerId": "24345", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:46:25.860", "Id": "24340", "Score": "7", "Tags": [ "haskell", "functional-programming" ], "Title": "Palindrome test in Haskell" }
24340
<p>I am trying to design a class that will log errors to a text file, the application is using threads heavily so it may be that 2 errors that need to be written at the same time. I know there are 3rd party solutions available but for this particular case I would like to roll my own. What I have at the moment seems to work, I was just curious to see if anyone has any tips,improvements etc. The main aim is to not Block the UI while waiting for errors to be logged.</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Reflection; using System.Collections.Concurrent; using System.Windows.Forms; using System.Threading.Tasks; /// &lt;summary&gt; /// Error Logger will keep a list of all the exceptions and write them to a log periodically /// This is to ensure we dont get file locks trying to write to the file from multiple threads /// &lt;/summary&gt; public class ErrorLogger : IDisposable { internal class ExceptionInfo { public Exception ExceptionObject { get; set; } public DateTime Date { get; set; } public int UserId { get; set; } } private static ErrorLogger _instance = null; public static ErrorLogger Instance { get { if (_instance == null) { _instance = new ErrorLogger(); } return _instance; } } private Timer _timer = new Timer(); private Task _writeTask = null; private ConcurrentQueue&lt;ExceptionInfo&gt; _exceptions = new ConcurrentQueue&lt;ExceptionInfo&gt;(); public ErrorLogger() { _timer.Interval = 1000; _timer.Tick += new EventHandler(_timer_Tick); _timer.Start(); } void _timer_Tick(object sender, EventArgs e) { if (_writeTask == null) { _writeTask = Task.Factory.StartNew(delegate { WriteLog(); }); } else if (_writeTask.IsCompleted &amp;&amp; _exceptions.Count &gt; 0) { _writeTask.Dispose(); _writeTask = Task.Factory.StartNew(delegate { WriteLog(); }); } } public void LogErrror(Exception ex) { _exceptions.Enqueue(new ExceptionInfo() { ExceptionObject = ex, Date = DateTime.Now }); } private void WriteLog() { string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"First Choice Software\Pronet Outlook"); string filePath = Path.Combine(directory, @"ErrorLog.txt"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!File.Exists(filePath)) { File.Create(filePath).Close(); } ExceptionInfo exInfo = null; System.IO.StreamWriter sw = null; try { sw = new System.IO.StreamWriter(filePath, true); while (_exceptions.TryDequeue(out exInfo)) { string errorMessage = string.Format("{1}{5}{5}{5}{5}{5}{1}Version : {6}{1}Date : {0}{1}UserId : {2}{1}Message : {3}{1}Stack Trace : {4}", DateTime.Now, Environment.NewLine, exInfo.UserId, exInfo.ExceptionObject.Message, exInfo.ExceptionObject.StackTrace, "========", Assembly.GetExecutingAssembly().GetName().Version.ToString(4)); Debug.Write(errorMessage); char[] c = errorMessage.ToCharArray(); sw.Write(c, 0, c.Length); } } catch { } finally { if (sw != null) { sw.Close(); sw.Dispose(); } } } public void LogErrror(Exception ex, int pUserId) { _exceptions.Enqueue(new ExceptionInfo() { ExceptionObject = ex, Date = DateTime.Now,UserId = pUserId }); } public void Dispose() { _exceptions.Enqueue(new ExceptionInfo() { ExceptionObject = new Exception("Disposing") }); _timer.Stop(); _timer.Dispose(); if (_writeTask != null) { //If there are exceptions still to be logged, log them now, blocking UI now is ok if (_writeTask.IsCompleted &amp;&amp; _exceptions.Count &gt; 0) { WriteLog(); } else if (!_writeTask.IsCompleted) { _writeTask.Wait(); } _writeTask.Dispose(); } _exceptions = null; _instance.Dispose(); _instance = null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:03:03.587", "Id": "37539", "Score": "2", "body": "What are the reasons for rolling out your own logger? What functionality you find missing in existing solutions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:41:03.907", "Id": "37544", "Score": "0", "body": "It's not that existing solutions don't offer functionality, but I'd rather not include a dependency just to log errors. I'm trying to keep the application size down to a minimum with as few 3rd part references as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T19:18:44.063", "Id": "37561", "Score": "0", "body": "I believe I would use a Queue and TraceSource. So you'd make your Logger class, have a method such as WriteLog(string) that method would add to your queue of strings. Then in either a different thread, or a timer, or something have it empty out your queue. But if you use TraceSource you can turn on and off tracing from a config file without having to recompile. And you can also change the location of your log file on a whim." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T22:52:10.567", "Id": "37570", "Score": "0", "body": "I think having a disposable singleton is a bad idea. Case in point: your `Dispose()` has a race condition (what happens if `_writeTask` is checked when it hasn't completed yet, but already exited the loop?). Also, I think it will cause stack overflow, since it's calling itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-01T10:57:43.263", "Id": "63944", "Score": "0", "body": "any final solution with full source code working ? maybe more complex sample for notify errors in each thread and after WaitAll shows a summary ?" } ]
[ { "body": "<p>Instead of creating a task to check the queue every second it's probably better to just to create it once and wait for the data (errors) to arrive. <code>BlockingCollection</code> will help here to provide automated blocking until the new data is available. I've simplified file operations here (each log entry will cause the file to be opened/closed), and it might be acceptable if you don't expect lots of exceptions from your application (as for me that's a reasonable assumption). </p>\n\n<p>With a bit of more advanced code (e.g. using <code>CancellationTokenSource</code>) you could add a logic to keep the file opened for certain period, but I would initially go with simple solution, and change it only when it becomes the bottleneck....</p>\n\n<p>P.S. I strongly dislike creation of exception in order to log the fact of disposition. It shows that your log doesn't contain exceptions only, so you should consider having exception object as an optional parameter in log entry.</p>\n\n<pre><code>public class ErrorLogger : IDisposable\n{\n private class ExceptionInfo\n {\n public Exception ExceptionObject { get; set; }\n public DateTime Date { get; set; }\n public int UserId { get; set; }\n }\n\n private static readonly Lazy&lt;ErrorLogger&gt; _instance = new Lazy&lt;ErrorLogger&gt;(); //if you want to enforce the usage of singleton you should declare private default constructor.\n\n public static ErrorLogger Instance { get { return _instance.Value; } }\n\n private readonly Task _writeTask = Task.Run(WriteLog);\n private readonly BlockingCollection&lt;ExceptionInfo&gt; _exceptions = new BlockingCollection&lt;ExceptionInfo&gt;();\n\n public void LogError(Exception ex)\n {\n _exceptions.Add(new ExceptionInfo { ExceptionObject = ex, Date = DateTime.Now });\n }\n\n public void LogError(Exception ex, int pUserId)\n {\n _exceptions.Add(new ExceptionInfo { ExceptionObject = ex, Date = DateTime.Now, UserId = pUserId });\n }\n\n private void WriteLog()\n {\n string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @\"First Choice Software\\Pronet Outlook\");\n string filePath = Path.Combine(directory, @\"ErrorLog.txt\");\n\n if (!Directory.Exists(directory))\n Directory.CreateDirectory(directory);\n\n foreach (var exInfo in _exceptions.GetConsumingEnumerable())\n {\n string errorMessage = string.Format(@\"\n========================================\nVersion : {4}\nDate : {0}\nUserId : {1}\nMessage : {2}\nStack Trace : {3}\", DateTime.Now,\n exInfo.UserId,\n exInfo.ExceptionObject.Message,\n exInfo.ExceptionObject.StackTrace,\n Assembly.GetExecutingAssembly().GetName().Version.ToString(4));\n\n Debug.Write(errorMessage);\n File.AppendAllText(filePath, errorMessage)\n }\n }\n\n public void Dispose()\n {\n LogError(new Exception(\"Disposing\"));\n _exceptions.CompleteAdding();\n _writeTask.Wait();\n _exceptions.Dispose();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T22:57:21.593", "Id": "37571", "Score": "0", "body": "This probably won't matter much in a GUI application, but I think having a thread blocked most of the time is quite wasteful. And since the alternative here is not much more complicated, I fail to see why would this be a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T05:07:06.087", "Id": "37585", "Score": "0", "body": "@svick I followed the pattern of saving a log to disk in a separate thread as it was in original solution. I think having one thread dedicated to this task is a better choice then creating (out of threadpool, but still...) the thread every second. I would suggest to use the standard logging library, but it seems not an option for asker." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:41:34.707", "Id": "37629", "Score": "0", "body": "Since the `Task` class implements `IDisposable`, shouldn't `_writeTask` be `.Dispose()`'d in your `Dispose()` method after the `.Wait()`? Same goes for the `_exceptions` `BlockingCollection` object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T20:17:37.703", "Id": "37661", "Score": "0", "body": "@JesseC.Slicer There is a nice article [Do I need to dispose of Tasks?](http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx) I agree that in order to be strict I should have `BlockingCollection` disposed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T20:38:27.940", "Id": "37664", "Score": "0", "body": "@almaz Stephen Toub's pretty trustworthy, so kudos for posting that." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T21:30:09.083", "Id": "24358", "ParentId": "24342", "Score": "2" } } ]
{ "AcceptedAnswerId": "24358", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T14:56:34.393", "Id": "24342", "Score": "1", "Tags": [ "c#", "multithreading", "exception-handling" ], "Title": "Multi Threaded Error Logger" }
24342
<p>I wrote a custom server control. The data in it can be manipulated on the client and the changes will be written into the hidden field. The data represents a property of the control and should be retrieved on a postback. I achieved this by using the value changed event to set the property and all its dependencies. Is this a good a way to do this? Or can this code be improved?</p> <pre><code>public class Control : CompositeControl { private bool mProperty; private HiddenField hiddenField; public virtual bool Property { get { return mProperty; } set { mProperty = value; if (contentPanel != null) contentPanel.Visible = value; if (hiddenField != null &amp;&amp; hiddenField.Value != value.ToString().ToLower()) hiddenField.Value = value.ToString().ToLower(); } } protected override void CreateChildControls() { Controls.Clear(); CreateControlHierarchy(); ClearChildViewState(); } protected virtual void CreateControlHierarchy() { CreateHiddenField(); CreateContent(); } protected virtual void CreateHiddenField() { hiddenField = new HiddenField(); hiddenField.ID = "hiddenField"; hiddenField.Value = Property.ToString().ToLower(); hiddenField.ValueChanged += hiddenField_ValueChanged; Controls.Add(hiddenField); } protected virtual void CreateContent() { contentPanel = new Panel(); contentPanel.ID = "content"; contentPanel.Vsiible = Property; Controls.Add(contentPanel); } void hiddenField_ValueChanged(object sender, EventArgs e) { Property = Convert.ToBoolean(hiddenField.Value); } protected override void OnInit(EventArgs e) { EnsureChildControls(); base.OnInit(e); } } </code></pre>
[]
[ { "body": "<p>You can just expose hiddenField.Value in the property.</p>\n\n<pre><code>public bool Property\n{\n get\n {\n EnsureChildControls();\n return Convert.ToBoolean(hiddenField.Value);\n }\n set\n {\n EnsureChildControls();\n hiddenField.Value = value.ToString();\n }\n}\n</code></pre>\n\n<p>Property will expose the current value on postback by it self.</p>\n\n<p>You could also expose an event on your control that you refire in the ValueChanged event of the hidden field.</p>\n\n<pre><code>public event EventHandler PropertyChanged;\n\n...\n\nvoid hiddenField_ValueChanged(object sender, EventArgs e)\n{\n ContentPanel.Visible = Property;\n if (PropertyChanged != null) PropertyChanged(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>I moved the visibility here since it's more related to the value changing than the property itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:22:25.920", "Id": "24409", "ParentId": "24344", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T15:16:25.087", "Id": "24344", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Asp.Net Custom Server Control: PostBack handling" }
24344
<p>I wrote a python module that needs to load a file parser to work. Initially it was just one text parsing module but I need to add more parsers for different cases.</p> <pre><code>parser_class1.py parser_class2.py parser_class3.py </code></pre> <p>Only one is required for every running instance. I'm thinking load it by command line:</p> <pre><code>mmain.py -p parser_class1 </code></pre> <p>I wrote this code in order to select the parser to load when the main module is called:</p> <pre><code>#!/usr/bin/env python import argparse aparser = argparse.ArgumentParser() aparser.add_argument('-p', action='store', dest='module', help='-i module to import') results = aparser.parse_args() if not results.module: aparser.error('Error! no module') try: exec("import %s" %(results.module)) print '%s imported done!'%(results.module) except ImportError, e: print e </code></pre> <p>But, I was reading that this way is dangerous, maybe not standard.</p> <p>Then is this approach ok? </p> <p>Or must I find another way to do it?</p> <p>Why?</p>
[]
[ { "body": "<h1>Regarding the safety aspect of your question.</h1>\n<p>The reason why <code>exec()</code> can be dangerous is that is can allow a nefarious agent to execute code that you never intended.</p>\n<p>Let's assume for example that somewhere in your program, you have sensitive data elements such as:</p>\n<pre><code>username = secret_username\npassword = never_share\n</code></pre>\n<p>And let's also assume that someone calls your program like this:</p>\n<pre><code>mmain.py -p 'parser_class1;print globals()'\n</code></pre>\n<p>Then your <code>exec()</code> statement would actually be:</p>\n<pre><code>exec(&quot;import %s&quot; %('parser_class1;print globals()'))\n</code></pre>\n<p><em>And this would result in your program printing out all variables in your global space for them...</em> <strong>including your username and password.</strong></p>\n<p>By making your program utilize the <code>__import__</code> method as mentioned by @Jaime, you can at least prevent people from executing non-import statements in your code.</p>\n<p>But, you should, whenever possible also examine the input from a user before using it to execute any dynamic code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T17:34:47.717", "Id": "33084", "ParentId": "24349", "Score": "4" } }, { "body": "<h3>Sanitising your inputs with argparse</h3>\n\n<p>As has already been mentioned in comments and @eikonomega’s answer, running arbitrary code from the user is generally dangerous. Using <code>__import__</code> or <code>importlib</code> restricts their ability somewhat.</p>\n\n<p>You can make it even safer by restricting the set of available modules, by passing a <code>choices</code> flag to <code>add_argument</code>. Like so:</p>\n\n<pre><code>aparser.add_argument('-p',\n action='store',\n dest='module',\n help='-i module to import',\n choices=['parser1', 'parser2', 'parser3'])\n</code></pre>\n\n<p></p></p>\n\n<p>argparse will now enforce that only the values \"parser1\", \"parser2\" or \"parser3\" can be entered here – anything else will cause it to exit and print a usage message, e.g.:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ python conditional_imports.py -p foo\nusage: conditional_imports.py [-h] [-p {parser1,parser2,parser3}]\nconditional_imports.py: error: argument -p: invalid choice: 'foo' (choose from 'parser1', 'parser2', 'parser3')\n</code></pre>\n\n<p></p></p>\n\n<p>It’s also better for the end-user, because the help/usage message will tell them the available options, rather than leaving them to guess.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-19T10:27:30.817", "Id": "155759", "ParentId": "24349", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:02:11.530", "Id": "24349", "Score": "7", "Tags": [ "python", "dynamic-loading" ], "Title": "Load modules conditionally Python" }
24349
<p>I've been trying to create a tree module in JavaScript for implementing a "family tree" style structure. I'm not very experienced in newer JavaScript design styles and want to make sure I am going along the right path with the code I have written so far. Can someone let me know if I am on the right track with how this is organized?</p> <pre><code>var TREE = (function() { var treeList = [], //Tree container //Constructor for Member object Member = function(name, mother, father, children){ this.name = name || null; this.mother = mother || null; this.father = father || null; this.children = children || null; }, //Constructor for Tree object Tree = function(name){ this.name = name || null; this.memberList = [(new Member("root"))]; }; //Tree methods Tree.prototype.addMember = function(name, mother, father, children){ this.memberList.push(new Member(name, mother, father, children)); } Tree.prototype.getMemberList = function(){ return this.memberList; } return { create : function(treeName){ treeList.push(new Tree(treeName)); return treeList[treeList.length - 1]; }, getTreeList : function(){ return treeList; } }; }()); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T02:01:58.450", "Id": "37579", "Score": "0", "body": "I suggest you finish up the code first before we review it. That way, further optimizations can be done with your code. As far as I can see, this code should work as intended." } ]
[ { "body": "<p>Looks okay to me,</p>\n\n<ul>\n<li><p>I would not expose function names mentioning <code>node</code>, but rather <code>familyMember</code> or <code>member</code>.</p></li>\n<li><p>You expose only <code>name</code> through addNode, but you have <code>name, mother, father, children</code> in the constructor of Node.</p></li>\n<li><p>Your var statement is not well indented, making the code harder to understand</p></li>\n<li><p>I am curious as to treeList, what use case do you have in mind for that?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:38:37.497", "Id": "37627", "Score": "0", "body": "Thanks for the comments. I still have quite a few things to add to the module but I wanted to make sure it was structured correctly. For instance I wasn't sure whether the \"Node\" object should be accessible outside of the \"Tree\" context. For your question, the treeList is supposed to let me add and keep track of more than one tree if I required." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T01:04:13.083", "Id": "24360", "ParentId": "24356", "Score": "1" } } ]
{ "AcceptedAnswerId": "24360", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T20:21:35.903", "Id": "24356", "Score": "2", "Tags": [ "javascript" ], "Title": "Javascript Module Design" }
24356
<p>I was given a homework assignment in Java to create classes that find Prime number and etc (you will see in code better).</p> <pre><code>class Primes { public static boolean IsPrime(long num) { if (num%2==0){ return false; } for (int i=3; i*i&lt;=num;i+=2) { if (num%i==0) { return false; } } return true; } // End boolen IsPrime public static int[] primes(int min, int max){ int counter=0; int arcount=0; for (int i=min;i&lt;max;i++){ if (IsPrime(i)){ counter++; } } int [] arr= new int[counter]; for (int i=min;i&lt;max;i++){ if (IsPrime(i)){ arr[arcount]=i; arcount++; } } return arr; } // End Primes public static String tostring (int [] arr){ String ans=""; for (int i=0; i&lt;arr.length;i++){ ans= ans+arr[i]+ " "; } return ans; } public static int closestPrime(long num){ long e = 0 , d = 0 , f = num; for (int i = 2; i &lt;= num + 1 ; i++){ if ((num + 1) % i == 0){ if ((num + 1) % i == 0 &amp;&amp; (num + 1) == i){ d = num + 1; break; } num++; i = 1; } } num = f; for (int i = 2; i &lt; num; i++){ if ((num - 1) % i == 0){ if ((num - 1) % i == 0 &amp;&amp; (num - 1) == i){ e = num - 1; break; } num--; i = 1; } } num = f; if (d - num &lt; num - e) System.out.println("Closest Prime: "+d); else System.out.println("Closest Prime: "+e); return (int) num; } // End closestPrime }//end class </code></pre> <p>The goal of my code is to be faster (and correct). I'm having difficulties achieving this. Suggestions?</p> <pre><code>class Primes { public static boolean IsPrime(int num) { if (num==1){ return false; } for (int i=2; i&lt;Math.sqrt(num);i++) { if (num%i==0) { return false; } } return true; } // End boolen IsPrime public static int[] primes(int min, int max){ int size=0; int [] arrtemp= new int[max-min]; for (int i=min;i&lt;max;i++){ if (IsPrime(i)){ arrtemp[size]=i; size++; } } int [] arr= new int[size]; for (int i=0;i&lt;size;i++){ arr[i]=arrtemp[i]; } return arr; } public static String tostring (int [] arr){ String ans=""; for (int i=0; i&lt;arr.length;i++){ ans= ans+arr[i]+ " "; } return ans; } public static int closestPrime(int num) { int count=1; for (int i=num;;i++){ int plus=num+count, minus=num-count; if (IsPrime(minus)){ return minus; } if (IsPrime(plus)) { return plus; } count=count+1; } } // End closestPrime }//end class </code></pre> <p>I think you can improve this code a bit:</p> <p>Test Code:</p> <pre><code>/** Ex2: Overall time: 2545 m-sec */ public class PrimesTester { public static void main(String[] args){ long t1 = new Date().getTime(); // primes testPrime(100000); testPrime(1000000); testPrime(10000000); testPrime(100000000); long t2 = new Date().getTime(); System.out.println("Ex2: Overall time: "+(t2-t1)+" m-sec"); } public static void testPrime(int num) { System.out.println(); System.out.println("***** Testing class Primes for: "+num+"*****"); int min= num, max = min+min/2; long t1 = new Date().getTime(); // primes int[] primes = Primes.primes(min,max); long t2 = new Date().getTime(); long p10_6 = Primes.closestPrime(min); long t3 = new Date().getTime(); System.out.println("Ex2: prime test, time: "+(t2-t1)+" m-sec , number of primes: "+primes.length); System.out.println("Ex2: closestPrime test, time: "+(t3-t2)+" m-sec , prime: "+p10_6); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T02:16:43.403", "Id": "37580", "Score": "2", "body": "Hello and Welcome to Programmers. This question is off-topic here but on topic for Stack Overflow (if it's broken) and Code Review (if it's not and you just want to make it better) Which do you want me to move it to? Have a pleasant day." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T02:20:32.883", "Id": "37581", "Score": "0", "body": "@WorldEngineer Hi, tnx for quick answer, i need to improve this code. feel free to move it to the right place. (i think Code Review will do the trick)" } ]
[ { "body": "<p>Your <code>IsPrime</code> method looks already pretty good to me, just one little thing there in the line: </p>\n\n<pre><code>if (num % 2 == 0) {\n return false;\n}\n</code></pre>\n\n<p>It would return <code>false</code>for <code>num=2</code>, but <code>2</code>is also a prime number. So just in case I would add:</p>\n\n<pre><code>if(num==2){\n return true; // the first prime number is 2\n}\nif( num%2==0 || num&lt;2){\n return false; // numbers smaller than 2 (also negative numbers) can't be primes\n}\n</code></pre>\n\n<p>In you <code>primes</code> method you are checking all possible numbers from <code>min</code>to <code>max</code>, now you said it was a <em>homework</em> so I don't know if you are supposed to use this, but instead of an <code>array</code> you can use a <code>ArrayList</code>. The <code>ArrayList</code>can hold <code>Integer</code> (! not <code>int</code>, thats a little different) and it will change it's size dynamically. Like this:</p>\n\n<pre><code>public static int[] primes(int min, int max) {\n ArrayList&lt;Integer&gt; primesList = new ArrayList&lt;Integer&gt;();\n\n for( int i=min; i&lt;max; i++ ){\n if( isPrime(i) ){\n primesList.add(i);\n }\n }\n // after you found all primes, copy the results in an array, that can be returned\n int[] primesArray = new int[primesList.size()];\n for(int i=0; i&lt;primesArray.length; i++){\n primesArray[i] = (int) primesList.get(i);\n }\n\n return primesArray;\n}\n</code></pre>\n\n<p>True, this doesn't look much better. But as you can see you don't have to set a size to the <code>ArrayList</code> when initializing it. In your original code you have two loops, each checking if the loop index is a prime. Each prime check is again a loop with up to <code>n/2</code> steps. So if you are checking <code>m</code> numbers you may end up with <code>2*m*(n/2)</code> operations.</p>\n\n<p>In my version you also have two loops, but you only have to check ones for primes. So you have <code>n/2</code> steps to check for primes and then again <code>primes.length</code> steps to copy the result in an array. And the number of found primes will be much smaller than <code>n/2</code> so, all in all, this method has way less than <code>m*(n/2)</code> operations (best case even exactly <code>m*(n/2)</code>)</p>\n\n<p>In your fourth method <code>closestPrime</code> you are actually reusing your prime-finding algorithm to check all numbers that are smaller or greater than <code>num</code>. Now I can't tell you which one is faster, but it is definitely easier to just reuse your <code>isPrime</code> method, to check the closest prime to <code>num</code>. When you already have a method that does a good job, reuse it! </p>\n\n<p>Now you didn't ask for it, but if I may give you a few tips for code style:</p>\n\n<ul>\n<li>methods (and variables) should begin with a small letter. It serves nothing else but easier understanding the code.</li>\n<li>avoid unreadable variable names. Now you know what <code>ans</code> or <code>arcount</code> stands for, but in a few weeks it gets harder to understand. Just say <code>arrayCounter</code> and you always know what it means</li>\n<li>you may declare variables like this : <code>int e=0, f=2,...</code> but thats nothing else than <code>int e=0; int f=2; ...</code> and after almost 12 years of Java I can tell you the second version is way easier to keep track of you code.</li>\n</ul>\n\n<p>That's it, I hope I could help a little bit</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:06:56.783", "Id": "37615", "Score": "0", "body": "Hi, thx for the answer i think i got your point. what do you think about the second one? do you think it can be improved more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:48:24.787", "Id": "37618", "Score": "0", "body": "Looks pretty much improved to me. The `Math.sqrt` is a really good idea. Just make sure you check for negative inputs in the `IsPrime()` because primes can only be natural numbers. I am not sure if there is a case where `closestPrime`will actually try a negative number, but just in case. Just out of interest: what should happen when `closestPrime` is called with a prime as argument? Now you could run some tests and print out the calculation time (`long start= System.currentTimeMillis(); (... do calculation...) System.out.println(\"time=\"+(System.currentTimeMillis()-start));" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:58:27.573", "Id": "37633", "Score": "0", "body": "Yes, the goal of this code its to be tested in the code that i just added. but i just cant get better result then 2545 m-sec... my code test out 200,000 m-sec... any idea how i can achieve better result?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:50:34.317", "Id": "37645", "Score": "0", "body": "Making the `primeList` a static member of the class would allow `isPrime` to leverage existing lists of primes (only test against divisibility by primes, not by every even number). This might yield a speedup. Calculating the nearest prime would get faster as well, if the cache already holds numbers up to that region. If you take enough care, you can even parallelize prime tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:51:30.540", "Id": "37646", "Score": "0", "body": "I don't see any ways for improvement. It's all in the `IsPrime` method now. I only see a way to make the code shorter in your `closestPrime()`: `for(int i=0;i<num;i++){\n if (IsPrime(num-i)){\n return num-i;\n }\n if (IsPrime(num+i)) {\n return num+i;\n }\n }` But you don't really save many operations with this. Well you could check if `num`is an even number and iterate through odd numbers like: `for(int i=(num%2==0?1:0); i<num;i+=2){...}` or something like that" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:04:54.177", "Id": "24376", "ParentId": "24361", "Score": "2" } }, { "body": "<blockquote>\n <p>The goal of my code is to be faster (and correct). I'm having difficulties achieving this. Suggestions?</p>\n</blockquote>\n\n<p>This is a neverending task. My suggestion is to stop performance improvements without a goal. To test the correctness, you should write unit tests.</p>\n\n<p>To explain this a little bit more: There are some advanced algorithms, like sieves, deterministic prime tests, and so on. They depend on the fact that you have to know them or that you have the math background.<br>\nOne of the questions is the expected input. Depending on the input, the algorithm can be optimized.<br>\nAn other approach would be trading computations against memory. You could precalculate all primes and store them inside the class.<br>\nAn other question is the architecture of the platform, depending on the virtual machine and the platform, there could be different techniques.<br>\nYou could use a native call, to do it in c or assembler.<br>\nAnd so on, there is no end.</p>\n\n<hr>\n\n<p>Some obvious things from your code:</p>\n\n<p>Use a code convention, best practice would be the java code convention from sun/oracle.<br>\nAnd, as already said, avoid abbreviations.</p>\n\n<hr>\n\n<pre><code>long t1 = new Date().getTime(); // primes\n</code></pre>\n\n<p>If you want to measure the distance between two moments, use <code>System.currentTimeMillis()</code>.</p>\n\n<hr>\n\n<pre><code>for (int i=2; i&lt;Math.sqrt(num);i++)\n</code></pre>\n\n<p>This will most probably calculate the sqrt for every iteration. sqrt is one the more expensive operations. Do it once and save the result in a variable.<br>\nAnd you do not need to test all divisors. You do not have to test with numbers, which are known not to be prime (This means, you do not have to test with any number 2*n, n>1. Only with numbers 2*n + 1, n>0. Or only with numbers 6n +- 1, n > 0. Or any similar approach around the local minimums of the euler phi function)</p>\n\n<hr>\n\n<pre><code> int [] arr= new int[size];\n for (int i=0;i&lt;size;i++){\n arr[i]=arrtemp[i];\n\n } \n</code></pre>\n\n<p>To copy an array, you can use <code>System.arraycopy(...)</code>.</p>\n\n<hr>\n\n<pre><code>for (int i=min;i&lt;max;i++){\n if (IsPrime(i)){\n arrtemp[size]=i;\n size++;\n } \n }\n</code></pre>\n\n<p>To find all primes, you could use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a>, which is one of the fastest ways inside the java integer range.</p>\n\n<hr>\n\n<pre><code>int [] arrtemp= new int[max-min];\n</code></pre>\n\n<p>To reduce memory usage, increase locality and help the caches, you could use a <code>BitSet</code>. A custom, handmade implementation would be more efficient than the one found inside the java library.</p>\n\n<hr>\n\n<pre><code>public static boolean IsPrime(long num) {\n ....\n}\n</code></pre>\n\n<p>You could use a deterministic Miller-Rabin test here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T21:43:52.617", "Id": "37669", "Score": "0", "body": "i think i get your point, but some how i don't understand how to execute it in to my code. so the IsPrime will save all the primes that it find in to array, and for me to find a way to reuse IsPrime again.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T17:07:11.150", "Id": "24394", "ParentId": "24361", "Score": "3" } }, { "body": "<p>In a comment I made the point that caching is good. Here is an implementation <code>CachingPrimes</code> that showes some performance improvements:</p>\n\n<pre><code>class CachingPrimes {\n private static ArrayList&lt;Long&gt; cache = new ArrayList&lt;Long&gt;();\n // start with two primes. The last prime has to be an odd number\n static { cache.add((long) 2); cache.add((long) 3); }\n\n // largest prime is at least upTo\n public static void expandCache(long upTo) {\n long last = cache.get(cache.size() - 1);\n if (last &gt;= upTo) return;\n for (long candidate = last; candidate &lt;= upTo; candidate += 2) {\n for(;; candidate += 2) {\n if (isPrime(candidate)) {\n cache.add(candidate);\n break;\n }\n }\n }\n }\n\n public static boolean isPrime(long num) {\n if (num == 2 ) return true;\n if (num &lt; 2 ) return false;\n if (num % 2 == 0) return false;\n\n long upperBound = (long) Math.sqrt(num); // bug\n expandCache(upperBound);\n\n for (long prime : cache) {\n if (prime &gt; upperBound) break;\n if (num % prime == 0) return false;\n }\n return true;\n }\n\n public static long[] primes(long min, long max) {\n expandCache(max);\n int start = 0;\n int count = 0;\n for(long prime : cache) {\n if (prime &lt; min) start++;\n if (min &lt;= prime &amp;&amp; prime &lt;= max) count++;\n }\n long[] out = new long[count];\n for (count--; count &gt;= 0; count--) {\n out[count] = cache.get(start + count);\n }\n return out;\n }\n\n public static long closestPrime(long num) {\n expandCache(num);\n long smaller = 0, larger = 0;\n for (long prime : cache) {\n if (prime &lt; num) smaller = prime;\n if (prime == num) return prime;\n if (prime &gt; num) {\n larger = prime;\n break;\n }\n }\n long\n smaller_d = num - smaller,\n larger_d = larger - num;\n long nearest = (smaller_d &lt;= larger_d) ? smaller : larger;\n System.out.println(\"Closest prime: \" + nearest);\n return nearest;\n }\n}\n</code></pre>\n\n<p>I compared the speed of this implementation to your (original) code (with all numbers that could be primes changed to <code>long</code>).</p>\n\n<pre><code> testPrime(100000); // very small difference between implementations\n testPrime(1000000); // I'm twice as fast\n testPrime(10000000); // I'm 2–3 times as fast\n testPrime(100000000); // not tested\n</code></pre>\n\n<p>As you can see, my code isn't especially optimized. Using a different data structure from <code>ArrayList</code> could bring a speedup. Loops could be optimized. My code also has a bug: <code>upperBound = (long) Math.sqrt(num)</code> squared may be smaller than <code>num</code>. Some correction like <code>while (upperBound * upperBound &lt; num) upperBound++;</code> would be one solution that provides an exact value for <code>upperBound</code>. <code>square = upperBound * upperBound; if (square &lt; num) upperBound += num - square;</code> should be faster, but is very inexact.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T18:19:18.510", "Id": "24395", "ParentId": "24361", "Score": "0" } } ]
{ "AcceptedAnswerId": "24394", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T02:14:36.320", "Id": "24361", "Score": "1", "Tags": [ "java", "performance", "homework", "primes" ], "Title": "Primes Tester for speed performance" }
24361
<p>I am working on a site that themes itself based on images / logos. I have made a utility class that gets the colors from an image, shown below. I am fairly new to OOP with PHP, and I'm looking for feedback on what I could improve with the following. It is still in beta, so image-handling is a little sketchy and could use some work.</p> <p><strong>Image Used:</strong></p> <p><img src="https://i.stack.imgur.com/v8GKQ.png" alt="enter image description here" /></p> <p><strong>Class:</strong></p> <pre><code>class Image { private $_hex = array(); private $_size = array(); private $_topThree = array(); private $_im, $_mostCommon, $_minDem, $_tempHex, $_uniqueHex; public function __construct($image) { $ext = explode('.',$image); $ext = end($ext); if ($ext === 'png') { $this-&gt;_im = imagecreatefrompng($image); } elseif ($ext === 'jpg' || $ext === 'jpeg') { $this-&gt;_im = imagecreatefromjpeg($image); } else { die('The supplied extension is not supported. Supported formats include: jpg, jpeg, and png.'); } $this-&gt;_size = getimagesize($image); $this-&gt;setHex(); } public function showAll() { foreach($this-&gt;_uniqueHex as $k) { echo '&lt;div style=&quot;background-color:'.$k.'; width:100%; height:30px;&quot;&gt;'.$k.'&lt;/div&gt;'; } } public function getMostCommon() { $this-&gt;mostCommon($this-&gt;_hex); return $this-&gt;_mostCommon; } public function getTop() { $this-&gt;_tempHex = $this-&gt;_hex; $counted = array_count_values($this-&gt;_tempHex); arsort($counted); $i = 0; foreach ($counted as $k =&gt; $v) { if ($i &lt; 3) { $this-&gt;_topThree[$i] = $k; } $i++; } return $this-&gt;_topThree; } public function showTop() { if (empty($this-&gt;_topThree)) { $this-&gt;getTop(); } foreach($this-&gt;_topThree as $k) { echo '&lt;div style=&quot;background-color:'.$k.'; width:100%; height:30px;&quot;&gt;'.strtoupper($k).'&lt;/div&gt;'; } } ######################### ### PRIVATE FUNCTIONS ### ######################### private function setHex() { $x = 0; $y = 0; $this-&gt;_minDem = min($this-&gt;_size[0], $this-&gt;_size[1]); // Get RGB pixel by pixel while ($x &lt; $this-&gt;_minDem) { $colors = imagecolorat($this-&gt;_im, $x, $y); $r = ($colors &gt;&gt; 16) &amp; 0xFF; $g = ($colors &gt;&gt; 8) &amp; 0xFF; $b = $colors &amp; 0xFF; // Convert RGB to Hex $this-&gt;_hex[] = $this-&gt;toHex($r, $g, $b); $x++; $y++; } $this-&gt;removeWhiteBlack($this-&gt;_hex); $this-&gt;_uniqueHex = array_unique($this-&gt;_hex); } private function removeWhiteBlack($array) { $i = 0; foreach($array as $k) { $k = strtolower($k); if ($k === '#ffffff' || $k === '#000000') { unset($this-&gt;_hex[$i]); } $i++; } } private function mostCommon() { $counted = array_count_values($this-&gt;_hex); arsort($counted); $this-&gt;_mostCommon = key($counted); } private function toHex($r, $g=-1, $b=-1) { (is_array($r) &amp;&amp; sizeof($r) == 3) ? list($r, $g, $b) = $r : NULL; $r = intval($r); $g = intval($g); $b = intval($b); $r = dechex($r&lt;0?0:($r&gt;255?255:$r)); $g = dechex($g&lt;0?0:($g&gt;255?255:$g)); $b = dechex($b&lt;0?0:($b&gt;255?255:$b)); $color = (strlen($r) &lt; 2?'0':'').$r; $color .= (strlen($g) &lt; 2?'0':'').$g; $color .= (strlen($b) &lt; 2?'0':'').$b; return '#'.$color; } } </code></pre> <hr /> <h2>Usage:</h2> <pre><code>$image = new Image('FGC.png'); $topThree = $image-&gt;getTop(); $image-&gt;showTop(); echo $image-&gt;getMostCommon(); echo '&lt;pre&gt;', print_r($topThree, true), '&lt;/pre&gt;'; $image-&gt;showAll(); </code></pre> <hr /> <h2>Output:</h2> <p><strong>Top 3:</strong></p> <pre><code>&lt;div style=&quot;background-color:#155184; width:100%; height:30px;&quot;&gt;#155184&lt;/div&gt; &lt;div style=&quot;background-color:#009467; width:100%; height:30px;&quot;&gt;#009467&lt;/div&gt; &lt;div style=&quot;background-color:#dceae3; width:100%; height:30px;&quot;&gt;#DCEAE3&lt;/div&gt; </code></pre> <p><strong>Most Common Color:</strong></p> <pre><code>#155184 </code></pre> <p><strong>Top Three in array:</strong></p> <pre><code>Array ( [0] =&gt; #155184 [1] =&gt; #009467 [2] =&gt; #dceae3 ) </code></pre> <p><strong>Unique:</strong></p> <pre><code>&lt;div style=&quot;background-color:#155184; width:100%; height:30px;&quot;&gt;#155184&lt;/div&gt; &lt;div style=&quot;background-color:#61749d; width:100%; height:30px;&quot;&gt;#61749d&lt;/div&gt; &lt;div style=&quot;background-color:#fffffd; width:100%; height:30px;&quot;&gt;#fffffd&lt;/div&gt; &lt;div style=&quot;background-color:#ede2d1; width:100%; height:30px;&quot;&gt;#ede2d1&lt;/div&gt; &lt;div style=&quot;background-color:#e7d6bd; width:100%; height:30px;&quot;&gt;#e7d6bd&lt;/div&gt; &lt;div style=&quot;background-color:#e2cdad; width:100%; height:30px;&quot;&gt;#e2cdad&lt;/div&gt; &lt;div style=&quot;background-color:#948e96; width:100%; height:30px;&quot;&gt;#948e96&lt;/div&gt; &lt;div style=&quot;background-color:#babfd3; width:100%; height:30px;&quot;&gt;#babfd3&lt;/div&gt; &lt;div style=&quot;background-color:#009467; width:100%; height:30px;&quot;&gt;#009467&lt;/div&gt; &lt;div style=&quot;background-color:#9b8d87; width:100%; height:30px;&quot;&gt;#9b8d87&lt;/div&gt; &lt;div style=&quot;background-color:#3da686; width:100%; height:30px;&quot;&gt;#3da686&lt;/div&gt; &lt;div style=&quot;background-color:#6d9974; width:100%; height:30px;&quot;&gt;#6d9974&lt;/div&gt; &lt;div style=&quot;background-color:#c0aa92; width:100%; height:30px;&quot;&gt;#c0aa92&lt;/div&gt; &lt;div style=&quot;background-color:#dceae3; width:100%; height:30px;&quot;&gt;#dceae3&lt;/div&gt; &lt;div style=&quot;background-color:#19986c; width:100%; height:30px;&quot;&gt;#19986c&lt;/div&gt; &lt;div style=&quot;background-color:#858880; width:100%; height:30px;&quot;&gt;#858880&lt;/div&gt; &lt;div style=&quot;background-color:#90947c; width:100%; height:30px;&quot;&gt;#90947c&lt;/div&gt; &lt;div style=&quot;background-color:#707782; width:100%; height:30px;&quot;&gt;#707782&lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T18:03:36.567", "Id": "62709", "Score": "2", "body": "See http://99designs.com/tech-blog/blog/2012/05/11/color-analysis/ and https://github.com/99designs/colorific" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-06T08:56:23.000", "Id": "137870", "Score": "0", "body": "@DaveJarvis that's a pretty cool article" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T06:39:15.960", "Id": "515146", "Score": "0", "body": "What if \"most common\" is a tie? What if there is a tie for 3rd most common? Are you happy to arbitrarily lose otherwise qualifying colors? Do you ever want to present the counts for each color to see weighting? I personally do not support declaration inside of ternaries or in other words, ternaries that do not begin with a variable declaration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T19:52:23.883", "Id": "515199", "Score": "0", "body": "@mickmackusa this is all code I wrote when I first started as a developer 8+ years ago. I'd likely do it very differently now if I still wrote PHP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T19:54:13.423", "Id": "515200", "Score": "0", "body": "I'm honestly surprised this is getting activity 8 years later. I was going to delete but I like Sam's answer so I'll give them the points :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T20:02:41.997", "Id": "515201", "Score": "0", "body": "NVM, I see the tweet, lol" } ]
[ { "body": "<h2>General Feedback</h2>\n<p>The class looks okay. I like how the method names follow <a href=\"https://www.php-fig.org/psr/psr-12/#44-methods-and-functions\" rel=\"nofollow noreferrer\">PSR-12 recommendation</a> of method names in camelCase, however it is also recommended that an underscore not be used to indicate private properties<sup><a href=\"https://www.php-fig.org/psr/psr-12/#43-properties-and-constants\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<blockquote>\n<p>Property names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.</p>\n</blockquote>\n<p>The naming of some methods could be better - e.g. instead of <code>getTop()</code> a better name might be <code>getTopThreeUsedColors</code> - <code>getTop()</code> sounds like a method called to get something related to the top of the image. Maybe a better name for the class would be something like <code>ImageColorAnalyzer</code>.</p>\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md\" rel=\"nofollow noreferrer\">PSR-5</a> is in draft status currently but is commonly followed amongst PHP developers. It recommends adding docblocks above structural elements like classes, methods, properties, etc. Many popular IDEs will index the docblocks and use them to suggest parameter names when using code that has been documented. At least do it for the public methods since outside code could reference the docblocks and provide hints for the parameters, return type, etc.</p>\n<h2>Suspected bug</h2>\n<p>The description states that the code &quot;<em>gets the colors from an image</em>&quot; yet given that there is a single <code>while</code> loop in the method <code>Image::setHex()</code> which increments <code>$x</code> and <code>$y</code> at the same time it appears that it really gets the color at points along a diagonal line - like this:</p>\n<p><a href=\"https://i.stack.imgur.com/926WC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/926WC.png\" alt=\"enter image description here\" /></a></p>\n<p>To get all of the image colors it would likely need to have two loops- one to increment <code>$x</code> and one to increment <code>$y</code> independently.</p>\n<h2>Suggestions</h2>\n<h3>Check mime type</h3>\n<p>Instead of using the file extension to get the image type, check the MIME type using <a href=\"https://www.php.net/manual/en/function.finfo-file.php\" rel=\"nofollow noreferrer\"><code>fileinfo_file()</code></a> since a user could modify the extension, which may include a non-image files and that could lead to errors when the <code>imagecreatefrom*()</code> functions are called.</p>\n<h3>Getting top three colors</h3>\n<p>The method <code>Image::getTop()</code> iterates over all elements. Instead of looping, it could just take a slice of the array using <a href=\"https://www.php.net/manual/en/function.array-slice.php\" rel=\"nofollow noreferrer\"><code>array_slice()</code></a>.</p>\n<p>If a loop was needed, it could loop over the keys (using <a href=\"https://php.net/array_keys\" rel=\"nofollow noreferrer\"><code>array_keys($counted)</code></a> to avoid the need to maintain <code>$i</code> separately</p>\n<h2>Abstract common styles</h2>\n<p>In the loop of <code>Image::showAll()</code> each <code>&lt;div&gt;</code> contains three styles, the latter two being redundant. Those could be moved out to a <code>&lt;style&gt;</code> tag - either with a ruleset for <code>div</code> or other selector like a class name. In case performance/bandwidth is a concern this can decrease the amount of data returned by ~23%.</p>\n<h2>Skip white and black</h2>\n<p>Instead of calling <code>removeWhiteBlack()</code> the code could simply not add white and black to the array.</p>\n<h3>Array syntax</h3>\n<p>There isn't anything wrong with using <code>array()</code> but as of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP has Active support for versions 8.0 and 7.4</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a> - i.e. <code>[]</code>.</p>\n<h3>Converting RGB to Hex values</h3>\n<p>It looks like the code within <code>Image::toHex()</code> was pasted from an online source like <a href=\"https://www.sitepoint.com/dynamic-image-map-based-pixel-colour/\" rel=\"nofollow noreferrer\">this one</a>. There are other techniques, many of which are shorter - e.g. using <a href=\"https://php.net/sprintf\" rel=\"nofollow noreferrer\"><code>sprintf()</code></a>. See answers to <a href=\"https://stackoverflow.com/q/32962624/1575353\">this SO post</a> for simpler alternatives (except <a href=\"https://stackoverflow.com/a/32962693/1575353\">the answer by Rajarshi Das</a> since that is nearly identical to the current code).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-16T23:09:40.827", "Id": "257275", "ParentId": "24363", "Score": "2" } } ]
{ "AcceptedAnswerId": "257275", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-26T02:59:25.350", "Id": "24363", "Score": "5", "Tags": [ "php", "object-oriented", "css", "file", "image" ], "Title": "Getting color information from an image" }
24363
<p>This is my first program in C. I'd rather not form any bad habits now. Is there anything that looks like bad practice, or something just looks wrong?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main(void) { srand(time(NULL)); int r = rand() % 10 + 1; int correct = 0; int guess; int counter = 0; printf("Guess my number! "); do { scanf("%d", &amp;guess); if (guess == r) { counter++; printf("You guessed correctly in %d tries! Congratulations!\n", counter); correct = 1; } if (guess &lt; r) { counter++; printf("Your guess is too low. Guess again. "); } if (guess &gt; r) { counter++; printf("Your guess is too high. Guess again. "); } } while (correct == 0); return 0; } </code></pre>
[]
[ { "body": "<p>Here are some of the improvements i can suggest:</p>\n\n<ul>\n<li>move your <code>counter</code> variable , from the inside the <code>if</code> statements , as increasing the count is independent of the <code>if</code> condition.</li>\n<li><p>Use <code>srand(time(NULL));</code> , below the declarations , or else , your compiler may throw this warning , when compiled using C90 standard.</p>\n\n<p>warning: ISO C90 forbids mixed declarations and code [-pedantic]</p>\n\n<p><em>So to ensure <strong>portability</em></strong> , avoid statements between declarations.</p></li>\n<li><p>In the long run , more <em>meaningful</em> and <em>formal</em> names , can be used instead of names like <code>r</code> and <code>guess</code>.</p></li>\n</ul>\n\n<p>In my personal opinion , these two changes would be better:</p>\n\n<ul>\n<li><p>Using a <code>break;</code> , when the correct number is guessed , can eliminate the need for using an extra variable <code>correct</code>.</p></li>\n<li><p>I would prefer to use just a <code>while()</code> instead of <code>do{}while();</code>, if the program logic permits it.</p></li>\n</ul>\n\n<p>Here is the program , modified with the changes , i listed above:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nint main(void) \n{\n\nint random_num = 0;\nint guessed_num = 0;\nint counter = 0; \n\nsrand(time(NULL));\nrandom_num = rand() % 10 + 1;\n\nprintf(\"Guess my number! \"); \n\n while(1)\n {\n counter++; \n\n scanf(\"%d\", &amp;guessed_num);\n\n if (guessed_num == random_num) \n {\n printf(\"You guessed correctly in %d tries! Congratulations!\\n\", counter); \n break;\n }\n\n if (guessed_num &lt; random_num) \n printf(\"Your guess is too low. Guess again. \");\n\n if (guessed_num &gt; random_num) \n printf(\"Your guess is too high. Guess again. \");\n\n } \n\nreturn 0; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:38:15.453", "Id": "37602", "Score": "0", "body": "The C90 warning is nothing to be concerned about, beginner programmers should only use the C99/C11 standards." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:41:35.420", "Id": "37603", "Score": "2", "body": "I strongly disagree about using while(1) with a break instead of a loop that checks a flag variable. No matter, the comments about break and while are both _your personal opinions about coding style_. You need to state them as such, as there is no consensus among the whole software industry. On the contrary, several widely recognized programming standards don't share your opinion at all. Also, many would consider removing the {} after is as dangerous and bad style. Downvote until you have separated sound advise about good programming practice from personal opinions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:52:20.617", "Id": "37604", "Score": "0", "body": "Downvote changed to upvote :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T08:12:25.823", "Id": "24369", "ParentId": "24366", "Score": "7" } }, { "body": "<ul>\n<li>You need to use proper indention of everything inside main().</li>\n<li>Every scanf(\"%d\") leaves a trailing line feed <code>'\\n'</code> in stdin. They are skipped by further scanf(\"%d\") reads, but if you attempted to scanf a character or string somewhere, you would get odd behavior. It is better to clear stdin after each access. The simplest way to do this is to add a call to getchar() after each scanf call. You can also start the scanf format string with a space, like <code>scanf(\" %s\", str)</code>, the space will then discard left-over white spaces from stdin.</li>\n<li>The if statements could be rewritten as <code>if(guess == r) {...} else if(guess &lt; r) {...} else {}</code>, this will make the program slightly more effective since it prevents multiple, redundant checks of the same variable. If the guess == r then you don't need to check if it is less than r as well.</li>\n<li>Instead of using an int variable <code>correct</code> with possible values 0 and 1, use a <code>bool</code> variable with values <code>false</code> and <code>true</code> (stdbool.h).</li>\n<li>The counter++ should be removed from inside the if statements to the main body of the loop, as it is always increased no matter.</li>\n</ul>\n\n<p><strong>EDIT</strong> </p>\n\n<p>Also, consider adding new line characters after each print, for readable output.\nCode with the above suggestions:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n#include &lt;stdbool.h&gt;\n\nint main(void) {\n srand(time(NULL));\n\n int r = rand() % 10 + 1;\n bool correct = false; \n int guess; \n int counter = 0; \n\n while(!correct)\n {\n printf(\"Guess my number! \"); \n scanf(\"%d\", &amp;guess);\n getchar();\n\n if (guess &lt; r) {\n printf(\"Your guess is too low. Guess again.\\n\");\n }\n else if (guess &gt; r) { \n printf(\"Your guess is too high. Guess again.\\n\");\n }\n else /* if (guess == r) */ {\n printf(\"You guessed correctly in %d tries! Congratulations!\\n\", counter); \n correct = true; \n }\n\n counter++;\n } /* while(!correct) */\n\n return 0; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:46:58.087", "Id": "37679", "Score": "0", "body": "I like this, but I agree with @BarathBushan about moving `srand(time(NULL))` below the declarations. I like to keep declarations together so the body is only logic/function calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:55:58.943", "Id": "37680", "Score": "0", "body": "@tjameson It doesn't really matter where you put it. The remark in the other answer wasn't as much about style, as about compatibility with an obsolete version of the C standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T09:01:06.130", "Id": "37682", "Score": "0", "body": "Right, which is why I qualified it with a style reasoning. But don't worry, +1 from me for a great answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T09:37:06.713", "Id": "24370", "ParentId": "24366", "Score": "3" } }, { "body": "<pre><code>/*\n * File: guessing_game_codereview.c\n * Purpose: The Guessing Game\n * Date: 2015-08-28\n * Author: Robert A. Nader\n * Email: naderra at g ...\n * Platform: Linux\n * Compile: gcc -std=c89 -Wall -Wpedantic \\\n guessing_game_codereview.c \\\n -o guessing_game_codereview\n * Note: Should be fairly portable to any hosted implementation.\n * Kept source file line lengths under 80 characters.\n * ----------------------------------------------------------------------------\n * Added: this \"Sample Changelog\":\n * Added: sample source code documentation\n * Added: MAX_SECRET constant. (Could have used \"#define MAX_SECRET 10\"\n * but prefer \"const int MAX_SECRET = 10;\"\n * even at the cost of a couple of extra bytes)\n * Removed: needless boolean type\n * Removed: final else statement by using \"(guess != secret)\"\n * Note 1: \"do {} while();\" is correct in this case, so would a while () {} be!\n * Added: Test for non-integer user input, with appropriate error message.\n * Added: test for integer range, with appropriate error message.\n * Replace: return 0; for return EXIT_SUCCESS;\n */\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\nint main(void) {\n const int MAX_SECRET = 10;\n int secret;\n int guess = 0;\n int guess_count = 0;\n int input_trail_count;\n /* Seed - init the pseudo-random generator */\n srand(time(NULL));\n secret = rand() % MAX_SECRET + 1;\n do {\n printf(\"Guess my number between 1 and %d inclusive: \", MAX_SECRET); \n scanf(\"%d\", &amp;guess);\n /* Handle possible user string input by consuming\n and counting any remaining input characters */\n input_trail_count = 0;\n while ('\\n' != getchar()) { ++input_trail_count; };\n if (0 == input_trail_count) { /* no trailing chars after integer */\n if (guess &gt; 0 &amp;&amp; guess &lt;= MAX_SECRET) { /* integer within range */\n if (guess &lt; secret) {\n printf(\"Your guess [%d] is too low. Try again.\\n\", guess);\n } else if (guess &gt; secret) { \n printf(\"Your guess [%d] is too high. Try again.\\n\", guess);\n }\n ++guess_count;\n } else { /* integer out of range */\n printf(\"Error: integer value [%d] is out of range (1-%d) !\\n\",\n guess, MAX_SECRET);\n }\n } else { /* detected non-integer input: string */\n printf(\"Error: detected non-integer input, only integers allowed!\\n\");\n }\n } while (guess != secret);\n printf(\"You guessed my number [%d] in [%d] tries!\\n\", secret, guess_count);\n return EXIT_SUCCESS;\n}\n/* eof */\n</code></pre>\n\n<ul>\n<li>Added: this \"Sample Changelog\":</li>\n<li>Added: sample source code documentation</li>\n<li>Added: MAX_SECRET constant. (Could have used \"#define MAX_SECRET 10\"\n but prefer \"const int MAX_SECRET = 10;\"\n even at the cost of a couple of extra bytes)</li>\n<li>Removed: needless boolean type</li>\n<li>Removed: final else statement by using \"(guess != secret)\"</li>\n<li>Note 1: \"do {} while();\" is correct in this case, so would a while () {} be!</li>\n<li>Added: Test for non-integer user input, with appropriate error message.</li>\n<li>Added: test for integer range, with appropriate error message.</li>\n<li>Replace: return 0; for return EXIT_SUCCESS;</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-29T00:35:59.253", "Id": "187137", "Score": "5", "body": "We really appreciate that you chimed in with your first answer! I would recommend however that you not just say what you changed, but explain _why_ you would change it. If you add this in I think you would have a really good answer to this question!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-28T23:23:32.123", "Id": "102223", "ParentId": "24366", "Score": "0" } } ]
{ "AcceptedAnswerId": "24369", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T07:28:58.080", "Id": "24366", "Score": "6", "Tags": [ "beginner", "c", "game", "number-guessing-game" ], "Title": "\"Guess the Number\" game in C" }
24366
<p>I was working through another question <a href="https://stackoverflow.com/questions/15632476/">here</a> and have hacked up an answer:</p> <pre><code>def get_rows(): """ Get height of triangle from user""" while True: rows = input('Enter the number of rows: ') if 3 &lt;= rows &lt;= 33: return rows def triangle(rows, invert=True): """ Print the outline of a triangle, of variable size. Print out a regular or inverted version of the triangle as necessary """ if invert: height = -1 * rows else: height = 0 # inner padding for min height (3) inner_buffer = [0, 1, 3] while len(inner_buffer) &lt;= rows: inner_buffer.append(inner_buffer[-1]+2) level = 0 while level &lt;= rows: outer_padding = ' '*(rows - abs(height)) if height == 0: print(outer_padding + '*') else: inner_padding = ' '*( inner_buffer[ abs(height) ] ) print(outer_padding + '*' + inner_padding + '*') height += 1 level += 1 </code></pre> <p>At this stage I am working to re-implement this two ways using: recursion and <code>itertools</code>.</p> <p>But I am looking at this and wonder if it would be a good place to use decorators. If someone is happy to implement one triangle (either regular or inverted, I don't mind) I would love to see the difference in the 3 implementations.</p>
[]
[ { "body": "<p>Decorators are a tool that you use when you have many functions that share a behaviour, for example a particular calling convention or treatment of results. See the <a href=\"http://wiki.python.org/moin/PythonDecoratorLibrary\" rel=\"nofollow noreferrer\">Python Decorator Library</a> on the Python wiki for some examples, and <a href=\"https://stackoverflow.com/a/1594484/68063\">this answer</a> on Stack Overflow for a tutorial.</p>\n\n<p>Here you only have two functions, so it doesn't seem likely that decorators will be helpful. Use the right tool for the job!</p>\n\n<p>Anyway, comments on your code.</p>\n\n<ol>\n<li><p>No docstrings! What do these functions do and how do you call them?</p></li>\n<li><p>The <code>else: continue</code> in <code>get_rows()</code> is unnecessary.</p></li>\n<li><p>The <code>regular</code> keyword argument to <code>triangle</code> is ignored.</p></li>\n<li><p>Your function <code>triangle</code> seems very long for what it's doing. Why not use Python's <a href=\"http://docs.python.org/2/library/string.html#formatspec\" rel=\"nofollow noreferrer\"><code>format</code></a> language to do the padding? Like this:</p>\n\n<pre><code>def triangle(n, invert=True):\n \"\"\"Print inverted triangle of asterisks (with `n`+1 rows) to standard output.\n Print it the right way up if keyword argument `invert=False` is given.\n \"\"\"\n for i in reversed(xrange(n + 1)) if invert else xrange(n + 1):\n print('{:&gt;{}}{:&gt;{}}'.format('*', n - i + 1, '*' if i else '', 2 * i))\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:20:11.580", "Id": "37623", "Score": "1", "body": "+1 + two comments: 1) I'd put some parens on the thing being iterated (or separate it in a variable). 2) That string being formatted is really complicated: I'd probably write a simple string concatenation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T19:07:54.240", "Id": "37657", "Score": "0", "body": "Hi Gareth, thank you for your answer. Will re-edit according to first 3 points. Lol, I will have to wrap my head around your formatting - thank you very much for that! Appreciate your thoughts on decorators and using the right tools. Many thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:44:27.397", "Id": "24373", "ParentId": "24372", "Score": "4" } }, { "body": "<p>I would suggest that you read PEP8. Also, you can reduce code size by using certain coding styles:</p>\n\n<pre><code>height = -1 * rows if rows else 0\n</code></pre>\n\n<p>It should look more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T07:13:18.423", "Id": "37736", "Score": "0", "body": "Thanks for the reference to PEP8 - have certainly learned and tidied up many things through reading that. After a cursory look, it seems PEP8 discourages putting multi-line stmts on the same line, BUT... in simple cases (and I agree that the case you've given above is straight forward) it may be ok. Seems there is some lee-way on this.\nnb: the stmt above, does not test `if invert` so does not quite accomplish the intended task.\nWill edit above with a more tidy solution (using recursion, string formatting (as suggested by Gareth) and tidier logic.\nThanks for your comments people!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T08:26:33.957", "Id": "37738", "Score": "0", "body": "hmm, I think there is a typo error, there will be `if invert`. Also, you can have any number of condition in a if statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T09:54:50.070", "Id": "37743", "Score": "0", "body": "I do see your point here, the statement could be written `height = -1 * rows if invert else 0` and still achieve the desired end. PEP8 includes, \"While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements.\" This is not definitive, what is the general concensus re. compacting code in this sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T10:59:41.910", "Id": "37744", "Score": "0", "body": "Hmm, but you see its not a typical `if/else` compound statement where you have two clauses (header and suite). Its a simple expression, and its perfectly fine to use it like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T11:06:12.833", "Id": "37745", "Score": "0", "body": "Oh right! That makes sense to me now. thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T04:05:10.850", "Id": "24455", "ParentId": "24372", "Score": "0" } } ]
{ "AcceptedAnswerId": "24373", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:13:37.633", "Id": "24372", "Score": "3", "Tags": [ "python" ], "Title": "Drawing inverted triangles" }
24372
<p>I write abstract repository </p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace Framework.DataLayer { public class Context&lt;T&gt; : IContext&lt;T&gt; where T : class { private readonly DbContext _dbContext; public Context(DbContext dbContext) { _dbContext = dbContext; } public bool TryGet(Expression&lt;Func&lt;T, bool&gt;&gt; predicate, out T entity) { entity = List(predicate).SingleOrDefault(); return entity != null; } public T Get(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return List(predicate).Single(); } public List&lt;T&gt; List(Expression&lt;Func&lt;T, bool&gt;&gt; predicate = null) { IQueryable&lt;T&gt; result = _dbContext.Set&lt;T&gt;().AsQueryable(); if (predicate != null) result = result.Where(predicate); return result.ToList(); } public T Add(T t) { _dbContext.Entry(t).State = EntityState.Added; return t; } public void Delete(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { List(predicate).ToList().ForEach(p =&gt; { _dbContext.Entry(p).State = EntityState.Deleted; }); } public void Delete(T entity) { _dbContext.Entry(entity).State = EntityState.Deleted; } public T Update(T t) { _dbContext.Entry(t).State = EntityState.Modified; return t; } } } </code></pre> <p>Is this correct?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T07:12:31.733", "Id": "37673", "Score": "0", "body": "Why are you returning anything from `Add` and `Update`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-16T12:05:18.580", "Id": "62067", "Score": "0", "body": "I'm not quite sure how I feel about abstracting away something that is already quite heavy abstraction layer. What if you want to use `Include` for eager loading? Or `GroupJoin` for `LEFT OUTER JOIN` between unrelated entities? What if you want to select only 2 properties out of 20 in the entity? When just using EF, you could project the to anonymous type and generated SQL would be quite bearable, but you can't do it here..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T16:39:22.747", "Id": "62519", "Score": "0", "body": "Ask yourself: what is the value of this abstraction? Try to be as concrete as possible. You'll notice: there's not a lot there." } ]
[ { "body": "<p>For one, it is not an <em>abstract</em> repository, but a <em>generic</em> repository. Never mind. As mentioned in a comment, generic repositories are hardly ever helpful and I would never use them. But apart from that, there's a couple of things I can say about this code:</p>\n\n<ul>\n<li><p><code>TryGet</code> should be absolutely safe (that's what the \"Try\" prefix conveys), so use <code>FirstOrDefault()</code> and only return an entity if exactly one is fetched.</p></li>\n<li><p>I would not return a <code>List</code>, but an <code>IEnumerable</code>, so you retain deferred execution.</p></li>\n<li><p>If the repository is only internally used, e.g. to supply data for services, I would return <code>IQueryable</code>, so you can compose queries from different repositories, do projections, includes and everything you can do with <code>IQueryable</code> and not with <code>IEnumerable</code>.</p></li>\n<li><p>As said in another comment, it is not necessary to return anything from <code>Add</code> and <code>Update</code>, because you always modify a reference type.</p></li>\n<li><p>I would prefer method names like <code>MarkForDelete</code>, because that's what actually happens.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T16:28:20.713", "Id": "37678", "ParentId": "24374", "Score": "3" } } ]
{ "AcceptedAnswerId": "37678", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:56:58.173", "Id": "24374", "Score": "1", "Tags": [ "c#", "entity-framework" ], "Title": "Abstract repository for entity framwork" }
24374
<p>I have to run an external program from Python. The external program makes many temporary files (which conflict with other instance of same program).</p> <p>My strategy is:</p> <ol> <li>get current directory (native) path</li> <li>change to temp directory</li> <li>run external command</li> <li>copy output to native directory</li> <li>change back to native directory</li> </ol> <p>Here is my code:</p> <pre><code>import os, tempfile current_dir = os.getcwd() tmp_dir = tempfile.mkdtemp() input_file, outfile = 'input_file', 'result' os.system('cp %s %s' %(input_file, tmp_dir)) os.chdir(tmp_dir) cmd = 'pwd&gt; tmp_01.txt;ls -ltr &gt;&gt;tmp_01.txt' ##system command goes here os.system(cmd) os.system('cp tmp_01.txt %s/%s' %(current_dir, outfile)) os.chdir(current_dir) </code></pre> <p>My questions are:</p> <ol> <li>Is it right or is there a simpler way to do it? </li> <li>Do I need to remove the tmp directory?</li> <li>Is it safe to use this code as Python module/class in a web application? Does it make shell injection easy, or can it possible reveal more information than needed?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T03:53:31.650", "Id": "89543", "Score": "0", "body": "This code doesn't appear to do anything useful, so I've classified it as hypothetical / example code, which would be off-topic for Code Review." } ]
[ { "body": "<p>Give a try to shutil and subprocess.</p>\n\n<p>To copy all the files:\n<a href=\"http://docs.python.org/2/library/shutil.html#shutil.copyfile\" rel=\"nofollow\">http://docs.python.org/2/library/shutil.html#shutil.copyfile</a></p>\n\n<pre><code>import shutil\nshutil.copy(src_file, destination_file)\n</code></pre>\n\n<p>To make the system calls:\n<a href=\"http://docs.python.org/2/library/subprocess.html#subprocess.check_call\" rel=\"nofollow\">http://docs.python.org/2/library/subprocess.html#subprocess.check_call</a></p>\n\n<pre><code>import subprocess\nsubprocess.check_call('ls -al', shell=True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:22:11.737", "Id": "89472", "Score": "1", "body": "Please avoid shell and prefer using list arguments instead" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:22:49.323", "Id": "89473", "Score": "0", "body": "Also, these are not system calls" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T16:37:53.803", "Id": "24432", "ParentId": "24375", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:59:20.783", "Id": "24375", "Score": "3", "Tags": [ "python", "bash", "file-system", "child-process" ], "Title": "Run external command from Python" }
24375
<p>How can I refactor this code to be more clean?</p> <pre><code> $scope.unreserve = function () { var params = { 'wishlist_product_id' : product.wishlist_product_id }; WishlistService.unreserve(params, function (data) { if (data.success) { $rootScope.$broadcast('NotificationController.create', {type: 'success', message: 'Unreserve successfully'}); } else { $rootScope.$broadcast('NotificationController.create', {type: 'error', message: data.error_message}); } }); }; $scope.createManualProduct = function () { var params = {}; ProductService.addManualProduct(params, function (data) { if (data.success) { $rootScope.$broadcast('NotificationController.create', {type: 'success', message: 'Unreserve successfully'}); } else{ $rootScope.$broadcast('NotificationController.create', {type: 'error', message: data.error_message}); } }); }; </code></pre>
[]
[ { "body": "<p>There are 2 main changes I would make:</p>\n\n<ol>\n<li><p>ProductService.addManualProduct seems to require a callback. A way that is more consistent with Angular, and with a number of benefits, would be to return a promise, so you can use it like:</p>\n\n<pre><code>ProductService.addManualProduct(params).then(function() {\n // Do something\n}); \n</code></pre></li>\n<li><p>Using <code>$rootScope</code> should be avoided if there is an alternative, as it's effectively global over the entire app. One way, would be to change the <code>$rootScope.$broadcast</code> to <code>$scope.emit</code>, which can be \"picked up\" by a directive on some parent element. So you could have a template like:</p>\n\n<pre><code>&lt;div notification-center&gt;\n &lt;div ng-controller=\"myController\"&gt;\n &lt;!-- Buttons here to create/unreserve --&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And in myController, <code>$emit</code> an event:</p>\n\n<pre><code>$scope.$emit('notificationCenter::create', someData);\n</code></pre>\n\n<p>Then in a <code>notificationCenter</code> directive's controller, you can listen to this</p>\n\n<pre><code>{\n controller: function($scope) {\n $scope.$on('notificationCenter::create', function(e, data) {\n // Do something, like display the message\n });\n }\n}\n</code></pre>\n\n<p>An alternative approach would be to have the notificationCenter directive inside the template controlled by myController, and then use <code>$scope.$broadcast</code> to send messages to it.</p>\n\n<p>The \"clean\" aspect of this is that you could potentially have separate areas of the app, with separate notification areas, if you wish.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-26T12:25:57.160", "Id": "38111", "ParentId": "24378", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:29:49.020", "Id": "24378", "Score": "1", "Tags": [ "javascript", "angular.js" ], "Title": "Broadcast event in angularJS" }
24378
<p>Could you have a quick look over my code to see if it's safe from SQL injection etc.. and suggest any amendments?</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Retrieve Your Login Code&lt;/title&gt; &lt;/head&gt; &lt;body bgcolor=#ffffff&gt; &lt;?php echo "&lt;h2&gt;Search Results:&lt;/h2&gt;&lt;p&gt;"; //If they did not enter a search term we give them an error if ($find == "") { echo "&lt;p&gt;You forgot to enter a search term!!!"; exit; } // Otherwise we connect to our Database mysql_connect("server.com", "ipn", "pw!") or die(mysql_error()); mysql_select_db("ipn") or die(mysql_error()); // We perform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); //Now we search for our search term, in the field the user specified $iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id = '$find'"); //And we display the results while($result = mysql_fetch_array( $iname )) { echo "&lt;b&gt;Name: &lt;/b&gt;"; echo $result['iname']; echo " "; echo "&lt;br&gt;"; echo "&lt;b&gt;E-mail: &lt;/b&gt;"; echo $result['iemail']; echo "&lt;br&gt;"; echo "&lt;b&gt;Transaction Date: &lt;/b&gt;"; echo $result['itransaction_date']; vecho "&lt;br&gt;"; echo "&lt;b&gt;Payment Amount: &amp;pound&lt;/b&gt;"; echo $result['ipayerid']; echo "&lt;br&gt;"; //And we remind them what they searched for echo "&lt;b&gt;Search Term &lt;/b&gt;(Transaction ID): &lt;/b&gt; " .$find; //} echo "&lt;br&gt;"; echo "&lt;br&gt;"; echo "&lt;b&gt;Login Code: &lt;/b&gt;"; echo $result['ipaymentstatus']; echo "&lt;br&gt;"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches=mysql_num_rows($iname); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...&lt;br&gt;&lt;br&gt;"; } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T01:17:09.373", "Id": "37732", "Score": "1", "body": "mysql_connect (and related) are depreciated in PHP v5.5 http://php.net/manual/en/function.mysql-connect.php You should switch to use mysqli or more preferably a PDO system. This alone will greatly help against SQL injection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T13:59:34.357", "Id": "39522", "Score": "2", "body": "Could you not take the time to at least properly indent your code before asking others to proofread it?" } ]
[ { "body": "<pre><code>// We perform a bit of filtering\n$find = strtoupper($find);\n$find = strip_tags($find);\n$find = trim ($find);\n$find = mysql_real_escape_string($find);\n</code></pre>\n\n<p>one more step and you are safer. I recommend using <code>PDO</code> or <code>mysqli</code> to prevent sql injection completely. </p>\n\n<p>If you are not learning PHP and mySQL, but creating an application, I recommend using framework like symfony or lavarel instead :) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:14:07.020", "Id": "37616", "Score": "0", "body": "Thanks for that, ived added in the last string. How do i use mysqli insted? im very very new to all this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:19:18.653", "Id": "37617", "Score": "0", "body": "So you are learning about PHP and mySQL. I suggest you searching in Stackoverflow to find a good way to starting learning PHP and MYSQL :)\n\nYou can start from here http://stackoverflow.com/questions/1610543/recommended-way-to-learn-php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:01:07.220", "Id": "37620", "Score": "0", "body": "ok, so with that string added, it should be safe enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:34:54.017", "Id": "37625", "Score": "0", "body": "my code assumes that register_globals is turned on, how do i change it to make it work with register_globals off??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:50:14.820", "Id": "37644", "Score": "0", "body": "yes it is ;) \n@MarcJones put another question on stackoverflow :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T07:19:56.717", "Id": "37675", "Score": "0", "body": "@MarcJones don't forget to vote the answer and mark it as accepted :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T15:01:21.730", "Id": "39601", "Score": "0", "body": "Why was that downvoted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-28T09:27:53.493", "Id": "39628", "Score": "0", "body": "@MarcJones I had to check the year on this… `register_globals`!? Holy crap. :) In answer to your question, it depends where `find` comes from. If the search form has `method=\"GET\"`, you retrieve it with `$find = filter_input(INPUT_GET, 'find', FILTER_SANITIZE_STRING);`. If the method is `POST` then it's `INPUT_POST` instead. That filter also strips tags, by the way." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:02:04.487", "Id": "24380", "ParentId": "24379", "Score": "-1" } }, { "body": "<p>Really this won't be safe unless you use parameterized queries, which allow the database to combine the query in the form that is safest.</p>\n\n<p>See the <a href=\"http://php.net/manual/en/mysqli.prepare.php\">PHP docs for mysqli.prepare</a>\nand <a href=\"http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/\">this helpful article</a></p>\n\n<p>Also, just for your own sanity, I'd try separating your PHP from your HTML. You might want to look into a templating system as well, like Smarty, just to make your code easier to manage in the long run.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T11:39:23.150", "Id": "25560", "ParentId": "24379", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T12:32:45.003", "Id": "24379", "Score": "-1", "Tags": [ "php", "html", "mysql", "sql-injection" ], "Title": "Search for a transaction" }
24379
<p>I always wanted to ask this but couldn't for some reason. </p> <p>I had written this chunk of code about 3 months ago when one of my teacher explained what selection sort was using flow chart. I had a basic understanding of what arrays were. So I sat down and wrote this:</p> <pre><code>#include &lt;stdio.h&gt; #define MAX_NUMBER 10 void selection_sort(int [], int []); void selection_sort(int num[], int sorted[]) { int i, high = 0, k, j = 9, store; for(k = 0; k &lt; MAX_NUMBER; k++) { for(i = 0; i &lt; MAX_NUMBER; i++) { if(num[i] &gt; high) { high = num[i]; store = i; } } sorted[j] = high; // Place the highest number in the end of array and decrement array j--; num[store] = 0; // Place 0 in the place of maximum number that was in the array high = 0; // again make high as zero, so as to compare zerpo again with all the numbers that are in the array } } int main() { int num[MAX_NUMBER], sorted[MAX_NUMBER]; int i; printf("Enter %d numbers: ", MAX_NUMBER); for(i = 0; i &lt; MAX_NUMBER; i++) { scanf("%d", &amp;num[i]); } selection_sort(num, sorted); for(i = 0; i &lt; MAX_NUMBER; i++) printf("%d ", sorted[i]); return 0; } </code></pre> <p>and I took almost 30 minutes to write this. But as you know the program in text books are a lot faster and smaller. </p> <p>Can you please tell me what kind of programmer I can become? I have been programming for a good 6 months now.</p> <p>This code review monster got into my head after reading Steve McConnell: Code Complete. Still I have a lot of pages to go through.</p>
[]
[ { "body": "<ul>\n<li><p>You don't need two arrays, it works with one too, simply swap the\nvalues. This needs less memory.</p></li>\n<li><p>According to this:</p>\n\n<pre><code>int i, high = 0, k, j = 9, store;\n</code></pre>\n\n<p><code>j</code> is always one less than the size of the array. Don't use magic numbers, use the constant.</p></li>\n<li><p>If you want to reuse this <code>selection_sort</code> it would be adviseable to\nadd a parameter for the size, so you don't need the global constant.</p></li>\n<li><p>In the inner loop you also iterate through the array parts which also have been sorted. (This may also be the reason you choose to use two arrays)</p></li>\n<li><p>The result may be wrong if you'd only have negative values in the array (due <code>high = 0</code>)</p></li>\n</ul>\n\n<p>Here my improved implementation:</p>\n\n<pre><code>void selection_sort(int *num, size_t size)\n{\n size_t k, i, j, store; // for indexes\n int high, swap; // for values\n\n // no need to sort if the array is short enough\n if(size &lt;= 1) return;\n\n high = INT_MIN; // set the highest number to the minium\n j = size - 1;\n\n for(k = 0; k &lt; size; k++, j--)\n {\n for(i = 0; i &lt;= j; i++)\n {\n if(num[i] &gt;= high)\n {\n high = num[i];\n store = i;\n }\n }\n\n // swap the highest number with the number at the last position\n // in the array\n swap = num[j]; \n num[j] = num[store]; \n num[store] = swap;\n high = INT_MIN; // reset the highest number\n }\n}\n</code></pre>\n\n<p>There is also a similar implementation on <a href=\"http://en.wikipedia.org/wiki/Selection_sort\" rel=\"nofollow\">Wikipedia</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:20:20.533", "Id": "24387", "ParentId": "24383", "Score": "3" } }, { "body": "<p>Apart from the other answer , i would suggest </p>\n\n<pre><code>int i;\nint high = 0;\nint k;\nint j = 9;\nint store;\n</code></pre>\n\n<p>instead of single line declarations.</p>\n\n<pre><code>int i, high = 0, k, j = 9, store;\n</code></pre>\n\n<p>The former way , may take more space , but is convenient for adding a comment to each declaration and for improves readability for subsequent modifications.</p>\n\n<p>Also <a href=\"https://codereview.stackexchange.com/questions/23657/improving-my-game-code/23668#23668\">this answer</a> , makes a valid reason not to prefer single line declarations.</p>\n\n<p>One more point is that , generally in most code i have seen , functions are declared before main() and defined after main().</p>\n\n<p>So your program must look like,</p>\n\n<pre><code>void selection_sort(int [], int []); //Declaration\n\n\nint main()\n{\n\nretrun 0;\n}\n\nvoid selection_sort(int num[], int sorted[]) //Definition\n{\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T09:46:22.633", "Id": "24412", "ParentId": "24383", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T13:40:41.717", "Id": "24383", "Score": "1", "Tags": [ "c" ], "Title": "Selection sort review. Does it look good?" }
24383
<p>I have to set up a new JavaScript library for a big project, which isn't Object Oriented yet. So I built a small file to test some needs. The result is the following:</p> <pre><code>var Module = { Config: (function() { //- private members var _systemName = 'mySystem', _version = '1.1.4'; //- private methods //... //- public methods var api = { getSystemInfo: function() { return "system: '"+_systemName+"' @ version "+_version; } }; return api; })(), Dialog: { _: (function(){ $(document).ready(function() { $('.showDialog').on('click',function() { var obj = { element: this, foo: 'foo', bar: 'bar', target: $('#title') }; Module.Dialog.setParam(obj); Module.Dialog.show(); }) }); })(), setParam: function(config) { console.log('config set for dialog box'); console.log(config); }, show: function() { console.log('dialogbox show | '+Module.Config.getSystemInfo()); }, close: function() { console.log('dialogbox close'); } }, Savescreen: { setParam: function(config,foo) { console.log('config set for savescreen'); }, show: function() { console.log('savescreen show | '+Module.Config.getSystemInfo()); } } } </code></pre> <p>Goals:</p> <ul> <li>access via <code>Module.Object.Function()</code></li> <li>no instantiation via keyword new</li> <li>private members and methods (in config section or event-listner)</li> <li>easy structured and object orientated</li> <li>each section must have its own scope (section = <code>savescreen</code>, <code>config</code>, <code>dialogbox</code>, etc) </li> <li>each section should hold its event-listner</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:24:38.537", "Id": "37649", "Score": "5", "body": "Consider putting the opening `{` in the same line as the statement, e.g. `var foo = {`. When using `return` you are actually *required* to do this so it's a good idea to do it in any case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T18:00:08.567", "Id": "37656", "Score": "0", "body": "Agreed. You shouldn't use curly-brace-on-new-line style in JavaScript. In other languages people can argue over style preferences forever, but in JavaScript things may simply break if you use brace-on-new-line style. So the debate will at least be shorter :)" } ]
[ { "body": "<p>To start off, your module should be the bare minimum, but extendable (like jQuery). That way, you won't have problems with scalability and maintenance. Here's a simple module template, where everything gets declared in the <code>Module</code> namespace:</p>\n\n<pre><code>//this is a simple module declaration:\n(function(Module){\n\n //everything here is private unless attached to the Module namespace\n var imPrivate = 'cant see me!';\n\n //here's an example of an exposed functionality\n Module.imaPublicProperty = 'public property here';\n\n Module.imaPublicFunction = function(){\n console.log('im public');\n }\n\n //here's an example privileged methods, public methods that have access\n //to the private scope. These are your \"setters and getters\" in Java-speak\n Module.imaPrivilegedFunction = function(){\n console.log(imPrivate);\n }\n\n}(this.Module = this.Module || {}));\n</code></pre>\n\n<p>I suggest you build a helper function that actually appends your sections to your namespace. That way, the module would scale easily. Also, you don't have to fiddle with the base-code and lose commas along the way.</p>\n\n<p>Here's a simple, yet incomplete implementation using this new approach (it lacks the document.ready part). It is long, yet it's modular and easily maintainable. You can even split the section codes in separate files.</p>\n\n<pre><code>(function (ns) {\n\n ns.addSection = function (name, def) {\n ns[name] = new def();\n }\n\n}(this.Module = this.Module || {}));\n\n//adding config\nModule.addSection('Config', function () {\n var systemName = 'mySystem',\n version = '1.1.4',\n section = this;\n\n section.getSystemInfo = function () {\n return systemName + ' v' + version;\n }\n\n});\n\n//adding Dialog\nModule.addSection('Dialog', function () {\n\n var section = this;\n\n section.onDocumentReady = function () {\n $('.showDialog').on('click', function () {\n var obj = {\n element: this,\n foo: 'foo',\n bar: 'bar',\n target: $('#title')\n };\n section.setParam(obj);\n section.show();\n })\n }\n\n section.setParam = function (config) {\n console.log('config set for dialog box');\n console.log(config);\n }\n\n section.show = function () {\n console.log('dialogbox show | ' + Module.Config.getSystemInfo());\n }\n\n section.close: function () {\n console.log('dialogbox close');\n }\n\n});\n\n//Savescreen section\nModule.addSection('Savescreen', function () {\n\n var section = this;\n\n section.setParam = function (config, foo) {\n console.log('config set for savescreen');\n }\n\n section.show = function () {\n console.log('savescreen show | ' + Module.Config.getSystemInfo());\n }\n\n});\n</code></pre>\n\n<p>Here's how it's possibly used:</p>\n\n<pre><code>Module.Config.getSystemInfo();\n//mySystem v1.1.4\n</code></pre>\n\n<p>So basically, you have base code and you just append to the namespace the sections via a helper function. Keeps the code clean and loose.</p>\n\n<p>I suggest looking at <a href=\"http://alanlindsay.me/kerneljs/\" rel=\"nofollow\">KernelJS</a>, which implements this pattern</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T16:41:27.520", "Id": "37779", "Score": "0", "body": "thank you very much Joseph! looks very very smooth and has a excellent structure! thanks a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T03:05:57.060", "Id": "24406", "ParentId": "24393", "Score": "4" } } ]
{ "AcceptedAnswerId": "24406", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T16:20:54.133", "Id": "24393", "Score": "1", "Tags": [ "javascript", "jquery", "object-oriented" ], "Title": "js oop best practise" }
24393
<p>My first algorithm for finding the factors of a number was pretty slow and horrible (it started at \$O(n^2)\$, where <em>n</em> was not even the inputted number), but I eventually came up with this new code. I just want the first factors of a number (not the duplicates), so I used <code>sqrt(n)</code> instead of <code>n</code> for the loop. As for the prime factorization, it appears to be efficient but it could probably be improved.</p> <ol> <li>Could this program be written simpler and more efficiently?</li> <li>Are all of these <code>std::stringstream</code>s even necessary?</li> <li>Is there a better way of having <code>findPrimeFactorization()</code> output in the form of <code>w^x * y^z</code>?</li> </ol> <p></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cmath&gt; #include &lt;string&gt; #include &lt;sstream&gt; using std::cin; using std::cout; using std::vector; using std::string; using std::stringstream; string findFactors(unsigned, vector&lt;unsigned&gt; &amp;factors); string findPrimeFactorization(unsigned posInt); int main() { unsigned positiveInteger; cout &lt;&lt; "\n\n&gt; Pos. Integer: "; cin &gt;&gt; positiveInteger; vector&lt;unsigned&gt; factors; cout &lt;&lt; "\n\n * Factors:\n\n"; cout &lt;&lt; findFactors(positiveInteger, factors); cout &lt;&lt; "\n * Prime Factorization:\n\n "; cout &lt;&lt; findPrimeFactorization(positiveInteger) &lt;&lt; "\n\n\n"; system("PAUSE"); // I use Visual C++ } string findFactors(unsigned posInt, vector&lt;unsigned&gt; &amp;factors) { std::stringstream factorsStr; double sqrtInt = sqrt(static_cast&lt;double&gt;(posInt)); for (unsigned i = 1; i &lt;= sqrtInt; i++) { if (posInt % i == 0) { factors.push_back(i); unsigned x = posInt / i; factorsStr &lt;&lt; " " &lt;&lt; i &lt;&lt; " x " &lt;&lt; x &lt;&lt; "\n"; } } return factorsStr.str(); } string findPrimeFactorization(unsigned posInt) { std::stringstream primesStr; for (unsigned i = 2; i &lt;= posInt; i++) { int powerDegree = 0; while (posInt % i == 0) { posInt /= i; powerDegree++; } if (powerDegree &gt;= 1) { primesStr &lt;&lt; i; if (powerDegree &gt; 1) primesStr &lt;&lt; '^' &lt;&lt; powerDegree; if (i &lt;= posInt) primesStr &lt;&lt; " x "; } } return primesStr.str(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-30T05:35:15.447", "Id": "90133", "Score": "0", "body": "What was `n` then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-30T05:37:41.053", "Id": "90134", "Score": "0", "body": "@Nobody: I'll have to look back at my older code to find that." } ]
[ { "body": "<p>I have a couple of suggestions that you may wish to consider:</p>\n\n<ul>\n<li><p>Don't return a string with the complete statement, return a <code>std::vector</code>/<code>std::map</code> instead with the values, and later assemble the string. It will keep the values in a more usable form and separate out the concerns. You're half doing this with <code>findFactors</code>, go all the way!</p></li>\n<li><p>In <code>findPrimeFactorization</code>, your main loop has a terminating condition that varies both sides (<code>i &lt;= posInt</code>), which is a little confusing to reason about. Instead, rewrite it to a <code>while ( posInt != 1 )</code>, which is your actual termination.</p></li>\n<li><p>In <code>findPrimeFactorization</code>, to speed things up (slightly) you can try testing 2 separately, then 3, 5, 7... within the loop (other more complex shortcuts are available)</p></li>\n<li><p>In terms of writing out the prime factors, you can combine the ideas behind the questions <a href=\"https://codereview.stackexchange.com/questions/13176/infix-iterator-code\">infix_iterator code</a> and <a href=\"https://stackoverflow.com/questions/634087/stdcopy-to-stdcout-for-stdpair\"><code>std::copy</code> to <code>std::cout</code> for <code>std::pair</code></a> to get something that's nice, if a little obscure.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T13:20:54.110", "Id": "37689", "Score": "0", "body": "I'll read about std::map first; I've never heard about it before. I'm also unfamiliar with the other std functions, but they're still something to consider. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T19:24:42.503", "Id": "37717", "Score": "0", "body": "Better yet, I'll worry about these std functions at a later time. I have trouble understanding some of the documentation anyway. I did, however, replace the `for` loop with a `while` loop in the primes function. It does make more sense now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T22:35:32.373", "Id": "37725", "Score": "0", "body": "Sounds a good idea. std::map, vector & list are very useful container classes, learn when you're ready. Any other can wait a while :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T22:40:16.913", "Id": "37726", "Score": "0", "body": "Alright. :-) I have a feeling I won't cover it in my next programming class, but that isn't a problem. By the end of the class, I should be more familiar with containers. Until then, I'll see if I can adjust my code more." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T11:26:30.763", "Id": "24415", "ParentId": "24399", "Score": "5" } } ]
{ "AcceptedAnswerId": "24415", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T22:14:16.857", "Id": "24399", "Score": "4", "Tags": [ "c++", "optimization", "strings", "primes" ], "Title": "Simplifying and optimizing factors and prime factorization generator" }
24399
<p>I'm learning F#, and even though I'm able to do whatever I want, parts of my code looks really bad. I would love to get some suggestions on how to improve a couple of functions involving some conditional logic.</p> <pre><code>let stripLast (punct : char) (word : string) = if word.Length &gt; 0 &amp;&amp; word.LastIndexOf(punct) = word.Length - 1 then word.Substring(0, word.Length - 1) else word let countWord (dictionary : Dictionary&lt;string, int&gt;) word = if word = "" || (blacklisted word) then "" |&gt; ignore elif dictionary.ContainsKey(word) then dictionary.[word] &lt;- dictionary.[word] + 1 else dictionary.[word] &lt;- 1 </code></pre> <p>I'm guessing there are ways to make these much more elegant. For instance, the second function uses side-effects on a Dictionary and has return type unit, but I added a branch where I had to use ignore in (probably) a silly way. Please don't change the functionality, but show me a nicer way to write the code.</p>
[]
[ { "body": "<p><code>stripLast</code> looks good to me. You could try to use pattern matching for the empty string case, but I think it would actually make your code worse.</p>\n\n<p>Regarding <code>countWord</code>, instead of <code>\"\" |&gt; ignore</code>, you should write just <code>()</code> (this works, because F# considers <code>void</code> the same as zero-tuple).</p>\n\n<p>But that whole function is very imperative and so I think it's not very idiomatic. If you wanted to fix that, you would need to change the algorithm that uses that function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T23:27:42.390", "Id": "24402", "ParentId": "24401", "Score": "1" } }, { "body": "<p>This is probably the way I would write it:</p>\n\n<pre><code>let stripLast punct word =\n match String.length word with\n | n when n &gt; 0 &amp;&amp; word.[n-1] = punct -&gt; word.[..n-2]\n | _ -&gt; word\n\nlet countWord (dictionary : Dictionary&lt;_,_&gt;) = function\n | null | \"\" -&gt; ()\n | word when blacklisted word -&gt; ()\n | word -&gt;\n match dictionary.TryGetValue(word) with\n | true, n -&gt; dictionary.[word] &lt;- n + 1\n | _ -&gt; dictionary.Add(word, 1)\n</code></pre>\n\n<p>Here's a rundown of the changes:</p>\n\n<p>In <code>stripLast</code>:</p>\n\n<ul>\n<li>Use <code>String.length</code> instead of a type annotation (<code>punct</code> can also be inferred)</li>\n<li>Capture the length (which is used multiple times) using pattern matching</li>\n<li>Check only the last char (<code>LastIndexOf</code> searches the whole string)</li>\n<li>Use string slicing over <code>Substring</code> for conciseness</li>\n</ul>\n\n<p>In <code>countWord</code>:</p>\n\n<ul>\n<li>Allow the type args for <code>Dictionary&lt;_,_&gt;</code> to be inferred</li>\n<li>Use pattern matching to clearly show the cases to be handled</li>\n<li>Replace calls to <code>ContainsKey</code> and <code>Item</code> (<code>[]</code>) with one call to <code>TryGetValue</code></li>\n</ul>\n\n<p>A more functional approach, assuming you have a list of words, might be:</p>\n\n<pre><code>words \n |&gt; Seq.countBy (stripLast stripChar)\n |&gt; Seq.filter (fun (word, _) -&gt;\n match word with\n | null | \"\" -&gt; false\n | _ -&gt; not (blacklisted word))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:15:15.670", "Id": "37703", "Score": "0", "body": "Isn't the guard in `stripLast` kind of confusing? It says `match String.length word` but then the condition also checks the string itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T18:45:57.870", "Id": "37714", "Score": "0", "body": "Pattern matching captures as well as compares values. In the first case in `stripLast` it matches anything and captures that value; the comparison is handled entirely by the guard. I don't find it confusing but YMMV. Another way to write it is: `let n = String.length word; if n > 0 && word.[n-1] = punct then word.[..n-2] else word`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T06:09:49.447", "Id": "37734", "Score": "0", "body": "I don't know why you didn't lead with the functional approach you mentioned. The beauty of functional approaches is you get to avoid a lot of the semantic details altogether like how long the words are etc, in functional languages approaches like that should definitely be encouraged." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T14:08:15.430", "Id": "37750", "Score": "0", "body": "@JimmyHoffa: I agree, the functional approach is more elegant, but the OP asked how to make _his code_ better. And there are some scenarios it covers that my functional approach does not." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T16:46:43.513", "Id": "24434", "ParentId": "24401", "Score": "5" } }, { "body": "<p>But why not use just</p>\n\n<pre><code>let stripLast punct (word:string) = word.TrimEnd([|punct|])\n</code></pre>\n\n<p>for stripLast ? Should only one trailing comma be removed ? </p>\n\n<p>And I would use more helper functions for count word:</p>\n\n<pre><code>let whiteListed word = \n let blackListedOrEmpty = \n match word with\n | null | \"\" -&gt; true\n | _ -&gt; blacklisted word\n not blackListedOrEmpty\n\nwords \n|&gt; Seq.countBy (stripLast stripChar)\n|&gt; Seq.filter (fun (word, _) -&gt; whiteListed word )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-16T20:45:24.017", "Id": "27458", "ParentId": "24401", "Score": "0" } } ]
{ "AcceptedAnswerId": "24434", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T22:31:14.147", "Id": "24401", "Score": "4", "Tags": [ "f#" ], "Title": "Idiomatic conditionals in F#" }
24401
<p>This is for regenerating some things in a game a made. The code is very big and I think it can be compressed but I don't know how to do it.</p> <pre class="lang-vb prettyprint-override"><code>Private Sub regen() 'regen coins z = coin1 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin2 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin3 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin4 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin5 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin6 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin7 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin8 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin9 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin10 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin11 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin12 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin13 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin14 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin15 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin16 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin17 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin18 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin19 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin20 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin21 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin22 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin23 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin24 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin25 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin26 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin27 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin28 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin29 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin30 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin31 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() z = coin32 z.Location = zloc z.Hide() zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If zloc.Y &gt; 595 Then zloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If z.Location = zloc z.Show() 'regen medcoins p = medcoin1 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin2 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin3 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin4 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin5 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin6 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() p = medcoin7 p.Location = ploc p.Hide() ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If ploc.Y &gt; 595 Then ploc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If p.Location = ploc p.Show() 'regens hcoins h = hcoin1 h.Location = hloc h.Hide() hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If hloc.Y &gt; 595 Then hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If h.Location = hloc h.Show() h = hcoin2 h.Location = hloc h.Hide() hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If hloc.Y &gt; 595 Then hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If h.Location = hloc h.Show() h = hcoin3 h.Location = hloc h.Hide() hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) If hloc.Y &gt; 595 Then hloc = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height)) End If h.Location = hloc h.Show() End Sub </code></pre>
[]
[ { "body": "<p>Have you heard of functions? The easiest way to shorten this is to take the repeated code, put it in a function, then call the function with all your coins.</p>\n\n<p>You should make the if statement a loop. As it currently is coded, what happens if the 2nd try > 595?</p>\n\n<pre><code>Private Sub PlaceCoin(Coin coin)\n\n Coin.Hide()\n Point location = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height))\n\n While location.Y &gt; 595\n location = New Point(RandomNumber(playspace.Width), RandomNumber(playspace.Height))\n End While\n\n Coin.Location = location\n Coin.Show()\n\nEnd Sub\n</code></pre>\n\n<p>Then you would call it from your RegenCoins Sub</p>\n\n<pre><code>Private Sub RegenCoins()\n\n PlaceCoin(coin1)\n PlaceCoin(coin2)\n 'etc..\n\nEnd Sub\n</code></pre>\n\n<p>You could also put your coins into an array or list</p>\n\n<pre><code>Private Coin coins(NumberOfCoins)\n\nFor Each coin In coins\n PlaceCoin coin\nNext\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T21:54:27.970", "Id": "37722", "Score": "1", "body": "This will also make it easier to change the RegenCoins logic because one change, will change the logic for every coin rather than having to go through x number of lines of code to make the same change. One more suggestion: get rid of the magic number 595. It should be either a constant, a configurable value, or a calculated (assuming it is the size of the screen) value." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T02:11:30.477", "Id": "24405", "ParentId": "24403", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T00:28:57.823", "Id": "24403", "Score": "1", "Tags": [ ".net", "vb.net" ], "Title": "Regenerations in a game" }
24403
<p>While upgrading our code base to take advantage of new features in .Net 4.5, I'm trying to refactor our take of the classic Producer/Consumer algorithm, but I'm concerned my refactoring is going to increase the CPU usage.</p> <p>Each instance of my <code>WorkItemConsumer</code> class is basically a <code>System.Threading.Thread</code> that is able to process at most <code>MaxConcurrentHandlers</code> items, each of which is handled by a TPL <code>System.Threading.Task</code>.</p> <p>In my previous implementation, I made use of explicit locking to read from the <code>Queue&lt;T&gt;</code>. Also, the class wrapping the queue set an <code>AutoResetEvent</code> to signal when a new item has been produced. Here was the code:</p> <pre><code>protected override void Run(string[] args) { while (true) { var index = WaitHandle.WaitAny(new[] {StopRequested, queue_.ItemsAvailable}); if (index == 0) break; if (tasks_.Count == MaxConcurrentHandlers) WaitAndDiscardAnyCompletedTask(); var item = queue_.PopItem(); // "null" denotes a signal to stop processing subsequent work items if (item == null) break; tasks_.Add(CreateWorkItemHandler(item)); } while(tasks_.Count &gt; 0) WaitAndDiscardAnyCompletedTask(); } </code></pre> <p>I would like to take advantage of the <code>BlockingCollection&lt;T&gt;</code> class, which gives me most of the features I want. It allows a consumer to know when no more items will ever be published and it also allows my to remove any explicit locking. However, I don't have a way to being signaled when new work items are available.</p> <p>Here is the new code:</p> <pre><code> protected override void Run(string[] args) { while (!queue_.IsCompleted) { if (StopRequested.WaitOne(0)) break; if (tasks_.Count == MaxConcurrentHandlers) WaitAndDiscardAnyCompletedTask(); foreach (var item in queue_.GetConsumingEnumerable().Take(MaxConcurrentHandlers - tasks_.Count)) tasks_.Add(CreateWorkItemHandler(item)); } while(tasks_.Count &gt; 0) WaitAndDiscardAnyCompletedTask(); } </code></pre> <p>How would you refactor this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T19:57:13.850", "Id": "37720", "Score": "1", "body": "I think the only way to tell if it increases CPU usage is to put a profiler on it, and run it each way." } ]
[ { "body": "<p>Well, after more resarch and testing, it appears that the <code>GetConsumingEnumerable()</code> method of the <code>BlockingCollection&lt;T&gt;</code> is actually blocking when there are no items to consume. And it handles the case where the collection is completed as well.</p>\n\n<p>The final touch, it that, instead of using a <code>ManualResetEvent</code> to signal the consumer to stop, like the original code, I'm using a <code>CancellationToken</code> instead.</p>\n\n<p>This allows me to simplify the code drastically.</p>\n\n<p>Here is the final snippet:</p>\n\n<pre><code> protected override void Run(string[] args)\n {\n try\n {\n foreach (var item in queue_.GetConsumingEnumerable(cancellation_.Token))\n {\n tasks_.Add(CreateWorkItemHandler(item));\n if (tasks_.Count == MaxConcurrentHandlers)\n WaitAndDiscardAnyCompletedTask();\n }\n }\n catch (OperationCanceledException /* e */)\n {\n }\n\n while (tasks_.Count &gt; 0)\n WaitAndDiscardAnyCompletedTask();\n }\n</code></pre>\n\n<p>PS: I should have done more testing before posting. But, I'm leaving the question and its answer here for reference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T08:16:28.380", "Id": "24464", "ParentId": "24410", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:52:59.797", "Id": "24410", "Score": "1", "Tags": [ "c#", ".net", "multithreading", "collections" ], "Title": "Does refactoring a while loop increase CPU usage?" }
24410
<p>I would like to hear the opinion of more experienced AngularJS developers on whether the following directive is best practice...</p> <p>I was trying to make to make a directive that will include HTML that:</p> <ul> <li>Can include compiled elements (other directives, like ng-src in the example below) </li> <li>Interpolated values ({{ value }}) </li> <li>Can include values/functions from the parent scope without modifying it (i.e. the directive has isolated scope)</li> </ul> <p>Example usage: </p> <pre><code>&lt;div ng-controller="Ctrl"&gt; &lt;tag&gt; &lt;h1&gt;&lt;a href="{{ url }}"&gt;{{ url }}&lt;/a&gt;&lt;/h1&gt; &lt;img ng-src="{{ image }}" /&gt; &lt;/tag&gt; &lt;/div&gt; </code></pre> <p>Controller and directive implementation:</p> <pre><code>var testapp = angular.module('testapp', []); var Ctrl = function($scope) { $scope.url = "http://google.com"; $scope.image = "https://www.google.gr/images/srpr/logo4w.png"; }; testapp.directive('tag', function() { return { restrict: 'E', transclude: true, scope: { }, compile: function compile(tElement, tAttrs, transclude) { return function(scope) { transclude(scope.$parent, function(clone) { tElement.append(clone); }); } } } }); </code></pre> <p>Fiddle: <a href="http://jsfiddle.net/x5WcB/3/" rel="nofollow">http://jsfiddle.net/x5WcB/3/</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:39:45.163", "Id": "45064", "Score": "1", "body": "Am i wrong or the third compile argument comes null? compile(tElement, tAttrs, transclude)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-08T16:27:51.040", "Id": "81554", "Score": "0", "body": "You should use `link` here instead of `compile`. `link` gets passed the scope as the first argument." } ]
[ { "body": "<p>I am a bit confused, your directive basically would do what Angular already does?</p>\n\n<p>When I comment out the entire <code>testapp.directive('tag', function() {</code> block, I see no change in the functionality of this code in fiddle.. I think you need a more extensive example for us to provide a meaningful review.</p>\n\n<p>Other than that:</p>\n\n<ul>\n<li>Your code looks fine to me</li>\n<li>JsHint.com cannot find anything wrong besides some missing semicolons</li>\n<li>You have 0 comments in your code</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-08T16:21:39.370", "Id": "81551", "Score": "0", "body": "In this specific case there is no benefit, but a directive will often process information into a particular object and include extra methods. Eg. I could create a `tag` object within the directive and expose this as part of the isolated scope. The `tag` object might have useful methods such as `delete`, which removes the entire node. You could then add a button inside the `tag` node which invokes `tag.delete()`. Whether you use a link or a button or whatever to invoke it is left up to the html that consumes the directive, and isn't predetermined by the directive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-25T05:50:01.107", "Id": "96647", "Score": "0", "body": "I honestly can't remember what I was thinking when I posted the question but I would like to believe that there was a reason why I wanted to do this manually and was just setting up a test case for it :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T13:40:38.650", "Id": "44573", "ParentId": "24411", "Score": "2" } } ]
{ "AcceptedAnswerId": "44573", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:58:46.243", "Id": "24411", "Score": "4", "Tags": [ "javascript", "angular.js" ], "Title": "AngularJS directive that manually transcludes content and has isolated scope" }
24411
<p>I'm trying to get to grips with the DateTime class in PHP. Previously I've used date() and mktime() when playing with dates.</p> <p>Here's the head of a calendar table, and I'm pretty sure I'm doing this in a stupid way! That fact that I'm setting the format each time, and modifying the original date with each Interval, seems 'lumpy': </p> <pre><code>&lt;table class="twelve"&gt; &lt;thead&gt; &lt;tr&gt; &lt;?php $date = new DateTime('2013-04-01'); ?&gt; &lt;th style="width:16%"&gt;&lt;?php echo $date-&gt;format('Y'); ?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;th style="width:12%"&gt;&lt;?php $date-&gt;add(new DateInterval('P1D')); echo $date-&gt;format('D jS');?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; </code></pre> <p>Can anyone point me towards a better way to do this. I'm planning to create a function to spit these calendars out, but I've provided an inline example here so you can see the way I'm using DateTime etc for now.</p> <p>Thanks</p>
[]
[ { "body": "<p>I like it.\nYou could use loops and use a variable for 'DateInterval(P1D)'.</p>\n\n<pre><code>&lt;table class=\"twelve\"&gt;\n&lt;thead&gt;\n&lt;tr&gt;\n&lt;?php $date = new DateTime('2013-04-01'); \n $day = new DateInterval('P1D');\n?&gt;\n&lt;th style=\"width:16%\"&gt;&lt;?php echo $date-&gt;format('Y'); ?&gt;&lt;/th&gt;\n&lt;th style=\"width:12%\"&gt;&lt;?php echo $date-&gt;format('D jS');?&gt;&lt;/th&gt;\n&lt;?php \nfor($i = 0;$i &lt;= 6; $i++){\n $date-&gt;add($day)\n echo '&lt;th style=\"width:12%\"&gt;'.$date-&gt;format('D jS').'&lt;/th&gt;';\n}?&gt;\n&lt;/tr&gt;\n&lt;/thead&gt;\n&lt;/table&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T17:27:47.477", "Id": "37943", "Score": "2", "body": "+1 very nice. You might consider `<th style=\"width:12%\"><?php echo $date->format('D jS) ?></th>` to avoid stringified markup" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T15:24:23.760", "Id": "24502", "ParentId": "24413", "Score": "2" } } ]
{ "AcceptedAnswerId": "24502", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T10:58:13.937", "Id": "24413", "Score": "1", "Tags": [ "php", "datetime" ], "Title": "PHP DateTime increments, a neater / more efficient way?" }
24413