body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Is it possible to shorten this piece of PHP code?</p>
<p>Honestly, I think it does not look clean but like a mess.</p>
<pre><code>if(Input::exists() && $token) {
if($validation->error('firstname') && $validation->error('lastname')) {
echo str_repeat(' ', 20), '<div class="addition error">↳ You did not enter your name.</div>', "\n";
} else if($validation->error('firstname')) {
echo str_repeat(' ', 20), '<div class="addition error">↳ You did not enter your first name</div>', "\n";
} else if($validation->error('lastname')) {
echo str_repeat(' ', 20), '<div class="addition error">↳ You did not enter your last name.</div>', "\n";
}
}
if(!Input::exists()) {
echo str_repeat(' ', 20), '<div class="addition">↳ We will address you by this name.</div>', "\n";
}
if(Input::exists() && $token) {
if($validation->error('emailConfirm') == 'match') {
echo str_repeat(' ', 20), '<div class="addition error">↳ The email address you entered does not match.</div>', "\n";
} else if($validation->error('emailConfirm') == 'type') {
echo str_repeat(' ', 20), '<div class="addition error">↳ You did not re-enter a valid email address.</div>', "\n";
} else if($validation->error('emailConfirm')) {
echo str_repeat(' ', 20), '<div class="addition error">↳ You did not re-enter your email to confirm.</div>', "\n";
}
}else if(!Input::exists()) {
echo str_repeat(' ', 20), '<div class="addition">↳ Re-enter your email to make sure it\'s correct.</div>', "\n";
}
</code></pre>
| [] | [
{
"body": "<p>You are repeating the same code:</p>\n\n<pre><code>echo str_repeat(' ', 20), '<div class=\"addition error\">↳ You did not enter your name.</div>', \"\\n\";\n</code></pre>\n\n<p>Replace it with a function which will do the job:</p>\n\n<pre><code>function message($content, $class = ''){\n return str_repeat(' ', 20) . '<div' . (($class) ? \" class='$class'\" : '') . \">$content</div>\\n\";\n}\n</code></pre>\n\n<p>You are using construction:</p>\n\n<pre><code>if () {} else if() {}\n</code></pre>\n\n<p>This is the same as: </p>\n\n<pre><code>if () {} else { if() {} }\n</code></pre>\n\n<p>I guess, that it is not what you want to use, the correct construction should be:</p>\n\n<pre><code>if () {} elseif() {} \n</code></pre>\n\n<p>The code itself can be rewritten like this:</p>\n\n<pre><code>function message($content, $class = ''){\n return str_repeat(' ', 20) . '<div' . (($class) ? \" class='$class'\" : '') . \">$content</div>\\n\";\n}\n\nif (!Input::exists()){\n echo message('We will address you by this name.', 'addition');\n echo message('Re-enter your email to make sure it\\'s correct.', 'addition');\n} elseif (Input::exists() && $token) {\n if($validation->error('firstname') && $validation->error('lastname')) {\n echo message('You did not enter your name.', 'addition error');\n } elseif($validation->error('firstname')) {\n echo message('You did not enter your first name', 'addition error');\n } else {\n echo message('You did not enter your last name.', 'addition error');\n }\n\n if($validation->error('emailConfirm') == 'match') {\n echo message('The email address you entered does not match.', 'addition error');\n } elseif($validation->error('emailConfirm') == 'type') {\n echo message('You did not re-enter a valid email address.', 'addition error');\n } else {\n echo message('You did not re-enter your email to confirm', 'addition error');\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T11:30:44.173",
"Id": "47644",
"ParentId": "47636",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47644",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T08:41:59.547",
"Id": "47636",
"Score": "3",
"Tags": [
"php",
"validation"
],
"Title": "Shortening if-statements of displaying errors"
} | 47636 |
<p>I've tried this <a href="http://codeforces.com/contest/412/problem/C" rel="nofollow">problem</a> on Codeforces. Given a set of string patterns, all of which are the same length, and which consist of literal lowercase ASCII characters and <code>?</code> wildcards, find a pattern that satisfies them all.</p>
<p>I want to optimize and simplify it further and make it a more elegant solution, if possible.</p>
<pre><code>import sys
def main():
n = int(sys.stdin.readline())
t = sys.stdin.readlines()
l = len(t[0])
result = ''
if n==1:
result = t[0].replace('?', 'x')
else:
for y in range(0,l-1):
let = t[0][y]
for x in range(1,n):
if let == '?' and t[x][y]!= '?':
let = t[x][y]
if t[x][y] != let and t[x][y] != '?':
result += '?'
break
elif x == n-1:
if let == '?':
result += 'x'
else:
result += let
print result
main()
</code></pre>
| [] | [
{
"body": "<p>Use more meaningful variable names, for example:</p>\n\n<ul>\n<li><code>lines</code> instead of <code>t</code></li>\n<li><code>length</code> instead of <code>l</code></li>\n<li>Since <code>y</code> is a character position, I would rename to <code>pos</code></li>\n<li><code>let</code> to <code>letter</code>, because it's not much longer and a bit more readable (since <code>let</code> is keyword in some other programming languages, I find it confusing to read)</li>\n</ul>\n\n<hr>\n\n<p>Since <code>lines[0]</code> is kind of special, and you make many references to it, it would be good to give it a name:</p>\n\n<pre><code>first = lines[0]\n</code></pre>\n\n<hr>\n\n<p>Your input lines end with a trailing newline character, but in the main logic of pattern matching this is just noise, not an important detail. I recommend this:</p>\n\n<pre><code>first = lines[0].strip()\n</code></pre>\n\n<p>This will get rid of the trailing newline character, and in the main logic you don't have to worry about checking letters until <code>first[-1]</code>, you can consider the letters in <code>first</code>, which is simpler.</p>\n\n<hr>\n\n<p>If you make changes to the script, you have to repeat all the tests to see if it's still working. That's very troublesome. To make that easier, add some unit tests, and refactor the <code>main</code> method to make it more testable, for example:</p>\n\n<pre><code>import unittest\nfrom test.test_support import run_unittest\n\ndef main():\n n = int(sys.stdin.readline())\n lines = sys.stdin.readlines()[0:n]\n print find_common_pattern(lines)\n\ndef find_common_pattern(lines):\n # the rest of the code from the old version of `main`\n\nclass FindPatterns(unittest.TestCase):\n def test_given_examples(self):\n self.assertEqual('xab', find_common_pattern(['?ab\\n', '??b\\n']))\n self.assertEqual('?', find_common_pattern(['a\\n', 'b\\n']))\n self.assertEqual('xaxb', find_common_pattern(['?a?b\\n']))\n\nrun_unittest(FindPatterns)\n</code></pre>\n\n<p>After this, it will be easy to follow my suggestions below and verify that the script is still working correctly, passing all test cases. (Feel free to add more!)</p>\n\n<hr>\n\n<p>Instead of <code>range(0, length-1)</code>, you can write simply <code>range(length-1)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>if let == '?' and t[x][y]!= '?':\n let = t[x][y]\nif t[x][y] != let and t[x][y] != '?':\n result += '?'\n</code></pre>\n</blockquote>\n\n<p>If the first <code>if</code> was true, the second will not be true, and it's a waste to evaluate it again. You could make the second <code>if</code> an <code>elif</code> instead.</p>\n\n<hr>\n\n<p>The last <code>elif</code> in your <code>for</code> loop is a bit dirty: it's for checking if you're on the last line. The condition will be evaluated for every line where the current position is <code>?</code>, which is a bit wasteful. It would be better to refactor that loop to perform that check only once at the end, for example:</p>\n\n<pre><code>for pos in range(length):\n letter = first[pos]\n newletter = letter\n for x in range(1, len(lines)):\n if letter == '?' and lines[x][pos] != '?':\n letter = lines[x][pos]\n elif lines[x][pos] != letter and lines[x][pos] != '?':\n newletter = '?'\n break\n if letter == '?':\n result += 'x'\n else:\n result += newletter\n</code></pre>\n\n<p>After this refactoring, you don't need the value of <code>x</code> inside the loop anymore, so you could rewrite more intuitively as:</p>\n\n<pre><code>for line in lines[1:]:\n if letter == '?' and line[pos] != '?':\n letter = line[pos]\n elif line[pos] != letter and line[pos] != '?':\n newletter = '?'\n break\n</code></pre>\n\n<hr>\n\n<p>Since the characters <code>?</code> and <code>x</code> appear several times in the code, I would treat them as constants and name them for example:</p>\n\n<ul>\n<li><code>ANYCHAR = '?'</code></li>\n<li><code>SAMPLECHAR = 'x'</code></li>\n</ul>\n\n<hr>\n\n<p>Instead of running <code>main</code>, the common way is like this:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>This way, your script will still run as before when you do <code>python script.py</code>, and at the same time it will be possible to import it from another python script as a library without automatically running it. It's a good practice to get used to, even if you don't intend to make this a library.</p>\n\n<hr>\n\n<p>Putting it all together, and some other minor improvements, this would be more Pythonic, and slightly more readable and efficient:</p>\n\n<pre><code>ANYCHAR = '?'\nSAMPLECHAR = 'x'\n\ndef find_common_pattern(lines):\n first = lines[0].strip()\n lines = lines[1:]\n if not lines:\n return first.replace(ANYCHAR, SAMPLECHAR)\n result = ''\n for pos in range(len(first)):\n letter = first[pos]\n newletter = letter\n for line in lines:\n if line[pos] != ANYCHAR:\n if letter == ANYCHAR:\n letter = line[pos]\n elif line[pos] != letter:\n newletter = ANYCHAR\n break\n if letter == ANYCHAR:\n result += SAMPLECHAR\n else:\n result += newletter\n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:34:24.247",
"Id": "83553",
"Score": "0",
"body": "Thanks very much for such an informative answer. Just one question; I'm a bit confused on how \"if not lines:\" works. Could you expand please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:36:53.793",
"Id": "83554",
"Score": "0",
"body": "Sure! An empty list is false in Python, that's why it works. This technique is actually recommended by [PEP8](http://legacy.python.org/dev/peps/pep-0008/)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T14:25:29.687",
"Id": "47651",
"ParentId": "47638",
"Score": "7"
}
},
{
"body": "<p>(This answer is in Python 3. Feel free to make the necessary adjustments to run it on 2.x)</p>\n\n<h1>Introduction</h1>\n\n<p>The review posted by janos underscores the need for good names, following coding conventions. The post suggests incremental improvements, which is a step in the right direction.</p>\n\n<p><strong>To make more radical improvements to your code</strong>, you need to recognize the deeper structural problems, which arise because you're <strong>not using the full flexibility of Python</strong> and because you aren't using <strong>the right data structure to simplify your algorithm</strong>.</p>\n\n<h1>Handling the input</h1>\n\n<p>The only responsibility of <code>main()</code>should be to collect and sanitize the input and subsequently output the result:</p>\n\n<pre><code>def main():\n pattern_count = int(sys.stdin.readline())\n patterns = itertools.islice(sys.stdin, pattern_count)\n result = intersect_patterns(p.strip() for p in patterns)\n print(result)\n</code></pre>\n\n<p>The calculation should be kept separate, in the <code>intersect_patterns</code> function.</p>\n\n<h1>Join instead of <code>+=</code></h1>\n\n<p>It would be more elegant to separate the concatenation of the resulting string from the calculation of its contents. You can achieve this by using <a href=\"https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/\">Python's <code>yield</code> keyword</a> to create a generator whose elements can be joined like so:</p>\n\n<pre><code>def intersect_patterns(lines):\n return ''.join(_intersect_patterns(lines))\n</code></pre>\n\n<h1>Iterating <em>the right way</em></h1>\n\n<p>You are making your algorithm a lot more complex by iterating over the input in the traditional <strong>line-by-line fashion</strong> when you are in fact interested in examining <strong>one <em>column</em> at a time</strong>. </p>\n\n<p>The solution is to think of the <strong>lines as rows</strong> and the <strong>characters as columns <em>in a matrix</em></strong>. To iterate over the columns instead of the rows, <em>transpose it</em> using the built-in <a href=\"https://docs.python.org/3.4/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code> function</a> with the <code>*</code> operator, as shown in <a href=\"https://stackoverflow.com/a/7313210/1106367\">this answer on StackOverflow</a>.</p>\n\n<pre><code>def _intersect_patterns(lines, wildcard='?', fill='x'):\n for column in zip(*lines):\n literals = {char for char in column if char != wildcard}\n if not literals:\n yield fill\n elif len(literals) == 1:\n yield literals.pop()\n else:\n yield wildcard\n</code></pre>\n\n<h1>The right data structure for the job</h1>\n\n<p>Wow, where did all the code go? It turns out that there is a data structure which can do most of the work for you: the <a href=\"https://docs.python.org/3.4/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow noreferrer\"><code>set</code></a> (which we create using a set comprehension, or <code>{...}</code>), because for each column, we only need to examine the unique literals, disregarding any wildcards, to determine what to put in the intersecting pattern we are calculating.</p>\n\n<h2>There are only three possible cases</h2>\n\n<p>The column we are examining contains...</p>\n\n<ol>\n<li><strong>No literals → only wildcards</strong>, so we need to insert <em>a literal (for instance <code>x</code>)</em> into the output.</li>\n<li><strong>Exactly one unique literal</strong>, so we need to insert <em>that literal</em> into the output.</li>\n<li><strong>More than one unique literal</strong>, so we need to insert <em>a wildcard</em> into the output.</li>\n</ol>\n\n<p>We simply <code>yield</code> the correct character on every iteration. Our caller can then take care of assembling the result string and printing it.</p>\n\n<h1>Conclusion</h1>\n\n<ul>\n<li><p>Before racing to implement a solution, think about the <strong>algorithms and data structures</strong> that might help you. For example, iterate over the data in a way that makes sense and use what the standard library has to offer.</p></li>\n<li><p>Analyze the possible scenarios <strong>by writing them down</strong> before coding them, which will help you discover the simplest solution.</p></li>\n<li><p><a href=\"http://blog.codinghorror.com/curlys-law-do-one-thing/\" rel=\"nofollow noreferrer\">Separate your concerns.</a></p></li>\n<li><p>If you need to write if statements for special cases, you might be doing it wrong.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:59:53.720",
"Id": "83718",
"Score": "2",
"body": "It's elegant and beautiful, great post! Just one drawback compared to the original ugly one is the way you build `literals` is wasteful, because you iterate over all characters in the column when it would be enough until you find two different. That's of course easy to fix, and it will still be elegant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-22T18:02:10.523",
"Id": "334469",
"Score": "1",
"body": "Very good @Adam I wanted to award you a bounty for this answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:19:59.623",
"Id": "47763",
"ParentId": "47638",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47763",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T09:31:30.203",
"Id": "47638",
"Score": "6",
"Tags": [
"python",
"programming-challenge"
],
"Title": "String pattern riddle"
} | 47638 |
<p>My goal is to parse defines in Objective-C code:</p>
<pre><code>#define wowFont [UIFont fontWithName:(DEV)?@"one":@"two" size:(DEV? 10: 12)]
#define wowColor [UIColor colorWithRed:(DEV?240/255.0f:255.0f) green:((DEV)? 230.0f / 255.0f) blue: 10.0f]
</code></pre>
<p>I try to write grammar for it:</p>
<pre><code>grammar Defines::Grammar {
token TOP {
\s*<define_expression>\n
}
token define_expression {
^^ #define $<keyword>=\w+ \s+ $<value> = <general_expression>
}
token general_expression{
# here, determine parenthes
<simple_expression>|[(]<general_expression>[)]|<value_expression>
}
token simple_expression{
# here, determine ?: behaviour
\s*<general_expression>\s*[?]\s*<general_expression>\s*[:]\s*<general_expression>\s*
}
token value_expression {
# stop here, need to determine ?: operator here
<numeric_expression>|<string_expression>|<function_invocation_expression>|<bareword_expression>
}
token function_invocation_expression {
[\[] (<class>|<bareword_expression>) \s+ <function_body>\s* [\]]
}
token function_body {
<bareword_expression>|<bareword_expression> \s* [:] <general_expression>
}
token bareword_expression {
[\w_]+
}
token string_expression {
\@["][^"]["]
}
token numeric_expression {
# we could +-*/ numeric expressions, also we can put lead sigil [-]. put parentheses and it could be a <number>
<numeric_expression> [*/+-] <numeric_expression> | [-+]<numberic_expression> | [(] <numeric_expression> [)] | <number>
}
token number {
# number expression here, ok
# not needed legal sign here, numeric_expression already have it
\d+ [\.] \d+
}
}
</code></pre>
<p>Could anybody help to improve it?</p>
<p>P.S: As a part of answer (I hope that somebody will find this documents helpful) I place here a link to Perl 6 book (I found out that Grammars section is good enough for beginning). <a href="https://github.com/perl6/book/downloads" rel="nofollow">Perl 6 Book</a></p>
| [] | [
{
"body": "<p>It doesn't look like this code is currently working.</p>\n\n<p>AFAIK Objective-C uses the normal C preprocessor. The preprocessor works on a token level, and does not know about stuff like method calls. It is entirely irrelevant that <code>[</code> starts a method call or an array subscript, for the preprocessor it's just some token. So as a rough sketch:</p>\n\n\n\n<pre class=\"lang-c prettyprint-override\"><code>token TOP {\n ^^ \\s* '#define' \\s* $<name>=<bareword> \\s* $<value>=(<token>+) $$\n}\n</code></pre>\n\n<p>Notice that my <code>#</code> is inside a string and is thus not interpreted as a comment!</p>\n\n<p>There are however some special cases to consider:</p>\n\n<ol>\n<li><p>Arguments to the macros:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define MIN(a, b) (((a) < (b)) ? a : b)\n</code></pre>\n\n<p>Here, the <code>a</code> and <code>b</code> tokens have special meaning to the preprocessor.</p></li>\n<li><p>Line continuations:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define MIN(a, b) \\\n (((a) < (b)) ? a : b)\n</code></pre></li>\n<li><p>Token concatenation with <code>##</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// \"MANGLE(foo, bar)\" → foobar\n#define MANGLE(prefix, name) prefix##name\n</code></pre></li>\n</ol>\n\n<p>The next problem is that <code>\\s</code> is any Unicode whitespace, including newlines. It would be recommendable to restrict that to horizontal whitespace. It would make sense to override the <code>ws</code> rule:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>token ws {\n <!ww> \\h*\n}\n</code></pre>\n\n<p>With support for line continuations:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>token ws {\n <!ww> [ \\h | \\\\\\n ]*\n}\n</code></pre>\n\n<p>We can now use sigspace (significant whitespace) to simplify our <code>token</code>s as <code>rule</code>s, e.g:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>rule TOP {\n ^^ '#define' $<name>=<bareword> $<value>=(<token>+) $$\n}\n</code></pre>\n\n<p>What is a token? Identifier, number, character, symbol, or string. You attempt to match a string with <code>\\@[\"][^\"][\"]</code>, but this fails for various reasons:</p>\n\n<ul>\n<li><p>In Perl 6, the <code>[…]</code> denotes a non-capturing group, but not a character class. These now look like <code><[…]></code>. Especially, a negated character class looks like <code><-[…]></code>.</p></li>\n<li><p>If that were a Perl 5 regex, you'd only be allowing a single letter inside the string, because the <code>[^\"]</code> charclass is not being repeated.</p></li>\n</ul>\n\n<p>If we also want to handle escapes inside the string, a string token might be matched by</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>token string {\n \\@\\\" [ <-[\\\"\\\\]> | \\\\. ]* \\\"\n}\n</code></pre>\n\n<p>Similar errors also occur in other tokens.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T07:00:56.670",
"Id": "83596",
"Score": "0",
"body": "great guide! thanks! wow! you've found so many white spots in my code! BTW, why you use double start sign (^^) and double end sign ($$)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T07:04:32.237",
"Id": "83597",
"Score": "0",
"body": "I try to make grammar for narrow defines class, like obj-c method calls and simple string/numeric expressions"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T13:07:50.963",
"Id": "47649",
"ParentId": "47639",
"Score": "3"
}
},
{
"body": "<p>I was about to submit this when I saw that you had visited #perl6. I'll leave this post as is because it is supposed to help others that might one day read this as well as you.</p>\n\n<p><strong>TL;DR</strong> I recommend you: make sure you're ready for an immature compiler, ecosystem, doc, etc; <strong>use Rakudo Star and the Rakudo debugger</strong>; start small and take small steps, making each step work before moving forward; rely very heavily on #perl6 -- they welcome any and all comers, including \"newbies\" and lots of basic questions.</p>\n\n<hr>\n\n<p>First, let me make sure you are not wasting your time due to wrong expectations. I am pretty sure there are currently only a handful of folk using P6 in production and they are doing so for only a small range of use cases. Powerful parsing is one of them, so what you are attempting is reasonable, but it's slow and you need to be willing to patiently deal with the many other frustrations that can result from P6's immaturity. If this hasn't put you off, welcome aboard! :)</p>\n\n<p>Second, let me make sure I am not wasting your time. Your code doesn't compile using the tools I'm using. I used a procedure you can repeat to test your code with the latest Rakudo Perl 6 compiler HEAD:</p>\n\n<ul>\n<li>I joined <a href=\"https://kiwiirc.com/client/irc.freenode.net/perl6\" rel=\"nofollow\">#perl6, the freenode IRC channel</a>. (A very friendly channel. All are welcome.)</li>\n<li>I tested code by entering a line of the form \"m: ...\". (Replace the \"...\" with code, or a suitable \"pastebin\" URL as explained below, otherwise you'll get a \"Stub code executed\" exception. An evalbot spots such lines, runs the code using the HEAD of the Rakudo compiler using the MoarVM backend, and displays the result.)</li>\n<li>I ran your code privately (recommended if you don't want to \"spam\" the channel with attempts that aren't interesting to others) so you won't be able to see this in <a href=\"http://irclog.perlgeek.de/perl6/today\" rel=\"nofollow\">the public IRC log</a>. To run code privately enter the command <code>/msg camelia r: say $*PERL</code>, switch to the \"camelia\" window, and enter lines there.</li>\n<li>So I entered \"m: <a href=\"https://gist.github.com/raiph/11084741\" rel=\"nofollow\">https://gist.github.com/raiph/11084741</a>\" which attempted to compile a copy of your code. It failed to compile.</li>\n</ul>\n\n<p>Third, let's radically improve your debugging options. One option when debugging grammars is to use the Grammar::Tracer module. This is occasionally useful but for most purposes there's a much better option: Rakudo's good-trending-great debugger. <strong>Use the debugger all the time unless you have a compelling reason not to.</strong> The Rakudo debugger is not available using the on channel evalbots I just discussed above; it requires that you install something. I recommend the Rakudo Star package unless you have a compelling reason to use something else. Rakudo Star includes the debugger, modules, and doc including info on how to start the debugger.</p>\n\n<p>Fourth, <strong>start simple and build up from there</strong>, only making another small step forward when what you currently have works. For example, a first step might be:</p>\n\n<pre><code>say so '#define foo [blah]' ~~ rule { '#define' <ident> .* }\n</code></pre>\n\n<p>prints:</p>\n\n<pre><code>True\n</code></pre>\n\n<p>meaning the string on the left of the <code>~~</code> was \"accepted\" by the thing on the right.</p>\n\n<p>The thing on the right is a <code>rule</code> which is one of several convenient forms of regex introduced by P6. The P6 regex engine never backtracks once it's matched an atom in a rule and it replaces appropriate spaces in your rule with implicit calls to the whitespace matching rule called <code><ws></code>. The above line is equivalent to:</p>\n\n<pre><code>say so '#define foo [blah]' ~~ regex { :ratchet '#define' <.ws> <ident> <.ws> .* }\n</code></pre>\n\n<p>(The <code>.</code> in <code><.ws></code> tells P6 to call the <code><ws></code> rule without saving the text it matched in the match object being built up by the processing of the regex.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T06:58:04.273",
"Id": "83595",
"Score": "0",
"body": "yeah, thanks for example and beginning guide! I will upvote your answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T08:26:11.507",
"Id": "83603",
"Score": "3",
"body": "I don't have enough points to comment on amon's great answer. ^ and $ anchor to the start and end of a string respectively. In P6 ^^ and $$ anchor to start and end of a single line within a string. See spec at http://perlcabal.org/syn/S05.html#New_metacharacters"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:38:31.037",
"Id": "47658",
"ParentId": "47639",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T09:59:42.833",
"Id": "47639",
"Score": "3",
"Tags": [
"parsing",
"perl",
"grammar"
],
"Title": "Perl 6: Grammar issues (simple defines)"
} | 47639 |
<p>I have some old RAR files and I know the general format of passwords I used to use, so I have generated a dictionary file combining those words in a variety of ways. The dictionary file is 500mb and I've wrote a python program to use the dictionary. </p>
<p>The issue is that the program has been running all night and is only 1% of the way in. I've now divided the dictionary file up and I am now running multiple instances of the program, but each instance is running pretty slow.</p>
<p>I would love any advice on how to improve the speed. I'm very new to Python, which will be obvious by my code (but I'm really enjoying Python).</p>
<pre><code>import itertools
import sys, traceback
import os
with open('dictionary.txt') as infile:
words = [line.strip() for line in infile]
for word1 in itertools.product(words, repeat=1):
fword = word1[0]
print "Attempting: " + fword
# open unrar and test password
output = os.popen("unrar.exe x protected.rar -p" + fword)
outstring = output.read()
slng = len(outstring)
# unrar.exe returns "All OK" for correct password
validate = outstring.find("All OK", 0, slng)
if validate != -1:
print "Found password: " + fword
with open('correct_password.txt', 'w') as outfile:
outfile.write(fword)
sys.exit(0)
else:
# continue searching
print "invalid password"
raw_input("Password was not in this dictionary!")
</code></pre>
<p>Sample dictionary.txt</p>
<pre><code>FableLand
FableWay
FableTree
FableSpirit
FableApple
</code></pre>
| [] | [
{
"body": "<p>The line that jumps out at me as being a performance concern is this one:</p>\n\n\n\n<pre><code>words = [line.strip() for line in infile]\n</code></pre>\n\n<p>You’re generating a list that contains every word in <code>dictionary.txt</code>. This means a 500 MB dictionary file will create a similarly large list (which is going to be a huge structure). It also means that if the password is early on in the list, you still have the whole file as a list in memory.</p>\n\n<p>This gets followed by the line</p>\n\n\n\n<pre><code>for word1 in itertools.product(words, repeat=1):\n fword = word1[0]\n</code></pre>\n\n<p>and I’m not sure quite why you’re getting the words out in this way. As you go through <code>itertools.product</code>, you get tuples, and you need to get the first element out. Using an iterable is generally good for performance, but the problem is creating the list in the first place, more than iterating over it.</p>\n\n<p>The advice in <a href=\"https://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python\">How to read large file, line by line in Python</a> is helpful here. Consider reading your file as</p>\n\n\n\n<pre><code>with open('dictionary.txt') as f:\n for line in f:\n # try that line as your password\n</code></pre>\n\n<p>That’s probably going to give a noticeable benefit.</p>\n\n<hr>\n\n<p>Other comments:</p>\n\n<ul>\n<li><p>Right now, all the functionality is tied up together. I’d separate the code which tests a password, and the code which gets an iterable of passwords from <code>dictionary.txt</code>. For example:</p>\n\n\n\n<pre><code>def try_password(fword, rar_file):\n print \"Attempting: %s\" % fword\n\n # open unrar and test password\n output = os.popen(\"unrar.exe x %s -p %s\" % (fword, rar_file))\n outstring = output.read()\n\n # unrar.exe returns \"All OK\" for correct password\n validate = outstring.find(\"All OK\", 0, len(outstring)) \n if validate != -1:\n print \"Found password: %s\" % fword\n return 0\n else:\n # continue searching\n return 1\n\nwith open('dictionary.txt') as f:\n for line in f:\n attempt = try_password(line.strip(), 'protected.rar')\n if attempt == 0:\n break\n</code></pre>\n\n<p>Now you could also use the same code which gets your passwords to tackle, say, a bunch of encrypted ZIP files.</p>\n\n<p>I added the return codes <code>0</code> and <code>1</code> to denote success and failure when trying a password.</p>\n\n<p>What did the <code>slng</code> variable stand for? Anyway, it was only used once so I removed it.</p>\n\n<p>There are a few other tweaks I made, but nothing very major.</p></li>\n<li><p>Your <code>import sys, traceback</code> statement should really be split onto two separate lines. Quoting from <a href=\"http://legacy.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP 8</a>, the Python style guide:</p>\n\n<blockquote>\n <p>Imports should usually be on separate lines</p>\n</blockquote></li>\n<li><p>Why is the final line a <code>raw_input</code> instead of a <code>print</code> statement?</p>\n\n<ul>\n<li>Where did <code>dictionary.txt</code> actually come from? You say you “generated” it, so could you just bypass the step where you write the passwords out to a file and just try them directly within the generator?</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T00:08:03.333",
"Id": "83581",
"Score": "0",
"body": "So much great advice. It is going to take me a little while to digest it all. I really appreciate your time and effort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T11:23:02.403",
"Id": "47643",
"ParentId": "47640",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T10:38:38.583",
"Id": "47640",
"Score": "7",
"Tags": [
"python",
"performance",
"beginner"
],
"Title": "RAR dictonary attack"
} | 47640 |
<p>I implemented Aho-Corasick string matching in Haskell. It is a purely functional implementation compared to many other implementations.</p>
<p>The input to build an automata is <code>[([a],b)]</code>. which is a list of <code>(pattern,output)</code> pairs.
<code>b</code> has to form a monoid, so we know what to do when more than one match occurs at the same place.</p>
<p>I borrowed many idea from the <a href="http://twanvl.nl/blog/haskell/Knuth-Morris-Pratt-in-Haskell" rel="nofollow">KMP implementation by Twan van Laarhoven</a>(which I suspect is a implementation of the MP instead of KMP algorithm).</p>
<pre><code>import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function
import Control.Arrow
data Automaton a b = Node {delta :: a -> Automaton a b,
output :: b
}
-- assume the input function eq is a equivalence relation, then this
-- produce all the equivalent classes.
equivalentClasses :: (a->a->Bool)->[a]->[[a]]
equivalentClasses eq = foldl parts []
where parts [] a = [[a]]
parts (x:xs) a
| eq (head x) a = (a:x):xs
| otherwise = x:parts xs a
buildAutomaton :: (Monoid b,Eq a) => [([a],b)] -> Automaton a b
buildAutomaton xs = automaton
where automaton = build (const automaton) xs mempty
-- this builds one node of the automaton. Tying the knot happens everywhere
build :: (Monoid b,Eq a)=> (a -> Automaton a b) -> [([a],b)] -> b -> Automaton a b
build trans' xs out = node
where node = Node trans out
trans a
| isNothing next = trans' a
| otherwise = fromJust next
where next = lookup a table
table = map transPair $ equivalentClasses (on (==) (head . fst)) xs
transPair xs = (a, build (delta (trans' a)) ys out)
where a = head $ fst $ head xs
(ys,zs) = partition (not . null . fst) $ map (first tail) xs
out = mappend (mconcat $ map snd zs) (output $ trans' a)
-- this function simulates the automaton.
match :: Eq a => Automaton a b -> [a] -> [b]
match a xs = map output $ scanl delta a xs
-- an example to check if a list is a sublist of another list
isInfixOf' :: Eq a => [a] -> [a] -> Bool
isInfixOf' xs ys = getAll $ mconcat $ match (buildAutomaton [(xs, All True)]) ys
</code></pre>
| [] | [
{
"body": "<p>It would be nice if the code was ordered for exposed functions versus internal helpers. It looks like <code>buildAutomaton</code> is the exposed API along with the <code>Automaton</code> data type. However, <code>buildAutomaton</code> is the one function missing any comments or docs.</p>\n\n<p><code>trans</code> looks a lot like <code>maybe</code> from the Prelude/Data.Maybe.</p>\n\n<p>Use explicit imports to make clear where your functions are coming from.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:49:25.557",
"Id": "49260",
"ParentId": "47642",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T10:53:47.790",
"Id": "47642",
"Score": "5",
"Tags": [
"algorithm",
"strings",
"haskell"
],
"Title": "Aho-Corasick string matching in Haskell"
} | 47642 |
<p>I'm a beginner developer, I'm learning online (mostly from the Apple documentation guides), and couple a days ago I started a notes app project. It's the first app I'm building without a guide.</p>
<p>It's very simple so I'd love to post it here and get your feedback on how to improve my code to be more efficient.</p>
<p>The app have two view controllers:</p>
<ol>
<li><p>NotesListViewController</p></li>
<li><p>CreateNotesViewController</p></li>
</ol>
<p>I use Core Data so I created an entity called <code>Note</code> that have one string attribute called <code>content</code>, after that I created the model class from the entity section by doing <code>editor/create NSManagedObject subclass</code>.</p>
<p>So those are my class:</p>
<p>NotesListViewController.h:</p>
<pre><code>#import <UIKit/UIKit.h>
@interface NotesListViewController : UITableViewController
- (IBAction) unwindToList:(UIStoryboardSegue *)segue;
@end
</code></pre>
<p>NotesListViewController.m:</p>
<pre><code>#import "NotesListViewController.h"
#import "Note.h"
#import "CreateNotesViewController.h"
@interface NotesListViewController ()
@property (nonatomic, strong) NSMutableArray *notes;
@property (nonatomic) NSInteger editedRow;
@end
@implementation NotesListViewController
- (NSManagedObjectContext *) managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]){
context = [delegate managedObjectContext];
}
return context;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"editSegue"]) {
CreateNotesViewController *destination = (CreateNotesViewController *)[segue destinationViewController];
NSInteger indx = [self.tableView indexPathForCell:sender].row;
Note *noteToPass = self.notes[indx];
destination.note = noteToPass;
self.editedRow = indx;
NSManagedObject *selectedNote = [self.notes objectAtIndex:[self.tableView indexPathForSelectedRow].row];
destination.editNote = selectedNote;
} else if ([[segue identifier] isEqualToString:@"addSegue"]) {
self.editedRow = -1;
}
}
- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
CreateNotesViewController *source = (CreateNotesViewController *)[segue sourceViewController];
Note *recieivedNote = source.note;
if (recieivedNote != nil && self.editedRow == -1) {
[self.notes addObject:recieivedNote];
} else if (recieivedNote != nil)
{
[self.notes replaceObjectAtIndex:self.editedRow withObject:recieivedNote];
}
[self.tableView reloadData];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.notes = [[NSMutableArray alloc] init];
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Note"];
self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.notes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *noteToDisplay = [self.notes objectAtIndex:indexPath.row];
[cell.textLabel setText:[noteToDisplay valueForKey:@"content"]];
return cell;
}
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[context deleteObject:[self.notes objectAtIndex:indexPath.row]];
NSError *error = nil;
if ([context save:&error]) {
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
}
[self.notes removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
@end
</code></pre>
<p>CreateNotesViewController.h:</p>
<pre><code>#import <UIKit/UIKit.h>
#import "Note.h"
@interface CreateNotesViewController : UIViewController
@property (nonatomic, strong) Note *note;
@property (strong) NSManagedObject *editNote;
@end
</code></pre>
<p>CreateNotesViewController.m:</p>
<pre><code>#import "CreateNotesViewController.h"
@interface CreateNotesViewController ()
@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
@property (weak, nonatomic) IBOutlet UITextView *myTextView;
@end
@implementation CreateNotesViewController
- (NSManagedObjectContext *) managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]){
context = [delegate managedObjectContext];
}
return context;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (sender != self.saveButton) return;
if (self.myTextView.text.length > 0) {
self.note.content = self.myTextView.text;
NSManagedObjectContext *context = [self managedObjectContext];
if (self.editNote) {
[self.editNote setValue:self.myTextView.text forKey:@"content"];
} else {
// creating a new managed object
NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:context];
[newNote setValue:self.myTextView.text forKey:@"content"];
}
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
else
{
NSLog(@"Saved! %@ %@", error, self.myTextView.text);
}
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.myTextView.text = self.note.content;
// listen for keyboard hide/show notifications so we can properly adjust the table's height
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)adjustViewForKeyboardReveal:(BOOL)showKeyboard notificationInfo:(NSDictionary *)notificationInfo
{
// the keyboard is showing so ƒ the table's height
CGRect keyboardRect = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration =
[[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.myTextView.frame;
// the keyboard rect's width and height are reversed in landscape
NSInteger adjustDelta = UIInterfaceOrientationIsPortrait(self.interfaceOrientation) ? CGRectGetHeight(keyboardRect) : CGRectGetWidth(keyboardRect);
if (showKeyboard)
frame.size.height -= adjustDelta;
else
frame.size.height += adjustDelta;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.myTextView.frame = frame;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
[self adjustViewForKeyboardReveal:YES notificationInfo:[aNotification userInfo]];
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
[self adjustViewForKeyboardReveal:NO notificationInfo:[aNotification userInfo]];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
</code></pre>
<p>Note.h:</p>
<pre><code>#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Note : NSManagedObject
@property (nonatomic, retain) NSString * content;
@end
</code></pre>
<p>In the Note.m file I didn't added anything:</p>
<pre><code>#import "Note.h"
@implementation Note
@dynamic content;
@end
</code></pre>
<p>And I use storyboard to create my interface that looks like this:</p>
<p><img src="https://i.stack.imgur.com/c38Sl.png" alt="enter image description here"></p>
<p>So it's very basic, you can only:</p>
<ol>
<li>create a note (saved using core data)</li>
<li>view your notes list</li>
<li>edit a note (updated using core data)</li>
<li>delete a note (deleted using core data)</li>
</ol>
<p>I really enjoy programming in Objective-C and want to get better and better, so if you could be kind enough to give me your feedback on the code that would be awesome.</p>
| [] | [
{
"body": "<p>Look into the NSFetchedResultsController to power your table view. It's something specifically designed to be used with UITableViews that are powered by Core Data. </p>\n\n<p>In essence, it uses a fetch request and returns how many objects are in each section, how many sections there are, what header/footer information they have etc. It has the added benefit that if the underlying managed object context changes (for example when a new object is added, updated or deleted) the fetched results controller is updated automatically. When that happens you can send your table view a reloadData message so it's updated as if by magic. An NSFetchedResultsController adds another level of complexity to Core Data, but since you're already confidently using the framework my guess is you'll like it ;-)</p>\n\n<p>As a side note: look into Protocols. UIKit uses them extensively, they can be very useful and they're easy to create. With Protocols you can put one controller in charge of presenting and dismissing another view controller without having to rely on an unwind segue. The benefit is that one controller can hold on to a managed object, it gets changed in another view controller, and when that's dismissed the originating controller can use the changed object (to save or evaluate it).</p>\n\n<p>I've got a full working project on GitHub which illustrates both the NSFetchedResultsController and uses a Protocol to dismiss the Detail View. It's similar to what you're building (a CRUD Project - as in Create, Read, Update, Delete):</p>\n\n<p><a href=\"https://github.com/versluis/Master-Detail-CRUD\" rel=\"nofollow\">https://github.com/versluis/Master-Detail-CRUD</a></p>\n\n<p>Then of course there's adding a search feature to your table view... but that's for another time. When you're ready, I have a demo project for that too: <a href=\"https://github.com/versluis/TableSearch2014\" rel=\"nofollow\">https://github.com/versluis/TableSearch2014</a></p>\n\n<p>Let me know if it helps, and have fun with Objective C!</p>\n\n<p>PS: Kudos for sharing, and for not starting from a template. Well done!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T23:21:28.907",
"Id": "83577",
"Score": "0",
"body": "It helps allot :) thank you. I will implement your suggestions! @Jay Versluis"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T15:42:25.847",
"Id": "47655",
"ParentId": "47645",
"Score": "2"
}
},
{
"body": "<p>I don't know a whole lot about CoreData or NSManagedObjects, so I can't offer a whole lot of help in this realm, but here are some general style things I noticed (plus a few other things).</p>\n\n<p>You don't need the unwind segue method in your <code>.h</code> file. You can still hook up storyboard segues with it only being in the <code>@implementation</code>, and no other class needs to call this method.</p>\n\n<p>I can't see when the NSManagedContext property, <code>editNote</code> is used outside the second view controller, so this likewise probably doesn't need to be in the <code>.h</code> (but maybe I'm overlooking something).</p>\n\n<hr>\n\n<pre><code>id delegate = [[UIApplication sharedApplication] delegate];\n</code></pre>\n\n<p>The return from this method call is an object of type <code>UIApplication</code>. Your <code>delegate</code> variable should also be of type <code>UIApplication</code>, rather than simply <code>id</code>.</p>\n\n<p>Moreover, what you do in the following line doesn't make sense. I think you're trying to do a verification check that the <code>delegate</code> object responds to that selector, in which case you want:</p>\n\n<pre><code>if ([delegate respondsToSelector:@selector(managedObjectContext)]){\n context = [delegate managedObjectContext];\n}\n</code></pre>\n\n<hr>\n\n<p>When preparing for a segue and doing anything with a destination view controller, it's not good enough to simply compare the name of the destination segue. We should also be verifying the class of the destination view controller. In such a simple project, you won't run into a problem, and personally, I make the habit of giving every segue a unique name, but this isn't always necessarily the case. The proper way to grab a destination view controller looks like this:</p>\n\n<pre><code>if ([[segue identifier] isEqualToString:@\"MySegue]) {\n if ([[segue destinationViewController] isKindOfClass:[MyViewController class]]) {\n MyViewController *destination = [segue destinationViewController];\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I can't understand what or why you're doing what you're doing in <code>CreateNotesViewController</code>'s <code>prepareForSegue</code>. We need to do this stuff before we try to segue, given the possibility of a save failure.</p>\n\n<p>The save button should have an IBAction method of its own. It should go through the save process. If you want it to immediately segue after saving, then have it call the segue programmatically. But certainly after a save failure, perhaps the user should get the choice to either segue (and lose all their unsaved stuff, depending on segue type and other stuff) or just segue anyway.</p>\n\n<p>And either way, this sorts of code doesn't belong in <code>prepareForSegue</code>--that method is designed to allow you to set up the destination view controller and pass information to it--you shouldn't be slowing down a segue with something like a save process.</p>\n\n<hr>\n\n<p>Methods like this:</p>\n\n<pre><code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil\n{\n self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];\n if (self) {\n // Custom initialization\n }\n return self;\n}\n\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n // Do any additional setup after loading the view.\n}\n\n\n- (void)didReceiveMemoryWarning\n{\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n</code></pre>\n\n<p>Can and should be simply deleted. This is a subclass. If you're doing nothing with the method beyond invoking the superclass's implementation, then it's nothing but clutter--especially for one of the subclassed objects in all of iOS.</p>\n\n<hr>\n\n<p>Right now I don't understand the need for the <code>Note</code> class. Why doesn't an <code>NSString</code> work instead of a class with no methods and a single <code>NSString</code> property?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:11:33.863",
"Id": "85424",
"Score": "0",
"body": "The Note class is used by Core Data, it's a Managed Object Subclass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:26:06.987",
"Id": "85425",
"Score": "0",
"body": "Ah, I see that now. Makes more sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:46:04.380",
"Id": "47777",
"ParentId": "47645",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47655",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T11:35:07.263",
"Id": "47645",
"Score": "3",
"Tags": [
"beginner",
"objective-c",
"ios"
],
"Title": "Simple iPhone Notes app"
} | 47645 |
<p>I implemented a throttled database service trait for wrapping my service code in a future, supplying a slick session and throttling the # of requests in accordance to the length of the thread pool queue.</p>
<p>My main reason for this was to transfer the responsibility for database session / transaction handling away from the controllers into the service layer of the application. </p>
<p>However, since I am fairly new to play and Scala in general and I am working alone, I would really like some input regarding my code. Is it a good practice at all? Am I about to face any negative performance implications? Are there ways to optimize / refactor my code?</p>
<p>The code can also be found on <a href="http://pastebin.com/8XuH6hQS" rel="nofollow">Pastebin</a>.</p>
<pre><code>import daos.exceptions.TabChordDBThrottleException
import java.util.concurrent.{LinkedBlockingQueue, TimeUnit, ThreadPoolExecutor}
import scala.concurrent._
import play.api.db.slick
import play.core.NamedThreadFactory
/**
* Implement this trait to get a throttled database session Wrapper
*/
trait ThrottledDBService {
/** Override to use a different Application */
protected def app = slick.Config.app
/** Override to use different Databasename*/
protected def dataBaseName = slick.Config.defaultName
protected object DBConfiguration {
private def buildThreadPoolExecutionContext(minConnections: Int, maxConnections: Int) = {
val threadPoolExecutor = new ThreadPoolExecutor(minConnections, maxConnections,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue[Runnable](),
new NamedThreadFactory("tabchord.db.execution.context"))
ExecutionContext.fromExecutorService(threadPoolExecutor) -> threadPoolExecutor
}
val partitionCount = app.configuration.getInt(s"db.$dataBaseName.partitionCount").getOrElse(2)
val maxConnections = app.configuration.getInt(s"db.$dataBaseName.maxConnectionsPerPartition").getOrElse(5)
val minConnections = app.configuration.getInt(s"db.$dataBaseName.minConnectionsPerPartition").getOrElse(5)
val maxQueriesPerRequest = app.configuration.getInt(s"db.$dataBaseName.maxQueriesPerRequest").getOrElse(20)
val (executionContext, threadPool) = buildThreadPoolExecutionContext(minConnections, maxConnections)
}
/** A predicate for checking our ability to service database requests is determined by ensuring that the request
queue doesn't fill up beyond a certain threshold. For convenience we use the max number of connections * the max
# of db requests per web request to determine this threshold. It is a rough check as we don't know how many
queries we're going to make or what other threads are running in parallel etc. Nevertheless, the check is
adequate in order to throttle the acceptance of requests to the size of the pool.
@see https://github.com/TechEmpower/FrameworkBenchmarks/pull/124
*/
protected def isDBAvailable: Boolean = {
val dbc = DBConfiguration
dbc.threadPool.getQueue.size() < (dbc.maxConnections * dbc.maxQueriesPerRequest)
}
/**
* Wraps the block with a Future in the appropriate database execution context and slick session,
* throttling the # of request in accordance to the rules specified in the db config and.
*
* Terminates the future with a @TabChordDBThrottleException in case of queue overload
* @param body user code
* @return Future of the database computation
*/
protected def throttled[A](body: slick.Session => A):Future[A] = {
future{
if(isDBAvailable){
slick.DB(dataBaseName)(app).withSession {
s =>
body(s)
}
} else {
throw new TabChordDBThrottleException("Too many Requests pending in Threadpool")
}
}(DBConfiguration.executionContext)
}
/**
* Wraps the block with a Future in the appropriate database execution context and slick transaction,
* throttling the # of request in accordance to the rules specified in the db config and.
*
* Terminates the future with a @TabChordDBThrottleException in case of queue overload
* @param body user code
* @return Future of the database computation
*/
protected def throttledTransaction[A](body: slick.Session => A): Future[A] = {
throttled {
s => s.withTransaction {
body(s)
}
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T12:30:29.473",
"Id": "47647",
"Score": "3",
"Tags": [
"beginner",
"scala"
],
"Title": "Slick database throttling trait based on the Playframework Slick plugin"
} | 47647 |
<p>It seems like there are many ways implementing inheritance in JavaScript. Which version do you prefer or would you suggest another solution?</p>
<p>The code should run in IE8+ so my first version would not fit…</p>
<pre><code>function Animal(name) {
this.name = name
}
Animal.prototype = {
eat: function() {
console.log(this.name + ': *eat*')
}
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype, {
miaou: {
value: function() {
console.log(this.name + ': *miaou*')
}
}
})
var garfield = new Cat("Garfield");
garfield.eat(); // Garfield: *eat*
garfield.miaou(); // Garfield: *miaou*
// ------------
//
// possible alternative:
// […] see http://ejohn.org/blog/simple-javascript-inheritance/ for definition
// of Class
var Animal2 = Class.extend({
init: function(name) {
this.name = name
},
eat: function() {
console.log(this.name + ': *eat*')
}
});
var Cat2 = Animal2.extend({
init: function(name) {
this._super(name)
},
miaou: function() {
console.log(this.name + ': *miaou*')
}
});
var garfield2 = new Cat("Garfield2");
garfield2.eat(); // Garfield: *eat*
garfield2.miaou(); // Garfield: *miaou*
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T23:34:52.873",
"Id": "83579",
"Score": "0",
"body": "It looks like you're looking for opinions as to which to use, and not a code review."
}
] | [
{
"body": "<p>As Joseph mentioned, opinion questions is not what CodeReview is about.</p>\n\n<p>I tend to review every OO approach with these 4 questions:</p>\n\n<p><strong>Approach 1</strong></p>\n\n<ul>\n<li>Does <em>instanceof</em> still work ? -> Yes, good</li>\n<li>Do you introduce new properties, causing potential naming clashes -> No, good</li>\n<li>Can parameters easily be provided to the constructors -> Yes, good</li>\n<li>Can I easily have properties in .prototype -> Yes, good</li>\n</ul>\n\n<p><strong>Approach 2</strong></p>\n\n<ul>\n<li>Does <em>instanceof</em> still work ? -> Yes, good</li>\n<li>Do you introduce new properties, causing potential naming clashes -> Yes, not so good</li>\n<li>Can parameters easily be provided to the constructors -> Yes, good</li>\n<li>Can I easily have properties in .prototype -> Yes, good</li>\n</ul>\n\n<p>The second approach uses <code>_super</code>, which is not perfect but definitely acceptable, and the framework was written by John Resig..</p>\n\n<p>In the end, you should use the right tool for the job, and since you provided example code, we can't really tell you which approach is best.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T01:06:46.083",
"Id": "47686",
"ParentId": "47650",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47686",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T14:10:41.650",
"Id": "47650",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"inheritance"
],
"Title": "Simple inheritance with functions in subclasses"
} | 47650 |
<p>I'm trying to get a better handle of code organization and how HTML5 (really HTML) stack works in general. I've worked mostly with ASP.NET Webforms and done some MVC as well. Let me say now, "I hate magic". I hate figuring out the magic. I just want it to work in the manner that it's supposed to. So I posted this little HTML5 site on GitHub. Nothing fancy. At all. The structure is very MVC like and I do as much separation of files and code-behind as possible.</p>
<p>All I'm using is: HTML, JavaScript, jQuery, no CSS, and CSHTML (as codebehind).</p>
<p>So in short, is this good? Is this bad? What could be better?</p>
<p><a href="https://github.com/gamebeta2003/HTML5TestSite" rel="nofollow">Code on Github</a></p>
<p>Mainpage.cs (Model)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for Mainpage
/// </summary>
///
namespace Models
{
public class Mainpage
{
private SqlConnection sqlConn;
private string connStr;
public Mainpage()
{
//
// TODO: Add constructor logic here
//
}
private void sqlInit()
{
connStr = ConfigurationManager.ConnectionStrings["TestInput"].ConnectionString;
sqlConn = new SqlConnection(connStr);
}
public Mainpage(int id, string ld, DateTime? dm, string op1, string op2)
{
ID = id;
LineDesc = ld;
DateMade = dm;
Options1 = op1;
Options2 = op2;
}
public int ID { get; set; }
public string LineDesc { get; set; }
public DateTime? DateMade { get; set; }
public string Options1 { get; set; }
public string Options2 { get; set; }
public void Save()
{
sqlInit();
string insertStr = "usr_InsertValues";
SqlCommand sqlCmd = new SqlCommand(insertStr, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter sp;
if (DateMade.HasValue)
sp = new SqlParameter("@p2", DateMade.Value);
else
sp = new SqlParameter("@p2", DBNull.Value);
SqlParameter[] sps = new SqlParameter[] {new SqlParameter("@p1", LineDesc),
sp,
new SqlParameter("@p3", Options1),
new SqlParameter("@p4", Options2)};
sqlCmd.Parameters.AddRange(sps);
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
</code></pre>
<p>Default.cs (ViewModel)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Default
/// </summary>
///
namespace ViewModels
{
public class Default
{
public Default()
{
//
// TODO: Add constructor logic here
//
}
public Default(string desc, string sop1, string sop2, string sop3)
{
Description = desc;
SelectedOp1 = sop1;
SelectedOp2 = sop2;
SelectedOp3 = sop3;
}
public string Description { get; set; }
public string SelectedOp1 { get; set; }
public string SelectedOp2 { get; set; }
public string SelectedOp3 { get; set; }
public List<string> Option1 { get; set; }
public List<string> Option2 { get; set; }
public List<string> Option3 { get; set; }
public void Save()
{
Models.Mainpage mp = new Models.Mainpage(0, Description, new DateTime?(DateTime.Now), SelectedOp1, SelectedOp2);
mp.Save();
}
}
}
</code></pre>
<p>Default.cshtml (Controller/Code behind)</p>
<pre><code>@{
var linedesc = Request.Form["linedesc"];
var datemade = DateTime.Now.ToString();
var food = Request.Form["options1"];
var drinks = Request.Form["options2"];
string[] data = new String[4] {linedesc, datemade, food, drinks};
// Go back to Default.html and keep values selected, ie. values don't reset
var blah = "hi";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (IsPost)
{
ViewModels.Default vm = new ViewModels.Default(linedesc, food, drinks, null);
vm.Save();
}
Json.Write(data, Response.Output);
}
</code></pre>
<p>Default.html (View)</p>
<pre><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing Stuff</title>
<script type="text/javascript" src="/Views/JS/jquery-2.0.3.js"></script>
<script type="text/javascript" src="/Views/JS/Default.js"></script>
</head>
<body>
<form id="mainpage" method="post" action="../Controllers/Default">
<div style="clear:both;" id="dbInput">
<label for="linedesc">Description:</label>&nbsp;
<input type="text" id="linedesc" name="linedesc" />
<br /><br />
<input id="fruits" name="options1" value="fruits" type="radio" />
<label for="fruits">Fruits</label>&nbsp;
<input id="candies" name="options1" value="candies" type="radio" />
<label for="candies">Candies</label>&nbsp;
<input id="snacks" name="options1" value="snacks" type="radio" />
<label for="snacks">Snacks</label>
<br /><br />
<label for="options2">Choose beverage:</label>&nbsp;
<select id="options2" name="options2">
<option value="Coca-Cola">Coca-Cola</option>
<option value="Sprite">Sprite</option>
<option value="Root Beer">Root Beer</option>
<option value="Orange Juice">Orange Juice</option>
</select>
<br /><br />
<label for="options3">Sample:</label>&nbsp;
<select id="options3" name="options3">
</select>
<input type="submit" id="submit1" name="submit1" value="Submit" />
</div>
</form>
</body>
</html>
</code></pre>
<p>Default.js (JavaScript)</p>
<pre><code>$(document).ready(function () {
//$('#submitText').click(function () {
// $('#txtHolder').html('<span>I am like code behind in txtHolder.</span>');
// $('#results').html('<span>Results are here today.</span>');
//});
$('#mainpage').submit(function (e) {
e.preventDefault();
alert("hi");
var formData = $(this).serialize();
var frm = $(e.target);
$.ajax({
url: "../../Controllers/Default.cshtml",
data: formData,
type: "POST",
dataType: "json",
success: function (response) {
alert(response);
var options3 = $("#options3");
options3.empty();
for (var i = 0; i < response.length; i++)
{
options3.append(
$("<option></option>").text(response[i]).val(response[i])
);
}
// Adds data to dropdown
},
error: function () {
alert("Sorry, there seems to be a problem contacting the server.");
}
});
});
});
</code></pre>
| [] | [
{
"body": "<p>On the HTML side, don't use <code><br/></code> to force the content to a new line. Place contents in <code><div></code> instead.</p>\n\n<pre><code><div>\n <label for=\"linedesc\">Description:</label>&nbsp;\n ...\n</div>\n<div>\n <input id=\"fruits\" name=\"options1\" value=\"fruits\" type=\"radio\" />\n ...\n</div>\n<div>\n <label for=\"options2\">Choose beverage:</label>&nbsp;\n ...\n</div>\n<div>\n <label for=\"options3\">Sample:</label>&nbsp;\n ...\n</div>\n</code></pre>\n\n<p>On the JS side of things, load scripts last to avoid blocking the UI. It's better if the user can see the page first while scripts load, rather than a blank page because scripts load. Place them before <code></body></code> preferrably.</p>\n\n<pre><code> <script type=\"text/javascript\" src=\"/Views/JS/jquery-2.0.3.js\"></script>\n <script type=\"text/javascript\" src=\"/Views/JS/Default.js\"></script>\n</body>\n</code></pre>\n\n<p>And some script improvements:</p>\n\n<pre><code>// A function to a jQuery function is shorthand for $(document).ready(fn);\n$(function () {\n\n // I highly guess this is a static container. I'd cache it\n // in a variable to avoid jQuery fetching it again every submit.\n var options3 = $(\"#options3\");\n\n //Commented out code is useless code. Get rid of it.\n\n $('#mainpage').submit(function (e) {\n e.preventDefault();\n\n // And unless you have reason for the alert, don't use it.\n // In debugging, console.log() is better, and breakpoints are even better than both\n\n //e.target and \"this\" in this handler is the same\n var form = $(this);\n var formData = form.serialize();\n\n // You can use the form action attribute for the url. Don't hardcode. \n // If it's different, you can store it in a data-* variable\n // Use data-* variables for dynamic stuff generated on page.\n // Helps you get along with backend devs who generate the HTML but hate writing JS (or mixing code with it);\n var url = form.attr('action'); //form.data('action') if it was in data-action=\"URL\" in the HTML\n\n // Shorthand AJAX post. Nulled the third since we use promises.\n $.post(url, formData, null, 'json')\n .done(function (response) {\n options3.empty();\n\n for (var i = 0; i < response.length; i++) {\n // jQuery also accepts self-closing tags to create elements.\n // Also, there's an appendTo() function, which looks much cleaner in this case\n $('<option/>').text(response[i]).val(response[i]).appendTo(option3);\n }\n // Adds data to dropdown\n }).fail(function () {\n // In this case, it's a warning. I'll let the alert through.\n // There are things called \"modals\" too, much prettier than alerts. Just sayin' :D\n alert(\"Sorry, there seems to be a problem contacting the server.\");\n });\n });\n});\n</code></pre>\n\n<p>Then I'm no expert in C# and the backing data store, but it's better if on the values of your choices, you used the ID's of the choices rather than the text. Scenario: What if someone modified the data to have 2 or more \"Coca-Cola\" entries. How would you know which is which?</p>\n\n<p>But, if you had a unique id for each item, then you'd know which one regardless if you named them the same. In the real world, that's how you differentiate 2 or more people of the same name on Facebook (or any site for that matter) - the user id.</p>\n\n<pre><code>// In the HTML\n<select>\n <option value=\"1\">Coke</option>\n <option value=\"2\">Pepsi</option>\n <option value=\"3\">Coke</option>\n <option value=\"4\">Dr. Pepper</option>\n</select>\n\n// In your data storage, something like:\n[\n {\"id\":1,\"text\":\"Coke\"}, <-- This is a different coke\n {\"id\":2,\"text\":\"Pepsi\"},\n {\"id\":3,\"text\":\"Coke\"}, <-- This is also a different coke\n {\"id\":4,\"text\":\"Dr. Pepper\"}\n]\n</code></pre>\n\n<p>I'll leave the C# to the other guys here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:16:01.640",
"Id": "83852",
"Score": "0",
"body": "1 - Doesn't .ready already handle having the script load after the page loads? 2 - I didn't quite understand what you meant by the ID suggestion? Aren't I already doing that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:20:12.040",
"Id": "83855",
"Score": "1",
"body": "@dotnetN00b 1. I'm not talking about when the script executes. I'm talking about when the script loads (from the server). If your scripts are on the `<head>` and took too long to load (from the server), all you get is a blank white page. Placing them to the bottom makes the page render first, and have it block loading somewhere later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:20:41.043",
"Id": "83857",
"Score": "0",
"body": "@dotnetN00b As for ID, something like `<option value=\"1\">Coca-Cola</option>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:51:06.397",
"Id": "84034",
"Score": "0",
"body": "Also, even if I use divs to cause a newline effect, I'd still need another <br /> to have the content have actual space between them. Or is there another way to do that? In short, is there a way to replace \"<br /><br />\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:39:48.057",
"Id": "84040",
"Score": "0",
"body": "@dotnetN00b Use margins or paddings to add some space between them."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T04:25:13.173",
"Id": "47761",
"ParentId": "47652",
"Score": "5"
}
},
{
"body": "<p>One small point on the c# side. As SqlConnection implements <code>IDisposable</code> I would rather consider wrapping that in using statement within the Save method. This way if a problem occurs in the <code>ExecuteNonQuery</code> method you can ensure the SqlConnection is closed and you don't incur any leaks.</p>\n\n<pre><code>using (SqlConnection connection = new SqlConnection(connectionString))\n{\n connection.Open();\n // Do work here; connection closed on following line.\n}\n</code></pre>\n\n<p>In saying that I might also consider passing in the SqlConnection to the model class. This way you take away the responsibility of the Model from knowing how to create this aspect.</p>\n\n<p>To do this, you might consider using an interface for your model which takes a connection.</p>\n\n<pre><code>interface IPersistable\n{\n void Save(SqlConnection connection);\n}\n\npublic class ModelContext\n{\n private readonly string _connectionString = ConfigurationManager.ConnectionStrings[\"TestInput\"].ConnectionString;\n\n public void Save(IPersistable model)\n {\n using(var connection = new SqlConnection(_connectionString))\n {\n connection.Open();\n model.Save(connection);\n }\n }\n}\n\npublic class Mainpage : IPersistable \n{\n public void Save(SqlConnection connection)\n {\n string insertStr = \"usr_InsertValues\";\n SqlCommand sqlCmd = new SqlCommand(insertStr, sqlConn);\n sqlCmd.CommandType = CommandType.StoredProcedure;\n\n SqlParameter sp;\n if (DateMade.HasValue)\n sp = new SqlParameter(\"@p2\", DateMade.Value);\n else\n sp = new SqlParameter(\"@p2\", DBNull.Value);\n\n SqlParameter[] sps = new SqlParameter[] {new SqlParameter(\"@p1\", LineDesc),\n sp,\n new SqlParameter(\"@p3\", Options1),\n new SqlParameter(\"@p4\", Options2)};\n sqlCmd.Parameters.AddRange(sps);\n\n sqlCmd.ExecuteNonQuery();\n }\n}\n</code></pre>\n\n<p><strong>ViewModel.Save()</strong></p>\n\n<p>I'm not a huge fan of having the viewmodel responsible for calling the model to persist the data. I'm not sure where you could move this to as I haven't looked at the rest of the code but I would typically put that call in the controller and use a mapping layer to copy the properties from ViewModel to model.</p>\n\n<p>My main reason is that it seems to violate the boundary between the viewmodel and model in that now viewmodels know about models. I tend to prefer the level of dependency direction going toward a ViewModel not away from it i.e. <em>View => ViewModel, Controller => ViewModel</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:20:19.360",
"Id": "83856",
"Score": "0",
"body": "So I would create a Model, take the data from ViewModel and put in Model, pass that Model to ModelContext, and finally call all of that from the Controller (or what I have as the Controller). Correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T01:05:11.843",
"Id": "83859",
"Score": "0",
"body": "@dotnetN00b yep, spot on. So the controller is controlling everything and pulling the strings (so to speak) and the actual implementations are doing very specific work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T09:41:46.010",
"Id": "47768",
"ParentId": "47652",
"Score": "2"
}
},
{
"body": "<p>For the JavaScript,</p>\n\n<ul>\n<li>Drop the commented out code</li>\n<li>Avoid alert, it is very annoying</li>\n<li>You do not use <code>frm</code>, drop it</li>\n<li>You can merge the assignment of <code>options3</code> and <code>empty</code> into one line </li>\n<li><code>options3</code> is a terrible name, both for an <code>id</code> as a variable name</li>\n</ul>\n\n<p>Other than, that code looks fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:53:04.567",
"Id": "47874",
"ParentId": "47652",
"Score": "3"
}
},
{
"body": "<p>Razor is a <strong><em>view engine.</em></strong> It's completely abusive to try to use it as a \"controller\" as you've done here. If you want a code behind, then Aspx & webforms is the correct architecture to use. </p>\n\n<p>But that suffers from the same issues as the abuse of razor you've done here. Tightly coupled view/business logic. It's evil. <em>Evil.</em> Don't do this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-16T23:44:10.540",
"Id": "117019",
"ParentId": "47652",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T14:33:17.420",
"Id": "47652",
"Score": "4",
"Tags": [
"c#",
"javascript",
"beginner",
"jquery",
"html"
],
"Title": "Is my web site structured correctly?"
} | 47652 |
<p>I learned to program in Java and C# and in my free time I am using Ruby because it is fun. Unfortunately I have the feeling that I write Ruby code like I am making Java or C# code. I have learned to use regex instead of strings for comparison, using each instead of for-loops, keeping method names lowercase, and how to use code blocks (which are quite similar to lambda expressions in C#).</p>
<p>I would love to improve the Rubiness of my code and I hope you would be willing to give me one or more pointers on a piece of code I made. It answers <a href="http://projecteuler.net/problem=27" rel="nofollow noreferrer">Project Euler problem 27</a>.</p>
<pre><code>class Integer
def prime?
return false if self < 1
2.upto(Math.sqrt(self)) do |i|
return false if self % i == 0
end
true
end
end
def get_amount_of_primes_from_quadratic_formula(a,b)
primes = []
still_all_primes = true
n = 0
while still_all_primes
result = n**2 + a*n + b
if result.prime? then
primes << result
else
still_all_primes = false
end
n += 1
end
primes.size
end
def get_product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()
max_product = 0
max_primes = 0
-999.upto(1000) do |a|
-999.upto(1000) do |b|
primes = get_amount_of_primes_from_quadratic_formula(a,b)
if primes > max_primes then
max_primes = primes
max_product = a*b
end
end
end
max_product
end
start = Time.now
answer = get_product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()
puts "The answer is #{answer} and it took #{Time.now-start} seconds."
</code></pre>
<p>I think I can improve on the if-then statement and write it more concise, and also the two "upto-loops" where I first declare the variables <code>max_primes</code> and <code>max_product</code> can be written in a more Ruby-way I am sure. </p>
<p>I would be very grateful if you could let me know how to write more like Ruby!</p>
<p>Links that ask similar questions which I am reading in the meantime:</p>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/354/advice-on-making-ruby-code-more-ruby-like">Advice on making ruby code more ruby-like</a></li>
<li><a href="https://codereview.stackexchange.com/questions/16378/ruby-method-return-values-how-to-be-more-ruby-like">Ruby method return values - how to be more Ruby-like?</a></li>
<li><a href="https://codereview.stackexchange.com/questions/15413/how-to-make-my-script-nicer-more-ruby">How to make my script nicer / more Ruby?</a></li>
</ul>
| [] | [
{
"body": "<p><strong>Succinctness</strong><br>\nAs rubyists, we love being succinct, and we love playing with enumerations.</p>\n\n<p>You will see very few literal <code>false</code> and <code>true</code> in ruby code, as well as very few explicit <code>return</code> calls.</p>\n\n<p>For example:</p>\n\n<p>Instead of writing <code>return false if self < 1</code> we will prefer to compound the condition to <code>self >= 1 && ...</code> which will do the same thing, but we \"save\" <code>return false</code>.</p>\n\n<p><strong>The power of Enumeration</strong><br>\nRuby has a very powerful <a href=\"http://www.ruby-doc.org/core-1.9.3/Enumerable.html\" rel=\"nofollow\"><code>Enumerable</code></a>, and is used widely, often more than once in a line (using method chaining).</p>\n\n<p>For example:</p>\n\n<blockquote>\n<pre><code>2.upto(Math.sqrt(self)) do |i|\n return false if self % i == 0\nend\n</code></pre>\n</blockquote>\n\n<p>Here you check if any of the numbers in the range are a divisor for <code>self</code>, and break if there is any. A more ruby way of doing it will be:</p>\n\n<pre><code>return false if 2.upto(Math.sqrt(self)).any? { |i| self % i == 0 }\n</code></pre>\n\n<p>We'll also prefer to more succinct range syntax <code>(2..Math.sqrt(self))</code>, which is simply shorter...</p>\n\n<p>So now, our <code>def prime?</code> method could be reduced to a one-liner:</p>\n\n<pre><code>class Integer\n def prime?\n self > 1 && !(2..Math.sqrt(self)).any? { |i| self % i == 0 }\n end\nend\n</code></pre>\n\n<p><strong>Mapping</strong><br>\nAnywhere in the code I see the following pattern:</p>\n\n<pre><code>result = []\nsome_loop do\n result << something\nend\n</code></pre>\n\n<p>A red flag is raised, and I look for a way to use <code>map</code> to do the same thing:</p>\n\n<pre><code>result = some_loop.map { something }\n</code></pre>\n\n<p>Your code goes over all the non-negative integers, and takes counts how many of them result in a prime, until the first non-prime.</p>\n\n<p>\"All the non-negative integers\" can be expressed in ruby as <code>(0..Float::INFINITY)</code>, so we can write:</p>\n\n<pre><code>(0..Float::INFINITY).map { |n| n**2 + a*n + b }.take_while { |result| result.prime? }.count\n</code></pre>\n\n<p>This code takes each integer, <em>maps</em> it into the result of <code>n**2 + a*n + b</code>, takes all the results until they are no longer prime, and counts how many are there.</p>\n\n<p>Cool! Right? The only problem with the code above, is that it will take infinity to complete it, as it takes <em>all</em> the numbers and maps them, and <em>then</em> checks for how many to take.</p>\n\n<p>To solve this problem ruby now has...</p>\n\n<p><strong>Lazy Enumerables</strong><br>\nAs of ruby 2.0, <a href=\"http://railsware.com/blog/2012/03/13/ruby-2-0-enumerablelazy/\" rel=\"nofollow\">lazy enumerables</a> allows you to calculate values in an infinite stream only as needed.</p>\n\n<p>To solve the problem above, all we need to do now is to add the <code>lazy</code> operator on the range:</p>\n\n<pre><code>(0..Float::INFINITY).lazy.map { |n| n**2 + a*n + b }.take_while(&:prime?).count\n</code></pre>\n\n<p>And we have another one-liner!</p>\n\n<p><strong>Everything is an enumerable</strong><br>\nSo you want to save on your \"upto-loops\"? Let's do it!</p>\n\n<p>You want to enumerate over each pair of numbers from <code>-999</code> to <code>1000</code>, so what you actually want is to have a long matrix of those pairs:</p>\n\n<pre><code>[[-999, -999], [-999, -998],...,[1000, 1000]].do_something_smart\n</code></pre>\n\n<p>To do that, you can use <a href=\"http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-product\" rel=\"nofollow\"><code>product</code></a>:</p>\n\n<pre><code>(-999..1000).to_a.product((-999..1000).to_a)\n</code></pre>\n\n<p>But since both <code>a</code> and <code>b</code> have the same range, we can even DRY this up, and use <a href=\"http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-repeated_permutation\" rel=\"nofollow\"><code>repeated_permutation</code></a>:</p>\n\n<pre><code>(-999..1000).to_a.repeated_permutation(2)\n</code></pre>\n\n<p>Both of these solutions will give you the needed matrix, so we can move on the see what we should do with it...</p>\n\n<p>We want to get the coeffiecients that produce the number of primes, so let's do just that:</p>\n\n<pre><code>a, b = (-999..1000).to_a.repeated_permutation(2).max_by { |a, b| get_amount_of_primes_from_quadratic_formula(a,b) }\n</code></pre>\n\n<p>Now all we need to do is multiply them with each other!</p>\n\n<p><strong>Method naming</strong><br>\nYour names are very verbose, which is a good thing, but ruby idiom frowns upon <code>get_</code> prefixes. Also, prefer using verbs already in the language (<code>count</code>) over those which are not in the language (<code>amount_of</code>)</p>\n\n<p>So now the code will look like:</p>\n\n<pre><code>class Integer\n def prime?\n self > 1 && !(2..Math.sqrt(self)).any? { |i| self % i == 0 }\n end\nend\n\ndef count_quadratic_formula_primes(a,b)\n (0..Float::INFINITY).lazy.map { |n| n**2 + a*n + b }.take_while(&:prime?).count\nend\n\ndef product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()\n a, b = (-999..1000).to_a.repeated_permutation(2).max_by { |a, b| count_quadratic_formula_primes(a,b) }\n a * b\nend\n\nstart = Time.now\nanswer = product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values\n\nputs \"The answer is #{answer} and it took #{Time.now-start} seconds.\"\n</code></pre>\n\n<p>15 lines of hard-core ruby-style code!</p>\n\n<p>Enjoy!</p>\n\n<hr>\n\n<p><strong>Update</strong><br>\nIt seems that <code>lazy</code> adds considerable overhead to the performance of the code. So it is not advisable to use it.</p>\n\n<p>Fortunately this works:</p>\n\n<pre><code>(0..Float::INFINITY).take_while { |n| (n**2 + a*n + b).prime? }.count\n</code></pre>\n\n<p>My code still runs ~2 times slower than the original (ends in 18 seconds), but it is more reasonable than with <code>lazy</code>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T07:37:33.843",
"Id": "83598",
"Score": "1",
"body": "also, you can `inject` your a*b :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T14:58:12.590",
"Id": "83634",
"Score": "0",
"body": "I like your code better, but it takes 130 seconds, while the original code takes 10. The prime function is a beauty. I suspect that the count_quadratic_formula_primes method is slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:08:21.950",
"Id": "83648",
"Score": "0",
"body": "@user2609980 - yes, apparently `lazy` add a lot of overhead... see my update"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:24:49.140",
"Id": "83649",
"Score": "3",
"body": "user2609980, I'm surprised at the difference in execution times, but I'd pay no heed to that at this stage of your Ruby education. Uri has covered a wide swath of ground in his answer, acquainting you with typical Ruby coding style, the addition of a method to an existing Ruby class (`prime?`), the use of powerful enumerators `map`, `product`, `permutation`, `any?` and `take_while` from the `Enumerable` module, and `up_to` from the `Integer` class, and Ruby's new `lazy` operator. He has also nicely explained his reasons for coding it the way he has. Great answer, Uri."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T10:06:45.620",
"Id": "83730",
"Score": "0",
"body": "@CarySwoveland I am indeed very happy with the answer :-)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T13:08:48.723",
"Id": "89960",
"Score": "0",
"body": "Thanks once again :) My Ruby code improved a lot because of your answer and I keep coming back to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T13:14:49.313",
"Id": "89962",
"Score": "0",
"body": "@user2609980 - glad to be of service :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:04:26.340",
"Id": "420209",
"Score": "1",
"body": "Lovely stuff. Can I suggest instead of something like `!(1..10).any? {...}` that the OP use `(1..10).none? {...}`."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T07:02:23.010",
"Id": "47697",
"ParentId": "47656",
"Score": "6"
}
},
{
"body": "<h3>Rubocop Report</h3>\n\n<p>There are a couple of additional offenses against Ruby style guide and conventions that haven't been addressed in the excellent answer.</p>\n\n<ul>\n<li>Use <code># frozen_string_literal: true</code> top level comment (<a href=\"https://www.mikeperham.com/2018/02/28/ruby-optimization-with-one-magic-comment/\" rel=\"nofollow noreferrer\">why?</a>).</li>\n<li>Insert an empty line after guard clauses: <code>return false if self < 1</code>.</li>\n<li>Prefer the zero predicate over 0 check: <code>self % i == 0</code> -> <code>(self % i).zero?</code>.</li>\n<li>Try to keep the number of lines of each method below 10. <code>get_amount_of_primes_from_quadratic_formula</code> has 13 lines.</li>\n<li>Parameter names should be communicative. <code>a</code>, <code>b</code> should be refactored.</li>\n<li>Do not use <code>then</code> for multi-line <code>if</code>. <code>if result.prime? then</code> -> remove <code>then</code>.</li>\n<li>Omit parentheses when the method or def does not define arguments.</li>\n<li>Keep line lengths below 80 characters.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T09:54:20.487",
"Id": "224661",
"ParentId": "47656",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47697",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:10:00.987",
"Id": "47656",
"Score": "8",
"Tags": [
"ruby",
"primes",
"mathematics",
"programming-challenge"
],
"Title": "Make Project Euler 27 solution idiomatic Ruby"
} | 47656 |
<p><a href="http://projecteuler.net/problem=29" rel="nofollow">Here's a link to the problem.</a> Is there any way I could optimize/speed up this code, perhaps make it more Pythonic?</p>
<pre><code>"""How many distinct terms are in the sequence
generated by a^b for 2 <= a <= 100
and 2 <= b <= 100?"""
import math
from timeit import default_timer as timer
def distinctPowers(a_max, b_max):
products = []
for a in range(2, a_max + 1):
for b in range(2, b_max + 1):
if a ** b not in products:
products.append(a ** b)
return len(products)
start = timer()
ans = distinctPowers(100, 100)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %r in %r ms." % (ans, elapsed_time)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:42:35.573",
"Id": "83530",
"Score": "1",
"body": "What would you like to know about your code? It appears correct to me. Are you trying to speed it up?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:33:17.400",
"Id": "83566",
"Score": "0",
"body": "On a styling note, mixedCase is almost never used in Python. \"mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.\" See http://legacy.python.org/dev/peps/pep-0008/"
}
] | [
{
"body": "<p>You should check the data structure that you use. You are currently using a list, checking if the power exists, and then doing it again when you append unique entries.</p>\n\n<p>If you use a set then you can skip the check and do an add of the power. This is significantly faster... about 50 times if I calculated correctly. Your function would then look like this:</p>\n\n<pre><code>def distinctPowers(a_max, b_max):\n products = set()\n for a in range(2, a_max + 1):\n for b in range(2, b_max + 1):\n products.add(a ** b)\n return len(products)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:39:10.417",
"Id": "83560",
"Score": "0",
"body": "Using a list comprehension to create an iterator may also imrove runtime."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:56:07.077",
"Id": "47659",
"ParentId": "47657",
"Score": "3"
}
},
{
"body": "<p>You can append all of the items to list without checking for uniqueness and in the end get unique elements by converting the list to the set.\nWith this you can write a one-liner:</p>\n\n<pre><code>def distinctPowers(a_max, b_max):\n return len(set([a**b for a in range(2, a_max + 1) for b in range(2, b_max + 1)]))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:31:00.747",
"Id": "83797",
"Score": "0",
"body": "List comprehesions always doing magic..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:09:50.967",
"Id": "47674",
"ParentId": "47657",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47659",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:30:21.190",
"Id": "47657",
"Score": "1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler 29"
} | 47657 |
<p>I am using Spring Framework, Hibernate and JUnit. I am testing persisting of a UserEntity. </p>
<p>The UserEntity has the following associations:</p>
<ul>
<li>ManyToMany - City</li>
<li>ManyToMany - ActivityCategory</li>
<li><p>ManyToOne - UserType </p>
<pre><code>@Test
public void testCreateNotExistingEmail() {
UserTypeEntity userTypeEntity = userTypeDao.find(1L);
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
String password = encoder.encode("123456");
List<CityEntity> cityEntities = new ArrayList<>();
cityEntities.add(cityDao.find(1L));
cityEntities.add(cityDao.find(2L));
List<ActivityCategoryEntity> activityCategoryEntities = new ArrayList<>();
activityCategoryEntities.add(activityCategoryDao.find(4L));
activityCategoryEntities.add(activityCategoryDao.find(5L));
UserEntity userEntity = new UserEntity();
userEntity.setEmail("user@domain.com");
userEntity.setIsActive(true);
userEntity.setPassword(password);
userEntity.setUserTypeEntity(userTypeEntity);
userEntity.setCities(cityEntities);
userEntity.setActivityCategories(activityCategoryEntities);
userDao.create(userEntity);
UserEntity userEntityCreated = userDao.find(userEntity.getId());
Assert.assertNotNull(userEntityCreated);
Assert.assertEquals(2, userEntityCreated.getCities().size());
Assert.assertEquals(2, userEntityCreated.getActivityCategories().size());
}
</code></pre></li>
</ul>
<p>Is there anything I could do better in the test?</p>
| [] | [
{
"body": "<p>The name of your test method is <code>testCreateNotExistingEmail</code> but I don't see how it's related to what you're testing.</p>\n\n<p>What is the purpose of the test? Is it that you can successfully create a user entity if there is no other user entity with the same email? If so, then I would do something like this instead:</p>\n\n<pre><code>@Test\npublic void testCreateNotExistingEmail() {\n UserEntity userEntity = new UserEntity();\n userEntity.setEmail(\"nonexistent@domain.com\");\n userDao.create(userEntity);\n}\n\n@Test(expected=UniqueKeyIntegrityException.class)\npublic void testCannotCreateWithExistingEmail() {\n String email = \"user@domain.com\";\n\n // or something like this:\n Assert.assertNull(userDao.findByEmail(email));\n\n UserEntity userEntity = new UserEntity();\n userEntity.setEmail(email);\n userDao.create(userEntity); // success\n\n userEntity.setEmail(email);\n userDao.create(userEntity); // throws\n}\n</code></pre>\n\n<hr>\n\n<p>Do you need to set all those fields for the test? If not, then omit them. For example if a user without password is valid, then don't set a password in this test case, as it's unnecessary. Unit tests should be as short as possible.</p>\n\n<hr>\n\n<p>Keep in mind that every unit test method should test only one specific thing (though that can of course include multiple assertions). I would separate the tests targeted on <code>UserEntity</code> itself and the tests that verify the correct relationships (with city and category).</p>\n\n<hr>\n\n<p>Your tests on the relationships (with city and category) could be more strict. It would be better to compare the ids of each city and each category in <code>userEntity</code> and <code>userEntityCreated</code>. I would use separate test methods:</p>\n\n<ul>\n<li>One test for city relationships</li>\n<li>One test for category relationships</li>\n<li>For extra safety, one more test with city + category. This can be simplified, for example compare only the sizes as you already did.</li>\n</ul>\n\n<hr>\n\n<p>Beware of potential side effects. For example, if you have multiple tests that use <code>userDao</code>, make sure to reinitialize in <code>@Before</code> so that all tests start with the same setup and don't have side effects on one another.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:42:50.110",
"Id": "47665",
"ParentId": "47660",
"Score": "11"
}
},
{
"body": "<p>A minor remark: your test is named <code>testCreateNotExistingEmail</code>. The <code>@Test</code> annotation already indicates that this is a test so it doesn't have to be repeated in the methodname itself.</p>\n\n<p>Adding to that: I like to structure my tests in the format <code>[UnitOfWorkName]_[ScenarioUnderTest]_[ExpectedBehaviour]</code>.</p>\n\n<p>It is hard to tell what exactly your test does when I look at the code because the methodname indicates something about a nonexisting email, which leads me to think about an exception handled somewhere. </p>\n\n<p>But when I look at the code I see no assertions like that at all. In fact, I only see an email being used once in a seemingly irrelevant context.</p>\n\n<p>Some type of clarification is needed: a better method name. Something along the lines of <code>createUser_WithNonExistingEmail_ShouldReturn_StandardCitiesAndCategories</code></p>\n\n<p>Now when the test fails amongst a big group of tests, you can pinpoint more closely what scenario is going wrong exactly before you dig into it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:09:19.270",
"Id": "83543",
"Score": "0",
"body": "Thank you for your suggestion. I agree, that the name of the method could be better, but the name which you suggest is really very long. Therefore, in my opinion, it would be better to put the information into Javadoc comment. At least something like \"Test creation of a user with email ...\" is way better readable than \"TestCreationOfAUserWithEmail ... \"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:09:32.203",
"Id": "83544",
"Score": "0",
"body": "some IDE's (IntelliJ comes to mind) doesn't like it if the first word is not test, regardless if the @Test annotation is present. IMO that is a bad idea on their part, but sometimes we have to live with what we have"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:11:24.927",
"Id": "83546",
"Score": "4",
"body": "Why would it matter how long the method name is? It's something you will never call yourself. All that name has to do is show up in your test result window and be as descriptive as possible, you gain nothing by shortening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:17:45.117",
"Id": "83548",
"Score": "0",
"body": "@JeroenVannevel I am getting your point. In that case it is better to use more descriptive name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:20:14.140",
"Id": "83551",
"Score": "0",
"body": "@RobertSnyder IntelliJ generates tests with \"test\" in the beginning of method name, that's why I kept the \"test\" there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:25:41.323",
"Id": "83552",
"Score": "0",
"body": "@Yoda Indeed, they put a note though saying that if test was not at the beginning \"bad things will happen\".. naturally I can't find that note again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:48:13.300",
"Id": "83555",
"Score": "0",
"body": "@JeroenVannevel I have one more question. Why do you suggest the first letter in name of tested method to be uppercase?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:59:49.097",
"Id": "83556",
"Score": "1",
"body": "@Yoda: C# habit, in Java it should be lowercase. My mistake"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:45:09.500",
"Id": "47666",
"ParentId": "47660",
"Score": "15"
}
},
{
"body": "<p>The answers already given are good ones but I see that there are some points what aren't said.</p>\n\n<h2>First :</h2>\n\n<p>Your test does include some DB, maybe a generated when you test or a dev database on a server.<br/>\nIs you class <code>@Transactional</code> or not?<br/>\nPersonally I find it better that you make your tests @Transactional when you will do a save operation.<br/></p>\n\n<p><b>Why :</b></p>\n\n<p>You will be sure that your db is rolled back when your method ends.<br/>\nThis means, setting the DB back in original state as in the begin of the method.<br/>\nExecutions of tests can change in order so this can lead to failing of previous/further tests.</p>\n\n<h2>Second:</h2>\n\n<pre><code>Assert.assertNotNull(userEntityCreated);\nAssert.assertEquals(2, userEntityCreated.getCities().size());\nAssert.assertEquals(2, userEntityCreated.getActivityCategories().size());\n</code></pre>\n\n<p>Why do you not provide a text message with the assert for when it fails like this :</p>\n\n<pre><code>Assert.assertNotNull(\"userEntity is not createrd\",userEntityCreated);\nAssert.assertEquals(\"Size of city's is not correct\",2, userEntityCreated.getCities().size());\nAssert.assertEquals(\"Size of ActivityCategory is not correct\",2, userEntityCreated.getActivityCategories().size());\n</code></pre>\n\n<p><b>Why:</b>\nWhen your test fails you will see this error message, so you know directly what assert is failing in your method.</p>\n\n<p>Hope this can help you further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:13:40.193",
"Id": "83557",
"Score": "0",
"body": "Good points. All tests inherit from class TestDaoSetup which has ContextConfiguration(... configuration locations here ...), TransactionConfiguration and Transactional annotation. I like your second point. I will use it for sure. Unfortunatelly, I can not mark more answers as correct, they should really add it to this site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:18:14.303",
"Id": "83558",
"Score": "0",
"body": "That doesn't have to, we are here to help each other out ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:04:34.847",
"Id": "47671",
"ParentId": "47660",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "47666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:03:24.100",
"Id": "47660",
"Score": "21",
"Tags": [
"java",
"unit-testing"
],
"Title": "Writing better JUnit tests"
} | 47660 |
<blockquote>
<p>Write a function <code>undef</code> that will remove a name and a definition from the maintained by <code>lookup</code> and <code>install</code>.</p>
</blockquote>
<p>Here is my solution:</p>
<pre><code>void undef(char *name)
{
struct Nlist *tmp = hashtab[hash(name)];
if(!strcmp(tmp->name, name)) { // delete the head node
hashtab[hash(name)] = tmp->next;
free(tmp->name);
free(tmp);
return;
}
for(; strcmp(tmp->next->name, name); tmp = tmp->next)
;
struct Nlist *save = tmp->next; // save the desired node for deletion
tmp->next = tmp->next->next; // adjust the links
free(save->name);
free(save);
}
</code></pre>
<p>There are 2 main cases. The first is when we want to delete the head node, and when we want to delete a node from the rest of the list.</p>
<p>I will explain how my function works in the second case. The <code>for</code> loop will run until <code>tmp</code> will point to the node that precedes the desired node. Then I adjust the links and free the memory occupied by the desired node.</p>
<p>This approach is not good if the desired value is located at the head node, so I use a <code>if</code>-statement to check if the desired value is located at the head node. If it is, I adjust the head pointer and free the memory.</p>
<p>Here is the code for the entire program: <a href="http://ideone.com/t0bjiA" rel="nofollow">http://ideone.com/t0bjiA</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:31:15.393",
"Id": "83559",
"Score": "0",
"body": "Who wrote the rest of the program especially the `lookup` and `install` functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:55:12.727",
"Id": "83561",
"Score": "0",
"body": "They are extracted from k&r2, but they were adapted by me. As you can see, they look a little bit weird because I've tried to adapt them to work with a previous version of undef. I forgot to remove those changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T21:30:50.037",
"Id": "83572",
"Score": "3",
"body": "Consider posting the entire program here. Links tend to go away after a while and that would render this question rather useless without the context."
}
] | [
{
"body": "<p>It's not necessary to special-case the head of the list if you think about it in a different way. In particular, each entry in your <code>hashtable</code> is a pointer to an <code>Nlist</code> structure, so if you take the <em>address</em> of the <code>hashtable</code> entry, you can treat it just like any other node. Specifically, you can use this:</p>\n\n<pre><code>void undef(char *name)\n{\n struct Nlist **tmp = &hashtab[hash(name)];\n struct Nlist *old;\n\n /* find our matching node */\n for ( ; *tmp && strcmp(name, (*tmp)->name); tmp=&((*tmp)->next));\n\n /* if we have found it, delete and adjust pointer */\n if (*tmp != NULL) {\n old = *tmp;\n free(old->name);\n free(old->defn);\n *tmp = old->next;\n free(old);\n }\n}\n</code></pre>\n\n<p>Also note that <code>defn</code> was not being deleted in your original code, resulting in a memory leak.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T22:20:17.453",
"Id": "47680",
"ParentId": "47661",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47680",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:12:33.647",
"Id": "47661",
"Score": "2",
"Tags": [
"c",
"beginner",
"linked-list",
"hash-map"
],
"Title": "Implementation of the undef function"
} | 47661 |
<p>I am working on this project that has a reservation form which allow users specify which sort of service they require. I have a select menu with eight (8) options and I have two divs which would either show/hide depending on the value of the option been selected. Seen below is the select element:</p>
<pre><code><select name="serviceChoice" id="serviceChoice">
<option value="A">Option A</option>
<option value="B">Option B</option>
<option value="C" selected="selected">Option C</option>
<option value="D">Option D</option>
<option value="E">Option E</option>
<option value="F">Option F</option>
</select>
<div id="field_1" class="optionBox">I have several form fields</div>
<div id="field_2" class="optionBox">I have several form fields</div>
</code></pre>
<p>I have written my jQuery code to alternate between these divs, however I would like to know if there is a shorter better way to get this done. I would also like to clear the values of any input elements in a div which has been hidden due to the choice of the user. My code is as follows:</p>
<pre><code>(function($){
$('#field_1').show();
$('select[name=serviceChoice]').change(function(){
if( $('select[name=serviceChoice] option:selected').val() == 'A' ) {
$('.optionBox').hide();
$('#dropOff').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'B' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'C' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'D' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else {
$('.optionBox').show();
}
});
})(jQuery);
</code></pre>
| [] | [
{
"body": "<pre><code>// You can use the document.ready as both encapsulation as well as\n// to make sure the DOM is ready for operation.\n$(function ($) {\n\n // Unless these are dynamic (the set could change), it's better to cache them\n var optionBox = $('.optionBox');\n var dropOff = $('#dropOff');\n var pickUp = $('#pickUp');\n var field1 = $('#field_1');\n\n field.show();\n\n // Your select box has an ID. They are faster than attribute selectors \n // in both parsing ase well as fetching from the DOM\n $('#serviceChoice').change(function () {\n\n // The current context of this function is the DOM element, which is the select\n // You can use it to get the value, rather than using a selector again. Removes\n // the need for jQuery to parse the selector and look for it in the DOM\n switch ($(this).val()) {\n case 'A':\n optionBox.hide();\n dropOff.show();\n break;\n case 'B':\n case 'C':\n case 'D':\n optionBox.hide();\n pickUp.show();\n break;\n default:\n optionBox.show();\n }\n });\n});\n</code></pre>\n\n<p>Minus the comments, here's what you get:</p>\n\n<pre><code>$(function ($) {\n\n var optionBox = $('.optionBox');\n var dropOff = $('#dropOff');\n var pickUp = $('#pickUp');\n var field1 = $('#field_1');\n\n field.show();\n\n $('#serviceChoice').change(function () {\n\n switch ($(this).val()) {\n case 'A':\n optionBox.hide();\n dropOff.show();\n break;\n case 'B':\n case 'C':\n case 'D':\n optionBox.hide();\n pickUp.show();\n break;\n default:\n optionBox.show()\n }\n })\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T23:26:13.787",
"Id": "47683",
"ParentId": "47662",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47683",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:19:12.467",
"Id": "47662",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery conditional statement to check if a select option has either of 4 values selected"
} | 47662 |
<p>I've this function to list products from database by category. I'm using prepared statements, but wouldn't this make it pretty pointless to use them?</p>
<pre><code>function getProducts($category,$search_param,$pdo){
$query = "SELECT * FROM renkaat
INNER JOIN ajoneuvotyypit ON tyyppiID = ajoneuvotyyppiID
INNER JOIN vuodenajat ON vuodenaikaID = renkaat.vuodenaika
INNER JOIN valmistajat ON renkaat.valmistaja = valmistajat.valmistajaID
WHERE renkaat.$category= ?
";
$smt = $pdo->prepare($query);
$smt->execute(array($search_param));
//do stuff
}
</code></pre>
<p>And the function is simply called like this, with no escaping done:</p>
<pre><code>getProducts($_GET['category'],$_GET['search_param'],$pdo);
</code></pre>
<p>Should I escape the <code>$category</code>?</p>
| [] | [
{
"body": "<p>Yes, <code>$category</code> in your query string, coming directly from <code>$_GET</code> is a problem.</p>\n\n<p>You should validate <code>$category</code>, and that's not exactly the same as escaping. I assume you have a limited set of valid categories in your database, so validation should be something like:</p>\n\n<pre><code>$valid_categories = array(\"sector\", \"industry\", \"company\");\nif (!in_array($category, $valid_categories)) {\n // no no\n}\n</code></pre>\n\n<p>As for the other part of your question, paraphrased:</p>\n\n<blockquote>\n <p>Is it pointless to use prepared statements if there is a variable part in the query?</p>\n</blockquote>\n\n<p>It's not pointless, because every time you run the query for the same <code>$category</code> value, it can benefit from the previously prepared statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:19:04.730",
"Id": "83550",
"Score": "0",
"body": "I meant pointless from a security point of view, not performance, but thanks for the heads up! Luckily this little snippet was on the administration side and not the live site..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:07:07.347",
"Id": "47668",
"ParentId": "47667",
"Score": "10"
}
},
{
"body": "<p>Yes, this code is vulnerable to SQL injection, just like any dynamically composed SQL that is not properly quoted. The quoting mechanism for identifiers is database dependent, though.</p>\n\n<p>A bigger concern is how this situation came about in the first place. If you ever need to programmatically choose a column like that, your schema is probably poorly designed. There should be a small number of columns in the schema, all with fixed names. The fact that you have many columns, all with compatible types such that you can apply the same query over them, indicates that those attributes should all be upgraded to an <code>Attribute</code> entity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:17:30.260",
"Id": "83547",
"Score": "0",
"body": "Yeah, I wasn't the one creating this system in the first place. I'm just \"adding features\" here, but seems like that I've to go trough the whole code to check for these kinds of incidents."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T18:11:48.687",
"Id": "47669",
"ParentId": "47667",
"Score": "7"
}
},
{
"body": "<p>More than validating or quoting your queries you should parameterize them. <a href=\"https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php\">Here's</a> a different SO question which covers the topic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:08:32.527",
"Id": "83775",
"Score": "0",
"body": "It is parameterized?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T11:58:19.720",
"Id": "47710",
"ParentId": "47667",
"Score": "2"
}
},
{
"body": "<p>Yes, it is a problem, the following will give you all data from all categories:</p>\n\n<pre><code>$category = 'validcategory=\"searchparam\" OR 1 = 1 OR validcategory'\n</code></pre>\n\n<p>You should check if the $category exists first, maybe dynamic like this is better than defining an array in code:</p>\n\n<p><a href=\"https://stackoverflow.com/a/15671366\">https://stackoverflow.com/a/15671366</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T12:46:51.407",
"Id": "47711",
"ParentId": "47667",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47668",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:53:24.817",
"Id": "47667",
"Score": "10",
"Tags": [
"php",
"sql",
"pdo",
"sql-injection"
],
"Title": "Listing products from a database"
} | 47667 |
<p>I'm building a port scanner as an exercise. It contains a method to separate the ports that the user wants to have checked, which can include single ports and port ranges, ex: 22, 23, 80-120, 443-500, 1024, etc. It discards wrong ports such as negative ports, wrong range such as 120-80 instead of 80-120 which is the right form, and duplicate ports.</p>
<p>I'm wondering if there's a better way to do this, or to improve the code, make it shorter, using a more effective technique. The text box to enter the list of ports only accepts numbers, commas and dashes.</p>
<pre><code>private List<int> extractPorts(string ports) // the string argument contains a list of ports entered through a text box
{
string[] portList = ports.Split(','); // save everything between commas, including ranges like 80-120
List<int> listOfPorts = new List<int>(); // creates a new list of integers to save the valid given ports
for (int i = 0; i < portList.Length; i++ ) // iterates through port list including single ports and ranges
{
if (portList[i].Contains('-')) // if finds a range like 80-120...
{
try
{
int[] range = Array.ConvertAll(portList[i].Split('-'), int.Parse); // saves the edges of a range into an array ex: 80-120 as 80 and 120
for (int j = range[0]; j <= range[range.Length - 1]; j++) // iterates through the range saved above ex: from 80 to 120 the get
{
listOfPorts.Add(j); // every single port ex: in this case it gets 40 ports, from 80 to 120
} // if finds an error like a negative port or a wrong range like 120-100
} // instead of 100-120 will discard it
catch { }
}
else
listOfPorts.Add(Convert.ToInt32(portList[i])); // adds a single port to the list
}
List<int> intPortsList = listOfPorts.Distinct().ToList(); // eliminate duplicated ports
listOfPorts.Clear(); // clear the previous list
foreach (int item in intPortsList)
{
if (item <= 65536) // discard ports out of range
listOfPorts.Add(item);
}
listOfPorts.Sort(); // to sort the final list
return listOfPorts;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:27:44.447",
"Id": "83565",
"Score": "1",
"body": "Your code treats, e.g., \"123-45-678\" as identical to \"123-678\". Is that intentional? Is there a reason your code doesn't throw exceptions for crummy input, like \"1,-,2\" or \"123-45\"? It seems like it would be nice to let users know that their input is bad, rather than doing arbitrary \"magic\" to interpret the bogus input (IMO)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:33:21.173",
"Id": "83567",
"Score": "0",
"body": "the message of error to the user of course i will get done, for now i'm only trying to make the method work. Your code treats, e.g., \"123-45-678\" as identical to \"123-678\". Is that intentional? -> i didn't know that, i will try to improve it. The point that it doesn't get the 1st range because is not right(123-45), is descending and has to be ascending, what i have to do is maybe treat that 45 as a single port"
}
] | [
{
"body": "<p>First thoughts...</p>\n\n<ul>\n<li>Use an interface for your return type (e.g., <code>IEnumerable<int></code> instead of <code>List<int></code>)</li>\n<li>Use a <code>SortedSet<int></code> internally to get rid of duplicates, and do the sorting too. That should get rid of most of the bottom part of your function.</li>\n<li>Use <code>foreach</code> instead of <code>for</code> for your collection traversal</li>\n</ul>\n\n<p>So, with that said, here's some slightly modified code. Note that I'm using <code>UInt16</code> to prevent too-big items from being added in the first place (which means we don't have to remove them later). This is more efficient, but it is less-defensive. Alternatively, we could make the whole set be a <code>UInt16</code> type.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class PortParser\n{\n private static IEnumerable<int> extractPorts(string ports) \n {\n string[] portList = ports.Split(',');\n SortedSet<int> retval = new SortedSet<int>();\n\n foreach(string element in portList)\n {\n if (element.Contains(\"-\"))\n {\n // Range case...\n try\n {\n // Low value in [0], high value in [length - 1],\n // And ignore anything else in the middle.\n int[] range = Array.ConvertAll(element.Split('-'), int.Parse);\n\n // Add each number, from the low-end of the range to the\n // high end. If the range is inverted, we add nothing.\n for (int j = range[0]; j <= range[range.Length - 1] && j <= UInt16.MaxValue; j++) \n { \n retval.Add(j);\n }\n }\n catch { }\n }\n else\n {\n // Single port case...\n try\n {\n retval.Add(UInt16.Parse(element));\n }\n catch { }\n }\n }\n return retval;\n }\n\n static void Main(String[] args)\n {\n if(args.Length < 1)\n {\n System.Console.WriteLine(\"Please give me some numbers to play with!\");\n return;\n }\n\n IEnumerable<int> results = extractPorts(args[0]);\n\n foreach(int result in results)\n {\n System.Console.WriteLine(\"Scanning port \" + result);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:52:45.840",
"Id": "83568",
"Score": "0",
"body": "in this case is maybe a good idea not to try to fix the list of ports and advice the user to do it by himself, then proceed with the rest after the user got it fixed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T22:25:58.570",
"Id": "83575",
"Score": "1",
"body": "@fernando -- generally, yes, if you run into an ambiguous/malformed situation (such as 2-1-3), it's best to yell at the user, tell them what's broken, and make them fix up the input until everything is right. If your text field supports regex matching input, try something like /(([:digit:]+(,|$))|([:digit:]+-[:digit:]+(,|$)))+/. Then all you should have to worry about is too-big numbers and inverted ranges (and there's no reason you can't handle 5-1 just like 1-5). The purist approach would still have the function throw if the input violates the regex, however. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T20:44:22.170",
"Id": "47676",
"ParentId": "47673",
"Score": "3"
}
},
{
"body": "<h1>Comments</h1>\n\n<p>You have too many of them. Stick to comments that clarify the intent behind code instead of documenting the syntax. </p>\n\n<p>When I see </p>\n\n<pre><code>List<int> listOfPorts = new List<int>(); \n</code></pre>\n\n<p>I know already that it's a list of integers, intended to represent the ports. Comments should explain why you do what you do, for example:</p>\n\n<pre><code>// List of ints instead of strings so we can perform arithmetic logic\n</code></pre>\n\n<h1>Whitespace</h1>\n\n<p>This is more personal but your code feels very spread out. You don't have to leave a space between every line of code (although I'll admit that the braces are a major part of it).</p>\n\n<h1>Braces</h1>\n\n<p>If you omit braces, you will guaranteed end up with a logical error one day. What if you decide to add something else to this code snippet but aren't paying 100% attention? </p>\n\n<pre><code>else\n listOfPorts.Add(Convert.ToInt32(portList[i])); \n</code></pre>\n\n<p>This will be a pain to debug.</p>\n\n<p>For situations like this it is more forgiving, but honestly is there such a difference between</p>\n\n<pre><code>if (item <= 65536) \n listOfPorts.Add(item);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (item <= 65536) {\n listOfPorts.Add(item);\n} \n</code></pre>\n\n<h1>Exceptions</h1>\n\n<p>You have an empty catch block. That's no bueno, there should be some sort of feedback to the user that tells him what went wrong (at the very least there should be logging in place).</p>\n\n<h1>Abstraction</h1>\n\n<p>Your return statement is <code>List<int></code>. Is this a conscious design choice? You might want to read up on <a href=\"https://stackoverflow.com/questions/2697783/what-does-program-to-interfaces-not-implementations-mean\">the reasoning why I prefer <code>IEnumerable<int></code></a>.</p>\n\n<h1>Naming</h1>\n\n<p>Two variables are respectively <code>portList</code> and <code>listOfPorts</code>. First of all: remove the underlying datastructure from the name. </p>\n\n<p>In a way this can also be seen as enforcing encapsulation: it allows you to change the implementation to, for example, a <code>Dictionary</code> without suddenly having a discrepancy between the implementation and the variable name.</p>\n\n<p>More descriptive names could be <code>input</code>/<code>inputPorts</code>/<code>unparsedPorts</code> and <code>ports</code>/<code>parsedPorts</code>/<code>resultPorts</code>, etc.</p>\n\n<h1>Input boundaries</h1>\n\n<p>I don't see any boundary checks to verify the following things:</p>\n\n<ul>\n<li>No negative numbers</li>\n<li>No positive numbers outside the range of ports</li>\n<li>A range should only consist of 2 values</li>\n</ul>\n\n<h1>Loop clarity</h1>\n\n<p>I consider</p>\n\n<pre><code>int max = range[range.length - 1];\n// ...\nj <= max\n</code></pre>\n\n<p>to be easier to read than</p>\n\n<pre><code>j <= range[range.length - 1]\n</code></pre>\n\n<p>This is a minor gripe, but it can be confusing given how \"<= length - 1\" is usually interpreted in the condition section of a for loop (which usually gets refactored to \"< length\").</p>\n\n<h1>Duplicates</h1>\n\n<p>When you don't want duplicates, a <code>List<T></code> is not your preferred datastructure. Instead, use a <code>Set<T></code> like <a href=\"http://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>HashSet<T></code></a>. This will automatically take care of it for you.</p>\n\n<p>If you combine it with your sorting at the end you can use a <a href=\"http://msdn.microsoft.com/en-us/library/dd412070%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>SortedSet<T></code></a> instead:</p>\n\n<blockquote>\n <p>A <code>SortedSet<T></code> object maintains a sorted order without affecting performance as elements are inserted and deleted. Duplicate elements are not allowed. </p>\n</blockquote>\n\n<h1>Complexity</h1>\n\n<p>You're doing a lot of things with a lot of lists of ports (better naming would have come in handy here!).</p>\n\n<p>This is what you do:</p>\n\n<ul>\n<li>Create list (A) of input ports</li>\n<li>Parse A into another list (B)</li>\n<li>Create new list that holds unique values from B</li>\n<li>Clear B</li>\n<li>Add all ports that adhere to a boundary check to list B</li>\n<li>Sort B</li>\n</ul>\n\n<p>That's a lot of stuff that we can refactor.</p>\n\n<p>First of all: put that boundary check earlier in your code. Once a port is added to our result list of ports, it is a valid port. We don't want to copy everything to a new list just to add that boundary check (and you need more than that!).</p>\n\n<p>In fact, now it's already a lot easier: by using the <code>SortedSet<T></code> you will already do the sorting and duplicate removal so that's not needed either.</p>\n\n<p>Best part: <code>SortedSet<T></code> implements <code>IEnumberable<T></code> so you can simply return your set as-is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T21:57:24.333",
"Id": "83573",
"Score": "0",
"body": "@Travis: appreciate the edit, that was a rather silly mistake from my part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T22:16:57.107",
"Id": "83574",
"Score": "0",
"body": "Np. I almost deleted the section, but I figured if someone who'd given otherwise spot-on advice could make that mistake in reading the code, it might still be worth mentioning the potential hiccup in clarity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T21:04:32.343",
"Id": "47678",
"ParentId": "47673",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47678",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T19:51:59.107",
"Id": "47673",
"Score": "5",
"Tags": [
"c#",
"algorithm",
".net"
],
"Title": "Method to separate a list of ports to scan"
} | 47673 |
<p>This function tells that elements of content either (maybe) match regexes that you like or match regexes that you don't like.</p>
<p>This messy code requires <code>Data.Text.Lazy</code> but internally shuffles around internal and strict versions. Also list Monad code looks fishy to me.</p>
<p>How can it be made simpler, faster, more general (especially work with any Text and String)?</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
module Search (analyze) where
import qualified Data.Text.Lazy as T
import Data.Maybe()
import Text.Regex.TDFA
import Text.Regex.Base.Context()
import Text.Regex.Base.RegexLike()
import Text.Regex.TDFA.Text
import Data.Function (on)
import Data.Maybe (maybeToList)
matches :: [T.Text] -> T.Text -> [T.Text]
matches patterns content = map (T.fromStrict) $ concat $ do
pattern <- patterns
return $ maybeToList $ (on (=~~) T.toStrict) content pattern
analyze :: [T.Text] -> [T.Text] -> T.Text -> Either [T.Text] [T.Text]
analyze likes dislikes text =
case matches likes text of
liked@(_:_) ->
case matches dislikes text of
[] -> Right liked
disliked@(_:_) -> Left disliked
_ -> Left []
</code></pre>
| [] | [
{
"body": "<p>To fix lazy/strict shuffling you need to import <code>Text.Regex.TDFA.Text.Lazy</code> module. It contains TDFA-related instances for <code>Data.Text.Lazy</code></p>\n\n<p>Some other things to consider.</p>\n\n<p>You can skip <code>maybeToList</code> because <code>(=~)</code> returns <code>m target</code> for some monad <code>m</code>.</p>\n\n<pre><code>- return $ maybeToList $ (on (=~~) T.toStrict) content pattern\n+ return $ (on (=~~) T.toStrict) content pattern\n</code></pre>\n\n<p>This will work without any further changes because <code>(=~)</code> will select list monad and match failure will be represented by empty list.</p>\n\n<p>Do-notation for list monad can be replaced with single <code>map</code> and <code>concat . map f</code> -- with <code>concatMap</code></p>\n\n<pre><code>- matches patterns content = map (T.fromStrict) $ concat $ do\n- pattern <- patterns\n- return $ maybeToList $ (on (=~~) T.toStrict) content pattern\n+ matches patterns content = map T.fromStrict\n+ $ concatMap ((on (=~~) T.toStrict) content) patterns\n</code></pre>\n\n<p>Now it's time to add <code>import Text.Regex.TDFA.Text.Lazy</code> and remove text conversions</p>\n\n<pre><code>- matches patterns content = map T.fromStrict\n- $ concatMap ((on (=~~) T.toStrict) content) patterns\n+ matches patterns content = concatMap (content=~~) patterns\n</code></pre>\n\n<p>You can swap arguments and drop <code>patterns</code> varaible.</p>\n\n<p>As for the <code>analyse</code> function, it's just a matter of taste but I think it is more readable to enumerate all variants in single case:</p>\n\n<pre><code>analyze likes dislikes text\n = case (matches text likes, matches text dislikes) of\n ([], _) -> Left []\n (liked, []) -> Right liked\n (_, disliked) -> Left disliked\n</code></pre>\n\n<p>For the last step you can import <code>Text</code> type unqaulified to make function types look cleaner.</p>\n\n<p>Here is the result:</p>\n\n<pre><code>import Data.Text.Lazy (Text)\nimport qualified Data.Text.Lazy as T\nimport Text.Regex.TDFA.Text.Lazy\nimport Text.Regex.TDFA\n\nmatches :: Text -> [Text] -> [Text]\nmatches content = concatMap ((=~~) content)\n\nanalyze :: [Text] -> [Text] -> Text -> Either [Text] [Text]\nanalyze likes dislikes text\n = case map (matches text) [likes, dislikes] of\n [[], _] -> Left []\n [liked, []] -> Right liked\n [_, disliked] -> Left disliked\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T16:19:32.717",
"Id": "47719",
"ParentId": "47679",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T21:20:54.237",
"Id": "47679",
"Score": "3",
"Tags": [
"haskell",
"regex"
],
"Title": "How to simplify Regex with Data.Text?"
} | 47679 |
<p>I found myself writing code to run at a specified frequency more than once, so I decided to make this simple timer. My main concern is that this is not the most efficient way of doing this since with <code>SDL</code> I would just ask for the time in ms and sleep in ms.</p>
<p>I'm storing the current time in <code>timer_update()</code> to avoid the possibility of it becoming greater than the final time and generating a huge pause since it's unsigned.</p>
<p>Usage is pretty simple, <code>timer_init()</code> is called once before the loop and <code>timer_update()</code> is called once at the end of every iteration.</p>
<p><strong>timer.h</strong></p>
<pre><code>#ifndef TIMER_H
#define TIMER_H
typedef struct {
double step;
double tfinal;
} Timer;
void timer_init(Timer *timer, double hertz);
void timer_update(Timer *timer);
#endif
</code></pre>
<p><strong>timer.c</strong></p>
<pre><code>#include "timer.h"
#define _POSIX_C_SOURCE 199309L
#include <time.h>
#include <errno.h>
#include <stdio.h>
static unsigned long get_ms(void)
{
struct timespec buffer;
unsigned long temp;
if(clock_gettime(CLOCK_MONOTONIC, &buffer) != 0){
perror("clock_gettime");
return 0;
}
temp = buffer.tv_sec * 1000;
temp += buffer.tv_nsec / 1000000;
return temp;
}
static struct timespec ms_to_timespec(unsigned long ms)
{
struct timespec temp = {ms / 1000, (ms % 1000) * 1000000};
return temp;
}
void timer_init(Timer *timer, double hertz)
{
timer->step = 1000 / hertz;
timer->tfinal = get_ms() + timer->step;
}
void timer_update(Timer *timer)
{
unsigned long now = get_ms();
struct timespec required_sleep, rem;
if(now < timer->tfinal){
required_sleep = ms_to_timespec(timer->tfinal - now);
timer->tfinal += timer->step;
try_to_sleep:
if(nanosleep(&required_sleep, &rem) == -1 && errno == EINTR)
if(nanosleep(&rem, &required_sleep) == -1 && errno == EINTR)
goto try_to_sleep;
}
else
timer->tfinal += timer->step;
}
</code></pre>
| [] | [
{
"body": "<p>Rather than looping around <code>goto</code>, why not calculate how much time is remaining and convert it into ticks and <code>sleep (ticks)</code>? It would also be better to find some way to generate an event rather than lopping continuously, if timing is not very strict.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T23:51:12.223",
"Id": "84249",
"Score": "1",
"body": "The loop is only to handle the scenario where the sleep is interrupted. The problem with `sleep()` is that it takes seconds and the timer sleeps for ms. http://linux.die.net/man/3/sleep"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-02T02:43:26.587",
"Id": "105746",
"Score": "2",
"body": "@2013Asker, no problem, use [`usleep()`](http://linux.die.net/man/3/usleep)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:35:45.553",
"Id": "47959",
"ParentId": "47688",
"Score": "-2"
}
},
{
"body": "<blockquote>\n <p>Is this timer efficient?</p>\n</blockquote>\n\n<ul>\n<li><p>Yes, but there are two optimizations that I can see. Get rid of the <code>goto</code>\nand use a <code>do-while</code> loop. I have noticed a slight performance\nincrease when it has been written this way in other programs. </p>\n\n<p>This increase will become non-existent however if you have compiler\noptimization settings enabled. If they are enabled, they compile\ninto <a href=\"https://stackoverflow.com/a/2288893/1937270\">the exact same assembly code</a>. However, I also find a loop\nmore readable than a <code>goto</code>, so that is another reason to switch\nover.</p></li>\n<li><p>There other optimization I could see is by cleaning up your <code>if-else</code> a tiny bit (untested). This should speed up your code a tiny bit (again, if optimizations on your compiler are enabled, your results will vary).</p>\n\n<pre><code>if(now < timer->tfinal)\n{\n required_sleep = ms_to_timespec(timer->tfinal - now);\n\n // loop implementation\n}\ntimer->tfinal += timer->step;\n</code></pre>\n\n<p>You may wonder why this will speed up your code. The more branches you have, the more susceptible you are to a <a href=\"https://en.wikipedia.org/wiki/Branch_predictor\" rel=\"nofollow noreferrer\">branch prediction</a> failure and those failures can be expensive when it comes to efficiency.</p></li>\n</ul>\n\n<hr>\n\n<p>A few other notes:</p>\n\n<ul>\n<li><p>Use a <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html\" rel=\"nofollow noreferrer\">designated initializer</a> to initialize a structure <sup>(C99)</sup>.</p>\n\n<pre><code>struct timespec temp = \n{ \n .step = ms / 1000, \n .tfinal = (ms % 1000) * 1000000 \n};\n</code></pre></li>\n<li><p>Group your <code>#include</code>s and <code>#define</code>s together in a more organized fashion.</p>\n\n<pre><code>#include <time.h> // group library headers\n#include <errno.h>\n#include <stdio.h>\n#include \"timer.h\" // group user defined headers\n\n#define _POSIX_C_SOURCE 199309L // group defines\n</code></pre></li>\n<li><p>Your <code>!= 0</code> comparision check in your <code>if</code> conditional could be removed since it is redundant (the <code>if</code> will always execute if the conditional isn't equal to <code>0</code>). However, this may increase readability to you, so it would be okay to keep it.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-01T22:48:27.717",
"Id": "58801",
"ParentId": "47688",
"Score": "10"
}
},
{
"body": "<p>this Method is kind of ugly</p>\n\n<pre><code>void timer_update(Timer *timer)\n{\n unsigned long now = get_ms();\n struct timespec required_sleep, rem;\n\n if(now < timer->tfinal){\n required_sleep = ms_to_timespec(timer->tfinal - now);\n timer->tfinal += timer->step;\n\n try_to_sleep:\n if(nanosleep(&required_sleep, &rem) == -1 && errno == EINTR)\n if(nanosleep(&rem, &required_sleep) == -1 && errno == EINTR)\n goto try_to_sleep;\n }\n\n else\n timer->tfinal += timer->step;\n}\n</code></pre>\n\n<p>You have nested if statements that have no braces and you only need one if statement with a slightly longer conditional. This should stop one thing from being tested twice.</p>\n\n<pre><code>try_to_sleep:\nif((nanosleep(&required_sleep, &rem) == -1 && errno == EINTR) && nanosleep(&rem, &required_sleep)) {\n goto try_to_sleep;\n}\n</code></pre>\n\n<p>The else statement bracing style should match the if statement that it is attached to, even if it is a one liner or it should truly be one line.</p>\n\n<p>Using braces:</p>\n\n<pre><code>else {\n timer->tfinal += timer->step;\n}\n</code></pre>\n\n<p>One Lined</p>\n\n<pre><code>else timer->tfinal += timer->step;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T14:45:02.520",
"Id": "60804",
"ParentId": "47688",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T01:40:23.157",
"Id": "47688",
"Score": "10",
"Tags": [
"c",
"timer"
],
"Title": "Is this timer efficient?"
} | 47688 |
<p><a href="http://developer.android.com/training/basics/fragments/communicating.html">Android documentation</a> says: </p>
<blockquote>
<p>Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.</p>
</blockquote>
<p>My question is: Why should Fragments never communicate directly? Because it can cause problems or simply because of "good" code (clean code, maintenance...)?</p>
<p>Fragments communicate directly in my apps and I have not encountered any problem yet. Here an example of how I pass data from an "Event" fragment to a "Event Details" fragment:</p>
<pre><code>public class UpcomingEventsFragment extends Fragment {
private UpcomingEventsAdapter mAdapter;
private ListView listview;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_upcomingevents, container, false);
listview = (ListView) rootView.findViewById(R.id.upcomingevents);
mAdapter = new UpcomingEventsAdapter(getActivity());
listview.setAdapter(mAdapter);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event event = mAdapter.getItem(position);
Bundle args = new Bundle();
args.putString("id", event.getId());
EventDetailsFragment fragment = new EventDetailsFragment();
fragment.setArguments(args);
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
}
</code></pre>
| [] | [
{
"body": "<p>As the <a href=\"http://developer.android.com/guide/components/fragments.html\" rel=\"nofollow\">Fragments doc</a> says:</p>\n\n<blockquote>\n <p>You can think of a fragment as a modular section of an activity</p>\n</blockquote>\n\n<p>A fragment that assumes the existence of another fragment breaks the modularity. Fragments should be unaware of each other, be self-contained and work independently.</p>\n\n<p>Take for example the common use case when the activity uses a single small fragment on phones, and +1 larger fragment on tablets. The smaller fragment should not access the larger one directly because it may not be there. You might say the large fragment could safely assume the smaller one always exists, but that too would violate the modularity principle.</p>\n\n<p>When your app is perfectly modular, fragments don't know about each other. You can add a fragment, remove a fragment, replace a fragment, and they should all work fine, because they are all independent, and the activity has full control over the configuration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:10:15.290",
"Id": "83689",
"Score": "0",
"body": "But in my case, I don't use fragments to handle different layouts. I use them for Navigation Drawer so they are supposed to always exist. I have 1 Activity with multiple fragments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:16:40.857",
"Id": "83690",
"Score": "0",
"body": "In terms of the modular design principle, making fragments independent from each other seems to make good sense. But if you are 200% sure your fragments can always count on each other, then maybe it's ok to make an exception in your case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:43:30.980",
"Id": "83692",
"Score": "0",
"body": "Thanks for your clarification. So, regarding of the different answers, it's only for \"best practice\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T08:15:20.903",
"Id": "47698",
"ParentId": "47689",
"Score": "4"
}
},
{
"body": "<p>Android application design best practices suggest that fragments should be modular and independent from each other, so that you may able to arrange them differently - not just on screen, but also changing relationships among them - when you are targeting devices with widely different screen sizes, e.g. smartphones and tablets. Those very same best practices suggest that you don't see nor use the whole activity interface in a fragment, but only a subset that you have defined through a proper custom interface, which typically contains callback methods that are invoked in cases such as yours, when an action taken in a fragment must trigger the creation and display of another fragment.</p>\n\n<p>However, note that there is an <a href=\"http://developer.android.com/reference/android/app/Fragment.html#setTargetFragment%28android.app.Fragment,%20int%29\">interesting API</a> that has been thought exactly for the purpose of starting a fragment from another fragment, and possibly returning a result to the caller fragment, much like <code>startActivity</code> and <code>onActivityResult</code> do for activities. I do believe that, while modularity and independence are indeed best design practices, there may be cases when two fragments are strictly intertwined, so much that that dependency is preserved even on different devices; and the cited API is there to help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T13:15:14.137",
"Id": "47715",
"ParentId": "47689",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47698",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T01:46:16.333",
"Id": "47689",
"Score": "5",
"Tags": [
"java",
"android"
],
"Title": "Communicating with other fragments or to activity"
} | 47689 |
<p>I have this code:</p>
<pre><code>public class RecurLoopTest {
public static void main(String[] args) {
printit(2);
}
private static int printit(int n){
if(n>0){
printit(--n);
}
System.out.print(n+",");
return n;
}
}
</code></pre>
<p>I have drawn a execution flow/memory flow diagram for above program. Is this diagram correct or do I need some changes to make it correct?</p>
<p>What I have drawn looks like this:</p>
<p><img src="https://i.stack.imgur.com/Gq6pG.jpg" alt="enter image description here"></p>
<p><a href="https://creately.com/diagram/hu6inaj32/EbReNdNSdRqJI9xMbmr0byn2iM8=" rel="nofollow noreferrer">Link to edit diagram</a></p>
<p><a href="https://creately.com/diagram/hu6inaj32" rel="nofollow noreferrer">Link to view diagram</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-08T12:29:43.293",
"Id": "514188",
"Score": "0",
"body": "Wow, this diagram visually clearly communicates your _recursive_ algorithm: illustrated call-stack plus count-down iterator-parameter"
}
] | [
{
"body": "<p>It would be better to add the method arguments in the diagram, for example:</p>\n\n<pre><code>printit(0) -- n=0, prints \"0,\", returns 0\nprintit(1) -- n=1, prints \"0,\", returns 0\nprintit(2) -- n=2, prints \"1,\", returns 1\nmain()\n</code></pre>\n\n<p>I don't think you need 4 drawings side by side for this, just one like this would be clear enough already.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T06:58:32.503",
"Id": "47696",
"ParentId": "47691",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47696",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-20T02:34:16.047",
"Id": "47691",
"Score": "3",
"Tags": [
"java",
"algorithm",
"recursion",
"data-visualization"
],
"Title": "Execution flow diagram (call-stack) of recursive count-down"
} | 47691 |
<p>This is how it handles input:</p>
<ul>
<li>if negative, terminate program</li>
<li>if 0-2, display input without calculating</li>
<li>if greater than or equal to 3, calculate and display result</li>
</ul>
<p>I have also used some macros from an included file:</p>
<ul>
<li><code>nwln</code>: outputs a newline</li>
<li><code>PutStr</code>: displays a label</li>
<li><code>GetLInt</code>: receives a 32-bit integer</li>
<li><code>PutLInt</code>: displays a 32-bit integer</li>
</ul>
<p>My questions:</p>
<ol>
<li>Is my input validation reducing readability, or is that not important as long as the program proceeds with only the correct input?</li>
<li>Should I need to check for non-numerical values, or does it not really matter?</li>
<li>Since the result register (<code>EAX</code>) is 32-bit, should I take into account a possible result that may not fit in 32 bits? If I get a larger result, it won't display properly, and the user may be unaware.</li>
<li>Is doing a bunch of adds still faster than using <code>mul</code>? I'm also avoiding <code>mul</code> because I still have trouble getting all the bits in the right place.</li>
<li>Should any of these procedures be organized differently? I'm still not sure how important this is in assembly when most procedures have jumps or branches. In this program, it makes sense to have <code>check_input</code> after <code>get_input</code> and with no jump in between them.</li>
</ol>
<p>Other than that, I'd like a review on anything you may find.</p>
<pre><code>%include "macros.s"
.DATA
input_lbl: DB "Number: ", 0
bad_input_lbl: DB "Number must be positive!", 0
result_lbl: DB "Total: ", 0
input: DD 0
result: DD 0
.CODE
.STARTUP
; EAX - input
; EBX - input (for counter)
get_input:
PutStr input_lbl
GetLInt [input]
mov EAX, [input]
mov EBX, [input]
; EBX - input
check_input:
; terminate if input is negative
cmp EBX, 0
jl report_bad_input
; no need to calculate if below 3
cmp EBX, 3
jge calc_factorial
; input is 0, 1, or 2
jmp display_result
report_bad_input:
PutStr bad_input_lbl
.EXIT
; EAX - result
display_result:
nwln
mov [result], EAX
PutStr result_lbl
PutLInt [result]
.EXIT
; EAX - current value
; EBX - counter
; ECX - current total (for multiplication)
; EDX - counter (for multiplication)
calc_factorial:
; no need to multiply by 1
dec EBX
cmp EBX, 1
je display_result
; perform addition instead of multiplication
mov ECX, EAX
mov EDX, EBX
jmp mult_with_addition
jmp calc_factorial
; EAX - current total
; ECX - current total (for multiplication)
; EDX - counter (for multiplication)
mult_with_addition:
; determine if addition should stop
dec EDX
cmp EDX, 0
je calc_factorial
add EAX, ECX
jmp mult_with_addition
</code></pre>
<p><strong>Sample tests:</strong></p>
<blockquote>
<p>Input: 3<br>
Output: 6</p>
<p>Input: 2<br>
Output: 2</p>
<p>Input: 1<br>
Output: 1</p>
<p>Input: 0<br>
Output: 0</p>
<p>Input: -1<br>
Output: "Number must be positive!"</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T09:06:52.943",
"Id": "83605",
"Score": "0",
"body": "Why do you prefer macros over functions? Worried about performance (I might understand you if you were running on a 80386)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T09:09:56.427",
"Id": "83607",
"Score": "0",
"body": "@no1: No, these macros were from my assembly class, so I'm accustomed to using them."
}
] | [
{
"body": "<blockquote>\n <p>Is my input validation reducing readability, or is that not important as long as the program proceeds with only the correct input?</p>\n</blockquote>\n\n<p>Usually, \"does it implement required functionality?\" is even more important than \"is it readable?\"</p>\n\n<p>A \"Hello world\" program is very readable but doesn't implement required functionality.</p>\n\n<blockquote>\n <p>Should I need to check for non-numerical values, or does it not really matter?</p>\n</blockquote>\n\n<p>When you're programming for other people (e.g. professionally) there might be someone other than the programmer (e.g. there's a boss, a product manager, a UI designer) who specifies what is implemented: and your job as programmer is to decide how to implement that.</p>\n\n<p>Whether validating input \"matters\" depends on why you're writing the program, on who you're writing it for, and on who is going to use it.</p>\n\n<blockquote>\n <p>Since the result register (<code>EAX</code>) is 32-bit, should I take into account a possible result that may not fit in 32 bits? If I get a larger result, it won't display properly, and the user may be unaware.</p>\n</blockquote>\n\n<p>Again that's a matter of the program's \"requirements\". Different programs have different requirements.</p>\n\n<p>IIRC a 32-bit number is big enough for <code>13!</code> but not <code>14!</code>.</p>\n\n<blockquote>\n <p>Is doing a bunch of adds still faster than using <code>mul</code>?</p>\n</blockquote>\n\n<p><a href=\"http://www2.math.uni-wuppertal.de/~fpf/Uebungen/GdR-SS02/opcode_i.html\" rel=\"nofollow\">This</a> suggests that on a Pentium, <code>ADD</code> is about 3 cycles whereas <code>MUL</code> is about 10 cycles. So <code>MUL</code> is faster if you need to multiply by more than about 3 or 4.</p>\n\n<blockquote>\n <p>I'm also avoiding <code>mul</code> because getting the bits in the right place for it is complicated, and I still cannot seem to get it right.</p>\n</blockquote>\n\n<p>Perhaps ask about this on Stack Overflow.</p>\n\n<blockquote>\n <p>Should any of these procedures be organized differently? I'm still not sure how important this is in assembly when when most procedures have jumps or branches. In this program, it makes sense to have check_input after get_input and with no jump in between them.</p>\n</blockquote>\n\n<p>I suppose there are three reasons to use subroutines:</p>\n\n<ul>\n<li>Programmers who use high-level-languages are used to them; a nest of jump are \"spaghetti code\" and \"goto is considered harmful\" (compared with 'structured programming')</li>\n<li>A subroutine can be called from more than one place (i.e. reused)</li>\n<li>One of the problems with assembly is knowing what registers are used. You documented which registers are used by your code fragments. For larger programs you might want to define a standard used by all subroutine, for example, \"any subroutine may use/corrupt <code>eax</code> through <code>edx</code>; if it alters any other register (e.g. <code>esi</code>, <code>ebp</code>, etc.) then it must save previous value before changing it and restore old value after changing it before returning.</li>\n</ul>\n\n<p>For example your program might look like this if it were written with subroutines:</p>\n\n<pre><code>; assume the following calling conventions:\n; esi is the input parameter\n; eax is the output value\n; carry flag is set if there's an error\nmov esi, input_lbl\ncall PutStr\ncall GetUint\njnc input_ok\nmov esi, input_error\ncall PutStr\n.EXIT\ninput_ok:\nmov esi, eax\ncall factorial\njnc output_ok\nmov esi, factorial_overflow_error\ncall PutStr\n.EXIT\noutput_ok\npush eax ; preserve the factorial value\nmov esi, factorial_overflow_is\ncall PutStr\npop esi ; restore the factorial value\ncall PutUint\n.EXIT\n</code></pre>\n\n<hr>\n\n<pre><code>GetLInt [input]\nmov EAX, [input]\n</code></pre>\n\n<p>If <code>GetLInt</code> is a macro would it work to just say <code>GetLInt EAX</code>?</p>\n\n<hr>\n\n<pre><code>mov EBX, [input]\n</code></pre>\n\n<p><code>mov EBX, EAX</code> (i.e. move from register) would be faster and shorter than move from memory.</p>\n\n<hr>\n\n<pre><code>\"Number must be positive!\", 0\n</code></pre>\n\n<p><code>EBX</code> contains bits. Those bits can represent a signed or an unsigned number. You might like to use a different macro e.g. <code>GetLUInt</code> which errors if the user enters a <code>-</code> minus sign, and accepts unsigned integers e.g. <code>4000000000</code>.</p>\n\n<hr>\n\n<pre><code>nwln\n</code></pre>\n\n<p>Is this a macro not an opcode? It might be better to use e.g. upper case for macro names and lower case for opcode names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T09:43:47.490",
"Id": "83614",
"Score": "0",
"body": "I'm not sure why `nwln` is all lowercase, but that's just how it was written. I would have to modify the file myself if I wanted to make it all uppercase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:38:19.677",
"Id": "83662",
"Score": "0",
"body": "Also regarding the macros, I should say that it's considered \"safe and effective\" for students, so it's not something I would use in a serious program. It also doesn't come with `GetLUInt`, so I may have to find out how to add it. If I go up to 64-bit, then I can just change my registers and macros so that I can use larger numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:41:13.233",
"Id": "83663",
"Score": "0",
"body": "@Jamal [This](http://pdos.csail.mit.edu/6.828/2007/readings/i386/MUL.htm) says, \"A doubleword operand is multiplied by EAX and the result is left in EDX:EAX. EDX contains the high-order 32 bits of the product. The carry and overflow flags are set to 0 if EDX is 0; otherwise, they are set to 1.\" IOW I think you can do a multiply with a 64-bit result using ordinary 32-bit code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:48:07.233",
"Id": "83667",
"Score": "0",
"body": "I can try to figure that out, but I'll address the other issues first, particularly with the subroutines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:18:45.780",
"Id": "83678",
"Score": "0",
"body": "@Jamal IMO assembly code can avoid subroutines, if you're golfing for the sake of obscurity, or for minimum size, or for maximum speed; but using subroutines improves readability, maintainability (extensibility, decoupling, reusability), and encapsulation (single responsibility, well-defined standardized effects and side-effects). I'm not familiar with your specific macro library, nor in general with how macros are used idiomatically with a macro assembler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:22:13.267",
"Id": "83679",
"Score": "0",
"body": "I'm not at all trying to keep at a minimal size. I haven't been taught how to write readable assembly code, just working code. I'm still used to using jumps as opposed to calls, but I'm willing to learn better habits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:30:18.850",
"Id": "83680",
"Score": "0",
"body": "@Jamal I haven't been taught either; the sample I showed was off the top of my head. You might see that it improves readability: it allows top-down design (write the `main` logic and leave the implementation of the various subroutines as separate exercise). There are many possible 'standard' [calling conventions](http://en.wikipedia.org/wiki/X86_calling_conventions) you can choose from. My using the Carry Flag to return an error is non-standard (if the value is returned in EAX, perhaps better to choose another register e.g. EDX if you also need to return a separate error condition)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:33:38.997",
"Id": "83681",
"Score": "0",
"body": "@Jamal Those calling conventions are used e.g. for calling subroutines from a high-level language. There are other alternatives, see e.g. how the DOS/BIOS API uses registers. I don't know other/many native (i.e. designed to be called from assembly) assembly APIs; but calling conventions compatible with high-level languages are at least well-defined/regular."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T09:31:01.677",
"Id": "47701",
"ParentId": "47692",
"Score": "1"
}
},
{
"body": "<p>It appears that I've forgotten that 0! is equal to 1, not 0...</p>\n\n<p>I've made the following changes to fix that:</p>\n\n<ul>\n<li>Change <code>result</code>'s starting value from <code>0</code> to <code>1</code>. In this way, <code>1</code> will be displayed as a result right away (no calculations done for such input).</li>\n<li><p>Assigned <code>EAX</code> to <code>result</code> in <code>calc_factorial</code> instead of <code>display_result</code> (it doesn't make sense to mutate values in displaying code anyway...).</p>\n\n<p>Remove from here:</p>\n\n<pre><code>display_result:\n nwln\n mov [result], EAX // remove\n PutStr result_lbl\n PutLInt [result]\n .EXIT\n</code></pre>\n\n<p>Add to here:</p>\n\n<pre><code>calc_factorial:\n ; no need to multiply by 1\n dec EBX\n cmp EBX, 1\n mov [result], EAX // add\n je display_result\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T10:04:29.190",
"Id": "47703",
"ParentId": "47692",
"Score": "2"
}
},
{
"body": "<p>There are a couple of things that may be of use to you for this code, and some general comments that should be useful for any assembly language programs you write in the future.</p>\n\n<h2>Make it modular</h2>\n\n<p>The code that implements the factorial routine does a <code>je display_result</code> to exit, but that needlessly ties it to the display routine. In assembly language, it's generally better to use either a <code>ret</code> to return (implying it's written as a subroutine) or to have the routine \"fall through\" the end. Either is acceptable, but implementing as subroutines is more common.</p>\n\n<h2>Prefer subroutines to macros</h2>\n\n<p>The macros you've got might, underneath, result in a subroutine call to some code other than that which you've posted, or more likely, it implements directly the code used to perform those functions. There might be a slight performance advantage to replicating the code multiple times via a macro invocation, but more often, it just leads to code bloat. (Although even with this \"bloat\" it's probably smaller than the corresponding C program!)</p>\n\n<h2>Comment fully</h2>\n\n<p>If we look at the comment for <code>calc_factorial</code> it currently reads this way:</p>\n\n<pre><code> ; EAX - current value\n ; EBX - counter\n ; ECX - current total (for multiplication)\n ; EDX - counter (for multiplication)\n</code></pre>\n\n<p>This may be accurate, but which are inputs? Which are outputs? What does the routine do? I'd recommend a comment style something more like this:</p>\n\n<pre><code> ;****************************************************************************\n ; \n ; PrintString \n ; prints the string at DS:DX with length CX to stdout\n ;\n ; INPUT: ds:dx ==> string, cx = string length\n ; OUTPUT: CF set on error, AX = error code if carry set\n ; DESTROYED: ax, bx\n ;\n ;****************************************************************************\n</code></pre>\n\n<h2>Use <code>mul</code> rather than <code>add</code></h2>\n\n<p>The <code>mul</code> instruction is definitely going to be faster than the corresponding loop with <code>add</code> instructions. The <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_210.html\" rel=\"nofollow\"><code>mul</code> instruction</a> as a 32-bit instruction multiplies <code>EAX</code> by some other register, yielding a result in <code>EDX:EAX</code> meaning that the high part of the result will be in <code>EDX</code> and the low 32 bits of the result will be in <code>EAX</code>.</p>\n\n<h2>Structure code to avoid unconditional jumps</h2>\n\n<p>If we look at the code, (with comments removed for clarity) we can see that the code does a <code>jmp mult_with_addition</code> but it's jumping over an instruction that cannot be reached! For that reason, you could eliminate both <code>jmp</code> instructions. </p>\n\n<pre><code> calc_factorial:\n dec EBX\n cmp EBX, 1\n je display_result\n\n mov ECX, EAX\n mov EDX, EBX\n jmp mult_with_addition\n\n jmp calc_factorial\n\n mult_with_addition:\n dec EDX\n cmp EDX, 0\n je calc_factorial\n\n add EAX, ECX\n\n jmp mult_with_addition\n</code></pre>\n\n<h2>Minimize register moves</h2>\n\n<p>As much as practical, try to minimize register moves, preferring instead to have the data already in the register you need for instructions or subroutines which have register-specific needs. For example, because the <code>mul</code> instruction uses <code>EDX</code> and <code>EAX</code>, it makes sense to try to make sure that the number being multiplied is already in that register pair.</p>\n\n<h2>Don't fail silently</h2>\n\n<p>As with any code in any language, failing silently must be avoided. In the case of a factorial operation, an overflow condition should be checked and passed back to the calling code. If you use the <code>mul</code> instruction, and return a 32-bit result in <code>EAX</code>, checking for overflow is as simple as checking <code>EDX</code> for a zero value.</p>\n\n<h2>Look carefully at instruction encodings</h2>\n\n<p>In one place in your code, you have the instruction <code>cmp EDX,0</code> followed by a conditional jump based on the <code>Z</code> flag. In 32-bit mode, that instruction is probably coded as <code>83FA00</code> but if you had used <code>or EDX,EDX</code> it is likely to be coded as <code>09D2</code> which is one byte shorter. However, neither are really needed because the <code>dec EDX</code> instruction before it (encoded as <code>4A</code>) <em>already</em> sets the <code>Z</code> flag. There may be no reason to care about one or two bytes one way or the other, but if that's the case, why code in assembly at all? If you're going to do it, do it well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:21:37.643",
"Id": "83761",
"Score": "0",
"body": "Yeah, I know my assembly isn't too good. I didn't learn all the best practices from school, so now I have to teach myself. I don't think I'll be writing serious programs in assembly anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:41:15.083",
"Id": "83768",
"Score": "1",
"body": "I know. I like writing it because it helps with understanding some of the low-level aspects. I'm not going to waste my time trying to learn other assembly instruction sets, although I have already learned a tiny bit of MIPS."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:07:51.730",
"Id": "47750",
"ParentId": "47692",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47750",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T03:04:39.990",
"Id": "47692",
"Score": "5",
"Tags": [
"performance",
"validation",
"assembly"
],
"Title": "32-bit factorial calculator in x86 NASM assembly"
} | 47692 |
<p>I have a text file and I was curious about what character appears how often in the text.</p>
<p>Any review is appreciated.</p>
<pre><code>public class CountLetters {
public static void main(String[] args) throws Exception {
TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
File file = new File("C:/text.txt");
Scanner scanner = new Scanner(file,"utf-8");
while (scanner.hasNext()) {
char[] chars = scanner.nextLine().toLowerCase().toCharArray();
for (Character c : chars) {
if(!Character.isLetter(c)){
continue;
}
else if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
</code></pre>
<p>The output will be for example: </p>
<blockquote>
<pre><code>a: 1202
b: 311
c: 603
d: 510
e: 2125
f: 373
g: 362
h: 718
i: 1313
j: 5
k: 74
l: 678
m: 332
n: 1129
o: 1173
p: 348
q: 40
r: 812
s: 1304
t: 1893
u: 415
v: 195
w: 314
x: 86
y: 209
z: 9
</code></pre>
</blockquote>
| [] | [
{
"body": "<h3>Resources:</h3>\n<p>You should start using <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"noreferrer\"><code>try-with-resources</code>.</a> This statment does some work for you with resources that implement <code>AutoCloseable</code>. It closes these resources for you, so you don't have to worry about file-locks and remaining database connections:</p>\n<pre><code>File file = new File("C:/text.txt");\ntry(Scanner scanner = new Scanner(file, "utf-8")){\n //your code here ;)\n}\n</code></pre>\n<p>You also shouldn't throw <code>Exception</code> in the main method of your program. This can be very confusing to users. Instead you main-method should handle all exceptions "gracefully" by being wrapped into a <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html\" rel=\"noreferrer\">try-catch-block.</a></p>\n<h3>Conditionals:</h3>\n<blockquote>\n<pre><code>if(!Character.isLetter(c)){\n continue;\n}\n</code></pre>\n</blockquote>\n<p>This is an early return statement for the purpose of following conditions, meaning you don't have to write <code>else if</code> in your next condition.</p>\n<h3>Naming</h3>\n<p><code>hashMap</code> is not a good name. The map you use is not a Hash-Map, and <code>treeMap</code> would also not explain what the map does, what it <em>contains</em>.</p>\n<p>You might want to rename it to <code>characterMap</code></p>\n<p>all else equal, your naming is nice and consistent, and tells exactly what the variables do. You nicely follow <code>camelCase</code>-conventions. <strong>Keep it up!</strong></p>\n<h3>Summary:</h3>\n<p>Your code reads nicely and is easily understandable. You follow naming conventions and have descriptive and understandable variable names. You should work on your exception handling and the use of resources.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:25:48.053",
"Id": "83646",
"Score": "0",
"body": "I would name it `characters` instead of `characterMap` since that \"map\" doesn't add anything and instead removes some abstraction from your variable. It will cause a refactoring if you change the underlying datastructure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:30:53.413",
"Id": "83647",
"Score": "1",
"body": "@Jeroen ypu have a point. But changing the underlying datastructure will cause a refactoring either way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:41:17.563",
"Id": "83651",
"Score": "0",
"body": "I would use `StandardCharsets.UTF_8` rather than the `String`. Otherwise +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T09:24:00.317",
"Id": "83726",
"Score": "0",
"body": "@BoristheSpider In this case it would require `StandardCharsets.UTF_8.toString()` not just `StandardCharsets.UTF_8`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T11:13:58.590",
"Id": "47707",
"ParentId": "47704",
"Score": "19"
}
},
{
"body": "<p>My notes in code:</p>\n\n<pre><code>public class CountLetters {\n // Throwing Exception is too general, you should throw IOException\n public static void main(String[] args) throws Exception {\n // It is better practice to define Map, instead of TreeMap\n // The name of variable hashMap could be better, for example characterMap or characters\n TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();\n File file = new File(\"C:/text.txt\");\n Scanner scanner = new Scanner(file,\"utf-8\");\n\n while (scanner.hasNext()) {\n char[] chars = scanner.nextLine().toLowerCase().toCharArray();\n for (Character c : chars) {\n if(!Character.isLetter(c)){\n // 'continue' is unnecessary as last statement in a loop\n // It is better to put following 'else if' and 'else' here and to remove negation in condition\n // like this: if(Character.isLetter(c)){ if ( ... ) { ... } else { ... } }\n continue;\n }\n else if (hashMap.containsKey(c)) {\n hashMap.put(c, hashMap.get(c) + 1);\n } else {\n hashMap.put(c, 1);\n }\n }\n }\n\n // You should call scanner.close() here\n\n // I would wrap this into if (!hashMap.isEmpty()) { ... }, but it is not really needed\n for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n }\n }\n}\n</code></pre>\n\n<p>I would rewrite the class like this:</p>\n\n<pre><code>public class CountLetters {\n public static void main(String[] args) throws IOException {\n Map<Character, Integer> characters = new TreeMap<Character, Integer>();\n Scanner scanner = null;\n\n try {\n scanner = new Scanner(new File(\"C:/text.txt\"),\"utf-8\");\n\n while (scanner.hasNext()) {\n char[] line = scanner.nextLine().toLowerCase().toCharArray();\n\n for (Character character : line) {\n if (Character.isLetter(character)){\n if (characters.containsKey(character)) {\n characters.put(character, characters.get(character) + 1);\n } else {\n characters.put(character, 1);\n }\n }\n }\n }\n } finally {\n if (scanner != null){\n scanner.close();\n }\n }\n\n if (!characters.isEmpty()){\n for (Map.Entry<Character, Integer> entry : characters.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T16:07:42.387",
"Id": "83644",
"Score": "0",
"body": "It's great to see such a new user being so active! +1, and feel free to join us in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T11:24:40.503",
"Id": "47708",
"ParentId": "47704",
"Score": "8"
}
},
{
"body": "<ol>\n<li>I would change the map <code>hashMap</code> to <code>characterCounterMap</code>.</li>\n<li><p>Then I would initialized the map at first with characters, like</p>\n\n<pre><code>for(char c = 'a'; c <= 'z'; c++) {\n characterCounterMap.put(c,0);\n}\n</code></pre></li>\n<li><p>Then it will help you to shortening the if-else ladder, like</p>\n\n<pre><code>if(Character.isLetter(character)) {\n characterCounterMap.put(character, characterCounterMap.get(character) + 1);\n} // see no else\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T08:37:47.173",
"Id": "83725",
"Score": "4",
"body": "Caution! [`Character.isLetter()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isLetter\\(char\\)) is Unicode-aware, and supports more than just 'a'..'z'."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:23:15.033",
"Id": "47717",
"ParentId": "47704",
"Score": "8"
}
},
{
"body": "<p>All the points in Vogel612's answer should be taken into consideration. Your failure to close resources is your biggest issue.</p>\n\n<p>My main aim with this answer is to show how how this <em>should</em> now be done with Java 8.</p>\n\n<p>Your current method uses very traditional Java loops and conditions. Here is how the code should look with the Java 8 APIs:</p>\n\n<pre><code>public static void main(final String[] args) {\n final Path file = Paths.get(\"C:/text.txt\");\n try (final Stream<String> lines = Files.lines(file)) {\n final Map<Character, Integer> count = lines.\n flatMap(line -> IntStream.range(0, line.length()).mapToObj(line::charAt)).\n filter(Character::isLetter).\n map(Character::toLowerCase).\n collect(TreeMap::new, (m, c) -> m.merge(c, 1, Integer::sum), Map::putAll);\n count.forEach((letter, c) -> System.out.println(letter + \": \" + c));\n } catch (IOException e) {\n System.out.println(\"Failed to read file.\");\n e.printStackTrace(System.out);\n }\n}\n</code></pre>\n\n<p>This code has exactly the same function as your code but is significantly shorter - it leverages Java 8's new <code>Stream</code> API combined with the all new lambdas.</p>\n\n<p>The code uses <code>Files.lines</code> to get a <code>Stream<String></code> consisting of each line. It then uses <code>flatMap</code> to turn that into a <code>Stream<Character></code> by \"flattening\" a <code>Stream<Stream<Character>></code> which we get by creating an <code>IntStream</code> of <code>[0, line.length())</code> and calling <code>line.charAt</code> for each element of the <code>IntStream</code>. The <code>char</code> is then autoboxed to a <code>Character</code>.</p>\n\n<p>We use the <code>filter</code> method of <code>Stream</code> to strip out things that aren't letters.</p>\n\n<p>Now we use the new <code>Map.merge</code> method with takes a key and a value and in addition a lambda that takes two values. If the key does not exist in the map then it is simply added with the given value. If it does exist in the map then the lambda is called with the existing value and the new value; the value returned from the lambda is then put into the map.</p>\n\n<p>We use the <code>collect</code> method of the <code>Stream<Character></code> to \"reduce\" the stream to a mutable collection, in this case a <code>TreeMap</code>.</p>\n\n<p>Finally we use the new <code>forEach</code> method on <code>Map</code> to print out the contents of the map.</p>\n\n<p>As a demonstration of the power of Java 8, in order to sort the output by count rather than by the character (as you had in your post), simply change the print to:</p>\n\n<pre><code>count.entrySet().stream().\n sorted((l, r) -> l.getValue().compareTo(r.getValue())).\n forEach(e -> System.out.println(e.getKey() + \": \" + e.getValue()));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T09:27:40.947",
"Id": "83727",
"Score": "0",
"body": "This is really a nice rewrite to Java 8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-20T08:42:31.123",
"Id": "265973",
"Score": "0",
"body": "Something I just noticed... what's the reason you're flatmapping over an IntStream that calls into charAt instead of using `Arrays.stream` onto toCharArray? `flatMap(line -> Arrays.stream(line.toCharArray())` should work just as well and is IMO cleaner..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-20T09:11:51.153",
"Id": "265975",
"Score": "1",
"body": "@Vogel612 you may have a point - I remember having lots of issues with `char` and `int` and boxing/unboxing; the only downside I can see from using `toCharArray` is that it creates a new `char[]` - but creating the new `InterStream` might well be even worse. Another issue I spotted, now that I'm looking at it, is that in the last part `(l, r) -> l.getValue().compareTo(r.getValue())` could simply be [`Map.Entry.comparingByValue()`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html#comparingByValue--)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-06T19:43:31.797",
"Id": "356694",
"Score": "0",
"body": "`but is significantly shorter` I see that you consider this to be an advantage, but I do not believe shorter code is always _better_ . To me it is usually more difficult to read, to runtime it does not matter at all anyway.. So where is the advantage?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-06T21:12:14.840",
"Id": "356710",
"Score": "0",
"body": "@KorayTugay I believe it is only more difficult to use because you are not used to reading it. I think the above Java 8 code is more terse and expresses semantic meaning much better - you read what the _intent_ of the code is rather than all the boilerplate around the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-20T06:25:40.483",
"Id": "364410",
"Score": "0",
"body": "Instead of `charAt`, real Java 8 programs should use `String.codePoints`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-20T07:15:39.463",
"Id": "364418",
"Score": "0",
"body": "@RolandIllig not neccessary in this case. It's not a question is always looking at code points, it's a question of what you want to do with the data. If you then need to convert to a `Character` in, order to check `isLetter` for example, then you are better off with a `char`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-21T04:59:26.977",
"Id": "364658",
"Score": "0",
"body": "`isLetter` has a variant taking an `int`, because the `char` type can only represent a small subset of all possible Unicode code points. To support code points outside the Basic Multilingual Plane, the code should operate on code points, not on `uint16`."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:28:48.223",
"Id": "47722",
"ParentId": "47704",
"Score": "8"
}
},
{
"body": "<blockquote>\n<pre><code> TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();\n</code></pre>\n</blockquote>\n\n<p>In Java, we prefer types to be interfaces rather than implementations. In this case, the interface could be <code>Map</code>, but </p>\n\n<pre><code> SortedMap<Character, Integer> characterCounts = new TreeMap<>();\n</code></pre>\n\n<p>I think that you actually want <code>SortedMap</code>, as otherwise there is no need to use a <code>TreeMap</code>. You could even use <code>NavigableMap</code>, although you don't seem to be using that functionality. </p>\n\n<p>In modern Java versions, you don't need to specify the types in <code><></code> twice. The compiler will match the second to the first automatically. </p>\n\n<p>I changed the name to <code>characterCounts</code>, as that better describes the data that it holds. </p>\n\n<blockquote>\n<pre><code> if(!Character.isLetter(c)){\n continue;\n }\n else if (hashMap.containsKey(c)) {\n hashMap.put(c, hashMap.get(c) + 1);\n } else {\n hashMap.put(c, 1);\n }\n</code></pre>\n</blockquote>\n\n<p>Since you continue in the first clause, you don't need an <code>else</code>. You can instead say something like </p>\n\n<pre><code> if (!Character.isLetter(c)) {\n continue;\n }\n\n Integer count = characterCounts.get(c);\n if (count == null) {\n count = 0;\n }\n\n count++;\n characterCounts.put(c, count);\n</code></pre>\n\n<p>Now we don't have two <code>put</code> statements. And we don't call <code>contains</code> explicitly just to call <code>get</code>, which calls <code>contains</code> implicitly. We simply treat a null count as if it were zero. The rest of our logic is the same in both paths. </p>\n\n<p>I find the explicit increment easier to read than adding one. </p>\n\n<p>I added some whitespace for readability. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T15:50:47.720",
"Id": "210694",
"ParentId": "47704",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "47707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T10:28:02.340",
"Id": "47704",
"Score": "15",
"Tags": [
"java"
],
"Title": "Counting characters in a text file"
} | 47704 |
<p>Is this an efficient way to handle page requests in MVC?</p>
<p>index.php:</p>
<pre><code>require 'Classes/Autoloader.php';
Autoloader::start();
Session::start();
new Bootstrap();
</code></pre>
<p>Bootstrap.php</p>
<pre><code>class Bootstrap {
private $controller = null,
$action = null,
$args = null;
public function __construct() {
$this->manage_url();
if($this->page_exist()){
$this->request();
} else {
$error = new ErrorController();
$error->error404();
}
}
private function request(){
$controller = new $this->controller();
if(!$this->args){ $controller->{$this->action}(); }
else{
$count_args = count($this->args);
switch ($count_args) {
case 1:
$controller->{$this->action}($this->args[0]);
break;
case 2:
$controller->{$this->action}($this->args[0], $this->args[1]);
break;
case 3:
$controller->{$this->action}($this->args[0], $this->args[1], $this->args[2]);
break;
case 4:
$controller->{$this->action}($this->args[0], $this->args[1], $this->args[2], $this->args[3]);
break;
}
}
}
/**
* Get controller, action and parametes
*/
private function manage_url(){
$uri = $_SERVER['REQUEST_URI'];
$uri = trim($uri, '/');
$this->remove_query_or_hash($uri);
$exploded_uri = explode('/', $uri);
$this->controller = Util::istruthy_or($exploded_uri[0], 'Main').'Controller';
$this->action = Util::istruthy_or($exploded_uri[1], 'index');
$this->args = array_slice($exploded_uri, 2);
}
private function remove_query_or_hash(&$uri){
$query = strpos($uri, '?');
$hash = strpos($uri, '#');
if($query!==FALSE||$hash!==FALSE){
$idx = $query < $hash ? $hash : $query;
$uri = substr($uri, 0, $idx);
}
}
private function page_exist(){
$controller = class_exists($this->controller);
$method = method_exists($this->controller, $this->action);
if(!$controller||!$method){
return FALSE;
}
return TRUE;
}
}
</code></pre>
<p>Util istruthy_or():</p>
<pre><code>public static function istruthy_or(&$var, $val = NULL){
return isset($val) ? ($var ? $var : $val) : ($var ? $var : NULL);
}
</code></pre>
| [] | [
{
"body": "<p>MVC is a concept that stems from good OOP practices. It's about seperating your application to three different parts: <strong>Input<sub>Controllers</sub>, Processing<sub>Model</sub> and Output<sub>View</sub></strong>.</p>\n\n<p>What you are describing is the bootstrap page, which, at least from my perspective <strong>should not be a class</strong>.</p>\n\n<p>Here's my approach to this:</p>\n\n<h3>index.php</h3>\n\n<pre><code><?php\nrequire \"../bootstrap.php\";\n</code></pre>\n\n<h3>bootstrap.php</h3>\n\n<pre><code><?php\n//Pseudo-code ahead:\nrequire autoloader;\nstart router;\nadd router rules (either from file, or actually in the code)\n$route = $router->route($uri); //$route is a Route object which tells us \n //what controller to use, what are the parameters, etc.\n$controllerClass = $route->getControllerClass();\n$controllerAction = $route->getControllerAction();\n$controller = new $controllerClass($request); \n//Where $request is the Request object, containing the URI, GET, POST, COOKIES, etc.\n$viewParams = call_user_func_array([$controller, $controllerAction], $route->getParameters());\n//$route->getParameters() is an array of parameters from the route.\n//call_user_func_array will transform that array into actual arguments to pass in.\n\n$viewClass = $viewParams[\"class\"];\n$viewAction = $viewParams[\"action\"];\n$view = new $viewClass($request);\necho $view->render($viewParams);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T16:39:22.767",
"Id": "51843",
"ParentId": "47706",
"Score": "3"
}
},
{
"body": "<p>Your approach is great as long as you are the only one working with this code and all your uri ideally resolve to <code>/controller/action/args</code>. Problems will start when your client asks for a friendly uri like <code>/my-section/my-page</code> or someone else will have to maintain your code.</p>\n\n<p>To address the problem with uri you might need custom routing (rules for non-standard uri routing that apply <em>before</em> the standard <code>/controller/action/args</code>). For examples of such rules you should check how it's done in different frameworks and find the one that fits your liking. Here's how it's done in <a href=\"http://ellislab.com/codeigniter/user-guide/general/routing.html\" rel=\"nofollow\">CodeIgniter</a>.</p>\n\n<p>Second issue is a bit less clear. By looking at your code:</p>\n\n<pre><code>Autoloader::start();\nSession::start();\nnew Bootstrap();\n</code></pre>\n\n<p>One will never realise where exactly is the job gets done. You could do it a lot clearer by chaning, for example, to this:</p>\n\n<pre><code>$bootstrap = new Bootstrap();\n$bootstrap->process_request($_SERVER['REQUEST_URI']);\n</code></pre>\n\n<p>But that's not the only issue. Next you call <code>manage_url()</code>, which does not get any paramteter and therefore is untestable. You could make it testable by calling it with a parameter <code>manage_url($uri)</code> - this way you can call it in a test with different uris and see how it handles it's job. Then again, what is it's job? It does multiple things, thats why such a non-telling name.</p>\n\n<p>You could make your code a lot more clear for future developers (including yourself) by making each function do one task. For example:</p>\n\n<pre><code>public function process_request($uri)\n{\n\n // first you want a function to clear uri from unwanted parts\n $uri = $this->prepare_uri($uri); \n\n // then you want to apply custom routing I described earlier\n if (!$this->apply_custom_routing($uri)) {\n\n // if none matched, apply default routing of your manage_url()'s last part\n if (!$this->apply_default_routing($uri)) {\n\n // none valid routing found - 404\n $this->apply_error_routing();\n }\n }\n\n // now you know request details and can proceed\n $this->call_controller();\n\n}\n</code></pre>\n\n<p>Note that it's now pretty clear what each function does and each of them is at least somewhat testable, because their dependencies are clear.</p>\n\n<p>Also note, that you don't need that ugly <code>switch</code> statement in <code>request()</code>. There is a function for that type of situations (when you don't know amount of arguments beforehand):</p>\n\n<pre><code>call_user_func_array(array($this->controller, $this->action), $this->args);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T18:21:27.223",
"Id": "51850",
"ParentId": "47706",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "51850",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T11:06:08.030",
"Id": "47706",
"Score": "3",
"Tags": [
"php",
"mvc"
],
"Title": "Handling page requests in MVC"
} | 47706 |
<p>I have this common design in my application:</p>
<pre><code>public class MyListener1{
MyTask1 task1;
MyTask2 task2;
public class MyListener1{
public MyListener1(){
task1 = new MyTask1(this);
task2 = new MyTask2(this);
task1.execute();
task2.execute();
}
public void onResult1(String result){
//extract result
}
public void onResult2(String result){
//extract result
}
}
public class MyTask1 extends AsyncTask{
MyListener1 myListener1;
public MyTask1(MyListener1 myListener1){
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult1(result);
}
}
public class MyTask2 extends AsyncTask{
MyListener1 myListener1;
public MyTask2(MyListener1 myListener1){
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult2(result);
}
}
</code></pre>
<p>The <code>AsyncTask</code> is a library class that execute the code in a method <code>doInBackground()</code> in another thread when calling <code>execute()</code>, and call <code>onResult(String result)</code> when task finished.</p>
<p>Of course, I summarize the code, MyTask1 and MyTask2 have a little bit more code, but I soon realized that they could be factorize on a common task:</p>
<pre><code>public class MyListener1{
MyTask task1;
MyTask task2;
public class MyListener1{
public MyListener1(){
task1 = new MyTask(0,this);
task2 = new MyTask(1,this);
task1.execute();
task2.execute();
}
public void onResult(int taskId, String result){
switch(taskId){
case(0) : //extract result from task 0
case(1) : //extract result from task 1
}
}
public class MyTask extends AsyncTask{
int id;
MyListener1 myListener1;
public MyTask(int id, MyListener1 myListener1){
this.id = id;
this.myListener1 = myListener1;
}
@Override
public void onResult(String result){
myListener1.onResult(id, result);
}
}
</code></pre>
<p>I heard some people telling me to avoid "switch case" to identify a source and prefer to use "polyphormism" instead. In that case, I don't know what they mean.</p>
<p>So here is my question:</p>
<p><strong>Is there a better way to identify the source (the object calling) of a callback method than using an identifier for the caller?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T14:05:48.960",
"Id": "83629",
"Score": "1",
"body": "Something is not quite clear: you say that MyTask1 and MyTask2 have a little bit more code, but then you just merge them in one class. Is the \"little bit more code\" the same for both tasks?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T14:08:27.313",
"Id": "83631",
"Score": "0",
"body": "Something does not feel quite right about the listener referencing the tasks and the listener referencing the tasks. If you could please explain the whole project in more details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T14:12:48.507",
"Id": "83632",
"Score": "0",
"body": "Also, do you really need to share the listeners between both tasks? or could you have a different listener for each task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:01:35.157",
"Id": "83635",
"Score": "0",
"body": "@toto2 Yes, I can extract the code that is not the same between the two task and manage it somewhere else, so that I can merge MyTask1 and MyTask2 into MyTask\n\nAbout explaining it, Listener1 is actually in my project a ctrl for an Activity (it's an Android project). This ctrl does some HTTP request to a JSON API. The request are manage by the tasks, and call back the ctrl when they get the response.\nFinally, some ctrl need to do several tasks (remote call) so one \"listener\" can be the same for several task (that why I choose this example)."
}
] | [
{
"body": "<p>You could directly use the source object. This is commonly used in Swing when the same <code>ActionListener</code> has been added to more than one button. When the listener's <code>actionPerformed</code> method is invoked, the <code>EventObject</code> object that is passed featrues a <code>getSource</code> method that retrieves the source of the event. Then, you compare that source with button objects you have previously saved as fields in your class, and eventually perform a different action based on the equality comparison result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:46:47.527",
"Id": "83654",
"Score": "0",
"body": "Is there a reason why reference comparison id better than id comparison?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:34:58.033",
"Id": "83755",
"Score": "0",
"body": "@Pierre-Jean reference comparison is just another form of identifier comparison, except the identifier is managed by the virtual machine for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T12:48:23.980",
"Id": "47712",
"ParentId": "47709",
"Score": "4"
}
},
{
"body": "<p>A listener and callback mechanism is a common pattern in many places in Java.</p>\n\n<p>The logical place to look for examples is in the Swing API. Will get back to that in a second, but, there are two items that are useful first:</p>\n\n<ol>\n<li><p>Instead of using an <code>int</code> value to track the source of the event/Task, you should use the task itself.</p>\n\n<pre><code> public void onResult(String result){\n myListener1.onResult(this, result);\n }\n</code></pre></li>\n<li><p>The Listener itself should implement an interface, something like: <code>TaskResultListener</code>:</p>\n\n<pre><code> public interface TaskResultListener {\n public onResult(Task task, String result);\n }\n</code></pre>\n\n<p>and the constructor for the Task should take an instance of a <code>TaskResultListener</code> instead of a <code>MyListener1</code></p></li>\n</ol>\n\n<p>For examples of how this is used, consider the <code>ActionListener</code> interface and usage in Swing:</p>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionListener.html\">ActionListener</a></li>\n<li>Example implementation of ActionListener: <a href=\"http://docs.oracle.com/javase/8/docs/api/javax/swing/text/TextAction.html\">TextAction</a></li>\n<li>Example component that calls-back to an ActionListener: <a href=\"http://docs.oracle.com/javase/8/docs/api/javax/swing/AbstractButton.html#addActionListener-java.awt.event.ActionListener-\">JButton / AbstractButton</a></li>\n</ul>\n\n<p>In the Swing API, it is common to have support for multiple listeners. You have just one. That is OK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:45:32.497",
"Id": "83653",
"Score": "0",
"body": "I agree for the interface, but why comparing reference is \"proper\" than comparing id?\nIn other word, why `if (task==myTask1){//do something} else if (task==myTask2){//do something else}` is better than `if (id == myTask1.ID) {//do something} else if (id == myTask2.ID) {//do something else}` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:47:11.290",
"Id": "83655",
"Score": "1",
"body": "@Pierre-Jean - because you could have duplicate ID's, you only use the ID's to differentiate between tasks, and there is an established precedent/best practice to do it another way (using the class instance)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T12:48:48.750",
"Id": "47713",
"ParentId": "47709",
"Score": "6"
}
},
{
"body": "<p>Despite your explanation in the comments above, it is still not quite clear what you are really doing.</p>\n\n<p>I believe I understand that Listener1 will be used by more than one Activity. However, it would be helpful to know what Listener1 needs to access in each Activity, or if it needs to access anything at all.</p>\n\n<p>An option would be to not have a Listener1 at all. We could just define the AsyncTask's in the Activity and let them do their job. For example, create JsonFetchAgeAsyncTask and JsonFetchGenderAsyncTask and just override their onResult callbacks so that each one can modify something in the Activity.</p>\n\n<p>I somewhat understand that you do this in different Activity's and you want to re-use your AsyncTask's subclasses. You could instead define your AsyncTask's within an abstract parent Activity class and then make children Activity's. Those children Activity's would share the same AsyncTask's.</p>\n\n<p>Another option would be to use composition, which is actually what you are doing by sharing Listener1 between different Activity's. But it seems a bit off: I would at least change the name (not Listener) and I would define Task1 and Task2 within that class.</p>\n\n<p>I would need more details to give you better advice. More specifically, I'm not sure how Listener1 is related to the containing Activity's.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:34:02.720",
"Id": "47718",
"ParentId": "47709",
"Score": "2"
}
},
{
"body": "<p>I prefer your original code. It avoids the need for the switch by using two different classes, which (assuming they and their callback functions are well documented and have good names) is usually clearer and easier to understand.</p>\n\n<p>If you have duplicated code between your MyTask1 and MyTask2 classes, have you considered introducing a new superclass for them?</p>\n\n<p>Or, alternatively, if you're using (or could upgrade to) Java 8, how about passing in a lambda function argument to the task object, if the callback is the only difference between them?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:10:20.220",
"Id": "83645",
"Score": "1",
"body": "Android forked a long time ago from Java. I think they are still stuck at something which is close to Java 6 and there is no plan to bring Android closer to Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T04:01:20.567",
"Id": "83707",
"Score": "0",
"body": "Didn't realise Android was involved... yes, I should have guessed based on the class names, but it wasn't actually mentioned anywhere in the question. (Although what you say isn't entirely true -- a recent update added support for most of the new features of Java 7 -- I do suspect it will be a while before Android gets Java 8 features supported)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T22:58:51.210",
"Id": "83850",
"Score": "0",
"body": "Thanks. I was not aware of it, but Android 4.4 does support Java 7. I had looked into this a long time ago and I was left with the impression that they would not even try to keep Android close to Java."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T16:31:07.690",
"Id": "47720",
"ParentId": "47709",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "47713",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T11:32:10.777",
"Id": "47709",
"Score": "7",
"Tags": [
"java",
"callback"
],
"Title": "Identify Java Callback"
} | 47709 |
<p>Here's my solution for <a href="http://projecteuler.net/problem=30" rel="nofollow">Project Euler Problem 30</a>. Any optimizations in time, space, or style would be greatly appreciated.</p>
<pre><code>from timeit import default_timer as timer
def digit_powers(exponent):
def power(k):
return int(k) ** exponent
if exponent <= 1:
return "The exponent must be at least 2."
else:
total_sum = 0
upper_bound = (exponent + 1) * (9 ** exponent)
for number in range(10, upper_bound + 1):
digits = [x for x in str(number)]
if number == sum(map(power, digits)):
total_sum += number
return total_sum
start = timer()
ans = digit_powers(5)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [] | [
{
"body": "<p>In looking at your code, it seems well written and solves the problem in a straight forward manner. The one thing I would do is to remove the else after your argument check and remove a level of indent. That just helps to keep things flat... Flat is better than nested.</p>\n\n<p>Now onto optimization and potentially making it more complex than it needs to be in order to make it faster. In these problems it seems like a reasonable thing to do even though....Simple is better than complex.</p>\n\n<p>Here are a couple things I looked at as potential issues:</p>\n\n<ol>\n<li>When doing the <code>sum(map(power, digits))</code>, you are calculating the power of each digit many times. If this was a much more expensive calculation then only calculating 1 time is even more important.</li>\n<li>In this problem there is a conversion from int->str->int. If you can breakdown the digits without converting them it saves some time. It seems like a good thing to know how to do just in case your ever trying a different language where skipping those transitions may be even faster.</li>\n</ol>\n\n<p>To address these, I did two things:</p>\n\n<ol>\n<li>Pre-calculate 1-9 powers and store the results in a dictionary so they don't get recalculated (Memoization). It lets me look them up very quickly without calculating each time.</li>\n<li>Separate the digits using math.log10 as to avoid the int->str->int conversion.</li>\n</ol>\n\n<p>The first item is fairly straight forward, calculating for each digit:</p>\n\n<pre><code>powers = {}\nfor a in range(10):\n powers[a] = a ** exponent\n</code></pre>\n\n<p>The second part is a little trickier, what it does is uses math.log10 which gives a count of the digits, then it does a mod 10 to get the right most digit, looks up that power to add to the total and then finally does integer division to divide by 10 effectively moving the decimal place 1 position to the left (dropping the right most digit we just dealt with). This is probably a little different between Python 2/3 due to changes in int/float division. It is basically doing what you are using <code>[x for x in str(number)]</code> to do but without converting to string and adding the power of 5 dict lookup as it goes along:</p>\n\n<pre><code>savei = i\nfor _ in range(int(math.log10(i)) + 1):\n digit = i % 10\n total += powers[digit]\n i //= 10\n</code></pre>\n\n<p>Applying those changes to the code make it about twice as fast. Here is what I end up with for the function:</p>\n\n<pre><code>import math\n\ndef digit_powers(exponent):\n if exponent <= 1:\n return \"The exponent must be at least 2.\"\n\n powers = {}\n answer = 0\n # Get the powers\n for a in range(10):\n powers[a] = a ** exponent\n\n limit = (exponent + 1) * (9 ** exponent)\n\n # Search for them\n for i in range(10, limit):\n savei = i\n total = 0\n\n for _ in range(int(math.log10(i)) + 1):\n digit = i % 10\n total += powers[digit]\n i //= 10\n\n if (total == savei):\n answer += total\n\n return answer\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:27:48.267",
"Id": "47721",
"ParentId": "47714",
"Score": "6"
}
},
{
"body": "<p>You can make this much faster by precalculating the powers of each digit. Also note that the order of processing for digits doesn't matter so this code starts with the ones place. Here's what I came up with, and on my machine it ran 4x faster than the original code:</p>\n\n<pre><code>def digit_powers(exponent): \n if exponent <= 1:\n return \"The exponent must be at least 2.\"\n powdigits = [i**exponent for i in range(10)] \n total_sum = 0\n upper_bound = (exponent + 1) * powdigits[9]\n for number in range(10, upper_bound + 1):\n partialsum = tempnum = number\n while tempnum:\n partialsum -= powdigits[tempnum%10]\n tempnum /= 10\n if not partialsum:\n total_sum += number\n return total_sum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:06:17.970",
"Id": "83674",
"Score": "0",
"body": "I like how you avoided the math import... for some reason didn't think of doing that. Also using a comprehension for the powdigits is nice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:51:15.317",
"Id": "47725",
"ParentId": "47714",
"Score": "5"
}
},
{
"body": "<p>I doubt you will see my answer. Hopefully it can help someone else in the future. First I want to compare the answers above speedwise. As a tease I will include my own attempt</p>\n\n<h2>Comparison</h2>\n\n<pre><code>-------------------------------\n| Name | Time |\n| Joshua (OP) | 2000 ms |\n| clutton | 500 ms |\n| Edward | 300 ms |\n| Nebuchadnezzar | 20 ms |\n-------------------------------\n</code></pre>\n\n<p>So the answers above give a rough 4x-5x speed improvement. So how can we increase this to a 100x speed improvement? Well naively you check every number up to the limit \\$ 5*9^5 \\$. This means your code does <strong>443839</strong> checks, and for every check it has to compute the digit sum. In order to get a significant speed improvement we need a new algorithm.</p>\n\n<h2>New algorithm</h2>\n\n<p>One key observation is to note that once we have checked \\$0145\\$ we do not need to check \\$1450\\$ or any other combination of \\$(0, 1, 4, 5)\\$ since they all the the same power sum </p>\n\n<p>$$\nP_5[(0, 1, 4, 5)] = 0^5 + 1^5 + 4^5 + 5^5 = 4150 \n$$</p>\n\n<p>To check whether if some permutation of \\$(0, 1, 4, 5)\\$ is equal to it's power sum all we need to do is to sort the digits in the power sum and compare (assuming the tuple is already sorted).</p>\n\n<h2>Implementation</h2>\n\n<p>One way to find the unique tuples is with <a href=\"https://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement\" rel=\"nofollow\"><code>combinations_with_replacement()</code></a> from the <a href=\"https://docs.python.org/2.7/library/itertools.html\" rel=\"nofollow\">itertools</a> libary.</p>\n\n<p>The code uses two checks to further decrease the number of combinations to check. Naively with <code>combinations_with_replacements()</code> there are a total of <strong>5005</strong> numbers to check. The check </p>\n\n<pre><code>if power_sum % 10 in perm:\n</code></pre>\n\n<p>is pretty intuitively. It checks whether the last number in the <code>power_sum</code> is in the permutations. A necessity if some permutation of perm is equal to the digit power sum. This reduces the number to check to <strong>730</strong>. The final check is </p>\n\n<pre><code>if len_power > len_perm: return False\n</code></pre>\n\n<p>This cuts the number needed to check down to <strong>591</strong>. Not this is not a huge improvement, however it is a very cheap test to perform and it is more useful for higher powers. I have attached a small table below</p>\n\n<pre><code> P S Sum # 0 # 1 # 2 time\n--------------------------------------------------------------\n 3 4 1301 220 60 50 0.8685 ms\n 4 3 19316 715 224 165 5.0320 ms\n 5 5 248860 2002 730 591 10.7200 ms \n 6 1 548834 5005 1974 1603 32.0400 ms\n 7 4 25679675 11440 5040 4220 77.1300 ms\n 8 3 137949578 24310 12504 10812 136.8000 ms\n 9 4 2066327172 48620 24380 21224 428.4000 ms\n10 1 4679307774 92378 48706 42362 858.0000 ms\n11 8 418030478906 167960 92512 82456 2502.0000 ms\n12 0 0 293930 175452 159471 7021.0000 ms\n</code></pre>\n\n<p><code>P</code> is the power, <code>S</code> is the number of solutions. <code># 0</code> is the total number of permutations to iterate over. <code># 1</code> is the remaining numbers after the first check, and <code># 2</code> is the remaining numbers after the second check.</p>\n\n<h2>Code</h2>\n\n<pre><code>from itertools import combinations_with_replacement as CnR\n\ndef digit_power(power):\n total = -1\n for perm in CnR(xrange(10), power):\n power_sum = sum(i**power for i in perm)\n if power_sum % 10 in perm:\n power_sum_list = map(int, str(power_sum))\n if is_fift_power(power_sum_list, perm, power):\n total += power_sum\n return total\n\n\ndef is_fift_power(power_lst, perm, len_perm):\n len_power = len(power_lst)\n if len_power > len_perm: return False\n power_sort = [0]*(len_perm - len_power) + sorted(power_lst)\n return power_sort == list(perm)\n\n\nif __name__ == '__main__':\n import timeit\n print digit_power(5)\n times = 100\n result = timeit.timeit(\n \"digit_power(5)\", number=times, setup=\"from __main__ import digit_power\")\n print 1000*result/float(times), 'ms'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-18T21:56:17.027",
"Id": "132406",
"ParentId": "47714",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T12:50:10.993",
"Id": "47714",
"Score": "5",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler 30 -- Digit fifth powers"
} | 47714 |
<p>I'm making a game battle system, where there are 2 players.</p>
<ul>
<li>Every player can have multiple units to control, but only one at a time.</li>
<li>Every unit has an <code>int curSpeed</code> variable;</li>
</ul>
<p>I need to have in 2 variables who attacks first (<code>Player f</code>) and who attacks second (<code>Player s</code>), based on the speed of the current controlling unit.</p>
<p>At the moment I have this code:</p>
<ul>
<li><code>player_1</code> and <code>player_2</code> are instances of <code>Player</code> Class</li>
<li><code>current</code>, is a instance of <code>Unit</code> Class, it is the current controlling unit.</li>
</ul>
<pre><code>Player f = null; //Player attacking first
Player s = null; //Player attacking second
//Check the speed of the units, and determine who attack first
f = player_1.current.curSpeed > player_2.current.curSpeed ? player_1 : player_1.current.curSpeed < player_2.current.curSpeed ? player_2 : null;
//if f is null (units have the same speed)
if(f==null){
//Randomize who goes first
System.Random rnd = new System.Random();
int rng = rnd.Next(0,2);
f = rng == 0 ? player_1 : player_2;
s = rng == 0 ? player_2 : player_1;
}else{
s = f.id == player_1.id ? player_2 : player_1;
}
</code></pre>
<p>It is working, but I feel that this is confusing and the 'wrong way' to do it.</p>
<p>I need tips on how I can code this in a better way.</p>
<p><strong>UPDATE:</strong>
<em>New version of the code including all the suggestions can be found <a href="https://codereview.stackexchange.com/questions/47737/initial-starting-player-v2">here</a>.</em></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:50:41.960",
"Id": "83669",
"Score": "0",
"body": "if you want to show the new code, please post another question. you would invalidate the answers if you edit in the changes to this question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:52:18.160",
"Id": "83670",
"Score": "0",
"body": "@Malachi You're right. I'm sorry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:01:57.933",
"Id": "83673",
"Score": "0",
"body": "please do post a link in a comment to the new question though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:17:34.383",
"Id": "83677",
"Score": "0",
"body": "Here is the updated version: http://codereview.stackexchange.com/questions/47737/initial-starting-player-v2"
}
] | [
{
"body": "<p>Your code is indeed confusing, primarily because of the naming:</p>\n\n<p><code>f</code> should be <code>firstPlayer</code>, <code>s</code> should be <code>secondPlayer</code> and <code>curSpeed</code> should be <code>speed</code> or <code>currentSpeed</code> (it depends on whether there are other \"speeds\" to distinguish from).</p>\n\n<p>Another remark: properties are UpperCamelCase so this</p>\n\n<pre><code>player_1.current.curSpeed\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>player_1.Current.Speed\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:34:43.997",
"Id": "47729",
"ParentId": "47723",
"Score": "7"
}
},
{
"body": "<p>I really like this question for its simplicity and depth; getting two variables into a hi/lo state is something you run into all the time. Let's start with the original assignment below...</p>\n\n<pre><code>f = player_1.current.curSpeed > player_2.current.curSpeed ? player_1 : player_1.current.curSpeed < player_2.current.curSpeed ? player_2 : null;\n</code></pre>\n\n<p>It would be nice if you could actually order the players directly, using <a href=\"http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx\" rel=\"nofollow\">overloaded operators</a>, so that this would at least reduce to...</p>\n\n<pre><code>f = player_1 > player_2 ? player_1 : player_2;\n</code></pre>\n\n<p>with the following \"if\" statement being changed to...</p>\n\n<pre><code>if(player_1.current.curSpeed == player_2.current.curSpeed)\n</code></pre>\n\n<p>I'm not sure that the value of rng is going to be what you think it is. You probably simply want to use...</p>\n\n<pre><code>rng = rnd.Next(2);\n</code></pre>\n\n<p>if you're aiming for a value of either 0 or 1 with equal probability. I'd also suggest moving the initial assignment of \"f\" down into the else block, since now you don't need to check if \"f\" is null before doing the random-assign.</p>\n\n<p>You'll want to overload \">\" and \"<\" to compare two player's speed (to rank them correctly), and overload \"==\" to compare two player's IDs. This suggestion may offend some; it is reasonable to insist that if a < b is false, and b < a is false, a == b, and my suggested implementations won't follow that rule. If that is important to you, you could instead write, e.g., a \"faster\" function for your player class that will return a bool -- a.faster(b) == true would mean A is faster than B. In any case, this would be the modified code using operator overloading.</p>\n\n<pre><code>Player f = null; //Player attacking first\nPlayer s = null; //Player attacking second\n\n//Check the speed of the units, and determine who attack first\n\n//if units have the same speed...\nif(player_1.current.curSpeed == player_2.current.curSpeed){\n //Randomize who goes first\n System.Random rnd = new System.Random();\n int rng = rnd.Next(0,2);\n f = rng == 0 ? player_1 : player_2;\n s = rng == 0 ? player_2 : player_1;\n}else{\n f = player_1 > player_2 ? player_1 : player_2;\n s = f == player_1 ? player_2 : player_1;\n}\n</code></pre>\n\n<p>As an afterthought, the \"current.curSpeed\" seems redundant (the current current speed?), and very wordy. I'd suggest either dropping the \"current\" altogether (really think hard about if it's necessary), OR change the \"curSpeed\" to just \"Speed.\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:07:37.683",
"Id": "83659",
"Score": "0",
"body": "I know, i need to revise the naming. Anyway `current` is needed, because it is actually the active `Unit` class instance that the player is controlling, in other words: the players have 3 monsters, but only one of them can be used each round. So i need that variable to calculate wich one attack first, based on their `curSpeed`. (i do have `initialSpeed` and `curSpeed` inside my Unit class to track the initial value and the current value, since it can be changed during the battle)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:19:32.293",
"Id": "83711",
"Score": "0",
"body": "I don't like this solution. Equality operators should make sense for objects they are applied to. They do make sense for `int` value (speed), but they dont for `Player`s. There is no way to tell on what basis is one payer being compared to another (is it id, or score, or hit points, or level, or - would be my last guess - current unit's speed), without digging into implementation details, which is a sign of bad design. Implementing an `IComparer` instead is a better soultion in my opinion (if this kind of comparison is used often enough)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:30:34.260",
"Id": "83733",
"Score": "1",
"body": "If `<` and `==` are used for completely different things, how would you implement `<=`? Or would you just disallow that by not implementing `<=`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:14:42.480",
"Id": "83759",
"Score": "0",
"body": "@NikitaBrizhak First, the equality is clear: two players are equal if and only if their IDs are equal. WRT comparison criteria, I consider that to be encapsulation. If A < B, A goes first. If the rules determining how or why A < B is outside the scope of this code -- that is to say, it's the player's responsibility to determine rank -- then this approach is correct. Implementing [IComparer](http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx) is exactly as wrong (or right) as overloading \"<\", \">\", and \"==\" in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:22:30.820",
"Id": "83762",
"Score": "0",
"body": "@svick You cannot sanely implement <= or >= in these cases, and thus should not implement those operators. My answer addresses this obliquely (\"[...]it is reasonable to insist that if a < b is false, and b < a is false, a == b[...]\"). To reiterate, if this is important to you, you should use a (non-operator) function name off the class, like \"bool actsBefore(Player p)\". The reason I prefer \"<\" in this particular code is that the hi-lo code looks a lot more like the reusable generic case when normal comparison operators are used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:57:51.433",
"Id": "83882",
"Score": "0",
"body": "@TravisSnoozy, it is not exactly the same. Equlaity operations (and `IComparable` interface) imply an existance of some obvious criteria by which you can compare two instances (take `DateTime` as an example of such object). While `IComparer` is there, so you can make the comparision using different criteria or when there is no obvious way to compare two objects. It both prevents misusage errors (when you want to compare by ID, but you accidently compare by speed, because you forgot which way it is) and improves readability (`CurrentSpeedComparer.Compare(....)` leaves no questions, unlike `<`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:22:50.890",
"Id": "83992",
"Score": "0",
"body": "@NikitaBrizhak Then I humbly submit that you have your proposal backwards: [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx) should be used because it \"Compares the current instance with another object of the same type and returns an integer that indicates [...] the sort order [...].\" [IComparer](http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx) \"Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other,\" which is literally the same as how \"<\", \">\", and \"==\" overloads usually work."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:34:52.427",
"Id": "47730",
"ParentId": "47723",
"Score": "2"
}
},
{
"body": "<p>The way you're using <code>Random</code> is wrong. Instead of creating a new instance of <code>Random</code> every time you need a new random number, you should create a single instance of <code>Random</code>, store it, and then repeatedly call <code>Next()</code> on that single instance.</p>\n\n<p>The reason for this is that when you create <code>Random</code> using the default constructor, it uses the current time as its seed. But the time it uses has relatively low resolution, so when you create two instances of <code>Random</code> too close to each other, you're going to get the same result.</p>\n\n<p>To make this more concrete, try the following code:</p>\n\n<pre><code>while (true)\n{\n var random = new Random();\n Console.Write(random.Next(0, 2));\n Console.Write(\" \");\n Thread.Sleep(1);\n}\n</code></pre>\n\n<p>For me, the output is something like:</p>\n\n<blockquote>\n <p>1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0</p>\n</blockquote>\n\n<p>As you can see, this doesn't look very random, with long runs of the same number. (If you remove the sleep, each run is even longer.)</p>\n\n<p>Compare it with this code:</p>\n\n<pre><code>var random = new Random();\n\nwhile (true)\n{\n Console.Write(random.Next(0, 2));\n Console.Write(\" \");\n Thread.Sleep(1);\n}\n</code></pre>\n\n<p>Its output:</p>\n\n<blockquote>\n <p>0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 0 0 1 1 1 1 0 1 1 1 1 0 1 0 1 0 0\n 1 1 1 1 0 1 0 0 1 1 1 1 0 1 0 1 1 1 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 0 1 0 1 1 1 1\n 1 1 1 1 1 0 0 1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 1 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 0 1\n 1 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 1 1 1 1 1 0 1 1 1 1\n 0 1 0 0 0 1 0 1 1 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 0 0 0 0 1 0 1 0 1 1 0 1 0 0 0 0</p>\n</blockquote>\n\n<p>Now this looks much more random. And this time, removing the sleep won't change the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:56:19.820",
"Id": "83738",
"Score": "1",
"body": "I know that, anyway it is not my case, because this function it is not inside a loop. It is not called very often in time so i wont get the same result. Anyway i have moved the random instance outside the method, just to be sure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:25:24.343",
"Id": "47775",
"ParentId": "47723",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47729",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T17:49:31.423",
"Id": "47723",
"Score": "6",
"Tags": [
"c#",
"game",
"random"
],
"Title": "Initial starting player"
} | 47723 |
<p>I am fairly new to Python and programming in general so I hope the code in this post is not too messy. I have the following code which I use for taking images from an IP security camera:</p>
<pre><code>def Camera(timecount, cam_name, stream_url, username, password, work_dir, x):
x = x
work_dir = work_dir
h = httplib.HTTP(stream_url)
h.putrequest('GET', '/videostream.cgi')
h.putheader('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (username, password))[:-1])
h.endheaders()
errcode, errmsg, headers = h.getreply()
stream_file = h.getfile()
start = time.time()
end = start + timecount
while time.time() <= end:
if not os.path.isfile("/tmp/sec.lck"):
sys.exit()
x += 1
now = datetime.datetime.now()
dte = str(now.day) + "-" + str(now.month) + "-" + str(now.year)
dte1 = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + "." + str(now.microsecond)
cname = "Cam#: " + cam_name
dnow = """Date: %s """ % dte
dnow1 = """Time: %s""" % dte1
source_name = stream_file.readline() # '--ipcamera'
content_type = stream_file.readline() # 'Content-Type: image/jpeg'
content_length = stream_file.readline() # 'Content-Length: 19565'
b1 = b2 = b''
while True:
b1 = stream_file.read(1)
while b1 != chr(0xff):
b1 = stream_file.read(1)
b2 = stream_file.read(1)
if b2 == chr(0xd8):
break
# pull the jpeg data
framesize = int(content_length[16:])
jpeg_stripped = b''.join((b1, b2, stream_file.read(framesize - 2)))
# throw away the remaining stream data. Sorry I have no idea what it is
junk_for_now = stream_file.readline()
image_as_file = io.BytesIO(jpeg_stripped)
image_as_pil = Image.open(image_as_file)
draw = ImageDraw.Draw(image_as_pil)
draw.text((0, 0), cname, fill="white")
draw.text((0, 10), dnow, fill="white")
draw.text((0, 20), dnow1, fill="white")
img_name = cam_name + "-" + tod + "-" + str('%010d' % x) + ".jpg"
img_path = os.path.join(work_dir, img_name)
image_as_pil.save(img_path)
</code></pre>
<p>With it I run the code twice (2 separate threads) with the following code:</p>
<pre><code>def main():
parser = SafeConfigParser()
# Open the file with the settings
with codecs.open('Settings/settings.ini', 'r', encoding='utf-8') as f:
parser.readfp(f)
procs = list()
for cam_name in parser.sections():
cam_name = cam_name
stream_url = parser.get(cam_name, 'stream_url')
username = parser.get(cam_name, 'username')
password = parser.get(cam_name, 'password')
work_dir = parser.get(cam_name, 'work_dir') + tod + "/"
x = sum(1 for f in os.listdir(work_dir) if f.startswith(cam_name) and os.path.isfile(os.path.join(work_dir, f)))
for i in range(1):
q = multiprocessing.Process(target=Camera, args=(timecount, cam_name, stream_url, username, password, work_dir, x,))
procs.append(q)
q.start()
for p in procs:
p.join()
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>I am currently using the following to start and stop the script:</p>
<p>I added this just after the (<code>while time.time() <= end:</code>) in the camera thread / function:</p>
<pre><code>if not os.path.isfile("/tmp/sec.lck"):
sys.exit()
</code></pre>
<p>and changed the "<strong>main</strong>" function from just main() to the following:</p>
<pre><code>if __name__ == "__main__":
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
open('/tmp/sec.lck', 'w').close()
main()
elif 'stop' == sys.argv[1]:
os.remove("/tmp/sec.lck")
print "Stopping SecCam"
elif 'restart' == sys.argv[1]:
os.remove("/tmp/sec.lck")
time.sleep(1)
open('/tmp/sec.lck', 'w').close()
main()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
</code></pre>
<p>This appears to be working it checks for the sec.lck file if it is not there it exits.</p>
<p>Can this program be improved further?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:51:13.047",
"Id": "83657",
"Score": "0",
"body": "If you do not have the daemon code working then it is not yet ready for review. Other parts of your code may in fact be working, but, at this point, the overall question is off-topic because it is asking for help to write new code/fix broken code. When your code works as designed, bring it back here for review... Please see our [help/on-topic] for more details."
}
] | [
{
"body": "<p>These statements are pointless, you can safely remove them:</p>\n\n<blockquote>\n<pre><code>x = x\nwork_dir = work_dir\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The second statement is pointless, you can safely remove it:</p>\n\n<blockquote>\n<pre><code> sys.exit(2)\n sys.exit(0)\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The string <code>\"/tmp/sec.lck\"</code> appears in many places in the file.\nIt would be better to put it in a global variable at the top, for example:</p>\n\n<pre><code>LOCKFILE_PATH = \"/tmp/sec.lck\"\n</code></pre>\n\n<hr>\n\n<p>This is very tedious:</p>\n\n<blockquote>\n<pre><code> dte = str(now.day) + \"-\" + str(now.month) + \"-\" + str(now.year)\n dte1 = str(now.hour) + \":\" + str(now.minute) + \":\" + str(now.second) + \".\" + str(now.microsecond)\n</code></pre>\n</blockquote>\n\n<p>You could write it simpler using the <code>strftime</code> method:</p>\n\n<pre><code>datestr = now.strftime('%d-%m-%Y')\ntimestr = now.strftime('%H:%M:%S')\n</code></pre>\n\n<p>The variable names <code>dte</code> and <code>dte1</code> were poor,\nnot describing what they are, so I tried to give them more meaningful names.</p>\n\n<hr>\n\n<p>It would be better to not use <code>sys.exit</code> inside method calls.\nThis kind of control is best to keep at a central point,\nfor example in the main method,\nwhere you have the other condition checks that may end with <code>sys.exit</code>.</p>\n\n<hr>\n\n<p>It would be better to move the entire content of the <code>if __name__ == \"__main__\":</code> block to a method called <code>main</code> like this:</p>\n\n<pre><code>def main():\n # ... (all the code you previously had in the `if`)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-14T11:02:40.340",
"Id": "73599",
"ParentId": "47726",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:14:54.333",
"Id": "47726",
"Score": "3",
"Tags": [
"python",
"beginner",
"linux",
"image",
"networking"
],
"Title": "Script for obtaining images from an IP security camera"
} | 47726 |
<p>Does my code look secure right now? I know that I still have the password hashing and so forth, but what about SQL injections? Do I have any? Are there any other security issues?</p>
<pre><code><?php
$con=mysqli_connect("localhost","root","xxx","s");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $con->real_escape_string($_POST['name']);
$username = $con->real_escape_string($_POST['username']);
$email = $con->real_escape_string($_POST['email']);
$password1 = $con->real_escape_string($_POST['pass1']);
$password2 = $con->real_escape_string($_POST['pass2']);
if (empty($name) || empty($username) || empty($email) || empty($password1) || empty($password2))
{
echo "Complete all fields";
// you can stop it here instead of putting the curly brace ALL the way at the bottom :)
return;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
}
if (strlen($password1) <= 6)
{
echo $passlength = "Password must be at least 6 characters long";
}
// Password numbers
if (!preg_match("#[0-9]+#", $password1))
{
echo $passnum = "Password must include at least one number!";
}
if (!preg_match("#[a-zA-Z]+#", $password1))
{
echo $passletter = "Password must include at least one letter!";
}
if ($password1 <> $password2)
{
echo $passmatch = "Passwords don't match";
}
if(!(isset($emailvalid) || isset($passlength) || isset($passnum) || isset($passletter) || isset($passmatch))) {
mysqli_query($con,"INSERT INTO pass (Name,Username,Email,Password) VALUES ('$name','$username','$email','$password1')");
}
mysqli_close($con);
?>
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Consider parameterized queries over building a query string.</li>\n<li>If you really want to use encoding, do the encoding directly before passing it to mysql</li>\n<li>Factor out the password strength rules into a separate function. This function could output an array of violations.</li>\n<li>Don't mix logic and IO.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:01:19.693",
"Id": "47732",
"ParentId": "47728",
"Score": "-1"
}
},
{
"body": "<p>Unfortunately, this snippet could be written a lot better, and it's already been written <em>a lot</em> better. However, I'll assume this isn't anything close to production and you're doing it for the learning process!</p>\n\n<p>Consider delving into the PDO world before getting to familiar with the MySQLi functions. Doing so will keep you on a good track to learning correct object oriented programming too.</p>\n\n<p>Which bring us to the next point: your code is highly dependent and incredibly coupled and tight. I suggest you read up on some object oriented matters, like <a href=\"http://www.php.net/manual/en/language.oop5.basic.php\" rel=\"nofollow noreferrer\">this</a>, <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">this</a>, and <a href=\"https://stackoverflow.com/questions/9452054/why-should-i-start-writing-object-oriented-code-in-php\">this</a>.</p>\n\n<p>However, since your code isn't lookin' like that, I'll just jump to reviewing the code available.</p>\n\n<p>Firstly, in your check to see if the connection is successful, your fail block only <code>echo</code>s the error. That allows a broken connection to continue in the script; that's bad. A solution would be to throw an exception from a database connection class which would in turn allow the view to present a user friendly error.</p>\n\n<p>Up next, you're using a real escape function. <a href=\"http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow noreferrer\">Prepare your statements</a> instead.</p>\n\n<p>Your empty string checking is a good example of <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">guard clauses</a>, good job.</p>\n\n<p>Good for using the built-in email validation function!</p>\n\n<p>When comparing password equality, it is acceptable to use <code><></code> however it's easier to understand and read <code>!==</code>. I'd suggest switching those.</p>\n\n<p>And lastly, adding parameters to your queries would eliminate some of the SQL injection possibility currently open in your code. You could also <a href=\"https://stackoverflow.com/questions/261455/using-backticks-around-field-names\">place back ticks</a> (`) around your column and table names, but if your databases are made properly this shouldn't be necessary. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:19:37.423",
"Id": "83760",
"Score": "1",
"body": "The article comparing PDO to mysqli you linked to is over 2 years old, and is (perhaps conveniently) leaving out those features that mysqli supports, that are _not_ supported by PDO (yet). Yes, I too prefer PDO's API, but that does not deter from the fact that, to this day, mysqli still is the more powerful extension. I therefore disagree with your saying mysqli is _\"acceptible\"_, and PDO is preferable. Both are equally fine. Sometimes PDO is preferable, in other cases, mysqli is better. In the end, and in this case, it's all down to personal preference. oh, and `die` is bad practice. always."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:24:31.247",
"Id": "83763",
"Score": "1",
"body": "Injection of the second order is still possible, even when using prepared statements. Please, don't spread information hailing prepared statements as the ultimate answer to all vulnerabilities, because they're _not_. Placing backticks around the tables will work fine on MySQL (and related) DB's, but the use of backticks is **non-standard**, leaving them out really is the better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:29:30.557",
"Id": "83858",
"Score": "0",
"body": "I'll have to say, linking to that tuts + page was an ify decision for me, I felt hesistant and I should have left it out! I'll edit my answer to be less biased towards PDO and I'll make an effort to read a bit more about the differences. As for the back ticks, I agree that if your table is made properly in the first place they shouldn't be needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T05:46:11.757",
"Id": "83876",
"Score": "1",
"body": "It's not a matter of the backticks being needed or not, it's about them being a MySQL oddity... not a standard SQL thing. One of the plusses of PDO mentioned in the linked page is supporting multiple adapters, if you then write queries that specifically target MySQL, then you loose that _\"edge\"_"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:31:55.617",
"Id": "47747",
"ParentId": "47728",
"Score": "1"
}
},
{
"body": "<p>Not only is there code that does this type of stuff already out there, freely available. This question has been asked and answered a couple of times before on this site already. <a href=\"https://codereview.stackexchange.com/questions/30237/form-validation-security-and-input-specification/30248#30248\">This is one such example</a>.</p>\n\n<p>However, given that the answers currently posted here are either incomplete or, IMHO, wrong (suggesting bad practices, or providing incomplete info), I'll post a short review of mine here, too.</p>\n\n<p>You have a simple, procedural script. There's nothing <em>wrong</em> with that, per se. Although, nowadays, people will tell you to pour your code into objects and let each class do its own, specific task.<br>\nWhy should you use objects here? Well, that's really down to what kind of project you're putting together: is the site going to be a fully dynamic LAMP driven site? Is the code likely to grow, or is it probable that, as you go along, new features will be added to your site? Then yes, you should look into writing your own classes, or adopt a framework (ZendFW, Symfony2,... there are tons to choose from).</p>\n\n<p>If the amount of PHP you'll be using is relatively small, and its role won't exceed simple user input checks and some DB connectivity, then OO code is just going to add clutter, and bloat.</p>\n\n<p><strong><em>On the code</em></strong><br>\nConnecting to the DB, and executing queries alongside code that actually generates output for the user/client is one of the main reasons why PHP is said to be a badly designed language. Yes, PHP allows you to write that kind of code, but you should know that it's actually seen as <em>bad practice</em>. A saw doesn't prevent you from sawing off the branch you're sitting on, but that doesn't mean it's a good idea to do so... Same thing applies to programming.</p>\n\n<p>If you don't require object-oriented code (yet), at least create functions to handle the DB stuff, put them in a separate file, and call the functions when you need them:</p>\n\n<pre><code>require 'db_functions.php';//or require_once\n$db = getDbConnection(\n array(\n 'user' => 'username',\n 'pass' => 'yourpass'\n )\n);\n</code></pre>\n\n<p>Perhaps look into ways to keep the actual login credentials <em>oustide</em> of your code.</p>\n\n<p><strong><em>Escaping and assigning</em></strong><br>\nI cannot, for the life of me understand why you would do anything like:</p>\n\n<pre><code>$name = $con->real_escape_string($_POST['name']);\n</code></pre>\n\n<p>with all of your post values. All those values belong together: they represent the data the user posted to your script, to validate and process. Why would you assign them to individual variables? keep that data as a whole.<br>\nIf you want to check if an array has all values/keys set, then please use <code>isset</code> and then compare the values to an empty string. <code>empty</code> has a couple of oddities <a href=\"http://kunststube.net/isset/\" rel=\"nofollow noreferrer\">you should be aware of</a>.</p>\n\n<p>In this case, validating the post data can be easily done in a single loop:</p>\n\n<pre><code>$keys = array('name', 'username', 'email', 'pass1', 'pass2');\nforeach ($keys as $k)\n{\n if (!isset($_POST[$k]) || $_POST[$k] == '')\n exit();//<-- more on this later\n}\n</code></pre>\n\n<p>Code like this can be easily poured into a function, to which you can pass both the array to check (<code>$_POST</code>) and the keys to check (<code>$keys</code>). Just 2 simple arguments, and you never need to write code assigning and checking variables again, just a single function call will do.</p>\n\n<p>Now, the <code>real_escape_string</code> calls really are a bad idea. Quote chars, slashes... they're all <em>allowed</em> in email addresses. calling <code>real_escape_string</code> means that there is a chance that you're screwing up perfectly valid user input, and rendering it invalid. <em>don't</em>.</p>\n\n<p>Using prepared statements here would be the only proper way to go: don't process the input a user gave you. If the input is anything other than perfect, assume the input is invalid or possibly malicious.</p>\n\n<p><strong>Avoid too many regex's</strong><br>\nChecking for a password that contains both digits and characters <em>can</em> be done through regex, but that might not be the best tool for the job. The actual benchmarking is your job, but a regex often is slower than a simple loop, checking if a char is numeric or not.</p>\n\n<p>Either way: you are using <strong>2</strong> regular expressions for something that can be easily done with just one expression. I've posted an answer <a href=\"https://codereview.stackexchange.com/questions/42095/password-checker-in-php/42144#42144\">here</a> which goes into more details on the matter.</p>\n\n<p><strong>re-assigning again?</strong><Br>\nAfter validating the input (that, as I explained above, you may have rendered invalid yourself!), you then check variables like <code>$emailValid</code> again. That really ought to set off alarm bells.</p>\n\n<p>Just think about it: you check some things. If the very first thing you checked showed you the user sent invalid input, you still procede to check, validate, reassign all other values, only to then <em>again</em> check if all input is valid.<Br>\nThat's doing the same thing twice, isn't it? DRY (Do not Repeat Yourself) is a common expression/piece of advice in programming. Your code basically repeats the most basic input validation task. That can't be good, now can it?</p>\n\n<p>That's why throwing an exception is preferable, and that is also why separating output code, and logic/db related code into (at least) functions. These functions (functional units, as their name suggests) could be written to throw exceptions, which will then determine the output message the client will get to see.<br>\nHere's a basic example to clear this up. Remeber how I mentioned a function to check if all POST params are set? Here's how that would work in your case:</p>\n\n<pre><code>function checkKeys(array $data, array $keys)\n{//note the type-hints!\n foreach ($keys as $k)\n {\n if (!isset($data[$k]) || $data[$k] == '')\n throw new InvalidArgumentException($k.' parameter not set');\n }\n return true;\n}\n//your code:\ntry\n{\n checkKeys($_POST, array('name', 'username', 'email', 'pass1', 'pass2'));\n}\ncatch( InvalidArgumentException $e)\n{//catch Exception works, too\n echo 'Error: ', $e->getMessage();\n}\n</code></pre>\n\n<p>That should be enough to get you started for now ;-P</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:15:43.443",
"Id": "47799",
"ParentId": "47728",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T18:29:26.750",
"Id": "47728",
"Score": "3",
"Tags": [
"php",
"security",
"form"
],
"Title": "Password hashing/handling on a form"
} | 47728 |
<p>I have a function called <code>mult2</code> that takes in two square NumPy matrices and returns a matrix that is the result of a special multiplication:</p>
<pre><code>p=P(1,344)
PI,PIT=[],[]
for i in xrange(344):
PI.append(p**i)
PIT.append((p**i).transpose())
def mult2(a,b):
C=np.sum((a*b)**2,axis=1)
CE1=np.matrix([[0.0] for _ in xrange(len(a))])
API,PITB=[],[]
AB=a*b
for i in xrange(len(a)):
API.append(np.diag(np.diag(a*PI[i])))
PITB.append(np.diag(np.diag(PIT[i]*b)))
CE1+=np.sum(API[i]*PITB[i]*AB,axis=1)
CE2=np.matrix([[0.0] for _ in xrange(len(a))])
BPI,PITA=[],[]
for i in xrange(len(a)):
BPI.append(np.diag(np.diag(b*PI[i])))
PITA.append(np.diag(np.diag(PIT[i]*a)))
CE2+=np.sum(a*BPI[i]*PITA[i]*b,axis=1)
CE3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE3+=np.sum(AB*API[i]*PITB[i],axis=1)
CE1E2=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE1E2+=np.sum(API[i]*PITB[i]*API[i]*PIT[i]*b,axis=1)
CE2E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE2E3+=np.sum(a*BPI[i]*PITA[i]*BPI[i]*PIT[i],axis=1)
CE1E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
for j in xrange(len(a)):
CE1E3+=np.sum(np.matrix(API[i]*PITB[i]*API[j]*PITB[j]),axis=1)
CE1E2E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE1E2E3+=np.sum(np.matrix((API[i]*PITB[i])**2),axis=1)
return C-(CE1+CE2+CE3-CE1E2-CE1E3-CE2E3+CE1E2E3)
</code></pre>
<p><code>p</code> is another matrix of the same dimensions (<code>n</code> by <code>n</code>) as <code>a</code> and <code>b</code> specially a <a href="http://en.wikipedia.org/wiki/Circulant_matrix" rel="nofollow">circulant matrix</a>.</p>
<p>My trouble is that these matrices are 344 by 344 and I am looking to run this function lots of times.</p>
<p>Storing the matrices that are used later in the function in the lists actually sped up the computation significantly.</p>
<p>I know this is a very intensive computation so it should take a while to run. That being said, can anyone spot any improvements I can make?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:08:26.880",
"Id": "83675",
"Score": "0",
"body": "for anyone interested in the math: http://mymathforum.com/linear-algebra/42813-can-i-calculate-sum-using-matrix-multiplication.html"
}
] | [
{
"body": "<p>From what I can tell, you could combine all of the for loops into only 2 distinct loops:</p>\n\n<ol>\n<li>A loop to setup the matrices used for later calculations</li>\n<li>A loop to do the rest of the calculations</li>\n</ol>\n\n<p>Instead of performing list comprehension to create an array to pass to each numpy matrix, you could simply multiply a base array by the <code>len(a)</code> to create said array:</p>\n\n<pre><code>base_list = [[0.0]]*len(a) # Creates [[0.0], [0.0], [0.0], ... ]\n</code></pre>\n\n<p>This way you do not temporarily store each element in the <code>xrange</code> object without needing to.</p>\n\n<p>Use more descriptive variable names. What is <code>a</code>, <code>b</code>? Using more descriptive variable names helps improve comprehension and readability.</p>\n\n<hr>\n\n<p>Here is my version of <code>mult2()</code>:</p>\n\n<pre><code>def mult2(a, b):\n\n AB = a*b\n API, BPI, PITA, PITB = [],[],[],[]\n\n # Base list used to seed each np.matrix()\n base_list= [[0.0]]*len(a)\n\n C = np.sum((a*b)**2, axis=1)\n CE1 = np.matrix(base_list)\n CE2 = np.matrix(base_list)\n CE3 = np.matrix(base_list)\n CE1E2 = np.matrix(base_list)\n CE2E3 = np.matrix(base_list)\n CE1E3 = np.matrix(base_list)\n CE1E2E3 = np.matrix(base_list)\n\n # Create arrays used in later matrix calculations\n for index in xrange(len(a)):\n API.append(np.diag(np.diag(a*PI[index])))\n PITB.append(np.diag(np.diag(PIT[index]*b)))\n BPI.append(np.diag(np.diag(b*PI[index])))\n PITA.append(np.diag(np.diag(PIT[index]*a)))\n\n # Do matrix calculations\n for index in xrange(len(a)):\n CE1 += np.sum(API[index]*PITB[index]*AB, axis=1)\n CE2 += np.sum(a*BPI[index]*PITA[index]*b, axis=1)\n CE3 += np.sum(AB*API[index]*PITB[index], axis=1)\n CE1E2 += np.sum(API[index]*PITB[index]*API[index]*PIT[index]*b, axis=1)\n CE2E3 += np.sum(a*BPI[index]*PITA[index]*BPI[index]*PIT[index], axis=1)\n CE1E2E3 += np.sum(np.matrix((API[index]*PITB[index])**2), axis=1)\n\n for pos in xrange(len(a)):\n CE1E3 += np.sum(\n np.matrix(API[index]*PITB[index]*API[pos]*PITB[pos]), axis=1)\n\n return C - (CE1 + CE2 + CE3 - CE1E2 - CE1E3 - CE2E3 + CE1E2E3)\n</code></pre>\n\n<hr>\n\n<p>Remember, good code is readable code: group like statements together.</p>\n\n<p>Also, <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP8</a> is the Python standard style convention. It provides a very nice style guide for code and helps code look as Pythonic as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:18:00.750",
"Id": "84066",
"Score": "0",
"body": "my only revision is that there's a problem with using base_list to declare all the matrices. I replaced base_list with [[0.0]]*len(a) and it works perfect"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T01:09:26.613",
"Id": "84074",
"Score": "0",
"body": "Huh, odd. You're welcome in any case :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:22:36.167",
"Id": "47781",
"ParentId": "47733",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47781",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T19:08:29.693",
"Id": "47733",
"Score": "4",
"Tags": [
"python",
"performance",
"matrix",
"numpy"
],
"Title": "Performing a special multiplication on two square matrices"
} | 47733 |
<p><em>This is the updated code using all suggestions from the previous question that I made <a href="https://codereview.stackexchange.com/questions/47723/initial-starting-player">here</a>.</em></p>
<p>I have revised the naming of the variables, and i have included the classes that this part of code is using, in order to have a better understanding.</p>
<blockquote>
<p>I'm making a game battle system, where there are 2 players.</p>
<p>It is like a round based game.</p>
<ul>
<li>Every player can have multiple units to control, but can only use one of them each round..</li>
<li>Every unit has an <code>int CurrentSpeed</code> variable;</li>
</ul>
<p>I need to have in 2 variables who attacks first (<code>Player firstPlayer</code>)
and who attacks second (<code>Player secondPlayer</code>), based on the speed of
the active Unit.</p>
</blockquote>
<p>At the moment I have this code:</p>
<pre><code>public class Player {
public int Id { get; set; }
public string Name { get; set; }
public List<Unit> Party { get; set; }
public Unit Active { get; set; }
}
public class Unit {
public string Name;
public int InitialSpeed { get; set; }
public int CurrentSpeed { get; set; }
}
public class BattleSystem {
private void BattleTurn(){
Player firstPlayer = null; //Player attacking first
Player secondPlayer = null; //Player attacking second
//Check the speed of the units, and determine who attack first
firstPlayer = player_1.Active.CurrentSpeed > player_2.Active.CurrentSpeed ? player_1 : player_1.Active.CurrentSpeed < player_2.Active.CurrentSpeed ? player_2 : null;
//if firstPlayer is null (active units have the same CurrentSpeed)
if(firstPlayer == null){
//Randomize who goes first
System.Random rnd = new System.Random();
int rng = rnd.Next(2);
firstPlayer = rng == 0 ? player_1 : player_2;
secondPlayer = rng == 0 ? player_2 : player_1;
}else{
secondPlayer = firstPlayer.Id == player_1.Id ? player_2 : player_1;
}
}
}
</code></pre>
<p>The part of determine the <code>firstPlayer</code> is ok, but I don't like the checks and assignments of the <code>secondPlayer</code>, like checking the ids.</p>
<p>I need tips on how I can code this in a better way.</p>
| [] | [
{
"body": "<p>Do without the ternary expressions: because a ternary expression is very good for initializing one variable, but is much less good for initializing two variables.</p>\n\n<pre><code>// Declared but not initialized (to null), in order to guarantee that\n// they are each initialized in the subsequent if statements.\nPlayer firstPlayer;\nPlayer secondPlayer;\n\nif (player_1.Active.CurrentSpeed > player_2.Active.CurrentSpeed)\n{\n firstPlayer = player_1;\n secondPlayer = player_2;\n}\nelse if (player_1.Active.CurrentSpeed < player_2.Active.CurrentSpeed)\n{\n firstPlayer = player_2;\n secondPlayer = player_1;\n}\nelse\n{\n //Randomize who goes first\n ... etc ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:40:02.343",
"Id": "47740",
"ParentId": "47737",
"Score": "6"
}
},
{
"body": "<p>In addition to <strong>ChrisW's</strong> answer: </p>\n\n<ul>\n<li>There is little point in recreating <code>Random</code> variable every time you need it. You should consider saving it to the private field.</li>\n<li>You should also probably switch to C# coding style from what seems to be a Java style when it comes to using braces. Check <em>ChrisW's</em> example - opening braces go to the new line. Same goes for operators such as <code>else</code>.</li>\n<li>As a rule of a thumb - you should not expose public fields (unless you have a reason to). So <code>Unit.Name</code> should probably be an auto-property as well.</li>\n<li>It is a good idea to always have <code>Id</code> set accesor private.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:34:50.360",
"Id": "83734",
"Score": "1",
"body": "“There is little point in recreating `Random`” More than that: it's wrong, as I explain in [my answer to the previous question](http://codereview.stackexchange.com/a/47775/2041)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T12:16:44.627",
"Id": "83743",
"Score": "0",
"body": "For the brackets, for me it is really a **personal** coding style. I always coded in that way, so **for me** it is more readable. Can you please explain better you 3rd point? I do set public fields because i do have to set the values when i initialize a new instance of the class. If i set them private i cannot access them outside of that class. (I'm still learning, so I'm probably doing it wrong :P) Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:40:47.427",
"Id": "83750",
"Score": "0",
"body": "@WiS3 If you use a Microsoft IDE for editing, the braces snap to separate lines as you edit the file (unless you override the default formatting options)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:44:19.127",
"Id": "83751",
"Score": "0",
"body": "@svick I do use MonoDevelop mainly (because it integrate very well with Unity Engine)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:22:06.513",
"Id": "83878",
"Score": "0",
"body": "@WiS3, I do understand that. Nonetheless, you will eventually work in a team, and you will have to play by the rules. So it is good idea to keep your mind flexible right know and learn the ability to change your coding style depending on language. The longer you keep this \"i like it that way\"-mindset, the harder it will be to drop this habit later on. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:23:14.007",
"Id": "83880",
"Score": "0",
"body": "@WiS3, as for your question - check this article http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx (philosophical reason part in particular)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:40:51.090",
"Id": "47764",
"ParentId": "47737",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47740",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:17:14.550",
"Id": "47737",
"Score": "6",
"Tags": [
"c#",
"game"
],
"Title": "Initial starting player - v2"
} | 47737 |
<p>Please be über brutal, and treat this as a technical interview question.</p>
<p>I was wondering how this function that I wrote looks like. It groups together words that have the same alphabets (i.e anagrams). </p>
<p>Time Complexity: \$O(n^2)\$</p>
<p>Space Complexity: \$O(n)\$</p>
<pre><code>private static List<List<String>> groupAnagrams(ArrayList<String> words){
List<List<String>> groupedAnagrams = new ArrayList<>();
AbstractMap<String, String> sortedWords = new HashMap<>();
Set<Set<String>> sameAnagramsSet = new HashSet<>();
for(String word : words){
char[] wordToSort = word.toCharArray();
Arrays.sort(wordToSort);
sortedWords.put(word, new String(wordToSort));
}
for(Map.Entry<String, String> entry : sortedWords.entrySet() ){
Set<String> sameAnagrams = new HashSet<>();
sameAnagrams.add(entry.getKey());
for(Map.Entry<String, String> toCompare : sortedWords.entrySet()){
if(entry.getValue().equals(toCompare.getValue())){
sameAnagrams.add(toCompare.getKey());
}
}
if(sameAnagrams.size() > 0){
sameAnagramsSet.add(sameAnagrams);
}
}
for(Set<String> set : sameAnagramsSet){
groupedAnagrams.add(new ArrayList<>(set));
}
return groupedAnagrams;
}
</code></pre>
| [] | [
{
"body": "<p>Use the right abstractions in method parameters and local variables, for example instead of:</p>\n\n<blockquote>\n<pre><code>private static List<List<String>> groupAnagrams(ArrayList<String> words){\n AbstractMap<String, String> sortedWords = new HashMap<>();\n</code></pre>\n</blockquote>\n\n<p>would have been better as:</p>\n\n<pre><code>private static List<List<String>> groupAnagrams(List<String> words){\n Map<String, String> sortedWords = new HashMap<>();\n</code></pre>\n\n<p>that is:</p>\n\n<ul>\n<li><code>ArrayList</code> method parameter type changed to <code>List</code>. Or actually, if the ordering of words is not important, then <code>Collection</code> would be even better.</li>\n<li><code>AbstractMap</code> local variable type changed to simply <code>Map</code>.</li>\n</ul>\n\n<hr>\n\n<p>Instead of:</p>\n\n<blockquote>\n<pre><code>if(sameAnagrams.size() > 0){\n</code></pre>\n</blockquote>\n\n<p>this would be better:</p>\n\n<pre><code>if (!sameAnagrams.isEmpty()) {\n</code></pre>\n\n<hr>\n\n<p>If I'm reading it right, it seems the algorithm could have been simplified to a single <code>for</code> loop:</p>\n\n<pre><code>private List<List<String>> groupAnagrams(List<String> words) {\n Map<String, List<String>> groupedAnagramsMap = new HashMap<String, List<String>>();\n for (String word : words) {\n char[] wordToSort = word.toCharArray();\n Arrays.sort(wordToSort);\n String key = new String(wordToSort);\n List<String> anagrams = groupedAnagramsMap.get(key);\n if (anagrams == null) {\n anagrams = new ArrayList<String>();\n groupedAnagramsMap.put(key, anagrams);\n }\n anagrams.add(word);\n }\n return new ArrayList<List<String>>(groupedAnagramsMap.values());\n}\n</code></pre>\n\n<p>This implementation produces equivalent list of list, if you don't mind the ordering of items.</p>\n\n<p>If you could forgive changing the method signature to return <code>Collection</code> instead of list, then the last <code>new ArrayList</code> could be omitted, for cleaner and better result:</p>\n\n<pre><code>private Collection<List<String>> groupAnagrams(List<String> words) {\n // ... same as above\n return groupedAnagramsMap.values();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:39:20.020",
"Id": "83686",
"Score": "0",
"body": "I thought its always better to declare the apparent type of an object with its superclass/interface, in this it is abstractMap"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:03:06.837",
"Id": "83688",
"Score": "0",
"body": "`AbstractMap` implements `Map`, therefore `Map` is a better generalization of your purpose. It's better to design in terms of interfaces instead of implementations. The important thing is that `HashMap` implements `Map`. In contrast, the fact that `HashMap` extends `AbstractMap` is an implementation detail, and not at all important in your design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T02:27:40.987",
"Id": "135203",
"Score": "1",
"body": "Another key point in using `Map` is that, anything that properly implements `Map` would do the job, it need not extend `AbstractMap`. If your code depended on anything contained in `AbstractMap` and not in `Map` then using `AbstractMap` would have made sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:31:28.763",
"Id": "47746",
"ParentId": "47739",
"Score": "6"
}
},
{
"body": "<p>Great solution by janos. </p>\n\n<p>One minor thing to add is to avoid adding duplicates to the list</p>\n\n<pre><code>if (!anagrams.contains(word) {\n anagrams.add(word);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-04T04:44:39.503",
"Id": "109729",
"ParentId": "47739",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "47746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T20:39:52.550",
"Id": "47739",
"Score": "3",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Grouping Anagrams"
} | 47739 |
<p>This is a Python solution for all general cases. Any suggestions at all would be appreciated; in my opinion it's already quite good! <a href="http://projecteuler.net/problem=31" rel="nofollow">Here's a link to the problem.</a></p>
<pre><code>from timeit import default_timer as timer
def count_coins(target, operands):
ways_to_make = [1] # list of ways to make x at index x
for o in range(0, len(operands)):
for t in range(target + 1):
# initialise undefined target
if len(ways_to_make) <= t:
ways_to_make.append(0)
# add ways to make number recursively
if t >= operands[o]:
ways_to_make[t] += ways_to_make[t - operands[o]]
return ways_to_make[target]
start = timer()
ans = count_coins(200, [1, 2, 5, 10, 20, 50, 100, 200])
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [] | [
{
"body": "<p>It will be faster if you pre-generate the <code>ways_to_make</code> array:</p>\n\n<pre><code>def count_coins(sum, coins):\n ways_to_make = [0 for _ in range(sum + 1)]\n ways_to_make[0] = 1\n for coin in coins:\n for t in range(sum + 1):\n if t >= coin:\n ways_to_make[t] += ways_to_make[t - coin]\n\n return ways_to_make[sum]\n</code></pre>\n\n<p>This doesn't waste memory because you would allocate those elements anyway, and it's a lot faster to create a larger list once than extending it in every loop iteration. Not to mention that this gets rid of an <code>if</code> statement.</p>\n\n<p>I also changed the <code>for o in range(len(coins))</code> loop to the more intuitive <code>for coin in coins</code>. In my measurements this gave an extra speed boost too.</p>\n\n<p>Finally, I took the liberty to rename your function parameters to more meaningful names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:51:49.950",
"Id": "47748",
"ParentId": "47744",
"Score": "7"
}
},
{
"body": "<p>I will add a bit to janos's answer.</p>\n\n<p>The inner loop</p>\n\n<pre><code>for t in range(sum + 1):\n if t >= coin:\n ways_to_make[t] += ways_to_make[t - coin]\n</code></pre>\n\n<p>can be written better as </p>\n\n<pre><code>for t in range(coin, sum + 1):\n ways_to_make[t] += ways_to_make[t - coin]\n</code></pre>\n\n<p>It becomes automatically clear that here <code>t >= coin</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T14:26:19.690",
"Id": "48227",
"ParentId": "47744",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47748",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:24:14.257",
"Id": "47744",
"Score": "1",
"Tags": [
"python",
"optimization",
"programming-challenge"
],
"Title": "Any way to optimize this already fast Python solution to Project Euler 31 (coin sums)?"
} | 47744 |
<p>I'm writing a program to differentiate functions (perform basic calculus) in Haskell. The program works, but there's one function that looks very ugly to me:</p>
<pre><code>--some prerequisite definitions
--a mathematical value is either...
data Value =
Literal Double --a number, such as 4, -17.5, or 2.33e27
| Variable Symbol (Maybe Double) --a variable, which may or may not have a known value
| FCall --a function call, consisting of a function and two arguments
{
func :: Function,
arg1 :: Value,
arg2 :: Value
}
deriving (Eq)
--simplifies a mathematical value into a simpler form.
reduce :: Value -> Value
reduce val@(Literal _) = val --literals cannot be simplified
reduce (Variable _ (Just val)) = Literal val --bound variables can be simplified to literals
reduce var@(Variable _ Nothing) = var --unbound variables cannot be simplified
reduce fc@(FCall f a b) = --simplifying functions is messy...
if isDefined f ma mb
then matchLiterals ma mb
else retval
where ra = reduce a --reduce simplifies a Value to a Value
rb = reduce b
ma = eval ra --eval converts known values to Doubles and unknown Values to Nothing
mb = eval rb
retval = FCall f ra rb --returned in case of failure
matchLiterals (Just da) (Just db) = Literal $ (impl f) da db
matchLiterals _ _ = matchCase $ findCase (cases f) ra rb
matchCase (Just sc) = evalCase sc ra rb
matchCase Nothing = retval
</code></pre>
<p>The multitude of local functions defined in the <code>where</code> clause seems excessive, but I can't find a better way to handle the flow of execution. I've tried to break this up into several smaller functions, but since most of these can fail (evaluate to <code>Nothing</code>), I still have to use pattern matching to handle the results of these functions.</p>
<p>The flow of logic goes like this:</p>
<pre><code>if the function is defined for the given arguments:
if the arguments have definite known values:
evaluate and return the function call
else:
look for special cases (adding 0, multiplying/diving by 1, etc.)
if a special case was found:
evaluate and return the result of applying the special case to the arguments
else:
return another FCall with possibly simplified arguments
else:
return another FCall with possibly simplified arguments
</code></pre>
<p>It's possible I'm fretting over nothing (hah) and this code is perfectly fine, but it seems that this is not the optimal way to handle these conditions. Can anyone offer any advice about how I might better structure this code?</p>
| [] | [
{
"body": "<p>It is a matter of taste but I think <code>reduce</code> will be a bit more cleaner with <code>case</code>.</p>\n\n<pre><code>reduce exp = case exp of\n Literal{} -> exp\n Variable _ (Just var) -> Literal var\n Variable _ Nothing -> exp\n FCall f a b\n | isDefined f ma mb -> matchLiterals ma mb\n | otherwise -> FCall f ra rb\n where ra = reduce a\n rb = reduce b\n ma = eval ra\n mb = eval rb\n</code></pre>\n\n<p><code>Literal{}</code> is special pattern syntax that will still work even if you add more arguments to <code>Literal</code>.</p>\n\n<p>To reduce duplication (just a bit) in where, you can use <code>on</code> function from <code>Data.Function</code></p>\n\n<pre><code>on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n</code></pre>\n\n<p>it is like <code>(.)</code> but allows to apply function to both arguments</p>\n\n<pre><code>(ra,rb) = on (,) reduce a b\n(ma,mb) = on (,) eval ra rb\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:36:45.797",
"Id": "85722",
"Score": "1",
"body": "Also, on is often used infix, e.g `f \\`on\\` g` rather than `on f g`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T08:14:48.540",
"Id": "47766",
"ParentId": "47745",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T22:25:24.913",
"Id": "47745",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Function with excessively complex \"where\" clause"
} | 47745 |
<p>I made this math script, where you enter an equation and it solves it for you. I was wondering what you thought of the code, and what I could have done better or what doesn't follow Ruby best practices. The code is also on Github <a href="https://github.com/INOVA-Technology/Math" rel="nofollow">here</a> if you want to see the readme and how to use define_equation()</p>
<pre><code>#!/usr/bin/env ruby
require "readline"
require "cmath"
# PREFIXES = { -15 => "f", -12 => "p", -9 => "n",
# -6 => "µ", -3 => "m", 0 => "",
# 3 => "k", 6 => "M", 9 => "G",
# 12 => "T", 15 => "P", 18 => "E" }
def define_equation(file)
File.foreach(file) { |line|
name, var, equation = line.split(":")
Equations.class_eval %[
def #{name}(#{var})
#{equation}
end
]
}
end
def all_formulas
(Equations.instance_methods(false) - [:method_missing])
.map { |i| i.to_s.gsub(/_/, "-") }
end
class Equations
C = 3e8
def m_with_hz(frequency)
C / frequency
end
alias_method :hz_with_m, :m_with_hz
def qudrtc_frml_with_a_b_c(a, b, c)
positive = (-b + CMath.sqrt(b ** 2 - 4 * a * c)) / 2 * a
negative = (-b - CMath.sqrt(b ** 2 - 4 * a * c)) / 2 * a
# possibly add positive and negative .to_r as well as the float
[positive, negative]
end
def pythgrn_thrm_with_a_b(a, b)
a = Math.sqrt(a ** 2 + b ** 2)
a = "sqrt(#{(a ** 2).round})" unless a.to_i == a
a
end
def pythgrn_thrm_with_b_c(b, c)
a = Math.sqrt(c ** 2 - b ** 2)
a = "sqrt(#{(a ** 2).round})" unless a.to_i == a
a
end
def method_missing(m, *args, &block)
"That equation doesn't exist here. (yet)"
end
end
class Cli
attr_reader :equations
def initialize
@equations = Equations.new
end
def help
["To use an equation, just type something like this: hz-with-m 100",
"Thats 100 meters, converted to hertz",
"Or something like this: pythgrn-thrm-with-b-c 4 5",
"That's a^2 = 5^2 - 4^2, or more familiarly, a^2 + 4^2 = 5^2",
"You also can use e for scientific notation. Eg. 3e5 = 300000",
"Type quit to quit",
"",
"Available Equations:",
all_formulas]
end
def method_missing(m, *args, &block)
# checks if it only contains numbers, math symbols, and e
if args.all? { |arg| arg.match(/\A[\d+\-*\/.e ]+\z/) }
args.map! { |arg| eval(arg) }
@equations.send(m, *args)
else
"Invalid number"
end
end
def quit
exit
end
end
cli = Cli.new
case ARGV[0]
when "-l", "--load"
ARGV.shift
define_equation(ARGV.shift)
# I will add more stuff here
end
if __FILE__ == $0
puts "Type help for help."
Readline.completion_append_character = " "
Readline.completion_proc = proc { |s|
all_formulas.grep(/^#{Regexp.escape(s)}/)
}
loop do
command, *variables = Readline::readline("> ", true)
.downcase.strip.squeeze(" ").split(" ")
unless command.nil?
command.gsub!(/-/, "_")
puts begin
cli.send(command, *variables)
rescue ArgumentError
argc = cli.equations.method(command).arity
arg_list = (1..argc).map { |i| "<number_#{i}>" }.join(" ")
"Usage: #{command} #{arg_list}"
end
end
end
end
</code></pre>
<p>Here are the tests:</p>
<pre><code>#!/usr/bin/env ruby
require "rubygems"
gem "minitest"
require "minitest/autorun"
require "minitest/pride"
load "solve"
describe Equations do
before do
@equations = Equations.new
end
describe "m_with_hz" do
it "must return correct value" do
@equations.m_with_hz(300e12).must_equal 1.0e-06
@equations.m_with_hz(3e6).must_equal 100
end
end
describe "hz_with_m" do
it "must return correct value" do
@equations.hz_with_m(100e3).must_equal 3e3
@equations.hz_with_m(100.0e-12).must_equal 3e18
end
end
describe "qudrtc_frml_with_a_b_c" do
it "must return correct value" do
@equations.qudrtc_frml_with_a_b_c(1, 2, -3).must_equal [1.0, -3.0]
end
end
describe "pythgrn_thrm_with_a_b" do
it "must return correct value" do
@equations.pythgrn_thrm_with_a_b(3, 4).must_equal 5
@equations.pythgrn_thrm_with_a_b(4, 5).must_equal "sqrt(41)"
end
end
describe "pythgrn_thrm_with_b_c" do
it "must return correct value" do
@equations.pythgrn_thrm_with_b_c(4, 5).must_equal 3
@equations.pythgrn_thrm_with_b_c(3, 4).must_equal "sqrt(7)"
end
end
describe "equation does not exist" do
it "must warn user" do
@equations.doesnt_exist(500).must_equal "That equation doesn't exist here. (yet)"
end
end
end
describe Cli do
before do
@cli = Cli.new
@error_msg = "Invalid number"
end
describe "an equation is ran" do
it "must warn user if an invalid number is used" do
@cli.doesnt_matter("hello").must_equal @error_msg
@cli.doesnt_matter("34five").must_equal @error_msg
@cli.doesnt_matter("q12").must_equal @error_msg
end
it "must work if a valid equation is ran" do
@cli.doesnt_matter("123.3").wont_equal @error_msg
@cli.doesnt_matter("12e3").wont_equal @error_msg
@cli.doesnt_matter("1e-4").wont_equal @error_msg
end
end
end
describe "flags" do
describe "--load" do
before do
@cli = Cli.new
end
it "must load equations" do
# in progress
define_equation("sample_equations")
end
end
end
# write tests for importing equations
</code></pre>
| [] | [
{
"body": "<p>There is a bug in your quadratic formula. Watch your operator associativity!</p>\n\n<p>I'm not a fan of the method names <code>qudrtc_frml_with_a_b_c</code> and <code>pythgrn_thrm_with_a_b</code>, and I think that the poor naming is a symptom of a poor class design.</p>\n\n<p>First of all, drpng vwls makes your interface hard for others to use. Learn from <a href=\"https://stackoverflow.com/q/8390979/1157100\">Ken Thompson's greatest regret</a>.</p>\n\n<p>Next, I would remove \"formula\" and \"theorem\" from the method names. The caller generally doesn't care how you solve the quadratic equation — whether you do it by using the quadratic formula, completing the square, etc. Similarly, the fact that there is a Pythagorean Theorem is unimportant; the focus should be on the subject of the Pythagorean Theorem, which is the right triangle.</p>\n\n<p>Third, I question the benefit of adding all of these unrelated equations as methods of one class.</p>\n\n<p>Finally, the suffixes <code>…_with_a_b</code> and <code>…_with_b_c</code> for your Pythagorean solver suggest that your solution is too rigid. It would be nice if the user could enter all but one of the variables as constraints, and ask the program to solve for the remaining unknown.</p>\n\n<p>I suggest the following design. It takes advantage of one of Ruby's strengths, which is the ability to craft a human-friendly domain-specific language.</p>\n\n<pre><code>require 'cmath'\n\nclass QuadraticEquation\n attr_writer :a, :b, :c, :x\n\n def x\n positive = (-@b + CMath.sqrt(@b ** 2 - 4 * @a * @c)) / (2 * @a)\n negative = (-@b - CMath.sqrt(@b ** 2 - 4 * @a * @c)) / (2 * @a)\n [positive, negative]\n end\n\n def a\n (-@b * @x - @c) / (@x ** 2)\n end\n\n def b\n (-@a * @x ** 2 - @c) / @x\n end\n\n def c\n -@a * @x ** 2 - @b * @x\n end\nend\n\nclass RightTriangle\n attr_writer :a, :b, :c\n\n def a\n Math.sqrt(@c ** 2 - @b ** 2)\n end\n\n def b\n Math.sqrt(@c ** 2 - @a ** 2)\n end\n\n def c\n Math.sqrt(@a ** 2 + @b ** 2)\n end\n\n alias :hypotenuse :c\n alias :hypotenuse= :c=\nend\n</code></pre>\n\n<p>Here it is in use:</p>\n\n<pre><code>irb(main):001:0> require 'formula'\n=> true\nirb(main):002:0> triangle = RightTriangle.new\n=> #<RightTriangle:0x007fe14301f500>\nirb(main):003:0> triangle.hypotenuse = 5\n=> 5\nirb(main):004:0> triangle.a = 3\n=> 3\nirb(main):005:0> triangle.b\n=> 4.0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:49:23.153",
"Id": "83770",
"Score": "1",
"body": "+1 - nice answer! I like your design, but I would have not initialized the parameters as `0` - instead I would leave them as `nil` and define the getters as `@a || (-@b * @x - @c) / (@x ** 2)`. This way all getters will give valid results, and not just the ones which were not initialized"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:41:11.793",
"Id": "83783",
"Score": "0",
"body": "@UriAgassi I've incorporated your suggestion to leave the constraints uninitialized. I'm unsure about your second suggestion, though. Continuing with the `triangle` example, if the caller then sets `triangle.b = 7` and asks to solve for `triangle.a`, what would happen? I would be necessary to set `triangle.a = nil` before calling `triangle.a`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:44:24.000",
"Id": "83784",
"Score": "0",
"body": "@UriAgassi What do you think of abusing the `?` suffix? So, `a=` to set a constraint, `a` to retrieve a constraint, `a?` to solve for an unknown. It violates the naming convention that `?` marks a predicate, but works well for this domain-specific language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:56:02.913",
"Id": "83809",
"Score": "0",
"body": "I think it is very unconventional, but I kinda like it :-) it gives a consistent language, and once the ground rules are set, is self-explanatory. My problem is what if the caller does set all the variables? For example - `a=5, b=12, c=15`? now `c? == 13` and `c == 15` inconsistent sets should be validated with or without the new convention..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:25:01.650",
"Id": "83818",
"Score": "0",
"body": "@UriAgassi I've posted a second answer. In an over-constrained situation, just solve for the unknown as if it were never set."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T08:21:19.693",
"Id": "47767",
"ParentId": "47749",
"Score": "2"
}
},
{
"body": "<p>In response to a <a href=\"https://codereview.stackexchange.com/questions/47749/math-equation-solver/47767?noredirect=1#comment83770_47767\">comment</a> from @UriAgassi on my <a href=\"https://codereview.stackexchange.com/a/47767/9357\">previous answer</a>, I've devised this variant that distinguishes between retrieving constraints and solving for unknowns.</p>\n\n<p>The naming convention is:</p>\n\n<ul>\n<li><code>a=</code> to set a constraint</li>\n<li><code>a</code> to retrieve a constraint</li>\n<li><code>a?</code> to solve for an unknown</li>\n</ul>\n\n<p>It violates the naming convention that <code>?</code> marks a predicate, but works well for this domain-specific language.</p>\n\n<pre><code>require 'cmath'\n\nclass QuadraticEquation\n attr_accessor :a, :b, :c, :x\n\n def x?\n positive = (-b + CMath.sqrt(b ** 2 - 4 * a * c)) / (2 * a)\n negative = (-b - CMath.sqrt(b ** 2 - 4 * a * c)) / (2 * a)\n [positive, negative]\n end\n\n def a?\n (-b * x - c) / (x ** 2)\n end\n\n def b?\n (-a * x ** 2 - c) / x\n end\n\n def c?\n -a * x ** 2 - b * x\n end\nend\n\nclass RightTriangle\n attr_accessor :a, :b, :c\n\n def a?\n Math.sqrt(c ** 2 - b ** 2)\n end\n\n def b?\n Math.sqrt(c ** 2 - a ** 2)\n end\n\n def c?\n Math.sqrt(a ** 2 + b ** 2)\n end\n\n alias :hypotenuse :c\n alias :hypotenuse= :c=\n alias :hypotenuse? :c?\nend\n</code></pre>\n\n<p>One improvement is that the code above isn't littered with <code>@</code> sigils. However, the main benefit of disambiguating between retrieving constraints and solving for unknowns can be observed in an over-constrained situation:</p>\n\n<pre><code>irb(main):001:0> require 'formula'\n=> true\nirb(main):002:0> triangle = RightTriangle.new\n=> #<RightTriangle:0x007f90b401f800>\nirb(main):003:0> triangle.a, triangle.b, triangle.c = 5, 12, 37\n=> [5, 12, 37]\nirb(main):004:0> triangle.a?\n=> 35.0\nirb(main):005:0> triangle.c?\n=> 13.0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:21:28.003",
"Id": "47821",
"ParentId": "47749",
"Score": "1"
}
},
{
"body": "<p>I believe you are using <code>eval</code> <em>much</em> too liberally.</p>\n\n<p>The feature for adding new formulas is debatable (personally it is more of a security issue than a value feature, since you make <em>no</em> validations on the code you are evaluating), but for parsing arguments, the use of <code>eval</code> is completely redundant. Why don't you simply use built-in parsers for numbers, like <code>BigDecimal</code>?</p>\n\n<pre><code>require 'bigdecimal'\n\nBigDecimal.new(\"123.3\").to_f\n# => 123.3\nBigDecimal.new(\"12e3\").to_f\n# => 12000.0\nBigDecimal.new(\"1e-4\").to_f\n# => 0.0001\n</code></pre>\n\n<p>On a different note, I was not familiar with <code>Readline.completion_proc</code>, and it looks <em>really</em> cool! I'm going to look for where I might make use of that!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:54:56.163",
"Id": "47824",
"ParentId": "47749",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:00:26.177",
"Id": "47749",
"Score": "3",
"Tags": [
"ruby",
"mathematics",
"meta-programming"
],
"Title": "Math Equation Solver"
} | 47749 |
<p>Please be brutal and treat this as me coding this up for an interview.</p>
<p>A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence.</p>
<p>For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero.</p>
<p>Given a sequence of integers, sequence, return the length of the longest subsequence of sequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. </p>
<p>More examples:</p>
<ol>
<li><p><code>{ 1, 7, 4, 9, 2, 5 }</code></p>
<p>Returns: 6</p>
<p>The entire sequence is a zig-zag sequence.</p></li>
<li><p><code>{ 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 }</code></p>
<p>Returns: 7</p>
<p>There are several subsequences that achieve this length. One is 1,17,10,13,10,16,8.</p></li>
<li><p><code>{ 44 }</code></p>
<p>Returns: 1</p></li>
<li><p><code>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }</code></p>
<p>Returns: 2</p></li>
<li><p><code>{ 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5, 5, 5, 1000, 32, 32 }</code></p>
<p>Returns: 8</p></li>
<li><p><code>{ 374, 40, 854, 203, 203, 156, 362, 279, 812, 955, 600, 947, 978, 46, 100, 953, 670, 862, 568, 188, 67, 669, 810, 704, 52, 861, 49, 640, 370, 908, 477, 245, 413, 109, 659, 401, 483, 308, 609, 120, 249, 22, 176, 279, 23, 22, 617, 462, 459, 244 }</code></p>
<p>Returns: 36</p></li>
</ol>
<p>Worst case: \$O(n^2)\$<br>
Space Complexity: \$O(n)\$</p>
<pre><code>private static int longestAlternatingSequence(int[] values){
if(values.length == 1){
return 1;
}
int[] difference = new int[values.length-1];
for(int i = 1; i < values.length; i++){
difference[i-1] = values[i] - values[i-1];
}
int[] calculationsCache = new int[difference.length];
calculationsCache[0] = 1;
int max = Integer.MIN_VALUE;
for(int i = 1; i < difference.length; i++){
if(difference[i] > 0){
for(int j = 0; j < i; j++){
if(difference[j] < 0){
max = Math.max(max, calculationsCache[j]);
}
}
}else if(difference[i] < 0){
for(int j = 0; j < i; j++){
if(difference[j] > 0){
max = Math.max(max, calculationsCache[j]);
}
}
}else{
max = 0;
}
calculationsCache[i] = max + 1;
}
max = Integer.MIN_VALUE;
for(int value : calculationsCache){
max = Math.max(max, value);
}
return max + 1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:10:57.293",
"Id": "83693",
"Score": "0",
"body": "I don't really understand what does deleting means (mentioned in the last sentence). A few more examples and (with the expected output) would help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T01:01:06.980",
"Id": "83698",
"Score": "2",
"body": "@palacsint because I like you, I added more examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T02:18:17.177",
"Id": "83705",
"Score": "0",
"body": "Links on questions are for supporting documentation only. The actual code, and in all but the simplest cases, the description of what the code should do, should be a direct part of the question. Otherwise link-rot will make your question lose value over time. Please edit your question and include the relevant parts of the description. The wall-of-example-input/output is just data, and does not help to describe the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T09:30:25.720",
"Id": "83728",
"Score": "0",
"body": "@bazang When other programmers have difficulty understanding your question, consider restating it with mathematical rigour, [like this](http://codereview.stackexchange.com/q/31842/9357). The challenge is the same, except that that question asks for the sequence itself, while you just want the maximum length."
}
] | [
{
"body": "<ol>\n<li><p>Calling the method with an empty array throws a <code>java.lang.NegativeArraySizeException</code>. You should check that and throw an exception with a helpful error message.</p></li>\n<li><p>You could extract out a <code>createDifferenceArray</code> method for better readability:</p>\n\n<pre><code>private static int[] createDifferenceArray(int[] values) {\n int[] difference = new int[values.length - 1];\n for (int i = 1; i < values.length; i++) {\n difference[i - 1] = values[i] - values[i - 1];\n }\n return difference;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:08:59.247",
"Id": "47753",
"ParentId": "47751",
"Score": "2"
}
},
{
"body": "<p>Basically, you approach solves the problem adequately, and I have nothing to say about the existing code in terms of style.</p>\n\n<p>However, I think the general approach might be too costly, in terms of time and space requirements (even though I admit that there is no spec).\nBut since we should treat it as an interview question, then a potential interviewer could ask you\nhow to approach the problem more efficiently: for example, how could you process the array in one pass only?</p>\n\n<p>So here is a possible answer.</p>\n\n<h2>Algorithm's complexity</h2>\n\n<p>As you said, your current implementation requires:</p>\n\n<ul>\n<li>linear storage requirement</li>\n<li>quadratic execution time</li>\n</ul>\n\n<p>I have an alternative approach, using <strong>constant memory</strong> and <strong>linear time</strong>, which is based on an incremental algorithm: for each element of the array, you can determine the longuest zig-zag subsequence that can be built so-far.</p>\n\n<p>I prototyped the solution using Common Lisp, so here is my version (this could be translated easily as a simple <code>for</code> loop in Java, but this is left as an exercise ;-))</p>\n\n<pre><code>(defun max-zig-zag (sequence)\n (loop\n for last = nil then current\n for current in sequence\n for sign = 0 then (signum (- current last))\n for match = t then (or (eql await 0) (eql await sign))\n for await = 0 then (if match (- sign) await)\n count match))\n</code></pre>\n\n<p>This approach makes all your test examples pass:</p>\n\n<pre><code>(loop for (expected sequence) in \n '((6 (1 7 4 9 2 5))\n (7 (1 17 5 10 13 15 10 5 16 8))\n (1 (44))\n (2 (1 2 3 4 5 6 7 8 9))\n (8 (70 55 13 2 99 2 80 80 80 80 100 19 7 5 5 5 1000 32 32))\n (36 (374 40 854 203 203 156 362 279 812 955 600 947 978 46 100 953 670 862 568 188 67 669 810 704 52 861 49 640 370 908 477 245 413 109 659 401 483 308 609 120 249 22 176 279 23 22 617 462 459 244)))\n always (eql expected (max-zig-zag sequence)))\n\n=> T\n</code></pre>\n\n<p>I acknowledge that this might not be easy to follow through, so I'll try to write a step-by-step explanation.</p>\n\n<h2>Main idea</h2>\n\n<p>The difficulty in your question is that you allow <em>some</em> elements to be deleted (or, ignored). We are looking for sequences with maximum length, however. \nThe elements that can be ignored are those that do not alternate from previous ones: when you encounter a 2, and then the number 4, you can discard all the following elements that are greater than, or equal to, 4, without reducing the potential length of the subsequence: all numbers above 3 are just intermediate values.</p>\n\n<p>The suggested approach is a greedy count of all the alternations of slopes in the array (*).\nIt is built around a fixed number of variables that are updated at each element, during a unique iteration of the array; in fact, the input array could be an infinite stream of inputs, whereas the count value could be an infinite stream of integers that is updated for each input (and growing when needed).</p>\n\n<h2>Derivative</h2>\n\n<p>So, the main idea is to look at the <em>shape</em>, or the <em>derivative</em> of your numbers: you take the <code>current</code> value, and the <code>last</code> value, when iterating over the array, and you compute the difference: that gives you the slope.</p>\n\n<p>However, what is interesting is only the sign of this slope: the <code>sign</code> variable always contains the sign of the difference between current and last element, so that a 1 means that current value is higher, and -1 mean that is is lower than the last one.</p>\n\n<h2>Matching zig-zags</h2>\n\n<p>Initially, you await for any of those sign, either -1 or 1 (which is encoded by zero in the <code>await</code> variable).\nThis first time that <code>sign</code> differs from zero you have a match: you encountered a positive or negative variation of value; so, the new value of <code>await</code> is now the opposite of the current sign: if we saw a positive slope, like 1, we must read until there is a negative one.</p>\n\n<p>The <code>match</code> variable is initially true, and is otherwise true only when the <code>sign</code> variable equals the <code>await</code> variable (or, if <code>await</code> is zero, during the initialization phase). </p>\n\n<ul>\n<li>When <code>match</code> is false, we skip entries and let <code>await</code> keep its previous value.</li>\n<li>When true, <code>await</code> takes the opposite of current <code>sign</code>, which means that we await for a change in the slope.</li>\n</ul>\n\n<p>Then, <code>match</code> is true whenever we go up after having gone down, and respectively down after having gone up, discarding all continuous sequences of decreasing (or increasing) elements. </p>\n\n<p>Finally, we count the number of matches to have the longuest subsequence.</p>\n\n<hr>\n\n<p>(*) It is based on a data-flow approach (see Lustre, Signal, ...). In fact, the Common Lisp code above could probably easily be rewritten using the SERIES package.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:15:21.607",
"Id": "47834",
"ParentId": "47751",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47834",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:28:29.847",
"Id": "47751",
"Score": "7",
"Tags": [
"java",
"algorithm",
"interview-questions",
"dynamic-programming"
],
"Title": "Finding alternating sequence in a list of numbers"
} | 47751 |
<p>The following is an implementation of a tree in C++ designed for keys which do not have an order (otherwise a <code>std::map</code> could be used). <code>T</code> is a key type and <code>H</code> is a hash for <code>T</code>. </p>
<pre><code>#include <iostream>
#include <memory>
#include <utility>
#include <unordered_map>
template<typename T, typename H>
class tree;
template<typename T, typename H>
class tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };
template<typename T, typename H>
std::ostream& operator<<(std::ostream& s, const tree<T, H> &t);
template<typename T, typename H>
std::ostream& operator<<(std::ostream& s, const tree<T, H> &t)
{
for(auto i : t) {
s << i.first << std::endl;
s << *i.second << std::endl;
}
return s;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:39:13.880",
"Id": "83696",
"Score": "0",
"body": "What is the usecase for this? I have a suspicion that a custom container built on top of unordered_map might be more fitting. It seems rather odd to have a recursive map that never terminates. Have you considered a trie? I suspect it might fit what you're trying to do better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T01:58:33.393",
"Id": "83702",
"Score": "0",
"body": "My first use is minimax on some games. As to the recursion, it terminates when an unordered_map is empty."
}
] | [
{
"body": "<p>At least as it stands right now, quite a bit of your code accomplishes nothing.</p>\n\n<pre><code>template<typename T, typename H>\nclass tree;\n\ntemplate<typename T, typename H>\nclass tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };\n</code></pre>\n\n<p>When the declaration immediately precedes the definition like this, the declaration isn't really accomplishing anything--the definition by itself will do the same, so we can consolidate this down to just:</p>\n\n<pre><code>template<typename T, typename H>\nclass tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };\n</code></pre>\n\n<p>Likewise, your declaration of the stream insertion operator:</p>\n\n<pre><code>template<typename T, typename H>\nstd::ostream& operator<<(std::ostream& s, const tree<T, H> &t);\n</code></pre>\n\n<p>...can be eliminated with no loss. For these declarations to be meaningful/helpful, you'd do something like putting them in a header, with the definitions in a separate file. For most purposes, the class definitions need to be in a header as well though, so the utility of the class declarations may be open to some question. There are cases such things are used (e.g., <code><iosfwd></code> contains just \"forward\" declarations of the iostreams classes) but they're not very widely used (e.g., when was the last time <em>you</em> wrote code that used <code>#include <iosfwd></code>?)</p>\n\n<p>Another obvious issue is that you're publicly deriving from a standard container. The standard containers aren't really intended to be used as base classes, so this usage is somewhat fragile. Public derivation means it's trivial to assign the address of Tree object to a pointer an unordered_map. If the object is destroyed this way, you get undefined behavior because the base class doesn't declare its dtor as virtual.</p>\n\n<pre><code>// Note that we don't have a cast or anything like that indicate that we're doing \n// something dangerous here.\nstd::unordered_map<T, H> *base = new Tree<T, H>;\n// ...\ndelete base; // undefined behavior here.\n</code></pre>\n\n<p>...and there's basically nothing you can do from inside the class to prevent a user from doing this--by using public inheritance, you've told the world (and the compiler) that this usage <em>should</em> be perfectly fine, so the compiler doesn't require an explicit cast to do the conversion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T01:16:07.437",
"Id": "84604",
"Score": "0",
"body": "Okay, I had assumed that I needed to declare the class and function to use them in a recursive fashion, but after testing I see it's not the case with gcc. \n\nTwo the second point I can see that it would be more useful to put a reasonable interface on tree<T, H>. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:29:45.150",
"Id": "48155",
"ParentId": "47752",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48155",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T23:36:40.163",
"Id": "47752",
"Score": "5",
"Tags": [
"c++",
"c++11",
"tree"
],
"Title": "Tree implementation for unordered keys"
} | 47752 |
<p>I'm making a simple Tetris clone and would like to know how's my code for the map and pieces. I'm using <code>x</code>, <code>y</code>, <code>x_before</code>, <code>y_before</code>, <code>t0</code>, <code>t1</code> to allow smooth movement.</p>
<p><strong>colors.h</strong></p>
<pre><code>#ifndef TETRIS_COLORS_H
#define TETRIS_COLORS_H
typedef enum {
DARK_CYAN, DARK_RED, DARK_BROWN, DARK_MAGENTA,
DARK_GRAY, DARK_GREEN, DARK_BLUE, WALL, EMPTY
} Color;
#endif
</code></pre>
<p><strong>pieces.h</strong></p>
<pre><code>#ifndef TETRIS_PIECES_H
#define TETRIS_PIECES_H
#include "colors.h"
#include "map.h"
#include "definitions.h"
#define PIECE_COUNT 7
#define PIECE_ROWS 4
#define PIECE_COLUMNS 4
#define PIECE_POINTS (PIECE_ROWS * PIECE_COLUMNS)
#define PIECE_BLOCKS_SIZE 4
typedef struct {
int n;
int matrix[4][16];
Color color;
int x;
int y;
int x_before;
int y_before;
unsigned int t0;
unsigned int t1;
} Piece;
void piece_rotate(Piece *piece);
void piece_rotate_backwards(Piece *piece);
void piece_random(Piece *dest);
void piece_new(Piece *piece);
void piece_draw(Map *map, Piece *piece);
int piece_valid_position(Map *map, Piece *piece);
#endif
</code></pre>
<p><strong>pieces.c</strong></p>
<pre><code>#include "pieces.h"
#include <stdlib.h>
#include <string.h>
Piece i = {0,
0, 0, 0, 0,
1, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 1, 0,
0, 0, 1, 0,
0, 0, 1, 0,
0, 0, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 1, 1,
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0
, DARK_CYAN, 0, 0, 0, 0, 0, 0};
Piece j = {0,
1, 0, 0, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 1, 0,
0, 0, 1, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
1, 1, 0, 0,
0, 0, 0, 0
, DARK_RED, 0, 0, 0, 0, 0, 0};
Piece l = {0,
0, 0, 1, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 1, 0,
1, 0, 0, 0,
0, 0, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
, DARK_BROWN, 0, 0, 0, 0, 0, 0};
Piece o = {0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
, DARK_MAGENTA, 0, 0, 0, 0, 0, 0};
Piece s = {0,
0, 1, 1, 0,
1, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 1, 0,
0, 0, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
1, 1, 0, 0,
0, 0, 0, 0,
1, 0, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
, DARK_GRAY, 0, 0, 0, 0, 0, 0};
Piece t = {0,
0, 1, 0, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 1, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 1, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
, DARK_GREEN, 0, 0, 0, 0, 0, 0};
Piece z = {0,
1, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 1, 0,
0, 1, 1, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 1, 0, 0,
1, 1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 0
, DARK_BLUE, 0, 0, 0, 0, 0, 0};
Piece *piece_list[PIECE_COUNT] = {&i, &j, &l, &o, &s, &t, &z};
void piece_rotate(Piece *piece)
{
piece->n = ++piece->n % 4;
}
void piece_rotate_backwards(Piece *piece)
{
piece->n = (--piece->n > -1) ? piece->n : 3;
}
void piece_random(Piece *dest)
{
memcpy(dest, piece_list[rand() % PIECE_COUNT], sizeof(Piece)-sizeof(int) * 4);
}
void piece_new(Piece *piece)
{
piece_random(piece);
piece->x_before = piece->x = 1 + (GAME_COLUMNS - 2 - PIECE_BLOCKS_SIZE) / 2;
piece->y_before = piece->y = 1;
piece->t0 = piece->t1 = 0;
}
void piece_draw(Map *map, Piece *piece)
{
for(int i = 0; i < PIECE_BLOCKS_SIZE * PIECE_BLOCKS_SIZE; ++i)
if(piece->matrix[piece->n][i])
map_draw_block( map,
piece->y + i / PIECE_BLOCKS_SIZE,
piece->x + i % PIECE_BLOCKS_SIZE,
piece->color );
}
int piece_valid_position(Map *map, Piece *piece)
{
for(int i = 0; i < PIECE_BLOCKS_SIZE * PIECE_BLOCKS_SIZE; ++i)
if(piece->matrix[piece->n][i])
if(map_block_at( map,
piece->y + i / PIECE_BLOCKS_SIZE,
piece->x + i % PIECE_BLOCKS_SIZE )
!= EMPTY)
return 0;
return 1;
}
</code></pre>
<p><strong>map.h</strong></p>
<pre><code>#ifndef TETRIS_MAP_H
#define TETRIS_MAP_H
#include "colors.h"
typedef struct Map {
Color *blocks;
int rows;
int columns;
} Map;
Map *map_create(int rows, int columns);
void map_delete(Map *map);
void map_clear(Map *map);
void map_add_wall(Map *map);
Color map_block_at(Map *map, int row, int column);
void map_draw_block(Map *map, int row, int column, Color block);
void map_clear_row(Map *map, int row);
void move_rows_down(Map *map, int bottom_y);
#endif
</code></pre>
<p><strong>map.c</strong></p>
<pre><code>#include "map.h"
#include <stdlib.h>
Map *map_create(int new_rows, int new_columns)
{
Map *map = malloc(sizeof(Map) + sizeof(Color) * new_rows * new_columns);
if(map == NULL)
return NULL;
map->blocks = (Color *)(map + 1);
map->rows = new_rows;
map->columns = new_columns;
return map;
}
void map_delete(Map *map)
{
free(map);
}
void map_clear(Map *map)
{
for(int i = 0; i < map->rows * map->columns; ++i)
map->blocks[i] = EMPTY;
}
void map_add_wall(Map *map)
{
//Top
for(int i = 0; i < map->columns; ++i)
map->blocks[i] = WALL;
//Bottom
for(int i = 0; i < map->columns; ++i)
map->blocks[(map->rows -1) * map->columns + i] = WALL;
//Left and right
for(int i = 1; i < map->rows; ++i){
map->blocks[i * map->columns - 1] = WALL;
map->blocks[i * map->columns] = WALL;
}
}
Color map_block_at(Map *map, int row, int column)
{
return map->blocks[row * map->columns + column];
}
void map_draw_block(Map *map, int row, int column, Color block)
{
map->blocks[row * map->columns + column] = block;
}
void map_clear_row(Map *map, int row)
{
for(int x = 1; x < map->columns - 1; ++x)
map->blocks[row * map->columns + x] = EMPTY;
}
void move_rows_down(Map *map, int bottom_y)
{
for(int y = bottom_y; y > 1; --y)
for(int x = 1; x < map->columns - 1; ++x)
map_draw_block(map, y, x, map_block_at(map, y - 1, x));
map_clear_row(map, 1);
}
</code></pre>
| [] | [
{
"body": "<p>Overall this looks very nice. It's easy to read, and is very refined. A few notes:</p>\n\n<ul>\n<li><p>You can remove the <code>Map</code> from the first line of your structure.</p>\n\n<pre><code>typedef struct\n{\n Color *blocks;\n int rows;\n int columns;\n} Map;\n</code></pre></li>\n<li><p>Your function <code>map_delete()</code> only performs one action, freeing the memory of <code>map</code>. Unless you plan to expand on the <code>map</code> structure where you will have to free more members within the structure itself, I would get rid of it and just call <code>free(map)</code>. If you have compiler optimizations on, I guarantee that your compiler is already doing that for you anyways, so it should slightly decrease compilation time.</p></li>\n<li><p>You can simpilfy your <code>NULL</code> tests.</p>\n\n<pre><code>if(!map)\n</code></pre></li>\n<li><p>This is more of a style issue, but since this recently led to the <a href=\"http://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"nofollow noreferrer\">Apple <code>goto</code> security flaw</a>, I'm going to cover it. I don't think you are writing your brace-free single statement loops and test conditionals correctly. This is completely up to you to decide since <a href=\"https://softwareengineering.stackexchange.com/a/16530/94014\">this is a style issue</a>, but I prefer to do it like this:</p>\n\n<pre><code>if(!map) return NULL;\n</code></pre>\n\n<p>Other's may be more strict and tell you to use braces, but it's up to you. </p></li>\n<li><p>You need more comments. There are some lines in your code that I have trouble following. And if I have trouble following it, chances are that you will have trouble following it as well when you re-visit this project in a few months. Save yourself (and possibly others) the trouble and document your code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:33:47.983",
"Id": "47803",
"ParentId": "47754",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:10:46.857",
"Id": "47754",
"Score": "7",
"Tags": [
"c",
"game",
"tetris"
],
"Title": "Tetris code for pieces and map"
} | 47754 |
<pre><code>public void fizzbuzz(int count, int max, String fizzer) {
fizzer += (count % 3 == 0) ? "fizz":"";
fizzer += (count % 5 == 0) ? "buzz":"";
fizzer += (count % 3 != 0 && count % 5 != 0) ? count:"";
if (count != max) {
fizzer += "\n";
fizzbuzz(count+1,max,fizzer);
} else {
System.out.println(fizzer);
}
}
fizzbuzz(1,30,"");
</code></pre>
<p>The code is performing fizzbuzz over the range <code>count</code> to <code>max</code>. No variables are initialized within the method.</p>
<p>I'd love to get rid of <code>max</code>, and instead take only two arguments for the method (<code>String fizzer</code> and <code>int count</code>), but how can I? I can do it backwards (i.e. working down until reaching the trivial case <code>count == 0</code> and then stop), but is there a way to go from <code>1</code> to <code>n</code> with only one argument?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:32:29.547",
"Id": "83694",
"Score": "2",
"body": "Is there a requirement that it has to be recursive? Otherwise that is what I would first get rid of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:34:23.127",
"Id": "83695",
"Score": "0",
"body": "Sure, if you keep state variables around in a layer above the method scope (aka: instance variables) but that's really just putting them elsewhere instead of the method signature."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T05:01:54.930",
"Id": "83708",
"Score": "2",
"body": "Advice to reviewers: This being Code Review, answers of the form \"this is how you could solve FizzBuzz instead: _code_\" are insufficient. Your answer must have some bearing on the code in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T08:06:55.483",
"Id": "83724",
"Score": "3",
"body": "Use a `StringBuilder` rather than a `String`. Concatenation is evil. Also combining logic and printing is a big no-no - return the `StringBuilder` and print elsewhere."
}
] | [
{
"body": "<p><code>fizzer</code> and <code>max</code> don't change: instead they could both be member data of the class (passed to the class constructor).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:34:14.313",
"Id": "47757",
"ParentId": "47755",
"Score": "5"
}
},
{
"body": "<p>A wild suggestion, count the number of <code>\\n</code> in your output <code>String</code> and use that to determine when to exit the recursion!</p>\n\n<p>Also, I'll implement the <code>fizzbuzz</code> in one <code>if-else-if</code> block statement instead of three ternary statements, the main reason being that I don't have to append empty <code>Strings</code>. This may be just me though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T01:15:28.587",
"Id": "47760",
"ParentId": "47755",
"Score": "4"
}
},
{
"body": "<p>Recursion is usually not a favoured strategy in Java due to concerns about stack overflow and function call efficiency. However, we can still review FizzBuzz as an exercise in recursive programming.</p>\n\n<p>The first observation I have is that recursive solutions usually start by <strong>checking for the base case first.</strong> I recommend that you stick to that pattern. As a bonus, checking for <code>count > max</code> will prevent infinite recursion if the function is accidentally called with the <code>count</code> and <code>max</code> parameters reversed.</p>\n\n<p>Another typical feature of recursive solutions is that they <strong>avoid mutation and reassignment.</strong> When you recurse, previous values of your variables will already be kept on the stack for you, and that is generally sufficient to solve most problems. In your case, you've used <code>+=</code>, whereas you should be able to use just <code>+</code>.</p>\n\n<p>You've used three ternary conditionals. If you reorder them, you can avoid concatenating <code>+= \"fizz\"</code> followed by <code>+= \"buzz\"</code>.</p>\n\n<p>Since this is a pure function, it should probably be declared <code>static</code>, so that you don't have to instantiate an object just to call the code.</p>\n\n<p>Finally, note that the resulting string is already terminated by <code>\\n</code>, so perhaps you should call <code>System.out.print()</code> rather than <code>.println()</code>.</p>\n\n<pre><code>public void fizzbuzz(int count, int max, String accumulator) {\n // Check for the base case\n if (count > max) {\n System.out.print(accumulator);\n return;\n }\n\n // ... then proceed to the recursive cases.\n //\n // The first case below would be better written as (count % 15 == 0),\n // but I've kept it as (count % 3 == 0 && count % 5 == 0) for easier\n // comparison with your original code.\n String fizzer = (count % 3 == 0 && count % 5 == 0) ? \"fizzbuzz\\n\" :\n (count % 3 == 0) ? \"fizz\\n\" :\n (count % 5 == 0) ? \"buzz\\n\" : count + \"\\n\";\n fizzbuzz(count + 1, max, accumulator + fizzer);\n}\n</code></pre>\n\n<hr>\n\n<p>You asked about reducing the number of parameters. The first parameter I would eliminate is not <code>count</code> or <code>max</code>, but the accumulator. You could change it into a return value instead, and it would be more natural. The caller would have to be responsible for printing the result — and I would also consider that an improvement, since it keeps the calculation and the output routines separate.</p>\n\n<pre><code>public static String fizzbuzz(int count, int max) {\n if (count > max) {\n return \"\";\n }\n String fizzer = (count % 15 == 0) ? \"fizzbuzz\\n\" :\n (count % 3 == 0) ? \"fizz\\n\" :\n (count % 5 == 0) ? \"buzz\\n\" :\n count + \"\\n\";\n return fizzer + fizzbuzz(count + 1, max);\n}\n\npublic static void main(String[] args) {\n System.out.print(fizzbuzz(1, 30));\n}\n</code></pre>\n\n<hr>\n\n<p>Once you've done that, you can eliminate one more parameter by making it left-recursive instead of right-recursive.</p>\n\n<pre><code>public static String fizzbuzz(int n) {\n if (n <= 0) {\n return \"\";\n }\n String fizzer = (n % 15 == 0) ? \"fizzbuzz\\n\" :\n (n % 3 == 0) ? \"fizz\\n\" :\n (n % 5 == 0) ? \"buzz\\n\" :\n n + \"\\n\";\n return fizzbuzz(n - 1) + fizzer;\n}\n\npublic static void main(String[] args) {\n System.out.print(fizzbuzz(30));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:50:25.933",
"Id": "83756",
"Score": "0",
"body": "That String hurts me nearly as much as the recursion does. You'd be returning a new String that is just a bit longer than the last each time you returned. Have you considered a StringBuilder to not create a large set of String objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:25:55.653",
"Id": "83764",
"Score": "0",
"body": "What is `count` in the last code block?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:10:51.083",
"Id": "83777",
"Score": "0",
"body": "@MichaelT Since this is an exercise in recursive programming, I'm aiming for elegance rather than performance. You might want to submit an answer based on `StringBuilder`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:45:08.210",
"Id": "86351",
"Score": "0",
"body": "I've edited my question to include some code. Would something like that break convention of having a trivial case check at the top of a method? It's still done first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T16:19:33.487",
"Id": "86379",
"Score": "0",
"body": "Post rolled back — see http://meta.codereview.stackexchange.com/q/1763."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T04:30:59.877",
"Id": "47762",
"ParentId": "47755",
"Score": "16"
}
},
{
"body": "<p>The aspect of \"an exercise in writing a <em>recursive</em> fizzbzz\" has already been addressed in other answers. There are issues with this in Java (stack frames) that make it a less than ideal option for the language.</p>\n\n<p>Another issue that comes up is the <code>String</code>. Since <code>String</code> is an immutable, each time one is modified a new <code>String</code> is instantiated.</p>\n\n<p>From:</p>\n\n<pre><code>public void fizzbuzz(int count, int max, String fizzer) {\n fizzer += (count % 3 == 0) ? \"fizz\":\"\";\n fizzer += (count % 5 == 0) ? \"buzz\":\"\";\n fizzer += (count % 3 != 0 && count % 5 != 0) ? count:\"\";\n ...\n}\n</code></pre>\n\n<p>This will instantiate a three new strings, which are then thrown away as a new one is created. Furthermore, this string keeps on growing. With a sufficiently long fizzbuzz (or other recursive call) you will be creating and discarding an inordinate number of ever increasing length Strings.</p>\n\n<p>Instead of using an immutable String (yes, immutability is nice and one of the ideals of functional programming), consider working with a <code>StringBuilder</code> instead:</p>\n\n<pre><code>public void fizzbuzz(int count, int max, StringBuilder fizzer) {\n fizzer.insert('\\n');\n fizzer.insert(0, (count % 5 == 0) ? \"buzz\":\"\");\n fizzer.insert(0, (count % 3 == 0) ? \"fizz\":\"\");\n if (count % 3 != 0 && count % 5 != 0) {\n fizzer.insert(0, count);\n // insert(0, true ? 2 : \"\") has mixed types (int, String) - doesn't work\n }\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>Note that this is going to suffer from poor performance because of the O(N) <code>.insert</code> call (it has to shift the entire array that backs the StringBuilder). Over the entire range, this becomes O(N<sup>2</sup>). Looking at the <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.insert%28int%2Cjava.lang.String%29\" rel=\"noreferrer\">code for insert</a>, though, this isn't going to suffer from an excess of objects (just that painful <code>System.arraycopy</code>).</p>\n\n<p>One may wish to instead use a LinkedList which allows for O(1) insert and put each element in the list, and have the initial invocation then walk the list and print everything out in the proper order.</p>\n\n<p><sup><sub>As an aside, if you do want to play with recursive FizzBuzz in a Javaish environment, consider a nice Clojure or Scala approach which would play a bit nicer with recursion</sub></sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:54:56.813",
"Id": "83808",
"Score": "0",
"body": "If you're going to fuss about string instances, perhaps it's better to avoid adding `\"\"` unnecessarily?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:00:30.267",
"Id": "83811",
"Score": "0",
"body": "@ChrisW The strings defined at compile time are interned - they're not recreated each loop (neither are the \"buzz\" or \"fizz\"). Additionally, the insert call won't (shouldn't) do anything if passed value is zero length. I was attempting to keep as much of the original code structure as possible. a `null` isn't zero length in StringBuilder (it becomes `\"null\"`). That said, it would be trivial to move the ternary to an if statement - it was only necessary for one of them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:18:10.573",
"Id": "47809",
"ParentId": "47755",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47762",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:25:36.327",
"Id": "47755",
"Score": "12",
"Tags": [
"java",
"optimization",
"recursion",
"fizzbuzz"
],
"Title": "Short Java FizzBuzz using recursion and parameters"
} | 47755 |
<p>There are n balls kept on a table and connected by same singe connected string (which can be cyclic or maynot). Write the code to select a ball such that after lifting the whole structure from that ball height will be minimum. (algo+code+ mathematical proof of correctness)</p>
<p>Note, I do understand merits of unit testing in separate files. But deliberately added it to main method for personal convenience, so request you don’t consider that in your feedback.
Looking for request code review, optimizations and best practices and complexity verification.</p>
<ul>
<li>Complexity:</li>
<li>O(EV) - time complexity</li>
<li>O(V) - space complexity </li>
</ul>
<p> </p>
<pre><code>class GraphLiftBall<T> implements Iterable<T> {
/* A map from nodes in the graph to sets of outgoing edges. Each
* set of edges is represented by a map from edges to doubles.
*/
private final Map<T, List<T>> graph = new HashMap<T, List<T>>();
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(T node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new ArrayList<T>());
return true;
}
/**
* Given the source and destination node it would add an arc from source
* to destination node. If an arc already exists then the value would be
* updated the new value.
*
* @param source the source node.
* @param destination the destination node.
* @param length if length if
* @throws NullPointerException if source or destination is null.
* @throws NoSuchElementException if either source of destination does not exists.
*/
public void addEdge (T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
/* A node would always be added so no point returning true or false */
graph.get(source).add(destination);
graph.get(destination).add(source);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public List<T> edgesFrom(T node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
List<T> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableList(graph.get(node));
}
/**
* Returns the iterator that travels the nodes of a graph.
*
* @return an iterator that travels the nodes of a graph.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
final class BallPick<T> {
private final T ballId;
private final int depth;
BallPick (T ballId, int depth) {
this.ballId = ballId;
this.depth = depth;
}
public T getBallId() {
return ballId;
}
public int getDepth() {
return depth;
}
@Override
public String toString() {
return "BallPick [ballId=" + ballId + ", depth=" + depth + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ballId == null) ? 0 : ballId.hashCode());
result = prime * result + depth;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BallPick other = (BallPick) obj;
if (ballId == null) {
if (other.ballId != null)
return false;
} else if (!ballId.equals(other.ballId))
return false;
if (depth != other.depth)
return false;
return true;
}
}
public final class LiftBall<T> {
/**
* Returns the ball, which when picked, the distance/height/depth from the picked ball to
* last ball on the surface would be minimal.
* If two balls would result in the same height, eg: an isoceles triangle, then any ball would be valid answer
*
* @param graph - the graph, which represents balls connected by a string.
* @return - the ball which results in minimal height.
*/
public static <T> BallPick<T> leastMemory(GraphLiftBall<T> graph) {
final Iterator<T> itr = graph.iterator();
BallPick<T> ballPick = null;
int minValue = Integer.MAX_VALUE;
while (itr.hasNext()) {
T currNode = itr.next();
int val = bfs(currNode, graph);
if (val < minValue) {
minValue = val;
ballPick = new BallPick<T>(currNode, minValue);
}
}
return ballPick;
}
private static <T> int bfs(T node, GraphLiftBall<T> graph) {
Queue<T> thisLevel = new LinkedList<T>();
Queue<T> nextLevel = new LinkedList<T>();
final Set<T> visited = new HashSet<T>();
visited.add(node);
thisLevel.add(node);
int depth = -1;
while (!thisLevel.isEmpty()) {
T currNode = thisLevel.poll();
for(T neighbor : graph.edgesFrom(currNode)) {
if (!visited.contains(neighbor)) {
nextLevel.add(neighbor);
visited.add(neighbor);
}
}
if (thisLevel.isEmpty()) {
thisLevel = nextLevel;
nextLevel = new LinkedList<T>();
depth++;
}
}
return depth;
}
public static void main(String[] args) {
// A straight line of 3 balls 1 - 2 - 3, picking ball 2 would result in shortest depth.
GraphLiftBall<Integer> graphLiftBall1 = new GraphLiftBall<Integer>();
graphLiftBall1.addNode(1);
graphLiftBall1.addNode(2);
graphLiftBall1.addNode(3);
graphLiftBall1.addEdge(1, 2);
graphLiftBall1.addEdge(2, 3);
assertEquals(new BallPick<Integer>(2, 1), LiftBall.leastMemory(graphLiftBall1));
// A triangle of 3 balls
GraphLiftBall<Integer> graphLiftBall2 = new GraphLiftBall<Integer>();
graphLiftBall2.addNode(1);
graphLiftBall2.addNode(2);
graphLiftBall2.addNode(3);
graphLiftBall2.addEdge(1, 2);
graphLiftBall2.addEdge(2, 3);
graphLiftBall2.addEdge(3, 1);
assertEquals(new BallPick<Integer>(1, 1), LiftBall.leastMemory(graphLiftBall2));
// A square of 4 balls
GraphLiftBall<Integer> graphLiftBall3 = new GraphLiftBall<Integer>();
graphLiftBall3.addNode(1);
graphLiftBall3.addNode(2);
graphLiftBall3.addNode(3);
graphLiftBall3.addNode(4);
graphLiftBall3.addEdge(1, 2);
graphLiftBall3.addEdge(2, 3);
graphLiftBall3.addEdge(3, 4);
graphLiftBall3.addEdge(4, 1);
assertEquals(new BallPick<Integer>(1, 2), LiftBall.leastMemory(graphLiftBall3));
// A pyramid of 5 balls
GraphLiftBall<Integer> graphLiftBall4 = new GraphLiftBall<Integer>();
graphLiftBall4.addNode(1);
graphLiftBall4.addNode(2);
graphLiftBall4.addNode(3);
graphLiftBall4.addNode(4);
graphLiftBall4.addNode(5);
graphLiftBall4.addEdge(1, 2);
graphLiftBall4.addEdge(2, 3);
graphLiftBall4.addEdge(3, 4);
graphLiftBall4.addEdge(4, 1);
graphLiftBall4.addEdge(5, 1);
graphLiftBall4.addEdge(5, 2);
graphLiftBall4.addEdge(5, 3);
graphLiftBall4.addEdge(5, 4);
assertEquals(new BallPick<Integer>(5, 1), LiftBall.leastMemory(graphLiftBall4));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T02:05:34.883",
"Id": "83703",
"Score": "4",
"body": "What is E and what is V in your complexity comments?"
}
] | [
{
"body": "<p>Your assignment sounds like the <a href=\"http://en.wikipedia.org/wiki/Travelling_salesman_problem\" rel=\"nofollow\">traveling salesman problem (TSP)</a>.</p>\n\n<p>If you're looking for the exact shortest path, you have to pretty much brute force the answer, since TSP is NP-hard problem.</p>\n\n<p>If near optimal path is acceptable to you I suggest you look into genetic algorithms or ant colony system. The best algorithm really depends on acceptable error and ball count.</p>\n\n<p>(I would've added comment, but I can't for the lack of points)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T10:45:48.927",
"Id": "48968",
"ParentId": "47758",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:39:24.127",
"Id": "47758",
"Score": "2",
"Tags": [
"java",
"algorithm",
"graph"
],
"Title": "Lift ball which leads to shortest height"
} | 47758 |
<p>I'm reading <a href="http://freespace.virgin.net/hugo.elias/models/m_perlin.htm" rel="nofollow">this tutorial</a> and it's the first time I try something this new.</p>
<p>Here is my attempt:</p>
<pre><code>import sys
import math
import pygame
import random
pygame.init()
windowwidth, windowheight = 900, 500
windowsurface = pygame.display.set_mode((windowwidth, windowheight), 0, 32)
clock = pygame.time.Clock()
fps = 30
MAX_INT = (1<<31) - 1
grey = (128, 128, 128)
def linear_interpolate(a, b, x):
return a*(1-x) + b*x
def int_noise(x):
# I'm pretty sure I can use random.uniform(-1, 1) as I need a value in the range (-1, 1)
# I just saw this function on SO that is said to be faster that the build-in.
x = int(x)
x = ((x << 13) & MAX_INT) ^ x
x = ( x * (x * x * 15731 + 789221) + 1376312589 ) & MAX_INT
return 1.0 - x / 1073741824.0
def smooth_noise(x):
return int_noise(x)/2 + int_noise(x-1)/4 + int_noise(x+1)/4
def noise_interpolate(x):
int_x = int(x)
fractional_x = x - int_x
v1 = smooth_noise(int_x)
v2 = smooth_noise(int_x+1)
return linear_interpolate(v1, v2, fractional_x)
def perlin_noise(x):
total = 0
persistence = 1/4
octaves = 10
for i in range(octaves):
frequency = pow(2, i)
amplitude = pow(persistence, i)
total = total + noise_interpolate(x*frequency) * amplitude
return total
#---------------------------------------------------------------------------
def mainloop():
scale = 50
points = [(i, perlin_noise(0.6*i) * scale)
for i in range(0, windowwidth, 10)]
points.append((900, perlin_noise(0.5)))
while True:
clock.tick(fps)
pygame.display.set_caption('fps: %.2f' % clock.get_fps())
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# update game state
# draw
for i in range(len(points) - 1):
pygame.draw.line(windowsurface, grey,
(points[i][0], 350+points[i][1]),
(points[i+1][0], 350+points[i+1][1]), 1)
pygame.display.update()
if __name__ == '__main__':
mainloop()
</code></pre>
<p>I know the design is awful, but I'm more concerned if it is the correct way to write all this. From interpolating function, to the smoothing function, all the way to perlin.</p>
<p>I have the feeling that this Perlin noise function is completely wrong and very misleading, regardless the fact that I draw the wave onto the screen.</p>
| [] | [
{
"body": "<p>To begin with, you <em>cannot</em> use <code>random.uniform()</code> in your current design. The tutorial specifically emphasize that the noise function shall be seeded, that is, for the same argument it shall always return the same result.</p>\n\n<p>Second, the tutorial suggests that each octave must have its own noise generator. I believe it is essential (again, the noise it seeded, so you'd get literally the same noise for each octave).</p>\n\n<p>You can get away with <code>random.uniform()</code> by calculating noise tables (one per octave), and use them as noise functions. In fact, I'd recommend this approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:57:06.963",
"Id": "47820",
"ParentId": "47759",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T00:53:27.527",
"Id": "47759",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"pygame"
],
"Title": "Write and control Perlin noise for 1D"
} | 47759 |
<p>I am a beginner and I have made Login Form in HTML. I'm pretty sure it will look horrible to any developer, but hey, that's why I've posted it.</p>
<p>I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:13:58.597",
"Id": "83731",
"Score": "0",
"body": "Since username and password fields are mandatory so you can mark these fields as required. <input type=\"text\" id=\"username\" name=\"username\" required>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:14:50.860",
"Id": "83732",
"Score": "0",
"body": "I don't think the `required` attribute is a thing in XHTML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:40:49.713",
"Id": "83735",
"Score": "0",
"body": "Great Question!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:52:01.417",
"Id": "83736",
"Score": "0",
"body": "@ThomWiggers HTML 5 supports this attribute. http://www.w3schools.com/tags/att_input_required.asp"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T12:01:58.453",
"Id": "83740",
"Score": "1",
"body": "@Sandeep I know, but he's using XHTML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T12:19:13.907",
"Id": "83744",
"Score": "0",
"body": "My bad..I didn't notice that.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T14:32:18.197",
"Id": "83752",
"Score": "3",
"body": "As @paul [mentioned](http://codereview.stackexchange.com/a/47782/41042) below: Use HTML5. This means use `<!DOCTYPE html>` instead of what you have right now in your `doctype` declaration. [Reference](http://www.w3schools.com/tags/tag_doctype.asp)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T01:24:25.043",
"Id": "83860",
"Score": "0",
"body": "Note that `required` could be removed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:22:35.510",
"Id": "83941",
"Score": "0",
"body": "Don't all `<input>` tags need to be closed? Like `<input type=\"text\" id=\"username\" name=\"username\"/>` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:47:08.050",
"Id": "83979",
"Score": "0",
"body": "@SNag depends on the doctype he is using. For the current doctype, this is valid. If she switches to HTML5 then yes, you are correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:44:21.080",
"Id": "83999",
"Score": "0",
"body": "@stackErr: Thanks! I wasn't aware of validity dependency on doctype. Good to know!"
}
] | [
{
"body": "<p>Security-wise, you need to make sure you a) never trust the user and b) never trust the user.</p>\n\n<p>You should realise that anyone has access to the <code>GET</code> parameters, lines like </p>\n\n<pre><code><?php echo @$_GET['msg'];?>\n</code></pre>\n\n<p>should thus be avoided. Always call <code>htmlspecialchars()</code> on stuff you get from users etc when printing output. Otherwise I could craft an URL like <code>http://yourwebsite/form.php?msg=<script>alert(\"lololol\");</script></code> and inject arbitrary javascript on your webpages. It's quite easy to trick someone into clicking such a link, making them run my code in their session. </p>\n\n<p>People often find using error suppression (<code>@</code>) bad style, by the way. It's also quite slow.</p>\n\n<p>Also, you need to make sure your form isn't vulnerable to <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\" rel=\"nofollow\">CSRF attacks</a>. Protecting against this is usually done by adding a one-time, per request randomly generated token to your form. This topic is too big to cover here, so I'd ask Google. <a href=\"https://www.owasp.org/\" rel=\"nofollow\">OWASP</a> is generally a great resource for website security.</p>\n\n<p>HTML-wise, you should pay attention that you are writing XHTML, going by your <code>DOCTYPE</code>. That means you should take care to write valid XML. In XML you need to close every tag. You also need to close tags which only have an 'open' tag, like <code><img></code>, <code><br></code> and <code><input></code>. This is done by adding a forward slash (<code>/</code>) before the closing <code>></code>. So <code><input></code> needs to be <code><input /></code> in XHTML.</p>\n\n<p>If you want your form fields to actually submit results, make sure that they all have a <code>name</code> attribute. The checkbox currently doesn't.</p>\n\n<p>Lastly you're using <code><label></code> tags quite nicely. You should however note that <code>for</code> needs to reference an <code>id</code> of an <code><input></code> tag, so the <code><label></code> for the checkbox doesn' reference the correct field.</p>\n\n<p>I'm not quite a CSS wizard so I'll leave that up to someone else, but it looks pretty decent.</p>\n\n<p>Overall, once you fix these minor bugs, it's a better form than many I've seen in the wild :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T22:34:10.737",
"Id": "83847",
"Score": "0",
"body": "`htmlentities()` is overkill for most purposes, `htmlspecialchars()` gets the job done well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:10:36.930",
"Id": "83902",
"Score": "0",
"body": "@bjb568 I always forget which one to use :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:23:42.533",
"Id": "47774",
"ParentId": "47771",
"Score": "13"
}
},
{
"body": "<p>I'm not an expert on HTML, but I am quite decent in using it and can give you the following pieces of advice:</p>\n\n<ol>\n<li><p>Seperate the CSS from your HTML page, it is already good that you have seperated (most) CSS of the HTML elements, but you want to use an <em>external style sheet</em>, and include that in your page. This makes both parts more clear (tip: Do try to not mix programming languages) and allows you to reuse the stylesheet on multiple pages easily.</p></li>\n<li><p>Use <code>class</code> tags where they are applicable. The <code>class</code> tags can be reused and should be used multiple times generally, while the <code>id</code> tags are for unique elements. This means that <code><div id=\"container\"></code> and <code><div id=\"lower\"></code> should be a <code>class</code>, and not an <code>id</code>.</p></li>\n<li><p>Do not secretly sneak in some CSS in your HTML tags. You did it with your <code>loginmsg</code> label, you should give it an <code>id</code> field and reference that in your stylesheet.</p></li>\n<li><p>I would refrain from suppressing warning messages (the <code>@</code>) in PHP, they are usually there for a reason.</p></li>\n<li><p>You are (appereantly) sending the <code>msg</code>, which should appear in the <code>loginmsg</code> label, as a <em>GET</em> argument, thus you are receiving user input. In this case it is one that could easily be tampered with, <em>POST</em> arguments can also get tampered, but that is slightly more difficult.<br>\nYou should validate your input there, malicious attackers can try to inject javascript code into it, that will redirect someone to another (evil) page, as one of the examples.</p></li>\n</ol>\n\n<p>This is by no means a complete review, but it are all the points that I have spotted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T11:28:40.613",
"Id": "47776",
"ParentId": "47771",
"Score": "6"
}
},
{
"body": "<p>I'll only mention items not already addressed in other answers. Viewing the form in Firefox, I see this:<img src=\"https://i.stack.imgur.com/TUzWB.gif\" alt=\"enter image description here\"></p>\n\n<p>I've circled the odd extra space before the <code>Username:</code> label and drawn an arrow to show the missing bottom of the box. </p>\n\n<ol>\n<li><p>The extra space is what the user will see in the case that your PHP script doesn't return a message. One way to handle that would be to simply insert a <code><br/></code> tag between the two labels. </p></li>\n<li><p>The missing bottom of the box is due to the way you've sized the <code>container</code> in your CSS. It's a wee bit short.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:35:14.480",
"Id": "83781",
"Score": "0",
"body": "Actually, `<label for=\"loginmsg\">` shouldn't be a `label` at all, as there is no corresponding `<input id=\"loginmsg\">` form element. Furthermore, it should not be emitted at all if there is no message to display."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:07:28.887",
"Id": "47780",
"ParentId": "47771",
"Score": "5"
}
},
{
"body": "<p>This is one of those places where if you ask 10 developers the same question, you will get at least 15 answers, and they are all valid.</p>\n\n<p>My 2 cents:</p>\n\n<ul>\n<li><p>It's 2014. Use HTML5. </p></li>\n<li><p>Discover <a href=\"http://jsfiddle.net/\">jsfiddle.net</a> for this kind of thing.</p></li>\n<li><p>Put \"required\" on the username and password fields, it's free validation.</p></li>\n<li><p>There's nothing wrong with in-page CSS. I often mix sitewide and in-page as needed. For the purpose of this example, it works just fine. (This does NOT mean ignore CSS classes)</p></li>\n<li><p>Instead of <code>echo @$_GET['msg']</code> (and resulting security issues) try <code>echo $messages[$_GET['msg']]</code> where <code>$_GET['msg']</code> is a number. Define your messages server-side.</p></li>\n<li><p>Learn this pattern for unset variables: the ternary operator.</p>\n\n<pre><code>echo !empty($_GET['msg']) ? $messages[$_GET['msg']] : '' ;\n</code></pre></li>\n<li><p>The login message does not need a label (but it's not \"wrong\" to have it). incorporate the HTML in the stored message for cleaner output when there is no message</p></li>\n<li><p>Your checkbox needs both a <code>name=</code> and <code>value=</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T22:48:30.587",
"Id": "83849",
"Score": "0",
"body": "two questions: 1) what is the specific advantage(s) of HTML5 (in this case)? 2) Why not echo empty($_GET['msg']) ? '' : $messages[$_GET['msg']]; (without the negation)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:57:05.527",
"Id": "83890",
"Score": "1",
"body": "@ whoever edited my answer: it's simply \"required\", not class=\"required\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:59:12.503",
"Id": "83891",
"Score": "2",
"body": "@Rolazaro Azeveires: HTML5 does everything XHTML does, and more. Do you still use Windows 2000 or OSX Panther? Both were great in their day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T09:01:20.307",
"Id": "83892",
"Score": "1",
"body": "@Rolazaro Azeveires: There's absolutely nothing wrong with empty($_GET['msg']) ? '' : $messages[$_GET['msg']]; That's just part of the \"... 15 answers, and they are all valid\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:11:16.260",
"Id": "84106",
"Score": "0",
"body": "+99 for that reference about Win2K and OSX Panther. LOL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:34:12.883",
"Id": "84575",
"Score": "0",
"body": "@paul: Do you update just because? For no reason?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:57:02.603",
"Id": "47782",
"ParentId": "47771",
"Score": "17"
}
},
{
"body": "<p>I got width scroll bar window in my browser:</p>\n\n<pre><code>html, body {\n width: 100%;\n height: 100%;\n}\n</code></pre>\n\n<p>I am getting unnecessary scroll bars. Width and height are not needed, so please simply remove them from your CSS.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T09:44:59.203",
"Id": "47862",
"ParentId": "47771",
"Score": "1"
}
},
{
"body": "<p>Another thing:</p>\n\n<p>Wrap your checkbox within it's label, so that both the box and the \"Keep me logged in\" text are clickable and will de/activate the check. It's not essential, but it's good UX.</p>\n\n<pre><code><div id=\"lower\">\n <label class=\"check\" for=\"checkbox\"><input type=\"checkbox\"> Keep me logged in</label>\n <input type=\"submit\" value=\"Login\">\n</div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:24:41.490",
"Id": "83942",
"Score": "0",
"body": "Instead of wrapping the input in label, you could simply add an `id` for the input that matches the label's `for`.\n\n`<label class=\"check\" for=\"checkbox\">Keep me logged in</label><input type=\"checkbox\" id=\"checkbox\"/>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:43:50.087",
"Id": "84581",
"Score": "0",
"body": "Also, when wrapping an input *inside* a label, the `for` attribute can be omitted; use `for` only if you *don't* wrap the input inside a label. Both approaches are right (wrapping or `for`), just pick whatever fits your need."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:59:18.357",
"Id": "47870",
"ParentId": "47771",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T10:57:29.703",
"Id": "47771",
"Score": "22",
"Tags": [
"php",
"html",
"css",
"form",
"authentication"
],
"Title": "Login Form in HTML"
} | 47771 |
<p>I have implemented Insertion sort in Java. Please review it.</p>
<pre><code>public class InsertionSort {
public static void main(String[] args) {
int[] values = new int[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = Integer.parseInt(args[i]);
}
for (int i = 0; i < values.length; i++) {
if (i!=0 && values[i] < values[i - 1]) {
for (int j = i; j >= 1; j--) {
System.out.println(" j"+j);
if (values[j] < values[j-1]) {
int temp = values[j - 1];
values[j - 1] = values[j];
values[j] = temp;
} else {
break;
}
}
}
}
System.out.println(" sorted numbers");
for (int i = 0; i < values.length; i++) {
System.out.println(" "+values[i]);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Consider this:</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < values.length; i++) {\n if (i!=0 && values[i] < values[i - 1]) {\n</code></pre>\n</blockquote>\n\n<p><code>i</code> starts from 0, and then right after you use a condition <code>i!=0</code>. You could simplify to:</p>\n\n<pre><code>for (int i = 1; i < values.length; i++) {\n if (values[i] < values[i - 1]) {\n</code></pre>\n\n<hr>\n\n<p>Consider this:</p>\n\n<blockquote>\n<pre><code>if (values[i] < values[i - 1]) {\n for (int j = i; j >= 1; j--) {\n if (values[j] < values[j - 1]) {\n // ...\n } else break;\n</code></pre>\n</blockquote>\n\n<p>Notice that <code>j</code> starts from <code>i</code>, and you have the same <code>if</code> immediately inside the loop, otherwise break. In other words, you don't need that outer <code>if</code>, because you run the same thing immediately inside the loop.</p>\n\n<hr>\n\n<p>Consider this:</p>\n\n<blockquote>\n<pre><code>for (int j = i; j >= 1; j--) {\n if (values[j] < values[j - 1]) {\n ...\n } else break;\n</code></pre>\n</blockquote>\n\n<p>an equivalent but shorter and more traditional way to write the same thing:</p>\n\n<pre><code>for (int j = i; j >= 1 && values[j] < values[j - 1]; j--) {\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>Putting it all together:</p>\n\n<pre><code>for (int i = 1; i < values.length; i++) {\n for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {\n int temp = values[j - 1];\n values[j - 1] = values[j];\n values[j] = temp;\n }\n}\n</code></pre>\n\n<p>We have arrived at the <a href=\"http://en.wikipedia.org/wiki/Insertion_sort\">pseudo algorithm of insertion sort in wikipedia</a> ;-)</p>\n\n<hr>\n\n<p>I recommend using unit tests to check your implementations instead of printing text to the console and checking with your eyes. For example:</p>\n\n<pre><code>public Integer[] sort(Integer[] orig) {\n Integer[] values = orig.clone();\n for (int i = 1; i < values.length; i++) {\n for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {\n int temp = values[j - 1];\n values[j - 1] = values[j];\n values[j] = temp;\n }\n }\n return values;\n}\n\n@Test\npublic void testExamples() {\n Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 4, 3}));\n Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 3, 4}));\n Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{3, 5, 4}));\n}\n</code></pre>\n\n<p>Running this is just as easy as running a main method. This approach also encourages decomposing your problems to elementary operations. In this case I had to extract the sorting logic to its own method to be easier to test. In the end, you will naturally have multiple methods, which is a good thing, at virtually no extra cost.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:59:11.377",
"Id": "47796",
"ParentId": "47779",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T13:03:08.363",
"Id": "47779",
"Score": "4",
"Tags": [
"java",
"optimization",
"sorting",
"insertion-sort"
],
"Title": "Insertion Sort implementation in Java"
} | 47779 |
<p>This is my code for reading a file with a delimiter. Any suggestions to help improve my code efficiency?</p>
<p>I am not satisfied with using array data structure. Can any other data structure be used instead of an array?</p>
<pre><code>bool read_file(char *p_file_name,char *file_content[FILE_NO_OF_ROWS][FILE_NO_OF_COL],const char *delimiter, int& token_count )
{
using namespace std;
ifstream file_is_obj;
file_is_obj.open(p_file_name,ios::in);
string buffer,token;
int token_pos;
token_count=0;
if( file_is_obj.is_open())
{
while( !file_is_obj.eof() )
{
if(token_count >= FILE_NO_OF_ROWS)
{
break;
}
buffer.clear();
token_pos=0;
std::getline(file_is_obj,buffer);
for( int iter=0; token_pos != -1 || iter >= FILE_NO_OF_COL ; iter++)
{
token.clear();
token_pos=buffer.find(delimiter,0);
token=buffer.substr(0,token_pos);
if( !token.empty() )
{
buffer.erase(0,token_pos+strlen(delimiter));
file_content[token_count][iter] = new char[token.length()+1] ;
memset(file_content[token_count][iter],'\0',(token.length()+1)*sizeof(char));
token.copy( file_content[token_count][iter], token.length(), 0);
}
}
token_count++;
}
token_count-=1; // Token incremented for reading end of file
}
else
{
printf("\nFile not found (or) Error in opening the file");
return false;
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:51:03.840",
"Id": "83757",
"Score": "3",
"body": "Since your delimiter is a char have you tried using the delimiter overload for getline, `std::getline(file_is_obj,buffer,delimiter);`, to return the string up to but not including the delimiter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:09:35.590",
"Id": "83831",
"Score": "0",
"body": "Which if the data is in a consistent format still reduces the code considerably"
}
] | [
{
"body": "<p>Some comments:</p>\n\n<ol>\n<li>Use <code>std::vector</code> instead of an inflexible array. You're writing in C++, so you really ought to use the power of that language to write better code.</li>\n<li>Don't use <code>memset</code>. It's generally wise to avoid mixing old-style C library functions such as <code>memset</code>, <code>malloc</code> and so forth, with C++. Strange things can happen and there's usually a better C++ way to do things without those.</li>\n<li>Instead of using <code>string.find</code>, consider using other techniques such as <a href=\"http://www.cplusplus.com/faq/sequences/strings/split/\" rel=\"nofollow noreferrer\">the ones described here</a> to split a line into its constituent pieces.</li>\n<li>Rather than printing an error message, <code>throw</code> an exception. That way your code can be reused in situtations in which <code>std::cout</code> is not present or not visible.</li>\n<li>Do <strong>NOT</strong> embed <code>using namespace std;</code> into code like that! It's extremely <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice</a></li>\n</ol>\n\n<p><strong>EDIT:</strong>\nHere's a quick alternative using a variation of the string <code>split</code> I pointed to in point #3.</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\ntemplate <typename Container>\nContainer& split(Container& result,\n const typename Container::value_type& s,\n const typename Container::value_type& delimiters)\n{\n result.clear();\n size_t current;\n size_t next = -1;\n do {\n current = next + 1;\n next = s.find_first_of( delimiters, current );\n result.push_back( s.substr( current, next - current ) );\n } while (next != Container::value_type::npos);\n return result;\n}\n\nint main(int argc, char *argv[])\n{\n if (argc < 2) {\n std::cout << \"Usage readarray filename\\n\";\n return 0;\n }\n const std::string delimiter{\",\"};\n std::vector<std::vector<std::string> > v;\n // fetch the file into v\n std::string line;\n std::vector<std::string> fields;\n for( std::ifstream in(argv[1]); std::getline(in, line); ) {\n v.push_back(split(fields, line, delimiter));\n }\n // now print the results\n for (const auto &i : v) {\n for (const auto &j: i)\n std::cout << \"[\" << j << \"]\";\n std::cout << '\\n';\n }\n}\n</code></pre>\n\n<p>This uses C++11, but could easily be adapted for old compilers. Based on this input file:</p>\n\n<pre><code>alpha,frank,ruby,diamond\nbeta,joseph,emerald,circle\ngamma,may,onyx,triangle\n</code></pre>\n\n<p>The code produces this output:</p>\n\n<pre><code>[alpha][frank][ruby][diamond]\n[beta][joseph][emerald][circle]\n[gamma][may][onyx][triangle]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:40:04.707",
"Id": "83820",
"Score": "0",
"body": "1) When printing, use `const auto`. 2) Returning 0 means that the execution went fine. Instead, any other value > 0 means unsuccessful execution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:20:05.557",
"Id": "83832",
"Score": "0",
"body": "@Edward is there a reason for using `good()` instead of an implicit `bool` conversion? I know the semantics are a tiny bit different, but I'm fairly certain there would not be a difference in functionality here. Just curious if there's something I'm missing :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:25:31.223",
"Id": "83834",
"Score": "0",
"body": "@Corbin: The only reason is the tiny bit of semantic difference you note: `good()` is false if `eofbit` is set, but the `bool` conversion still returns `true` if `eofbit` is set but not `badbit` or `failbit`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:29:22.490",
"Id": "83837",
"Score": "0",
"body": "@Edward Right, but in this situation, I don't think that will happen. `std::getline` fails on EOF, so I think the only thing that would happen is an extra `getline` call that immediately fails. It seems the brevity of `for (std::ifstream in{argv[1]}; std::getline(in, line); ) { v.push_back(...); }` would be worth the potential extra call. Or would the behavior different? I just rarely see anyone stray for the idiomatic `for` pattern, so I suspect there must be something I'm missing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:03:44.120",
"Id": "47787",
"ParentId": "47784",
"Score": "5"
}
},
{
"body": "<p>Lets start with the function definition:</p>\n\n<pre><code>bool read_file(char *p_file_name,char *file_content[FILE_NO_OF_ROWS][FILE_NO_OF_COL],const char *delimiter, int& token_count )\n</code></pre>\n\n<p>You are passing C-Strings and arrays of C-String. That's not a good start. Who owns the pointers? Am I supposed to free the pointers after use create them? I can't tell based on this interface.</p>\n\n<p>About the only thing I can tell for sure is that token_count is an out parameter but I am not even sure if I should reset that to zero before starting (which means the user of the code does not know if they need to set it to zero before starting, which means the only safe thing to do is set it to zero (which means if you set it to zero inside the function you are wasting instructions))?</p>\n\n<p>Also passing arrays through a function is dodgy. Its not doing quite what you expect. In this case you are passing <code>char *(*)[FILE_NO_OF_COL]</code> through as the parameter. Which makes validation on the other side a pain. When passing arrays don't give the function a false sense of security be exact with your type (or learn how to pass an array by reference).</p>\n\n<p>Also I am betting <code>FILE_NO_OF_ROWS</code> and <code>FILE_NO_OF_COL</code> are macros. Don't do that macros are not confined by scope. Prefer to use static const objects. Note if you use a vector all that information is stored for you.</p>\n\n<p>Prefer to pass C++ objects. `std::string is always good for passing strings and why not a vector for a container of objects.</p>\n\n<p>Unlike normal; I will not complain about this (as it is confined to a very strict scope). But you should be aware that its frowned upon.</p>\n\n<pre><code> using namespace std;\n</code></pre>\n\n<p>Why take two lines to open a file?</p>\n\n<pre><code> ifstream file_is_obj;\n file_is_obj.open(p_file_name,ios::in);\n\n // I would have just done\n std::ifstream file_is_obj(p_file_name);\n</code></pre>\n\n<p>Declare variables as close to the point of usage as you need them. Declaring them out here seems like a waste. Also it makes the code more complex as you have to reset things manually rather than let the compiler do it.</p>\n\n<pre><code> string buffer,token;\n int token_pos;\n token_count=0;\n</code></pre>\n\n<p>Sure you can test if it is open. But usually that is a waste of time. If it failed to open nothing else is going to work. So exit the function now and reduce them number of levels of indention of the code.</p>\n\n<pre><code> if( file_is_obj.is_open())\n {\n</code></pre>\n\n<p>This is <strong>RARELY</strong> correct in any language.</p>\n\n<pre><code> while( !file_is_obj.eof() )\n {\n // STUFF\n }\n</code></pre>\n\n<p>The pattern for reading from a file is:</p>\n\n<pre><code> while( <READ Value> )\n {\n // Read Succeeded continue to processes code.\n // STUFF\n }\n</code></pre>\n\n<p>This is because EOF is not set until you read past the end of the file. The last successful read will read <strong>up-to</strong> but not past the end of file. Thus you have no data left to read but the EOF flag is not set and thus you enter the loop. When you attempt to read the next item it will fail and set the EOF flag. So if you are doing it your way your code should look like this:</p>\n\n<pre><code> while( !file_is_obj.eof() ) // This is now redundant.\n {\n <READ VALUE>\n if (file_is_obj.eof()) // You have to check for read failure \n { break; // In all languages.\n }\n // STUFF\n }\n</code></pre>\n\n<p>Thus it is better to use the standard pattern were you do the read as part of the test.</p>\n\n<p>If you declare buffer here. Then you would not need to manually clear it here (or reset token).</p>\n\n<pre><code> buffer.clear(); \n token_pos=0;\n</code></pre>\n\n<p>Looking at your string splitting code:</p>\n\n<pre><code> for( int iter=0; token_pos != -1 || iter >= FILE_NO_OF_COL ; iter++)\n</code></pre>\n\n<p>You are making assumptions about the result of <code>std::string::find()</code>. Why do you think <code>token_pos != -1</code> will ever be correct. The documentation is very clear. If there is no match to the find it returns <code>std::string::npos</code>. Dont make any assumptions on what that value is.</p>\n\n<p>The standard way of testing for out of bounds is less than <code>iter < FILE_NO_OF_COL</code> though your test is perfectly valid <code>iter >= FILE_NO_OF_COL</code> it looks weird.</p>\n\n<p>Prefer pre-increment to post increment. It makes no difference in this case. But in general siuation it can make a difference (because we use the same kind of loop with iterators). So to be consistent and always get the best loop characteristics use the pre-increment.</p>\n\n<p>Would not need to clear token if it was local.</p>\n\n<pre><code> token.clear();\n</code></pre>\n\n<p>This bit of code is real over-complex.</p>\n\n<pre><code> token_pos=buffer.find(delimiter,0);\n token=buffer.substr(0,token_pos);\n if( !token.empty() )\n {\n buffer.erase(0,token_pos+strlen(delimiter));\n file_content[token_count][iter] = new char[token.length()+1] ;\n\n memset(file_content[token_count][iter],'\\0',(token.length()+1)*sizeof(char));\n token.copy( file_content[token_count][iter], token.length(), 0);\n }\n }\n</code></pre>\n\n<ol>\n<li>You find the delimiter.</li>\n<li>You copy the token into another object.<br>\nWhich would clear it (so the above clear is usless).</li>\n<li>You manually allocate memory</li>\n<li>You manually clear all the memory.</li>\n<li>You do a second copy.<br>\nNote this second copy is wrong (as you don't copy the terminating '\\0' to make it a real C-String and thus you loose all information about its end.</li>\n</ol>\n\n<p>So you are copying the string twice. You are manually allocating memory (with no definition of how the memory should be released).</p>\n\n<p>Also any unset members of the array have there original values (which may be misleading). Either the caller of the function has to make sure that the array is correctly nulled out before calling (which you do not make clear in your interface) or you should be nulling out the undefined cells.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:43:52.823",
"Id": "47791",
"ParentId": "47784",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T14:34:10.200",
"Id": "47784",
"Score": "4",
"Tags": [
"c++",
"optimization",
"performance",
"file"
],
"Title": "Reading a file and storing the contents in an array"
} | 47784 |
<p>I would like to submit a portion of my code for Code Review, and I have done my best to comment the code (and include essential parts that may aid understanding of the program) for your convenience! Any optimisation that would increase the speed of the running of the program would be appreciated!</p>
<p>The program is designed to check through Civilization 5 mods to ensure that they have not make mistakes and finds mistakes that users would have to load the mod (which takes a long time compared with the amount of bugs that can be present) to discover. My program performs this task much faster than the conventional method and so will be useful for modders like myself to quickly check their mods.</p>
<p>First a little housekeeping:</p>
<pre><code>private static Vector<RequiresWhere> statements = new Vector<RequiresWhere> (); //all the requires-where added by the program or the user live here
private static Vector<String> baseGameStatements = new Vector<String> (); //when the base game files are run through this system, any errors are put here, and ignored later on
/*
* This is the sort of format for the requires-where statement
* taking the first requires as an example:
* the program requires that in the "register" there is at least two Tags with identifiers that match ANY CIVILIZATION.*
* (This is important, CIVILIZATION_ENGLAND and CIVILIZATION_FRANCE must both be present twice in the following tables)
* in the Tables with an identifier of:
* Civilization_UnitClassOverrides
* Civilization_BuildingClassOverrides
* Improvements
* the required tag can be present in any of those tables,
* so one CIVILIZATION in Improvements and another in Civilization_UnitClassOverrides would qualify the two required
*/
public static void reset()
{
addRequires(2, "(Civilization.*ClassOverrides)|Improvements", "CIVILIZATION.*", false);
addRequires(10, "Civilization_SpyNames", "CIVILIZATION.*", false);
addRequires(1, "Civilization_CityNames", "CIVILIZATION.*", false);
addRequires(1, "Civilization_Leaders", "CIVILIZATION.*", true);
addRequires(1, "Leader_Traits", "LEADER.*", true);
}
private RequiresWhere(int numMatches, String location, String tag, boolean exact)
{
this.numMatches = numMatches; //number of matches we want (if exact, well... x == numMatches, if not then could be x >= numMatches)
this.tag = tag; //the regex for the tag name we want (every different tag must have the requiredMatches, if tagA has 1 match and tagB has numMatches - 1 matches they don't add up!
this.location = location; //and the tables it belongs in
this.exact = exact; //do we require exactly numMatches or >= numMatches?
}
</code></pre>
<p>and then on to the part of the code that needs to be optimised:</p>
<pre><code>/*
* This method is called from the maincode routine, if store is true, the results are added to the baseGameRequires
* otherwise they are printed out to syso
*/
public static void executeRequires(boolean store)
{
for (RequiresWhere requires : statements) //for every requires-where statement
{
for (Table table : Table.getRegister().values()) // for every table in the register
{
if (table.isPrimary()) // make sure it is primary
{
for (String identifier : table.getRows().keySet()) //for every primary tag in this table
{
if (identifier.matches(requires.tag)) //if this tag matches our regex
{
int x = 0; //we have 0 matches
String tableNames = ""; //present in "" tables
for (String name : Table.getRegister().keySet()) //for every table name in the register
{
if (name.matches(requires.location)) //if this table matches our location regex
{
tableNames += tableNames.isEmpty() ? String.format("%s", name) : String.format(" or %s", name); // add this table to our names just in case there is not enough matches
for (Vector<Row> rows : Table.getTable(name).getRows().values()) // for every group of same name rows in this table
{
for (Row row : rows) // for every row in this group
{
for (Tag<?> tag : row.getTags()) //for every tag in this row
{
if (tag.get() instanceof String) //if the data in the tag is a string
{
if (((String) tag.get()).equals(identifier)) // does this match our primary tag that matches the tag regex?
{
x++; //register a match
}
}
}
}
}
}
}
if ((x != requires.numMatches && requires.exact) || (x < requires.numMatches && !requires.exact)) //if we don't have enough matches
{
String error = String.format("MISSING REQUIREMENT: The tag %s is required to have %s %s entr%s in table %s, it currently has %s", identifier, requires.exact ? "exactly" : "at least", requires.numMatches, requires.numMatches == 1 ? "y" : "ies", tableNames, x);
if (!baseGameStatements.contains(error) && !store) //if this error wasn't present in the baseGame (our users don't need to care about this)
{
System.out.println(error); //then print to syso
}
else if (store) // if this IS the baseGame
{
baseGameStatements.add(error); //store for later!
}
}
}
}
}
}
}
}
</code></pre>
<p>If anybody has questions about the purpose or specifics of the code, please ask!</p>
<p>Just in case anybody needs to know, this is the layout of the table register:</p>
<blockquote>
<p>Table class contains a HashMap of <code>Table</code> instances paired with their name, which are
accessed by <code>getTable(String name)</code> or <code>getTables()</code> for everything</p>
<p>A Table contains an <code>HashMap <String, Vector<Row>></code> which stores
Rows, grouped by their primary tag's name</p>
<p>a Row contains an LinkedHashMap of <code>Tag <?></code>s which can be varying types
such as int or String mapped to their name.</p>
<p>The Tag has a name and a ? data field.</p>
</blockquote>
<p>When the program first loads it checks the base game XML files and loads all the data into the register. It performs a few checks (which are not important here) then we get to our code above. After running all the base game data through the system it performs the same checks and parsing for a chosen mod (which is combined with the base game data), it therefore goes back through the code above, and makes sure that the mod contains tags in places where the game's Lua code demands they are (a big cause of error for modders is not knowing about the undocumented requirements and having the game complain because of it)</p>
<p><strong>EDIT:</strong> I have applied a lot of the below suggestion and also precompiled the regex for location and tag. This has taken the total runtime of the function down from ~15% to 2.8%! Any other suggestions would be appreciated!!! Especially with the algorithm itself!</p>
| [] | [
{
"body": "<p>First, some basics:</p>\n\n<ul>\n<li><p>Vector is a class that is deprecated.... actually, not deprecated, but discouraged....</p>\n\n<blockquote>\n <p>As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.</p>\n</blockquote>\n\n<p>and, if you need synchronization, which you do not, then you should be looking at <code>java.util.concurrent.*</code> classes anyway.</p></li>\n<li><p>Code Style: Java Code Style recommends putting the opening brace <code>{</code> on the same line as the condition/statement for if/for/while structures....</p></li>\n<li><p>If you are using String.format(...) anyway... you may as well replace:</p>\n\n<blockquote>\n<pre><code> tableNames += tableNames.isEmpty() ? String.format(\"%s\", name) : String.format(\" or %s\", name);\n</code></pre>\n</blockquote>\n\n<p>with:</p>\n\n<pre><code> tableNames = String.format(\"%s%s%s\", tableNames, tableNames.isEmpty() ? \"\" : \" or \", name);\n</code></pre>\n\n<p>but using a <code>StringBuilder</code> will be a good option too.</p></li>\n</ul>\n\n<p>With those small things out of the way .... and, by the way, the change from Vector is not really 'small', it has a big performance impact.... then you can look at the bigger items.</p>\n\n<ul>\n<li><p><a href=\"http://en.wikipedia.org/wiki/Code_refactoring#List_of_refactoring_techniques\">Function extraction</a> - break out your inner loops in to discrete functions. This has a number of performance benefits too, primarily related to how the Java code is compiled when it is used often.</p></li>\n<li><p>Use <code>for (Map.Entry<K,V> ... : map.entrySet()) {...}</code> loops, instead of <code>map.values()</code> and <code>map.keySet()</code></p></li>\n</ul>\n\n<p>In all, I would also wonder whether it is an option to keep things at the XML level, and use something like <a href=\"http://en.wikipedia.org/wiki/Saxon_XSLT\">Saxon</a>, or <a href=\"http://en.wikipedia.org/wiki/JDOM\">JDOM</a> (which I maintain) as a mechanism for running XPath expressions on. Saxon has the ability to index the documents, and XPath expressions end up being very efficient if the document is big, and static... which this may be. The Saxon index will be more efficient than what you have (or it should be).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:34:22.590",
"Id": "83765",
"Score": "0",
"body": "Yeah, I was sure I stopped using Vector a long time ago, but I guess in my conversion process I forgot to change them to ArrayList (or I might have been experimenting with some multithreading and didn't put them back). As for the braces, I find it difficult to read code which has the brace on the opening line of a statement, but I do acknowledge that it is the norm!\n\nAs for the Map.Entry, what benefits does it have over my current method, or is it just convention, because I don't see how it would produce more efficiency, by just looking at it and I am curious to know why :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:49:09.710",
"Id": "83769",
"Score": "0",
"body": "Furthermore, with Function extraction, how much do you think it would improve operation? And if I used this system, would the use of aggregate functions also help when using this system?\n\nAs for the Saxon or JDOM, the program is designed so that after the first run of the program all of the base game data is serialized to bypass several checks and the parsing the next time the program is loaded. This leaves the mod files, which tend to be quite small to be processed during standard runtime, would you still say that JDOM would be a good idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:52:51.430",
"Id": "83771",
"Score": "0",
"body": "Two different things: Java tends to compile code at the method level when Jit happens. You only call your method once, it will never be compiled. If you factor out the inner functions to be separate, then they will get compiled after a number of invocations (depends on JVM), and will be faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:54:03.497",
"Id": "83772",
"Score": "0",
"body": "JDOM/Saxon would require significant rewrite, for marginal potential gains.... Each of them will deal with a single document at a time... I understand your code aggregates the documents in to one place. I am uncertain whether you will see any benefits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:56:59.420",
"Id": "83773",
"Score": "0",
"body": "Ok, I will perform some Method Extraction and see if it makes much difference to the run time :D I have corrected the Vectors and that String formatting aswell :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:01:10.933",
"Id": "83812",
"Score": "2",
"body": "Well, as above, your suggestions (and precompiling the regex statements) have effectively cut the run-time down by 81%! so a great improvement. This leaves another check consuming 85% of runtime so I will post that one too in a separate thread"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:30:50.510",
"Id": "47795",
"ParentId": "47789",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T15:25:28.057",
"Id": "47789",
"Score": "10",
"Tags": [
"java",
"optimization",
"xml"
],
"Title": "Civilization 5 mod validator"
} | 47789 |
<p>Could you please review my script?</p>
<pre><code>#!/bin/ksh
T=/bb/bdap/bin/cms/tools
U=$T/upgrader
mv $T/conbase_updates $U/conbase_updates.br.drqs$1
cd $U
grep "^BR" config.alpha > config.br
./ConbaseUpgrader config.br conbase_updates.br.drqs$1
</code></pre>
| [] | [
{
"body": "<p>You might want to validate the value of <code>$1</code>, or at least that it's not empty, for example add a line like this near the top:</p>\n\n<pre><code>test \"$1\" || { echo usage: $0 param; exit 1; }\n</code></pre>\n\n<hr>\n\n<p>You are not checking for errors, for example what will happen if the <code>mv</code> command fails for whatever reason? Maybe you have no reason to suspect a problem there, but just in case it would be good to add the <code>-e</code> flag to the shebang (<code>#!/bin/ksh</code>) so that execution will stop immediately there. Otherwise execution would continue after the failed <code>mv</code>, and the <code>grep ... > ...</code> might clobber a file by accident.</p>\n\n<p>In any case, adding the <code>-e</code> flag in the shebang is a good practice in general.</p>\n\n<hr>\n\n<p>It seems your variables will not normally contain spaces. If they ever do, remember to quote them properly, for example:</p>\n\n<pre><code>mv \"$T/conbase_updates\" \"$U/conbase_updates.br.drqs$1\"\n</code></pre>\n\n<p>(in your current example it's unnecessary)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:26:43.223",
"Id": "47794",
"ParentId": "47793",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T16:10:04.353",
"Id": "47793",
"Score": "2",
"Tags": [
"ksh"
],
"Title": "ksh script to perform an upgrade"
} | 47793 |
<p>I am wondering if my current unit tests could be written better, I am most interested in whether it is possible to make the code look more concise, as currently it a <em>boiler-plated mess</em>.<br>
I have full access to Java 8, if that would help by making it more concise.</p>
<p>The <code>Arguments</code> class itself:</p>
<pre><code>public final class Arguments {
private Arguments() {
throw new UnsupportedOperationException();
}
public static int requirePositive(final int value) throws IllegalArgumentException {
return requirePositive(value, "value");
}
public static int requirePositive(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value <= 0) {
throw new IllegalArgumentException("the " + name + " must be positive: " + value);
}
return value;
}
public static int requireNegative(final int value) throws IllegalArgumentException {
return requireNegative(value, "value");
}
public static int requireNegative(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value >= 0) {
throw new IllegalArgumentException("the " + name + " must be negative: " + value);
}
return value;
}
public static int requirePositiveOrZero(final int value) throws IllegalArgumentException {
return requirePositiveOrZero(value, "value");
}
public static int requirePositiveOrZero(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value < 0) {
throw new IllegalArgumentException("the " + name + " must be positive or zero: " + value);
}
return value;
}
public static int requireNegativeOrZero(final int value) throws IllegalArgumentException {
return requireNegativeOrZero(value, "value");
}
public static int requireNegativeOrZero(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value > 0) {
throw new IllegalArgumentException("the " + name + " must be negative or zero: " + value);
}
return value;
}
public static int requireInRange(final int value, final int lowInclusive, final int highExclusive) throws IllegalArgumentException {
return requireInRange(value, lowInclusive, highExclusive, "value");
}
public static int requireInRange(final int value, final int lowInclusive, final int highExclusive, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (lowInclusive >= highExclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher exclusive bound: " + lowInclusive + " >= " + highExclusive);
}
if (value < lowInclusive || value >= highExclusive) {
throw new IllegalArgumentException("the " + name + " was not in range: " + value + ", expected: [" + lowInclusive + ", " + highExclusive + ")");
}
return value;
}
public static int requireInRangeClosed(final int value, final int lowInclusive, final int highInclusive) throws IllegalArgumentException {
return requireInRangeClosed(value, lowInclusive, highInclusive, "value");
}
public static int requireInRangeClosed(final int value, final int lowInclusive, final int highInclusive, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (lowInclusive > highInclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher inclusive bound: " + lowInclusive + " >= " + highInclusive);
}
if (value < lowInclusive || value > highInclusive) {
throw new IllegalArgumentException("the " + name + " was not in range: " + value + ", expected: [" + lowInclusive + ", " + highInclusive + ")]");
}
return value;
}
public static int requireIndexInRange(final int index, final int lowInclusive, final int highExclusive) throws IndexOutOfBoundsException {
if (lowInclusive >= highExclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher exclusive bound: " + lowInclusive + " >= " + highExclusive);
}
if (index < lowInclusive || index >= highExclusive) {
throw new IndexOutOfBoundsException("the index was not in range: " + index + ", expected: [" + lowInclusive + ", " + highExclusive + ")");
}
return index;
}
public static int requireIndexInRangeClosed(final int index, final int lowInclusive, final int highInclusive) throws IndexOutOfBoundsException {
if (lowInclusive > highInclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher inclusive bound: " + lowInclusive + " >= " + highInclusive);
}
if (index < lowInclusive || index > highInclusive) {
throw new IndexOutOfBoundsException("the index was not in range: " + index + ", expected: [" + lowInclusive + ", " + highInclusive + "]");
}
return index;
}
}
</code></pre>
<p>The <code>ArgumentsTest</code> test class:</p>
<pre><code>public class ArgumentsTest {
static {
assertTrue(true);
}
/** Arguments.requirePositive **/
@Test
public void testRequirePositive_int() {
int result = Arguments.requirePositive(1);
assertEquals(1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositive_intIAE1() {
Arguments.requirePositive(0);
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositive_intIAE2() {
Arguments.requirePositive(-1);
}
@Test
public void testRequirePositive_int_String() {
int result = Arguments.requirePositive(1, "test");
assertEquals(1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositive_int_StringIAE1() {
Arguments.requirePositive(0, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositive_int_StringIAE2() {
Arguments.requirePositive(-1, "test");
}
@Test(expected = NullPointerException.class)
public void testRequirePositive_int_StringNPE() {
Arguments.requirePositive(1, null);
}
/** Arguments.requireNegative **/
@Test
public void testRequireNegative_int() {
int result = Arguments.requireNegative(-1);
assertEquals(-1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegative_intIAE1() {
Arguments.requireNegative(0);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegative_intIAE2() {
Arguments.requireNegative(1);
}
@Test
public void testRequireNegative_int_String() {
int result = Arguments.requireNegative(-1, "test");
assertEquals(-1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegative_int_StringIAE1() {
Arguments.requireNegative(0, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegative_int_StringIAE2() {
Arguments.requireNegative(1, "test");
}
@Test(expected = NullPointerException.class)
public void testRequireNegative_int_StringNPE() {
Arguments.requireNegative(-1, null);
}
/** Arguments.requirePositiveOrZero **/
@Test
public void testRequirePositiveOrZero_int1() {
int result = Arguments.requirePositiveOrZero(0);
assertEquals(0, result);
}
@Test
public void testRequirePositiveOrZero_int2() {
int result = Arguments.requirePositiveOrZero(1);
assertEquals(1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositiveOrZero_intIAE() {
Arguments.requirePositiveOrZero(-1);
}
@Test
public void testRequirePositiveOrZero_int_String1() {
int result = Arguments.requirePositiveOrZero(0, "test");
assertEquals(0, result);
}
@Test
public void testRequirePositiveOrZero_int_String2() {
int result = Arguments.requirePositiveOrZero(1, "test");
assertEquals(1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequirePositiveOrZero_int_StringIAE() {
Arguments.requirePositiveOrZero(-1, "test");
}
@Test(expected = NullPointerException.class)
public void testRequirePositiveOrZero_int_StringNPE() {
Arguments.requirePositiveOrZero(0, null);
}
/** Arguments.requireNegativeOrZero **/
@Test
public void testRequireNegativeOrZero_int1() {
int result = Arguments.requireNegativeOrZero(0);
assertEquals(0, result);
}
@Test
public void testRequireNegativeOrZero_int2() {
int result = Arguments.requireNegativeOrZero(-1);
assertEquals(-1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegativeOrZero_intIAE() {
Arguments.requireNegativeOrZero(1);
}
@Test
public void testRequireNegativeOrZero_int_String1() {
int result = Arguments.requireNegativeOrZero(0, "test");
assertEquals(0, result);
}
@Test
public void testRequireNegativeOrZero_int_String2() {
int result = Arguments.requireNegativeOrZero(-1, "test");
assertEquals(-1, result);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireNegativeOrZero_int_StringIAE() {
Arguments.requireNegativeOrZero(1, "test");
}
@Test(expected = NullPointerException.class)
public void testRequireNegativeOrZero_int_StringNPE() {
Arguments.requireNegativeOrZero(0, null);
}
/** Arguments.requireInRange **/
@Test
public void testRequireInRange_3args() {
int result = Arguments.requireInRange(1, 1, 2);
assertEquals(1, result);
int result2 = Arguments.requireInRange(1, 0, 3);
assertEquals(1, result2);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_3argsIAE1() {
Arguments.requireInRange(1, 5, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_3argsIAE2() {
Arguments.requireInRange(1, 6, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_3argsIAE3() {
Arguments.requireInRange(1, 0, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_3argsIAE4() {
Arguments.requireInRange(1, 2, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_3argsIAE5() {
Arguments.requireInRange(1, 10, 20);
}
@Test
public void testRequireInRange_4args() {
int result = Arguments.requireInRange(1, 1, 2, "test");
assertEquals(1, result);
int result2 = Arguments.requireInRange(1, 0, 3, "test");
assertEquals(1, result2);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_4argsIAE1() {
Arguments.requireInRange(1, 5, 5, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_4argsIAE2() {
Arguments.requireInRange(1, 6, 5, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_4argsIAE3() {
Arguments.requireInRange(1, 0, 1, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_4argsIAE4() {
Arguments.requireInRange(1, 2, 5, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRange_4argsIAE5() {
Arguments.requireInRange(1, 10, 20, "test");
}
@Test(expected = NullPointerException.class)
public void testRequireInRange_4argsNPE() {
Arguments.requireInRange(1, 0, 2, null);
}
/** Arguments.requireInRangeClosed **/
@Test
public void testRequireInRangeClosed_3args() {
int result = Arguments.requireInRangeClosed(1, 1, 2);
assertEquals(1, result);
int result2 = Arguments.requireInRangeClosed(1, 0, 1);
assertEquals(1, result2);
int result3 = Arguments.requireInRangeClosed(1, 1, 1);
assertEquals(1, result3);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_3argsIAE1() {
Arguments.requireInRangeClosed(1, 6, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_3argsIAE2() {
Arguments.requireInRangeClosed(1, -4, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_3argsIAE3() {
Arguments.requireInRangeClosed(1, 2, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_3argsIAE4() {
Arguments.requireInRangeClosed(1, 20, 40);
}
@Test
public void testRequireInRangeClosed_4args() {
int result = Arguments.requireInRangeClosed(1, 1, 2, "test");
assertEquals(1, result);
int result2 = Arguments.requireInRangeClosed(1, 0, 1, "test");
assertEquals(1, result2);
int result3 = Arguments.requireInRangeClosed(1, 1, 1, "test");
assertEquals(1, result3);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_4argsIAE1() {
Arguments.requireInRangeClosed(1, 6, 5, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_4argsIAE2() {
Arguments.requireInRangeClosed(1, -4, 0, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_4argsIAE3() {
Arguments.requireInRangeClosed(1, 2, 5, "test");
}
@Test(expected = IllegalArgumentException.class)
public void testRequireInRangeClosed_4argsIAE4() {
Arguments.requireInRangeClosed(1, 20, 40, "test");
}
@Test(expected = NullPointerException.class)
public void testRequireInRangeClosed_4argsNPE() {
Arguments.requireInRangeClosed(5, 2, 20, null);
}
/** Arguments.requireIndexInRange **/
@Test
public void testRequireIndexInRange() {
int result = Arguments.requireIndexInRange(1, 1, 2);
assertEquals(1, result);
int result2 = Arguments.requireIndexInRange(1, 0, 3);
assertEquals(1, result2);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireIndexInRangeIAE1() {
Arguments.requireIndexInRange(1, 5, 5);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireIndexInRangeIAE2() {
Arguments.requireIndexInRange(1, 6, 5);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeIAE3() {
Arguments.requireIndexInRange(1, 0, 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeIAE4() {
Arguments.requireIndexInRange(1, 2, 5);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeIAE5() {
Arguments.requireIndexInRange(1, 10, 20);
}
/** Arguments.requireIndexInRangeClosed **/
@Test
public void testRequireIndexInRangeClosed() {
int result = Arguments.requireIndexInRangeClosed(1, 1, 2);
assertEquals(1, result);
int result2 = Arguments.requireIndexInRangeClosed(1, 0, 1);
assertEquals(1, result2);
int result3 = Arguments.requireIndexInRangeClosed(1, 1, 1);
assertEquals(1, result3);
}
@Test(expected = IllegalArgumentException.class)
public void testRequireIndexInRangeClosedIAE1() {
Arguments.requireIndexInRangeClosed(1, 6, 5);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeClosedIAE2() {
Arguments.requireIndexInRangeClosed(1, -4, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeClosedIAE3() {
Arguments.requireIndexInRangeClosed(1, 2, 5);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRequireIndexInRangeClosedIAE4() {
Arguments.requireIndexInRangeClosed(1, 20, 40);
}
}
</code></pre>
<p>Some extra notes:</p>
<ul>
<li>Using JUnit 4.x</li>
<li>The <code>static { assertTrue(true); }</code> is there to prevent Netbeans from removing the import if it would be unused in some test class.</li>
<li>All the non-named variants of my argument methods refer to the named-variant, but this is an <strong>implementation detail</strong>, and unit tests are not allowed to know about the implementation.</li>
<li>All code in question may of course be reviewed and I would appreciate <em>all</em> comments, even though the question is mainly about the unit tests.</li>
<li>Did I mention already that the test class feels way too bulky for what it is actually doing?</li>
</ul>
| [] | [
{
"body": "<p><strong>Test Names</strong></p>\n<p><code>testRequirePositive_intIAE1()</code> doesn't tell me anything besides what function is being tested. It is helpful to give some context as to why you think it should throw an exception. What makes <code>testRequirePositive_intIAE1()</code> different from <code>testRequirePositive_intIAE2()</code>? You have to go look at the test to know what is actually being tested. In this case, it is easy to deduce why the argument is invalid, but this will not be the case for more complicated methods.</p>\n<hr />\n<p><strong>Repetitiveness</strong></p>\n<p>As you pointed out, the test code is bulky and some times hard to follow. When you look at the code, there are lots of cases where each tests is doing the exact same thing, but with different inputs.</p>\n<p>This is a perfect case for <a href=\"https://stackoverflow.com/a/10143872/210526\">parameterized tests</a>. You provide the data with a static method and your test class is instantiated once for each data set.</p>\n<p>Touching on the previous point: Parameterized tests mean your actual test method can't describe why the data is intended to cause an error. So it is a good idea to include an additional <code>String</code> argument to provide that context.</p>\n<hr />\n<p><strong>Multiple Asserts</strong></p>\n<p><code>testRequireIndexInRangeClosed()</code><sup>1</sup> has three different assertions that are unrelated. These should be different tests (probably different data inputs for a parameterized test). This issue with this is that if the first assertion fails, the following assertions are not checked. This can hide information about what is wrong with the system.</p>\n<p><sup>1</sup> This is not the only instance of this in the test code.</p>\n<hr />\n<p><strong>Long Class</strong></p>\n<p>Just because all of the tested methods are in the same class doesn't mean all of the tests have to be in the same class too. Organize your tests just as you would with your actual code. If a class or method is too long, it likely means you should break it into smaller pieces.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:33:12.030",
"Id": "47802",
"ParentId": "47797",
"Score": "6"
}
},
{
"body": "<p>In addition to what <a href=\"https://codereview.stackexchange.com/users/15893/unholysampler\">@unholysampler</a> already said, I would offer some practical but <strong>very opinionated</strong> tips to writing unit tests.</p>\n\n<p>I don't really understand why you require the <code>name</code> parameters to be non-null. Your implementation doesn't need them to be. I think these checks violate the <a href=\"http://c2.com/cgi/wiki?YouArentGonnaNeedIt\" rel=\"nofollow noreferrer\">YAGNI doctrine</a>.</p>\n\n<p>In addition, I think it's redundant to write separate unit tests for the two variants of each method, one with a <code>String name</code> parameter and one without. If you write tests for just the methods without <code>name</code>, you will already cover all execution paths, so why bother? (Of course, assuming you can don't mind getting rid of the <code>name != null</code> requirement.)</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>int result = Arguments.requireInRange(1, 1, 2);\nassertEquals(1, result);\nint result2 = Arguments.requireInRange(1, 0, 3);\nassertEquals(1, result2);\n</code></pre>\n</blockquote>\n\n<p>why not simply:</p>\n\n<pre><code>assertEquals(1, Arguments.requireInRange(1, 1, 2));\nassertEquals(1, Arguments.requireInRange(1, 0, 3));\n</code></pre>\n\n<p>It's NOT less readable (might be actually more readable), and it saves you the pain of the throw-away local variables.</p>\n\n<p>Actually I would write it more like this:</p>\n\n<pre><code>int min = 10;\nint max = 20;\nassertEquals(min, Arguments.requireInRange(min + 1, min, max));\nassertEquals(min, Arguments.requireInRange(min, min, max));\nassertEquals(max - 1, Arguments.requireInRange(max - 1, min, max));\n</code></pre>\n\n<p>This way I find it easier to understand how the arguments of <code>requireInRange</code> were chosen and the purpose of those assertions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:54:54.793",
"Id": "47819",
"ParentId": "47797",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:00:15.030",
"Id": "47797",
"Score": "10",
"Tags": [
"java",
"unit-testing"
],
"Title": "Unit tests for an argument-checking class"
} | 47797 |
<p>I often find myself doing this (or similar) with Lists and other collection types:</p>
<pre><code>if (someList != null && someList.Count > 0)
//take some action on the list
</code></pre>
<p>so I got lazy and wrote the following extension methods to do it for me:</p>
<pre><code> public static bool IsNullOrEmpty(this IEnumerable self)
{
//Convert to collection here because IEnumerable doesn't have a count property
ICollection c = self as ICollection;
return c == null || c.Count < 1;
}
public static bool IsNotNullOrEmpty(this IEnumerable self)
{
return !self.IsNullOrEmpty();
}
public static bool IsNotNullAndContains<T>(this IEnumerable<T> self, T item)
{
return self.IsNotNullOrEmpty() && self.Contains(item);
}
</code></pre>
<p>Other than being lazy is there anything wrong with this or should I have just stuck with the manual check every time?</p>
<p>Edit:</p>
<p>Based on the answer from Jeroen Vannevel:</p>
<p>I originally had the first extension method (<code>IsNullOrEmpty</code>) defined as such:</p>
<pre><code>public static bool IsNullOrEmpty<T>(this IEnumerable<T> self)
{
return self == null || self.Count < 1;
}
</code></pre>
<p>which eliminated the need for the cast to <code>ICollection</code>, as <code>IEnumerable<T></code> implements the count property. I removed the type parameter though because I wasn't actually using it for anything. Should I have just kept it like that to prevent the cast and a potential type cast exception?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:35:17.930",
"Id": "83782",
"Score": "0",
"body": "If you want to use the `.Count` property, you should extend `ICollection` directly, or else this could fail on otherwise valid collections. Use the `.Count()` method in an IEnumerable extension. The second and third methods are a waste, however; particularly the simple inverted one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:58:05.353",
"Id": "83789",
"Score": "0",
"body": "I think the `ICollection` extension might be the better solution actually. Good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:17:41.227",
"Id": "83853",
"Score": "1",
"body": "You shouldn't need to do the && `someList.Count > 0` part. If you `for each` (etc) over an empty list, it will effectively do nothing and skip to the next part of you code. You will obviously need to check if it is null still (C#6 may have a solution to that coming soon as well)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:16:55.563",
"Id": "83926",
"Score": "0",
"body": "Yes, if I `foreach` the collection, it's taken care of. There are times when I want to select a certain numeric index from it though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:40:15.993",
"Id": "84009",
"Score": "1",
"body": "For IEnumerables, you could use the [LINQ .Any()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.any.aspx) method instead of comparing .Count() with 0. Count forces enumeration of the entire collection, where an empty .Any() call just needs to touch one item."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:15:51.317",
"Id": "84016",
"Score": "2",
"body": "IEnumerable does not expose `Any()`. `IEnumerable<T>` does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-20T20:40:09.160",
"Id": "466073",
"Score": "0",
"body": "Have an `IEnumerable.Any()` one-liner: `public static bool Any(this System.Collections.IEnumerable source) => source?.GetEnumerator().MoveNext() ?? throw new ArgumentNullException(nameof(source));`"
}
] | [
{
"body": "<p>It looks handy, but I have some thoughts on it.</p>\n\n<p>Firstly: when you create your own <code>IEnumerable<T></code> and don't implement <code>ICollection</code>, you'll get a logical error. It will try to convert it with <code>as</code>, which will return <code>null</code> because the conversion is not supported. Now your return statement <code>c == null</code> will return true and thus any collection that implements <code>IEnumerable<T></code> but not <code>ICollection</code> will always be considered null or empty.</p>\n\n<p>I don't know if there are collections in .NET that also have this scenario but you might want to check that as well.</p>\n\n<p>Secondly: your first two methods perform a very closely related action and as such it is okay to combine these actions in one method. The third however does two things are not really similar to eachother and the guideline of \"a method should do one thing\" feels violated.</p>\n\n<p>Generally: as soon as you add <code>And</code> to your methodname, it should be a red flag.</p>\n\n<p>Lastly: An empty collection (aka: <code>Count</code> = 0) is not a problem for iteration. The iterator will break out of the code block very soon in the process so there is no performance gain by checking <code>Count > 0</code>. <a href=\"https://softwareengineering.stackexchange.com/questions/235431/is-there-any-performance-benefit-in-checking-the-item-count-prior-to-executing-a/235699#235699\">More reading material here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:52:18.313",
"Id": "83786",
"Score": "0",
"body": "Thanks for the answer. A further question: Are you saying that my first two methods should only be one (leaving me to `Not` one method instead of calling another)? I have an update to add to my question if you could have a a look, regarding the ICollection business."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:55:29.983",
"Id": "83787",
"Score": "3",
"body": "I was referring to the \"null or empty\" compared to \"not null or empty and contains\", but yes: a method that is simply an inversion of another doesn't really add much value. If the follow up question is short then you should ask clarification here in the comments, otherwise make a new post. This will keep things clear for future readers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:57:00.353",
"Id": "83788",
"Score": "0",
"body": "I was worried about the clarification, but it's directly related to your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:45:42.443",
"Id": "83799",
"Score": "0",
"body": "Not only does an inversion of another method not add any value, it violates the DRY principle (http://en.wikipedia.org/wiki/Don't_repeat_yourself) and creates an extra method to maintain/test/etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:47:04.270",
"Id": "83800",
"Score": "0",
"body": "*\"Firstly: when you create your own IEnumerable<T> and don't implement ICollection, you'll get a ClassCastException.\"* I think you're getting confused between .NET and Java there. In .NET it's legal to have a class inherit `IEnumerable` but not `ICollection`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:57:47.737",
"Id": "83810",
"Score": "0",
"body": "@MattDavey: that was not my point but by reading over it again I noticed a mistake. My point still stands, except it is now an even more tricky problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:22:20.990",
"Id": "83929",
"Score": "0",
"body": "If you cast an object to an interface it doesn't implement it becomes null. The problem there is the object I'm casting is not actually null but the method would tell me it was."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:37:49.783",
"Id": "47805",
"ParentId": "47800",
"Score": "6"
}
},
{
"body": "<p>In my opinion, there shouldn't be a need for this method to begin with. There are very few cases I can think of that would involve passing around a <code>null</code> <code>IEnumerable</code> (or <code>List<T></code> for that matter). <code>IEnumerable</code> can still express a lack of things to iterate, so you don't often see <code>IEnumerable</code> members returning <code>null</code>. I often see <code>null</code> returned for <code>IEnumerable</code> when the better option would have been to fail or more explicitly inform the caller of an invalid operation. Take this <code>Repository</code> example:</p>\n\n<pre><code>public class Repository<T>\n{\n public IEnumerable<T> GetItems()\n {\n bool canConnectToDb = false;\n bool recordsReturned = false;\n\n // Case 1:\n if(!canConnectToDb)\n return Enumerable.Empty<T>();\n\n // Case 2:\n if(!canConnectToDb)\n return null;\n\n // Case 3:\n if(!recordsReturned)\n return null;\n }\n}\n</code></pre>\n\n<p>In \"Case 1\", the result is misleading. Sure, no records can be returned, but the reason isn't a lack of records to return. Instead, there is an error case that must be handled and an exception should be thrown. In \"Case 2\", <code>null</code> is being used to show an error state, which is misleading. What was the error? How can I differentiate between a null response, and error handling code using <code>try..catch</code>? In \"Case 3\", the correct return value would be an <em>empty</em> <code>IEnumerable</code>, not <code>null</code>.</p>\n\n<p>Which leads me to your extension methods...Usually checks like these are trying to cover up issues rather than failing early and identifying them. For example, lets apply your extension method to refactor the existing <code>Count()</code> extension method:</p>\n\n<pre><code>public static int Count<T>(this IEnumerable<T> iterator)\n{\n if(iterator.IsNullOrEmpty())\n return 0;\n else\n // Iterate and count...\n}\n</code></pre>\n\n<p>You just end up perpetrating the issue to create \"safe\" code that really only hides the issue (that <code>iterator</code> shouldn't have been passed in as null to begin with). The actual implementation probably looks more like:</p>\n\n<pre><code>public static int Count<T>(this IEnumerable<T> iterator)\n{\n if(iterator == null)\n throw new ArgumentException(\"iterator\");\n\n // Iterate and count...\n}\n</code></pre>\n\n<p>This allows it to fail early if it's improperly used, and doesn't make it this methods responsibility to make sure it can always execute given poor conditions.</p>\n\n<p>Lastly, if you do plan on using something like your extension methods, you should know that the extension methods that come with the .NET framework already make performance checks similar to your check if the object is an <code>ICollection</code>. That said, there is no performance check they can do on a custom type that implements <code>IEnumerable</code>, so if you want the count the only option is to iterate through the whole <code>IEnumerable</code>. You don't really need the count though, you just need to know if there is <em>anything</em> being returned, which the <code>Any()</code> extension method does. Instead of iterating through the whole collection, it'll just iterate once and immediately return true if there is anything, which can be a huge performance saver.</p>\n\n<p>A rework of your method:</p>\n\n<pre><code>public static bool IsNullOrEmpty(this IEnumerable iterator)\n{\n return iterator == null || !iterator.Any();\n}\n</code></pre>\n\n<p>Maybe I could be convinced by seeing a good application of this extension method, but I can't think of one.</p>\n\n<p>Edit - To address the concern of using another library you can't entirely trust, you have some other options:</p>\n\n<p>1) Use the <a href=\"http://en.wikipedia.org/wiki/Facade_pattern\" rel=\"noreferrer\">Facade Pattern</a> to create wrapper objects that do perform to your standards.</p>\n\n<p>2) Treat the issue at the call site to these external libraries and not further into your own code. For example:</p>\n\n<pre><code>var items = BadLibrary.GetItems<T>() ?? Enumerable.Empty<T>();\nInternalGoodMethod(items);\n\npublic static void InternalGoodMethod(IEnumerable<T> items)\n{\n if(items == null)\n throw new ArgumentException(\"items\");\n\n ....\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:48:22.623",
"Id": "83802",
"Score": "0",
"body": "I like the `Any()` extension to this. There are very few cases I can see to pass around a null `IEnumerable` as well, but it happens. I'm working on a project with another developer where we've established a spoken rule: No instance of IEnumerable<T> will ever be null. With that said, another project I'm working on doesn't have that rule and the other devs pass around null `List<T>`s and `IEnumerable<T>`s like they're going out of style. I don't have a specific example of the use of this right now, but a lot of them exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:52:37.843",
"Id": "83806",
"Score": "0",
"body": "Actually, I just tested: `IEnumerable` doesn't expose the `Any()` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:01:39.057",
"Id": "83813",
"Score": "0",
"body": "See my update regarding the use of `IEnumerable` in other libraries you must use. Also, `Any()` is most definitely an extension method on `IEnumerable` shipped with the .NET framework. You may be missing a `using System.Linq` in your code. http://msdn.microsoft.com/en-us/library/bb534972.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:05:20.963",
"Id": "83814",
"Score": "0",
"body": "My apologies, I see you're using the non-generic `IEnumerable` interface. For that you can use a `Cast<object>` call or write the extension yourself if you are worried about performance. See here: http://stackoverflow.com/questions/5604168/count-for-ienumerable"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:34:28.997",
"Id": "47813",
"ParentId": "47800",
"Score": "7"
}
},
{
"body": "<blockquote>\n<pre><code>public static bool IsNullOrEmpty(this IEnumerable self)\n{ \n //Convert to collection here because IEnumerable doesn't have a count property\n ICollection c = self as ICollection; \n return c == null || c.Count < 1;\n}\n</code></pre>\n</blockquote>\n\n<p>As already mentioned, the typecasting to <code>ICollection</code> is probably problematic, take <code>Enumerable.Range(0, 10);</code> for example.</p>\n\n<blockquote>\n<pre><code>public static bool IsNullOrEmpty<T>(this IEnumerable<T> self)\n{\n return self == null || self.Count < 1;\n}\n</code></pre>\n</blockquote>\n\n<p>Edited : - <strong>This is wrong</strong> thanks to comment\nPerhaps I'm wrong, but <code>self == null</code> couldn't ever happen, if <code>self == null</code> a <code>Object reference not set to an instance of an object</code> exception will be thrown at the moment the method will be invoked on a null value.</p>\n\n<p>IEnumerable objects, can also be implemented lazily, so the count will actually iterate over all of the Enumerable objects. I don't assume this is desirable for an 'All around' Null or empty check.</p>\n\n<p>Anyway, different needs require different object handling, though I mostly agree with Ocelot20 answer. </p>\n\n<ul>\n<li>When returning an IEnumerable object, you should usually don't return a null value but an Enumerable.Empty();</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:47:34.790",
"Id": "83873",
"Score": "0",
"body": "-1 \"Perhaps I'm wrong, but self == null couldn't ever happen\" - have you bothered to try it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:18:36.753",
"Id": "83888",
"Score": "0",
"body": "Np, downvote removed :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:28:42.073",
"Id": "83931",
"Score": "1",
"body": "For anyone wondering why `self == null` is incorrect (it took me a second to figure out what you were saying), the extension method is `static` and can be called on a null object."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:58:37.497",
"Id": "47839",
"ParentId": "47800",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47805",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:18:08.633",
"Id": "47800",
"Score": "5",
"Tags": [
"c#",
"extension-methods"
],
"Title": "Lazy man's IEnumerable extension verification method"
} | 47800 |
<p>Suppose I have a nested class structure like this:</p>
<pre class="lang-cs prettyprint-override"><code>namespace My.Namespace {
public class Foo {
public class Bar {
public class Baz {
public string Test { get; set; }
}
}
}
}
</code></pre>
<p>I need to get the nested type name of <code>Baz</code> without the namespace, i.e. <code>Foo+Bar+Baz</code> in a generic method. Unfortunately, <code>.Name</code> will just return <code>Baz</code> and <code>.FullName</code> will give me the namespace as well. Right now I'm using this:</p>
<pre class="lang-cs prettyprint-override"><code>protected T LoadSample<T>(string fileName)
{
var t = typeof(T);
var nestedTypeName = t.Namespace == null
? t.FullName // T is declared outside of a namespace
: t.FullName.Substring(t.Namespace.Length + 1);
...
}
</code></pre>
<p>But this just looks ugly. Is there a more standard method for getting just <code>Foo+Bar+Baz</code> in this situation?</p>
<p>To clarify what's going on inside this method, this is part of a unit test for an XML serialization class. <code>LoadSample</code> will load an XML file, wrap it in a little more XML to create an 'envelope', attempt to parse it, and return the result if it succeeds. The problem is that the 'envelope' that the XML serialization class expects the XML to specify the type name in a particular format. For example:</p>
<pre class="lang-xml prettyprint-override"><code><baz>
<test>Testing</test>
</baz>
</code></pre>
<p>Will be wrapped in an evelope like this:</p>
<pre class="lang-xml prettyprint-override"><code><evelope>
<messageType>urn:My.Namespace:Foo+Bar+Baz</messageType>
<message>
<test>Testing</test>
</message>
</evelope>
</code></pre>
| [] | [
{
"body": "<p>It sounds like this might be what you are looking for I think.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.reflectedtype%28v=vs.110%29.aspx\" rel=\"nofollow\">Type.ReflectedType Property (.NET 4.5)</a> </p>\n\n<pre><code>GetType(t).ReflectedType;\n</code></pre>\n\n<p>I am not sure what version of the framework that you are using though.</p>\n\n<hr>\n\n<p>this may only work if you nest it</p>\n\n<pre><code>(GetType(GetType(t).ReflectedType).ReflectedType).ToString() + \".\" + (GetType(t).ReflectedType).ToString() + \".\" + (GetType(t).Name).ToString();\n</code></pre>\n\n<p>that is kind of messy too though. </p>\n\n<hr>\n\n<p>There is also the <code>GetNestedTypes</code> and <code>GetNestedType</code> Methods which will return the types along the way. </p>\n\n<p>you may have to create a function that will recursively build the nested class name for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:09:03.287",
"Id": "83792",
"Score": "0",
"body": "That returns a `Type`. How does that help you get the name?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:22:00.143",
"Id": "83793",
"Score": "0",
"body": "This returns `Bar` because `Baz` is contained in `Bar`. It doesn't hold the entire sequence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:22:53.780",
"Id": "83794",
"Score": "0",
"body": "@JeroenVannevel see Edits. it's still really messy, the OP might be a better fit, unless they go with creating a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:23:44.180",
"Id": "83824",
"Score": "0",
"body": "@svick, this function takes a string parameter, but returns a type, so the OP doesn't really need the name, they need the type, probably for comparison based on the comment on Mat'sMug's answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:28:10.843",
"Id": "83825",
"Score": "0",
"body": "@Malachi The function doesn't return `Type`, it returns `T`. It's hard to say what exactly it does in the `...` part, but I don't think wild guessing about it makes much sense."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:06:31.863",
"Id": "47808",
"ParentId": "47804",
"Score": "2"
}
},
{
"body": "<p><code>System.Type</code> inherits a <code>Name</code> property from <code>System.Reflection.MemberInfo</code> (<a href=\"http://msdn.microsoft.com/en-us/library/system.type%28v=vs.110%29.aspx\" rel=\"nofollow\">MSDN</a>), which returns the name of the member, <em>not the fully qualified name</em>. As you've noticed that returns <code>Baz</code> when you want <code>Foo.Bar.Baz</code>.</p>\n\n<p>Either you use reflection to get the three types and concatenate their <code>.Name</code>, or you do what you did and chop off the namespace from the fully qualified name.</p>\n\n<p>And it's ugly. What are we trying to accomplish here?</p>\n\n<pre><code>protected T LoadSample<T>(string fileName)\n</code></pre>\n\n<p>If you're loading data from a file named by the <code>fileName</code> argument, and using reflection to instantiate <code>Baz</code>, I'd suggest abstracting this dirt away into a <code>SampleFactory<T></code>... I'm curious about what happens to the type's name in the rest of your code; reading your code makes me wonder <em>why</em> you would need to do this to <em>load a sample T from fileName</em>.</p>\n\n<p>Is it possible that your life would be simpler if <code>T</code> had a <code>new()</code> type constraint (i.e. if <code>T</code> had a parameterless constructor)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:45:14.793",
"Id": "83821",
"Score": "2",
"body": "It's actually a unit test for a serialization class. The sample file contains XML that gets loaded, wrapped in some more XML to create an 'envelope' which specifies the type name, and then that entire XML is passed on to the serializer which is supposed to parse it and generate the desired type. The serializer expects the envolope to specify the message type as `\"urn:message:My.Namespace:Foo+Bar+Baz\"`. The goal is to verify that `T` can be deserialized with this tool, without having to encode the entire envelope in my sample file, because I will be using the same samples for other tests."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:36:55.073",
"Id": "47822",
"ParentId": "47804",
"Score": "1"
}
},
{
"body": "<p>Well, one brute force way of doing it is to recurse over the type's DeclaringType property:</p>\n\n<pre><code>public static string TypeName (Type type)\n{\n if(type.DeclaringType == null)\n return type.Name;\n\n return TypeName(type.DeclaringType) + \".\" + type.Name;\n}\n</code></pre>\n\n<p>Running the following program:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var type = typeof(My.Namespace.Foo.Bar.Baz);\n var name = TypeName(type);\n}\n</code></pre>\n\n<p>returns the name <code>Foo.Bar.Baz</code> as you would expect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-20T17:32:42.130",
"Id": "205275",
"Score": "0",
"body": "Except it's `Foo+Bar+Baz`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T18:01:41.260",
"Id": "49659",
"ParentId": "47804",
"Score": "5"
}
},
{
"body": "<p>When reflecting on types you could look at the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.type.membertype?view=netframework-4.5\" rel=\"nofollow noreferrer\">MemberType</a> to determine whether to add the + sign before the name of the type:</p>\n\n<pre><code>public static string GetTypeName(Type type)\n{\n if (type.MemberType == MemberTypes.NestedType)\n {\n return string.Concat(GetTypeName(type.DeclaringType), \"+\", type.Name);\n }\n\n return type.Name;\n}\n</code></pre>\n\n<p>With your example types the output of:</p>\n\n<pre><code>GetTypeName(typeof(My.Namespace.Foo.Bar.Baz));\n</code></pre>\n\n<p>is Foo+Bar+Baz</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T17:13:43.517",
"Id": "404669",
"Score": "0",
"body": "Is there an advantage to examining `type.MemberType` rather than Dan's approach of checking `type.DeclaringType == null` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:46:18.843",
"Id": "203602",
"ParentId": "47804",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T17:36:59.677",
"Id": "47804",
"Score": "7",
"Tags": [
"c#",
".net",
"reflection"
],
"Title": "Get nested type name without namespace"
} | 47804 |
<p>How do I optimize this code further? Goal is to edit "js-tab" in one place. <a href="http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/" rel="nofollow">This</a> is what I tried to follow.</p>
<p>Full code <a href="http://codepen.io/TDogg137/pen/yKzlj/" rel="nofollow">here</a>.</p>
<pre><code>var ToggleTab = {
init: function() {
this.tab = $(".js-tab");
this.bindEvents();
},
bindEvents: function() {
this.tab.on("click", this.toggleTab);
//this.tab.on("click", $.proxy(this.toggleTab, this));
},
toggleTab: function(e) {
var showTab = $(this).data("tab-content");
e.preventDefault();
$(".js-tab").each(function() {
if ($(this).data("tab-content") === showTab) {
$(".js-tab-" + showTab).removeClass("hide");
} else {
$(".js-tab-" + $(this).data("tab-content")).addClass("hide");
}
});
}
};
$(function() {
ToggleTab.init();
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T10:03:42.593",
"Id": "83896",
"Score": "0",
"body": "Optimise for what - speed, memory, source file size? And what would be an acceptable value at which point you'll stop optimising? Unless you can answer these, you're wasting your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:04:31.463",
"Id": "83924",
"Score": "0",
"body": "An acceptable value is already in his question: \" Goal is to edit \"js-tab\" in one place.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:18:48.107",
"Id": "83991",
"Score": "0",
"body": "Just like Greg said.. also I'd like to use this.tab (like in bindEvents) inside toggleTab but I would get \"undefined\". Another way to say is I'd like to define a bunch of properties on init and reference them within the methods below. Hopefully I'm making sense."
}
] | [
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li>You are selecting the content <code>div</code>s with a class name, you should select them with an <code>id</code> instead</li>\n<li>It is much more readable, to simply hide all content, and then show what you need.</li>\n</ul>\n\n<p>With that I would counter propose the content to look like this:</p>\n\n<pre><code><div class=\"js-tab-content\" id='orange'>Orange Content</div>\n<div class=\"js-tab-content hide\" id='red'>Red Content</div>\n<div class=\"js-tab-content hide\" id='purple'>Purple Content</div>\n</code></pre>\n\n<p>and then <code>toggleTab</code> would be</p>\n\n<pre><code>toggleTab: function(e) { \n\n var showTab = $(this).data(\"tab-content\");\n e.preventDefault();\n\n $(\".js-tab-content\").hide();\n $('#' + showTab).show();\n}\n</code></pre>\n\n<p>Otherwise I like your code, it's solid.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:24:11.020",
"Id": "47811",
"ParentId": "47806",
"Score": "4"
}
},
{
"body": "<p>I've always been partial to writing JavaScript classes that take a root element:</p>\n\n<pre><code>function TabController() {\n // Maintain reference to \"this\" in event handlers\n this.toggleTab = this.toggleTab.bind(this);\n}\n\nTabController.prototype = {\n\n $element: null,\n\n constructor: TabController,\n\n init: function(element) {\n this.$element = $(element).on(\"click\", \".js-tab\", this.toggleTab);\n\n return this;\n },\n\n toggleTab: function(event) {\n var that = this,\n showTab = event.target.getAttribute(\"data-tab-content\");\n event.preventDefault();\n\n this.$element.find(\".js-tab\").each(function() {\n var tabContent = this.getAttribute(\"data-tab-content\");\n\n if (tabContent === showTab) {\n that.$element.find(\".js-tab-\" + showTab).removeClass(\"hide\"); \n } else {\n that.$element.find(\".js-tab-\" + tabContent).addClass(\"hide\");\n }\n });\n }\n};\n</code></pre>\n\n<p>Plus, I like to replace jQuery API calls that wrap cross browser native DOM methods -- e.g. <code>$(foo).data(\"bar\")</code> most times can be replaced with <code>element.getAttribute(\"data-bar\")</code>.</p>\n\n<p>And to use:</p>\n\n<pre><code>// using document.documentElement means you don't need a jQuery dom-ready event handler\nvar tabs = new TabController().init(document.documentElement);\n</code></pre>\n\n<p>While you technically only need one tabber per page, making this an instantiable class allows you to unit test your JavaScript.</p>\n\n<pre><code>describe(\"TabController\", function() {\n\n var element, tabs, event;\n\n function FauxEvent(type, target) {\n this.type = type;\n this.target = target;\n }\n\n FauxEvent.prototype.preventDefault = function() {};\n\n describe(\"toggleTab\", function() {\n\n beforeEach(function() {\n element = document.createElement(\"div\");\n tabs = new TabController().init(element);\n });\n\n it(\"shows a tab\", function() {\n element.innerHTML = [\n '<a class=\"js-tab\" data-tab-content=\"panel-1\">Tab 1</a>',\n '<div class=\"js-tab-panel-1 hide\"></div>'\n ].join(\"\");\n\n event = new FauxEvent(\"click\", element.firstChild);\n\n tabs.toggleTab(event);\n\n expect($(element.lastChild).hasClass(\"hide\")).toBe(false);\n });\n\n });\n\n});\n</code></pre>\n\n<p>This makes your code truly modular. You could go a step further and make the CSS class names and data attributes customizable:</p>\n\n<pre><code>function TabController() {\n // Maintain reference to \"this\" in event handlers\n this.toggleTab = this.toggleTab.bind(this);\n\n this.options = {\n classPrefix: \"js-tab\",\n hiddenClass: \"hide\",\n dataAttribute: \"data-tab-content\"\n };\n}\n\nTabController.prototype = {\n\n $element: null,\n\n options: null,\n\n constructor: TabController,\n\n init: function(element, options) {\n this.$element = $(element).on(\"click\", \".\" + this.options.classPrefix, this.toggleTab);\n jQuery.extend(this.options, options || {});\n\n return this;\n },\n\n toggleTab: function(event) {\n var that = this,\n showTab = event.currentTarget.getAttribute(this.options.dataAttribute);\n event.preventDefault();\n\n this.$element.find(\".\" + this.options.classPrefix).each(function() {\n var tabContent = this.getAttribute(that.options.dataAttribute);\n\n if (tabContent === showTab) {\n that.$element.find(\".\" + that.options.classPrefix + \"-\"\n + showTab).removeClass(that.options.hiddenClass);\n } else {\n that.$element.find(\".\" + that.options.classPrefix + \"-\"\n + tabContent).addClass(that.options.hiddenClass);\n }\n });\n }\n};\n</code></pre>\n\n<p>Some sample HTML</p>\n\n<pre><code><ul>\n <li class=\"js-tab\" data-tab-content=\"content-a\"><a href=\"#\">Tab 1</a></li>\n <li class=\"js-tab\" data-tab-content=\"content-b\"><a href=\"#\">Tab 2</a></li>\n</ul>\n\n<div class=\"js-tab-content-a\">\n Content A\n</div>\n<div class=\"js-tab-content-b\">\n Content B\n</div>\n\n<script type=\"text/javascript\">\n var tabs = new TabController().init(document.documentElement);\n</script>\n</code></pre>\n\n<p>JSFiddle: <a href=\"http://jsfiddle.net/CL8Ns/\" rel=\"nofollow\">http://jsfiddle.net/CL8Ns/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:32:20.130",
"Id": "83819",
"Score": "4",
"body": "Very nice review, more detailed than mine, welcome to CodeReview. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T23:27:47.773",
"Id": "83851",
"Score": "0",
"body": "Hi Greg, this is very thorough and I really appreciated. A few things: 1)Is this some kind of common pattern out there that perhaps you can send me a link to check out with more documentation? 2) I noticed you use \"new\" to instantiate which I thought should be avoided according to Crockford?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:41:25.250",
"Id": "83921",
"Score": "0",
"body": "I don't recall a website outlining this pattern. It's just a pattern I keep gravitating towards. Also, take Crockford's advice (and any Guru for that matter) with a grain of salt. The `new` keyword is not bad. He's just advising to not invoke object constructors unless you have a good reason to. Code like this is a good reason to, but notice the `options` property in my code is just using JSON instead of a JavaScript \"class.\" That's the root of what Crockford is saying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:44:43.363",
"Id": "83922",
"Score": "0",
"body": "Another thought about the `new` keyword too. Most modern browsers have performance enhancements around object oriented code, including object constructor functions, that allow JavaScript to be executed at near native speeds. If you are doing `new Foo()` a thousand times inside a loop, yeah you might see a performance issue. Otherwise, you won't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:30:13.003",
"Id": "83995",
"Score": "0",
"body": "@GregBurghardt - I tried your [code](http://codepen.io/TDogg137/pen/dJkcF) but it's not quite working. Should it work or this is just an example of your pattern?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T12:23:41.950",
"Id": "84137",
"Score": "0",
"body": "It's an example. It might be worth your while to investigate why it's not working. :) Or, \"I leave this as an exercise for the Reader.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T12:39:50.227",
"Id": "84139",
"Score": "0",
"body": "JSFiddle: http://jsfiddle.net/CL8Ns/ (also, I'll update my answer with working code)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:50:55.040",
"Id": "47818",
"ParentId": "47806",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "47818",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:04:31.810",
"Id": "47806",
"Score": "8",
"Tags": [
"javascript",
"jquery"
],
"Title": "Optimize this jQuery tab controller further"
} | 47806 |
<p>I finally managed to get the code to work properly. It makes the player object move faster if the user double taps the arrow key with a few 'ticks' (new frames) after the 1st stroke. - User presses and has a limited time to press again to sprint the object. If the time runs out the user has to try again.</p>
<p>However, It'd be better I believe to be working with time, miliseconds and not 'ticks', as what I intend involves lots of key combinations that have x seconds to be pressed.</p>
<p>I would like to know the redundancies in the code, what can be made into a class and something better then screen refresh to time things up (delays?).</p>
<pre><code>package
{
import flash.display.Sprite;
import flash.display.Graphics;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
public class Main extends Sprite {
var keys:Array = [];
var player:Sprite = new Sprite();
var sprint, condition1, condition2, timerStart, keyUp, keyDown:Boolean;
var timer:int;
public function Main():void {
player.graphics.beginFill(0x000000);
player.graphics.drawCircle(0, 0, 25);
player.graphics.endFill;
addChild(player);
player.x = 100;
player.y = 250;
player.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
function update(e:Event):void {
if ((timerStart)&&(timer>0)) {
timer --;
condition1 = true;
}
if (keyUp) {
if ((condition1) && (timer > 0)) {
condition2 = true;
}
if (sprint) {
timerStart = false;
condition1 = false;
condition2 = false;
sprint = false;
timer = 7;
}
if (timer <= 0) {
timerStart = false;
condition1 = false;
condition2 = false;
sprint = false;
timer = 7;
}
}
if (keys[Keyboard.RIGHT]) {
timerStart = true;
if ((condition1) && (condition2)) {
sprint = true;
}
if (sprint) {
player.x += 7;
} else player.x += 2;
}
function onKeyDown(e:KeyboardEvent):void {
keys[e.keyCode] = true;
keyUp = false;
keyDown = true;
}
function onKeyUp(e:KeyboardEvent):void {
keys[e.keyCode] = false;
keyUp = true;
keyDown = false;
}
} // class
} // package
</code></pre>
| [] | [
{
"body": "<p>From a once over</p>\n\n<ul>\n<li>Indentation is terrible, consider using a tool like <a href=\"http://jsbeautifier.org\" rel=\"nofollow\">jsbeautifier.org</a>, it works for ActionScript as well</li>\n<li>Keep working with <code>Event.ENTER_FRAME</code> <- It is the better approach in my mind</li>\n<li><p>Always be on the look out for copy pasted code, this:</p>\n\n<pre><code>if (sprint) {\n timerStart = false;\n condition1 = false;\n condition2 = false;\n sprint = false;\n timer = 7;\n}\n\nif (timer <= 0) {\n timerStart = false;\n condition1 = false;\n condition2 = false;\n sprint = false;\n timer = 7;\n}\n</code></pre></li>\n</ul>\n\n<p>could be </p>\n\n<pre><code> if (sprint || timer <= 0) {\n timerStart = false;\n condition1 = false;\n condition2 = false;\n sprint = false;\n timer = 7;\n }\n</code></pre>\n\n<ul>\n<li>Do not track <code>keyDown</code>, you do not use it, and it's value is always the opposite of <code>keyUp</code></li>\n<li><code>condition1</code> and <code>condition2</code> are very unfortunate names, you should try to be more descriptive </li>\n<li><p>This code could use some well named constants and indenting:</p>\n\n<pre><code>if (sprint) {\nplayer.x += 7;\n} else player.x += 2;\n</code></pre>\n\n<p>I would rather see</p>\n\n<pre><code>var FAST_SPEED = 7,\n NORMAL_SPEED = 2;\nif (isSprinting) {\n player.x += FAST_SPEED;\n} else {\n player.x += NORMAL_SPEED;\n}\n</code></pre>\n\n<p>or if I wanted to be fancy </p>\n\n<pre><code>player.x += isSprinting ? FAST_SPEED : NORMAL_SPEED;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:36:19.223",
"Id": "83827",
"Score": "0",
"body": "Ok, how do I time things if needed? 0,5 secs instead of the value 7 held by var timer for an example :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:41:08.417",
"Id": "83828",
"Score": "2",
"body": "That would be an SO question :\\"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:48:32.870",
"Id": "47817",
"ParentId": "47812",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:24:29.693",
"Id": "47812",
"Score": "4",
"Tags": [
"beginner",
"classes",
"actionscript-3"
],
"Title": "Character Sprint Spaghetti Code"
} | 47812 |
<p>I'm trying to code following requirements with lockfree in most-used-code-path that is to get a resource from pool.</p>
<ol>
<li><p>Same resource should be used n (<code>maxUsageCount</code>) number of times and then
destroyed and create a new one.</p></li>
<li><p>If there is an error with a resource, it should be marked <code>stale</code> by
client. Staled resource should be destroyed and not handed out to
the clients, a new resource should be created.</p></li>
<li><p>Resource must be closed after <code>maxUsageCount</code> otherwise its leak.</p></li>
</ol>
<p>Resource is threadsafe.</p>
<pre><code>public class ReusableResource<T extends ResourceProxy> {
public static interface Factory<T extends ResourceProxy> {
T create();
}
private final int maxUsageCount;
private final AtomicReference<ConcurrentLinkedQueue<T>> resources;
private final Object lock;
private final ReusableResource.Factory<T> factory;
public ReusableResource(int maxUsageCount,
ReusableResource.Factory<T> factory) {
if (maxUsageCount < 0)
throw new IllegalArgumentException("maxUsageCount " + maxUsageCount);
if (factory == null)
throw new IllegalArgumentException("factory " + factory);
this.maxUsageCount = maxUsageCount;
resources = new AtomicReference<ConcurrentLinkedQueue<T>>(
new ConcurrentLinkedQueue<T>());
lock = new Object();
this.factory = factory;
}
public T get() {
final ConcurrentLinkedQueue<T> tmpq = resources.get(); // load once
T res = tmpq.poll();
if (res == null) {
synchronized (lock) {
res = tmpq.poll(); // double check
// empty queue, first time or none left
if (res == null) {
final ConcurrentLinkedQueue<T> newq = new ConcurrentLinkedQueue<T>(
Collections.nCopies(maxUsageCount, factory.create()));
// checkout the one we are returning
res = newq.poll();
// overwrite q object, do not modify existing
this.resources.set(newq);
// no stale check on newly created instance
return res; // <<- exit,
}
}
}
if (res.isStaled()) {
synchronized (lock) {
// once staled its going to remain staled
// no need for double check
// call destroy on all remaining elements
// so that it can actually be closed
// this might cause more destroy then checkouts
// and so destroy must be idempotent
res.destroy();
while ((res = tmpq.poll()) != null)
res.destroy();
// create new resources queue, same as first time
final ConcurrentLinkedQueue<T> newq = new ConcurrentLinkedQueue<T>(
Collections.nCopies(maxUsageCount, factory.create()));
// checkout the one we are returning
res = newq.poll();
// overwrite q object, do not modify existing
this.resources.set(newq);
}
}
return res;
}
}
</code></pre>
<p>ResourceProxy.java</p>
<pre><code>public abstract class ResourceProxy implements Disposable {
private final AtomicInteger usageCount;
private volatile boolean staled;
public ResourceProxy(int maxUsageCount) {
if (maxUsageCount < 0) throw new IllegalArgumentException();
this.usageCount = new AtomicInteger(maxUsageCount);
this.staled = false;
}
@Override
public void destroy() {
if (usageCount.decrementAndGet() == 0) {
closeResource();
}
}
@Override
public void setStaled() {
this.staled = true;
}
@Override
public boolean isStaled() {
return staled;
}
abstract protected void closeResource();
}
</code></pre>
<p>Example usage:</p>
<pre><code>public class QueueConnectionProxy extends ResourceProxy implements
QueueConnection {
public static class Factory implements
ReusableResource.Factory<QueueConnectionProxy> {
private final int maxUsageCount;
public Factory(int maxUsageCount) {
if (maxUsageCount < 0) throw new IllegalArgumentException();
this.maxUsageCount = maxUsageCount;
}
@Override
public QueueConnectionProxy create() {
return new QueueConnectionProxy(maxUsageCount);
}
}
private final QueueConnection delegate;
public QueueConnectionProxy(int maxUsageCount) {
super(maxUsageCount);
delegate = createDelegate();
}
private QueueConnection createDelegate() {
// create QueueConnection
return createdQueueConnection
}
@Override
protected void closeResource() {
try {
if (delegate != null) delegate.close();
} catch (JMSException e) {
e.printStackTrace();
// TODO: log JMSException
}
}
@Override
public void close() throws JMSException {
destroy();
}
// other delegate methods
//
}
</code></pre>
<p>To create an instance of <code>ReusableResource</code>:</p>
<pre><code>ReusableResource<QueueConnectionProxy> reuse =
new ReusableResource<QueueConnectionProxy>(
10, new QueueConnectionProxy.Factory(10));
</code></pre>
<p>Client code:</p>
<pre><code>QueueConnection qc = null;
try {
qc = reuse.get();
} finally {
try { qc.close(); }
catch (JMSException e) { e.printStackTrace(); }
}
</code></pre>
| [] | [
{
"body": "<p>Welcome to Code Review.</p>\n\n<p>You have posted an very good quality post and that's why it takes so long to get an answer.</p>\n\n<p>I have 2 minor remarks to make.</p>\n\n<h2>First :</h2>\n\n<pre><code>if (maxUsageCount < 0) throw new IllegalArgumentException();\n</code></pre>\n\n<p>You do this check 3 times, I have no problem with that.<br/>\nBut what if your maxUsageCount is 0 ? <br/>\nI think this is an unwanted situation so better to do :</p>\n\n<pre><code>if (maxUsageCount <= 0) throw new IllegalArgumentException();\n</code></pre>\n\n<p><br/></p>\n\n<h2>Second :</h2>\n\n<p>The clientCode :</p>\n\n<pre><code>QueueConnection qc = null;\ntry {\n qc = reuse.get();\n} finally {\n try { qc.close(); }\n catch (JMSException e) { e.printStackTrace(); }\n}\n</code></pre>\n\n<p>You do not check if qc is null, what is possible when you get an exception.\nYou have 2 options for this.</p>\n\n<pre><code>QueueConnection qc = null;\ntry {\n qc = reuse.get();\n} finally {\n if (qc!=null) {\n try { qc.close(); }\n catch (JMSException e) { e.printStackTrace(); }\n }\n}\n</code></pre>\n\n<p><b>edit :</b><br/>\nThis last one is wrong cause <code>QueueConnection</code> doesn't implement <code>AutoClosable</code>.</p>\n\n<p><s>Or from java 7 you can use try-with-resource</s>\nWhen you extend <code>QueueConnection</code> and implement the <code>AutoClosable</code> you can do the following :</p>\n\n<pre><code>try (QueueConnectionAutoClosable qc = reuse.get()) {\n //custom code what you need to do.\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T13:29:37.333",
"Id": "49145",
"ParentId": "47816",
"Score": "5"
}
},
{
"body": "<p>In general it <em>looks</em> good, now going through the code to also see if it actually is good.</p>\n<h3>1. Exception messages</h3>\n<p>Your exception messages should be made clearer, an example of them is at the constructor of <code>ReusableResource</code>. If <code>maxUsageCount < 0</code> or <code>factory == null</code>, we get echoed the value of the variable back, but no indication whatsoever to what is actually wrong with it. It would be good to see it included. Also <code>maxUsageCount == 0</code> is most likely not wanted, is it? Lastly on this point, I would prefer <code>this.factory = Objects.requireNonNull(factory)</code> <strong>if</strong> you only use <code>factory</code> once, as the case is here. If it would be used multiple times, then there should be a simple <code>Objects.requireNonNull(factory)</code> check at the top of the method, to ensure the check only runs once.</p>\n<h3>2. Initialize objects as early as possible.</h3>\n<p>You are initializing both <code>resources</code> and <code>lock</code> in the constructor, and not at declaration time, which looks suspicious. They do not depend on either <code>maxUsageCount</code> or <code>factory</code> passed into the constructor. Hence I see no reason to initialize them late. This prevents duplicate code when adding more constructors.<br />\nThis also holds for <code>delegate</code> in <code>QueueConnectionProxy</code>.</p>\n<h3>3. Try to use more meaningful variable names.</h3>\n<p>As a reader of the code, it is very hard to get the meaning of <code>tmpq</code> in <code>ReusableResource.get()</code>, after some thinking (which is a precious resource) I realised it was meant to be temporary queue, just name it <code>tempQueue</code> then.</p>\n<h3>4. Consider factory methods.</h3>\n<p>The lines:</p>\n<pre><code>ReusableResource<QueueConnectionProxy> reuse = \n new ReusableResource<QueueConnectionProxy>(\n 10, new QueueConnectionProxy.Factory(10));\n</code></pre>\n<p>are simply too long. Your code would benefit from giving <code>ReusableResource</code> a static method that creates a new <code>ReusableResource</code>, more over it <em>seems</em> that the <code>10</code> parameter is specified two times there, though I might be wrong. In either case, your static method would be called as <code>ReusableResource.newInstance(10)</code> or <code>ReusableResource.newInstance(10, 10)</code>. This also hides the specification of the type parameter multiple times.</p>\n<h3>5. Use try-with-resources if possible</h3>\n<p>I do not know all places where try-with-resources is possible in your code after a brief look, but the following seems a good candidate:</p>\n<pre><code>QueueConnection qc = null;\ntry {\n qc = reuse.get();\n} finally {\n try { qc.close(); }\n catch (JMSException e) { e.printStackTrace(); }\n}\n</code></pre>\n<p>Which would become:</p>\n<pre><code>try (QueueConnection qc = reuse.get()) {\n //use\n}\n</code></pre>\n<p>For this you might need to implement <code>AutoClosable</code> yourself, I cannot tell if that is possible.</p>\n<p>That leads to the end of the review, unfortunately I am only able to touch the basic concepts and not the low level concurrency stuff as I consider myself not experienced enough to give advice upon that yet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T09:28:39.123",
"Id": "49215",
"ParentId": "47816",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T18:48:13.027",
"Id": "47816",
"Score": "12",
"Tags": [
"java",
"concurrency"
],
"Title": "java.util.concurrent bounded resuable resource implementation"
} | 47816 |
<p>I have a website where people can write articles and publish/unpublish them. This is done via single button on the page:</p>
<pre><code><a id="publish-button" href="#" class="btn btn-default <%= 'btn-success' if @article.published? %>">
<span class="glyphicon glyphicon-globe"></span>
</a>
</code></pre>
<p>As you can see, if an article is already published I'm adding additional <code>btn-success</code> class.</p>
<p>Now, this is the JavaScript code that handles Ajax clicks on that button:</p>
<pre><code>var $editor = $('#editor'); // Article container, it contains update action url as data-url
var $publishButton = $('#publish-button');
var togglePublished = function () {
var url = $editor.data('url');
var postData = {
article: {
stage: $publishButton.hasClass('btn-success') ? 'unpublished' : 'published'
},
_method: 'PUT'
};
$.ajax({
url: url,
data: postData,
method: 'POST',
success: function (article) {
$publishButton['published' == article.stage ? 'addClass' : 'removeClass']('btn-success');
}
});
};
$publishButton.click(function (e) {
e.preventDefault();
togglePublished();
});
</code></pre>
<p>My controller action just returns a JSON encoded article in this case:</p>
<pre><code>def update
if @article.update(article_params)
render json: @article
else
render json: { errors: @article.errors.full_messages }, status: :unprocessable_entity
end
end
</code></pre>
<p>There are few things I see wrong with this:</p>
<ol>
<li>My post data depends on class, which can be changed and changing it would require me to change it on two places: in template and in JS. </li>
<li>If I add <code>data-published</code> attribute to the button I would still have to add/remove class after Ajax has finished resulting in duplicated view logic (in HTML file and JS file).</li>
</ol>
<p>I can see two ways to avoid this and be DRY:</p>
<p><strong>Add conditional class only in JavaScript and run check upon page load</strong></p>
<p>This would be fairly easy to do but would result in a brief delay because conditional class would be added in JavaScript which runs after all HTML has already loaded.</p>
<p><strong>Extract button to partial view and return it from controller in Ajax</strong></p>
<p>This seems like a more solid approach but since my <code>update</code> action is used in other places too it has to return article as JSON. That's why I would have to create another controller action:</p>
<pre><code>def toggle_published
@article.toggle_published # Something like this
render partial: '_publish_button'
end
</code></pre>
<p>This reduces "restfulness" of my controller and it seems kind of silly to extract only one HTML element into a partial view.</p>
<p>Is there any better way to do this? It seems like a minor and insignificant code duplication but it's not an isolated example and as website complexity grows these things can multiply a lot and cause a lot of headaches.</p>
| [] | [
{
"body": "<p>You could theoretically overload the <code>show</code> action to only return the partial <code>if request.xhr?</code>. So if it's an ajax request, only render that button partial. But that's inelegant.</p>\n\n<p>Alternatively, you can simply keep the default <code>show</code> action, send the entire page back, and just pluck out the button element (similar to how <a href=\"https://github.com/rails/turbolinks\" rel=\"nofollow\">Turbolinks</a> work). It'll keep the controller RESTful and keep the update-magic in the JS only. The trade-off is that you'll be rendering stuff that you won't actually use for anything. However, you can avoid some of it by disabling layout rendering for XHR requests (which is somewhat less kludgy than just rendering a partial; at least you're still rendering the <code>show</code> template).</p>\n\n<p>However, having the publish button's state just defined by its color doesn't sounds like a very clear UI to me. Does a (presumably) green button mean \"not published; clicking will publish\" or \"already published; clicking will unpublish\"? I'd much prefer the button actually having a verb on it like \"Publish\" or \"Unpublish\" (or whatever you'd call it), so it's clear what the button will do.</p>\n\n<p>Regardless, using the <code>btn-sucess</code> class gives you the desired look, but it's semantically meaningless. The class name doesn't really describe the current state or the action the button will take.</p>\n\n<p>Picking the \"re-render the show template\"-option above will give you a chance to re-render the entire post with a <code>published</code> class. Then you can have a CSS rule like:</p>\n\n<pre><code>#post.published #publish-button {\n // set color etc.\n}\n</code></pre>\n\n<p>Not as simple as using the generic <code>btn-success</code> class, but to me it makes more sense to track the state for the post as a whole, rather than a single button.</p>\n\n<p>I imagine something like this for the view</p>\n\n<pre><code><article id=\"post_123\" data-url=\"...\" class=\"<%= 'published' if @article.published? %>\">\n <div id=\"editor\">...</div>\n <a id=\"publish-button\" href=\"#\" class=\"...\">\n ...\n </a>\n</article>\n</code></pre>\n\n<p>That'll mean that the element with the update URL is the same element that should be replaced by whatever is being sent back from the ajax-request. The JS only really needs to know that rule: Update the element with the <code>data-url</code> attribute. It doesn't need to know the specifics of re-styling individual elements.</p>\n\n<p>Even if you don't go that route, toggling a <code>published</code> class in both view and JS is at least more readable/straight-forward that toggling a semantically unrelated class like <code>btn-success</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:59:27.493",
"Id": "47841",
"ParentId": "47823",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:40:17.187",
"Id": "47823",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rails preventing ajax view duplication"
} | 47823 |
<p>I've got some architecture in my code similar to this. It is about the Construct method in the base class in the example below. This method contains the logic for constructing a building, which is the same in every building. Yet different buildings may want to do things differently, like a different roof. So I've used events to do this. Is this a valid architecture? I know it works, but is there a <strong>better</strong> way? I want to leave the logic of constructing any building in the base class, and not override it to just build another roof and copying 66% of its code.
Remember this is an example. In the code I had to create, it not uses 3 functions in the Construct base method as the logic flow, but over a dozen.</p>
<h2>Base class</h2>
<pre><code>public abstract class Building
{
/// <summary>
/// use this event in the derived class to lay another foundation.
/// </summary>
public event EventHandler OnFoundation;
/// <summary>
/// Use this event in the derived class to build different walls.
/// </summary>
public event EventHandler OnWalls;
/// <summary>
/// Use this event in the derived class to build a different roof.
/// </summary>
public event EventHandler OnRoof;
/// <summary>
/// The number of floors a building as determines how high it will be.
/// </summary>
public readonly int NumberOfFloors;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="argNumberOfFloors">The number of floors a building as determines how high it will be.</param>
protected Building(int argNumberOfFloors)
{
NumberOfFloors = argNumberOfFloors;
}
public void Construct()
{
//Lay the foundation.
if (OnFoundation != null)
{
OnFoundation(this, new EventArgs());
}
else
{
Foundation();
}
//Build the walls
if (OnWalls != null)
{
OnWalls(this, new EventArgs());
}
else
{
Walls();
}
//Build the roof
if (OnRoof != null)
{
OnRoof(this, new EventArgs());
}
else
{
Roof();
}
}
public void Foundation()
{
//Lay foundation
}
public void Walls()
{
for (int i = 0; i < NumberOfFloors; i++)
{
//Build walls
}
}
public void Roof()
{
//Build roof
}
}
</code></pre>
<h2>Implementations</h2>
<blockquote>
<p><strong>Villa</strong></p>
</blockquote>
<pre><code>public class Villa : Building
{
public Villa() : base(2)
{
base.OnRoof += Villa_OnRoof;
}
/// <summary>
/// A villa gets another roof, the rest stays the same
/// </summary>
void Villa_OnRoof(object sender, EventArgs e)
{
//Build another roof than the base class would.
}
}
</code></pre>
<blockquote>
<p><strong>SkyScraper</strong></p>
</blockquote>
<pre><code>public class SkyScraper : Building
{
public SkyScraper() : base(60)
{
base.OnFoundation += SkyScraper_OnFoundation;
}
void SkyScraper_OnFoundation(object sender, EventArgs e)
{
//A skycraper needs a better foundation.
}
}
</code></pre>
| [] | [
{
"body": "<p>This works but is very unusual. The standard way of doing this would actually be virtual methods</p>\n\n<pre><code>public abstract class building {\n ...\n protected virtual CreateWalls() {\n //create 4 walls by default\n }\n protected virtual CreateFoundation() {\n //straightforward foundation by default\n }\n\n public void Construct() {\n CreateWalls();\n CreateFoundation();\n }\n}\n\npublic class SkyScraper : Building {\n public override CreateFoundation() {\n //create deep foundation in bedrock\n }\n}\n</code></pre>\n\n<p>While this is the simplest and is certainly acceptable architecture it is always a good idea to also consider <a href=\"http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance/\">Composition over Inheritance</a></p>\n\n<p>So instead you might do something like</p>\n\n<pre><code>public abstract class Building {\n protected Building(WallConstruction walls, FoundationConstruction foundations, ...) {\n walls.ConstructFor(this);\n foundations.ConstructFor(this);\n }\n}\n</code></pre>\n\n<p>or even more generic</p>\n\n<pre><code>public abstract class Building {\n protected Building(IBuildingComponent[] components) {\n components.ForEach(x => x.ConstructFor(this));\n }\n}\n</code></pre>\n\n<p>a couple more things to consider. </p>\n\n<ul>\n<li>Does it make sense for a <code>Building</code> to be in an unconstructed state? Should this instead be something like <code>BuildingBuilder</code> (or just <code>Construction</code>) and have a <code>Build</code> method that produces a building?</li>\n<li>The whole <code>(EventArgs, object)</code> pattern for events really hasn't made much sense since we got good delegate signatures in .Net 3.5. Just make the signature for the event exactly what you want it to be and use a <code>Action</code> or <code>Func<></code> type.</li>\n<li><p>When using events, instantiate the event to an empty one</p>\n\n<pre><code> public event Action foo = delegate {};\n</code></pre>\n\n<p>that way the delegate will never be empty so there will be no need for a null check.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T22:03:57.383",
"Id": "83846",
"Score": "0",
"body": "I totally agree, except for your use of `ForEach` instead of `foreach` and `delegate {}` instead of `() => {}`. The latter being far less important, as it is simply a matter of style. The former for it's impurity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T04:11:43.123",
"Id": "83874",
"Score": "0",
"body": "I've heard the argument about `ForEach` but I don't see how it really holds water. Just don't affect any inputs. Any purity of other statements like `Select` is solely by convention anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:22:27.067",
"Id": "83940",
"Score": "0",
"body": "It's mostly about how unlike every other Linq statement, `ForEach` does not take and return a list. `Select` may have side effects, but it returns something that can be consumed. `ForEach` can only terminate a sequence of operations, and because it can only be used in such a different way and does nothing that the inbuilt `foreach` cannot, it's use is generally discouraged. It's more about the return than anything else, really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:00:49.843",
"Id": "83954",
"Score": "0",
"body": "All depends on how you implement `ForEach` :) I usually have it return the original list so I can keep chaining - it's basically an \"enumerate with side-effects\" valve. But it's is a legitimate matter of style - I wouldn't reject a PR with `foreach` or anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:26:39.457",
"Id": "83993",
"Score": "0",
"body": "@GeorgeMauer Glad I asked, and glad you answered. How could I have mist the virtual/override mechanism! Thanks for the refresher!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:42:31.330",
"Id": "47831",
"ParentId": "47825",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T19:55:06.663",
"Id": "47825",
"Score": "2",
"Tags": [
"c#",
"inheritance",
"event-handling"
],
"Title": "Can this architecture of base + derived classes be coded more efficient?"
} | 47825 |
<p>I've translated this code from <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a> and would like it to be more idiomatic <a href="/questions/tagged/f%23" class="post-tag" title="show questions tagged 'f#'" rel="tag">f#</a>:</p>
<pre><code>namespace Foo.App_Start
open System
open System.Web
open Microsoft.Web.Infrastructure.DynamicModuleHelper
open Ninject
open Ninject.Web.Common
type NinjectResolver(kernel:IKernel) =
let _kernel = kernel
interface System.Web.Http.Dependencies.IDependencyResolver with
member this.BeginScope():Http.Dependencies.IDependencyScope = upcast this
member this.GetService(t) =
_kernel.TryGet(t)
member this.GetServices(t)=
_kernel.GetAll(t)
member this.Dispose() = ()
//was static
[<AbstractClass; Sealed>]
type NinjectWebCommon () =
static let bootstrapper = new Bootstrapper()
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
//private static void RegisterServices(IKernel kernel)
static let RegisterServices(kernel:IKernel) =
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver <- new NinjectResolver(kernel)
do()
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
//private static IKernel CreateKernel()
static let KernelCreation(kernel:IKernel) =
System.Diagnostics.Debug.WriteLine "kernel Creation!"
RegisterServices(kernel)
let bs = fun () -> new Bootstrapper()
let kernelFun= System.Func<IKernel> (fun () -> bs().Kernel)
kernel.Bind<System.Func<IKernel>>().ToMethod(fun ac -> kernelFun) |> ignore
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>() |> ignore
let fetchedKernel:IKernel =System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof<IKernel>) :?> IKernel
fetchedKernel
static let CreateKernel():IKernel =
System.Diagnostics.Debug.WriteLine "standard kernel creating!"
let kernel= new StandardKernel()
//
try //RegisterServices(kernel) |> ignore;
KernelCreation(kernel)
with
| ex ->
System.Diagnostics.Debug.WriteLine "kernel disposing!"
kernel.Dispose()
raise ex
/// <summary>
/// Starts the application
/// </summary>
static member Start() =
DynamicModuleUtility.RegisterModule typedefof<OnePerRequestHttpModule> |> ignore
DynamicModuleUtility.RegisterModule typedefof<NinjectHttpModule> |> ignore
bootstrapper.Initialize(System.Func<_>(CreateKernel))
System.Diagnostics.Debug.WriteLine "app Start()"
//
//
/// <summary>
/// Stops the application.
/// </summary>
static member Stop() =
System.Diagnostics.Debug.WriteLine "app stop"
bootstrapper.ShutDown()
module DummyModuleToAttachAssemblyAttribute =
[<assembly: WebActivatorEx.PreApplicationStartMethod(typeof<NinjectWebCommon>, "Start")>]
////[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(FLochart.App_Start.NinjectWebCommon), "Stop")]
[<assembly: WebActivatorEx.ApplicationShutdownMethod(typeof<NinjectWebCommon>, "Stop")>]
do()
</code></pre>
| [] | [
{
"body": "<p>Your code seems like it's primarily plumbing. There are no algorithms or types that could be given the functional treatment. I have only two recommendations. </p>\n\n<ol>\n<li><p>Instead of <code>NinjectWebCommon</code> being abstract/sealed with static members you can make it a module with let-bound functions. </p></li>\n<li><p><code>_kernel</code> in <code>NinjectResolver</code> is unnecessary because primary constructor parameters are available throughout the body of the type. So you can just reference <code>kernel</code> throughout instead.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:18:33.560",
"Id": "47886",
"ParentId": "47828",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:14:09.187",
"Id": "47828",
"Score": "3",
"Tags": [
"f#",
"ninject"
],
"Title": "NinjectWebCommon implementation/translation - C# to F#"
} | 47828 |
<p>This is my first ever real 100% self made perl script, I'd like to know how I can improve it.</p>
<pre><code>#!/usr/bin/env perl
#this script takes a directory and sorts the files into folders by file ending
use strict;
use warnings;
use File::Copy;
sub sort_files {
my $dir = shift || '.'; #cwd if no directory given
$dir =~ s/\/$//; #remove trailing /
opendir(DIR, $dir) or die $!;
my @files = grep {
!/^\./ #does not start with .
&& -f "$dir/$_" #is file
} readdir DIR;
my $len = @files;
print "sorting $len files\n";
foreach my $file (@files){
my ($ext) = $file =~ /([^.]*$)/;#grabs file extension
my $dest = "$dir/$ext/";
if (not -d "dest"){ #create folder if it does not exist
mkdir $dest;
print "\tcreated directory $dest\n";
}
move "$dir/$file", $dest or die "$!";
print "\t$file moved to $dest\n"
}
}
sort_files @ARGV;
exit 0;
</code></pre>
<p>ninja edit: I just noticed that this script runs into problems if there is no file ending specified. Elegant solutions apreciated! (checking the file for <code>!/\./</code> would work, but that's not elegant in my book)</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T22:36:48.270",
"Id": "83848",
"Score": "0",
"body": "Also note that directory 0 cannot be specified as the argument."
}
] | [
{
"body": "<p>I've added a few comments in your source,</p>\n\n<pre><code>#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\nuse autodie; # automatic die/checks for http://search.cpan.org/~pjf/autodie/lib/autodie.pm#CATEGORIES\nuse File::Copy;\n\nsub sort_files {\n # my $dir = shift || '.';\n my $dir = shift // '.'; # defined short circuit to allow '0' as argument\n $dir =~ s/\\/$//;\n\n # opendir(DIR, $dir) or die $!;\n opendir(my $DIR, $dir); # use lexical variable instead of glob\n my @files = grep {\n !/^\\./ # not needed if you only want to skip '.' and '..'\n && -f \"$dir/$_\" \n } readdir $DIR;\n\n my $len = @files;\n print \"sorting $len files\\n\";\n\n foreach my $file (@files){\n my ($ext) = $file =~ /([^.]*$)/;\n\n #\n # what do you want to do when $ext is undefined?\n # my ($ext) = $file =~ /([^.]*$)/ or next; # to skip such files\n\n my $dest = \"$dir/$ext/\";\n # if (not -d \"dest\"){ # typo?\n if (not -d $dest){\n mkdir $dest; # added autodie to check on mkdir\n print \"\\tcreated directory $dest\\n\";\n }\n move(\"$dir/$file\", $dest) or die $!; # autodie doesn't handle File::Copy\n print \"\\t$file moved to $dest\\n\"\n }\n}\n\nsort_files(@ARGV); # parentheses around arguments for non core functions are good idea https://eval.in/139428 vs https://eval.in/139430\n# exit 0; # not needed\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:47:37.997",
"Id": "47852",
"ParentId": "47833",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47852",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:10:26.513",
"Id": "47833",
"Score": "4",
"Tags": [
"perl",
"file-system",
"file",
"directory"
],
"Title": "Perl file sorting script"
} | 47833 |
<p>I was asked to provide the solution of this rolling dice problem in an interview. When I showed him my solution, he said that there is another way to find the solution. I am looking for answer in PHP script only.</p>
<blockquote>
<p>Question:</p>
<p>Two persons are playing a game of rolling 2 dices. Each person rolls the two dices n times and records the outcomes (sum of value of two dices) of all the n attempts. So after n attempts of both the player we have two list corresponding to the n outcomes of two players.</p>
<p>They want to know that whether they have got all possible outcomes( 1 to 12) same number of times or not. If they got all the possible outcomes same number of times then they are called lucky otherwise unlucky.</p>
<p><strong>Input</strong>: Two Integer Arrays (L1, L2) corresponding to outcomes of two players.</p>
<p><strong>Output</strong>: Lucky or Unlucky depending on the case</p>
</blockquote>
<p>My Answer:</p>
<pre><code><?php
function rollingdice($input1,$input2)
{
foreach($input1 as $k=>$a)
{
if(in_array($a,$input2))
{$p = array_search($a, $input2);
unset($input2[$p]);
}
else
{ return 'Unlucky';}
}
return 'Lucky';
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T02:39:25.457",
"Id": "83865",
"Score": "0",
"body": "Couldn't you just compare the two arrays directly? Ideally after sorting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-04T15:32:56.473",
"Id": "91894",
"Score": "1",
"body": "_all possible outcomes (1 to 12)_ You can't roll a 1 with two dice. :)"
}
] | [
{
"body": "<p>Based on your use of <code>in_array()</code>, you don't appear to be concerned with the order of the elements. In that case, you can simply sort the arrays and compare them directly.</p>\n\n<pre><code>function compare($array1, $array2)\n{\n sort($array1);\n sort($array2);\n\n return ($array1 == $array2) ? \"Lucky\" : \"Unlucky\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T02:44:41.143",
"Id": "47843",
"ParentId": "47835",
"Score": "5"
}
},
{
"body": "<p>With extra <code>O(n)</code> space the complexity can be made <code>O(n)</code> only, without sorting that will take <code>O(nlogn)</code></p>\n<p>Use a map and add a value for each key as (previousValue +1) or (previousValue - 1) based on array type A or B.\nAlso use a counter to track an absolute increase or decrease if at end the counter is 0. Then the two array has same number of occurrence else not.</p>\n<p>[Edited: Added code]</p>\n<p>A java implementation</p>\n<pre><code>import java.util.HashMap;\n\npublic class Main {\n\n public static void main(String[] args) {\n\n HashMap<Integer, Integer> trackMap = new HashMap<>();\n int n = 6;\n int[] a = {4, 12, 4, 10, 6, 10};\n int[] b = {10, 12, 10, 4, 4, 6};\n int counter = 0;\n for (int i = 0; i < n; i++) {\n if (!trackMap.containsKey(a[i])) {\n trackMap.put(a[i], 1);\n counter++;\n } else {\n int prevVal = trackMap.get(a[i]);\n trackMap.put(a[i], prevVal + 1);\n counter = counter + ((Math.abs(prevVal) > Math.abs(prevVal + 1)) ? -1 : 1);\n }\n if (!trackMap.containsKey(b[i])) {\n trackMap.put(b[i], -1);\n counter++;\n } else {\n int prevVal2 = trackMap.get(b[i]);\n trackMap.put(b[i], prevVal2 - 1);\n counter = counter + ((Math.abs(prevVal2) > Math.abs(prevVal2 - 1)) ? -1 : 1);\n }\n }\n System.out.println(counter == 0 ? "Lucky" : "Unlucky");\n }\n}\n</code></pre>\n<p>Or instead if using counter, you cand finally iterate the hashMap if all value are zero then the person is lucky else not</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T03:39:34.100",
"Id": "483595",
"Score": "0",
"body": "Would you mind demonstrating this technique so that I can be sure I understand your theory?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T11:10:50.020",
"Id": "483636",
"Score": "0",
"body": "@mickmackusa sure. \nAlso looking if can be done using better complexity in term of space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T12:06:02.280",
"Id": "483647",
"Score": "1",
"body": "I only code in php. I thought this was a php question."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-27T19:42:24.850",
"Id": "246093",
"ParentId": "47835",
"Score": "2"
}
},
{
"body": "<p>@Mr AJ already gave you a valid answer on the algorithmic approach in his Java example, but since it seems Java is unfamiliar to you, I will just write out the algorithm here in a way that hopefully makes sense to you.</p>\n<p>There is no need to sort the arrays, doing so ensure more operational complexity than is needed here, as now your a guaranteeing that you are visiting each value in the arrays at least twice (once for sorting, once for reading out sorted values - yes this even happens under the hood in with a <code>==</code> comparison between two sorted arrays as happens in currently selected answer). You can achieve the goal by iterating each array a single time, such that you only visit each value once.</p>\n<p>Your logic should be along the lines of:</p>\n<ul>\n<li>Compare array sizes, if unequal then 'Unlucky'.</li>\n<li>Iterate over first array, building a map (perhaps an associative array or <code>stdClass</code> object in PHP). Keys are values encountered in the array (i.e. 2-12) and the values for this map are the counts of each of the corresponding dice values. You should probably also error on condition of getting value outside the 2-12 range in the array.</li>\n<li>Iterate over the second array, if a dice value is encountered that is not present as a key in the map built from first array, then 'Unlucky'. Otherwise you decrement the stored count in the map by one each time a corresponding dice value is encountered.</li>\n<li>Iterate over the map values, if any value is not equal to 0 then 'Unlucky' else 'Lucky'.</li>\n</ul>\n<p>This provides an <code>O(2n)</code> worst-case operational complexity, where <code>n</code> is the size of the arrays.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T13:15:59.487",
"Id": "246174",
"ParentId": "47835",
"Score": "2"
}
},
{
"body": "<p>After reading the other answers that speak in depth on the theory and big O, I thought I would script up my interpretation.</p>\n<p>Code: (<a href=\"https://3v4l.org/FiXKa\" rel=\"nofollow noreferrer\">Demo with echoed variables to show values and processes</a>)</p>\n<pre><code>function roll() {\n return rand(1, 6) + rand(1, 6);\n}\n\n$roller1 = [];\n$roller2 = [];\n$totalRolls = 1;\n\nfor ($i = 0; $i < $totalRolls; ++$i) {\n $roller1[] = roll();\n $roller2[] = roll();\n}\n\n$map = array_count_values($roller1);\n \n$outcome = 'Lucky';\nforeach ($roller2 as $roll) {\n if (!empty($map[$roll])) {\n --$map[$roll];\n } else {\n $outcome = 'Unlucky';\n break;\n }\n}\n\necho $outcome;\n</code></pre>\n<p>After the formation of the two arrays, php offers a simple function call to create the map of roll values and the number of instances of each value -- <code>array_count_values()</code>. This action is only necessary on the first array.</p>\n<p>The second array is then iterated and each value is checked against the map. If the given value is not a key in the map or it is has a falsey (<code>0</code>) value at the key, then there is a mismatch between <code>$roller1</code> and <code>$roller2</code> -- the outcome is <code>Unlucky</code> and the loop is sensibly broken/halted. As matches are found between the map and the second array, the encountered map keys have their respective value decremented (spent) to enable the correct action with <code>empty()</code>.</p>\n<p>As @MikeBrant said:</p>\n<blockquote>\n<p>This provides an <code>O(2n)</code> worst-case operational complexity, where n is the size of the arrays.</p>\n</blockquote>\n<p>the worse-case scenario is the only way to achieve the <code>Lucky</code> outcome.</p>\n<p>A best-case operational complexity (<code>Unlucky</code> outcome) where the map is generated (<code>n</code>) and the loop breaks on the first element in the second array (<code>1</code>) ...<code>o(n+1)</code>.</p>\n<p>As for speed, I don't know. I didn't benchmark this script against the double-sort&compare technique, but you will notice that my technique is calling <code>array_count_values()</code> and will make iterated <code>empty()</code> calls and every function call equates to some level of a performance hit (even if miniscule).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T23:00:00.973",
"Id": "246204",
"ParentId": "47835",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47843",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:30:34.447",
"Id": "47835",
"Score": "5",
"Tags": [
"php",
"array",
"interview-questions",
"php5",
"dice"
],
"Title": "Optimized solution for a rolling dice code puzzle"
} | 47835 |
<p>I've written a program to simulate a game of <a href="http://en.wikipedia.org/wiki/Mafia_%28party_game%29">Mafia</a> among several bots. Here's the directory structure the program lives in (to make understanding parts of the program easier):</p>
<pre class="lang-none prettyprint-override"><code>/
start
README.md # Readme file
wtfpl.txt # License
controller/
main.py
messages.py # Contains a list of strings. I only put it into
# a separate file because it's long.
players/
log
player_folder/ # Every player has one of these
to_server
from_server
players
run
</code></pre>
<p><code>main.py</code> is the actual program that I'm looking for feedback with, and it is run by running <code>./start</code> in the root folder (which just executes <code>controller/main.py</code>, nothing fancy).</p>
<p>I have a few concerns, most of which come down to "good style". I tried to follow PEP8 where appropriate (with the exception of tabs vs. spaces, because TABS FOREVER) but I'm sure there are places I screwed that up. Largely, though, I'm just concerned because I'm not an incredibly experienced programmer and a not-insignificant portion of that already limited experience is code golf, so I have almost no idea of how to make an actual real program not suck. I'm just hoping people can take a look at this and suggest ways to make it "better", for whatever definition of better they choose.</p>
<p>I think I've commented heavily enough/chosen good enough variable and function names to explain what the program actually does, but if you have any questions I'd be happy to answer. Additionally, I know I'm not supposed to edit this question with updates as I make them, but if you want to know what my code looks like <em>right now</em> I'll be updating the git repo <a href="https://github.com/undergroundmonorail/Mafia-Engine">here</a> with any updates as I make them.</p>
<p>Finally, one last thing: I use some <code>try: ... except:</code> blocks that blindly catch any exception and ignore it. I'm aware of how terrible this is, however, these bots are going to be written by other people, and I want to be catching any error at all and defaulting to "ignore the input", which is why I've done that.</p>
<pre class="lang-python prettyprint-override"><code>#!/bin/python2
import os
import sys
import random
import textwrap
from messages import messages
class Player(object):
"""Player object for each bot."""
vote = None
role = 0
# Messages to the player are stored in the player object themself until they
# are sent, allowing more than one message to be sent with relative ease.
messages = ''
def __init__(self, name):
self.name = name
def add_message(self, s):
self.messages += textwrap.dedent(s + '\n')
def get_role(self):
if self.role == 1:
return 'a mafioso'
if self.role == 2:
return 'the cop'
if self.role == 3:
return 'the doctor'
return 'a villager'
def m_read(p):
"""Return contents of player p's 'to_server' file, stripped of special
characters, and clear the file.
"""
with open(p.name + '/to_server', 'r+') as f:
s = filter(lambda c: c.isalnum() or c == ' ', f.read())
f.truncate(0)
return s
def m_write(players):
"""Write messages to each player to that player's 'from_server' file"""
# Convert Player object to a 1-element list to allow calling for a single
# player
if isinstance(players, Player):
players = [players]
for p in players:
with open(p.name + '/from_server', 'w') as f:
f.write(p.messages)
p.messages = ''
def execute(p):
"""Executes the bot associated with player p"""
os.chdir(p.name)
os.system('./run')
os.chdir('..')
def log(message):
"""Append message + newline to the log file. This happens a lot, so this
function exists as shorthand.
"""
with open('log', 'a') as f:
f.write(textwrap.dedent(message + '\n'))
def get_players(players):
"""Return a list of player objects for each player name in the input. Also
return the doc, cop and a list of the mafia seperately.
"""
def assign_roles(players):
# Shuffling the whole list ensures you aren't assigning multiple roles to one
# player, which we would have to account for with random.choice()
random.shuffle(players)
# Make 1/3rd of the players mafia, one player a doctor and one player a cop
for _ in xrange(len(players) / 3):
players[0].role = 1
players.append(players.pop(0))
players[0].role = 2
players.append(players.pop(0))
players[0].role = 3
# Return list of players, list of mafia, cop and doctor
return (players,
filter(lambda p: p.role == 1, players),
players[-1],
players[0])
# At least six players are required. Ensure that we have six. Do this by
# testing for at least seven, because...
if len(players) < 7:
sys.exit('Not enough players.')
# ...The log file is kept in the same directory as the players. Get rid of it
players.remove('log')
# Convert to Player object, assign roles, and return
return assign_roles(map(lambda p: Player(p), players))
def kill(p, players, mafia, cop, doctor):
"""Return every role the player p might be filling, with them removed."""
players.remove(p)
if p in mafia:
mafia.remove(p)
if cop is p:
cop = None
if doctor is p:
doctor = None
return players, mafia, cop, doctor
def main():
# Get player objects for all players, the doc, the cop, and a list of mafia
os.chdir('players')
players, mafia, cop, doctor = get_players(os.listdir('.'))
# Give everyone a list of players
for p in players:
with open(p.name + '/players', 'w') as f:
# Sort it so that it isn't ordered by role
f.write('\n'.join(sorted([l.name for l in players])))
# Clear the log file, so it's fresh for the new game
with open('log', 'w') as f:
f.truncate(0)
# Create a dictionary allowing you to look up player objects by their name
name_to_player = dict(map(lambda p: (p.name, p), players))
day = 0
# Day 0 doesn't have a suspect or victim, every subsequent day does
suspect, victim = None, None
# Game loop, exits when mafia is dead or mafia outnumbers village
while mafia and (len(players) - len(mafia)) > len(mafia):
log('Day {} begins.'.format(day))
# Randomize turn order every day. Bots /shouldn't/ be able to figure
# this out, but who knows what you crazy kids will come up with. :P
random.shuffle(players)
# Print a message at the beginning of each day. On the first day, power
# roles need to be old their role and mafia members need to know their
# allies. On every other day, the cop needs to know the result of their
# investigation and all players need to know who died.
if day == 0:
log("""\
Cop: {}
Doctor: {}
Mafia: {}""".format(
cop.name, doctor.name, ', '.join(m.name for m in mafia)))
for p in players:
p.add_message("""\
Rise and shine! Today is day 0.
No voting will occur today.
Be warned: Tonight the mafia will strike.""")
for m in mafia:
m.add_message("""\
You are a member of the mafia.
Your allies are:""")
m.add_message('\n'.join(p.name for p in mafia if p is not m))
cop.add_message('You are the cop.')
doctor.add_message('You are the doctor.')
else:
for p in players:
p.add_message('Dawn of day {}.'.format(day))
if victim is not None:
p.add_message('Last night, {} was killed.'.format(victim.name))
if victim is not None:
players, mafia, cop, doctor = kill(victim, players, mafia, cop, doctor)
log('{}, {}, was killed.'.format(victim.name, victim.get_role))
if suspect is not None:
cop.add_message('Investigations showed that {} is {}-aligned.'.format(
suspect.name, 'mafia' if suspect.role == 1 else 'village'))
log('These players are still alive: {}'.format(
', '.join(p.name for p in players)))
m_write(players)
# During a day, players may perform up to 50 actions (Action= vote or talk)
for r in xrange(50):
for p in players:
try:
execute(p)
command = m_read(p).split()
if command[0] == 'vote':
# Set the player's vote
if day != 0:
if command[1] == 'no':
if command[2] == 'one':
p.vote = None
log('{} has voted to lynch no one.'.format(p.name))
for l in players:
l.add_message('{} has voted to lynch no one.'.format(p.name))
else:
p.vote = name_to_player[command[1]]
log('{} has voted to lynch {}.'.format(p.name, command[1]))
for l in players:
l.add_message(
'{} has voted to lynch {}.'.format(p.name, command[1]))
elif command[0] == 'say':
# Send a message to all players
message = '{} says "'.format(p.name)
# Messages with an id higher than 4 have the name of a bot attached
# This screws with parsing a bit so we handle them seperately
if int(command[1]) > 4:
if len(command) == 4:
# Convert from a name to a player object and back to ensure
# that it's a correct name
message += '{}, '.format(name_to_player[command[3]].name)
message += messages[int(command[1])]
message += '{}"'.format(name_to_player[command[2]].name)
else:
if len(command) == 3:
message += '{}, '.format(name_to_player[command[2]].name)
message += '{}"'.format(messages[int(command[1])])
log(message)
for l in players:
l.add_message(message)
except:
# Do nothing on invalid input
pass
m_write(players)
# Tally up the votes for each player
votes = [p.vote for p in players]
# Shuffle to eliminate max() bias
random.shuffle(votes)
# The most voted player is lynched, with ties broken randomly
lynched = max(votes, key=votes.count)
if lynched is not None:
log('The town has killed {}!'.format(lynched.name))
log('They were {}.'.format(lynched.get_role()))
for p in players:
p.add_message("""\
The town has killed {}!
They were {}.""".format(lynched.name, lynched.get_role))
players, mafia, cop, doctor = kill(lynched, players, mafia, cop, doctor)
else:
log('The town opted to lynch no one today.')
for p in players:
p.add_message('The town opted to lynch no one today.')
m_write(players)
for p in players:
execute(p)
p.vote = None
# Don't go to night if a win condition's been met.
if not mafia or (len(players) - len(mafia)) <= len(mafia):
break
# Day ends, night begins
# MAFIA NIGHT ACTION
# Each mafioso votes for a victim. The most voted player is then killed,
# unless saved that night by the doctor.
for m in mafia:
m.add_message('It is night. Vote for a victim.')
m_write(mafia)
victim_votes = []
for m in mafia:
try:
execute(m)
victim_votes.append(name_to_player[m_read(m)])
log('{} votes to kill {}.'.format(m.name, victim_votes[-1].name))
except:
# Vote to kill no one on invalid input
victim_votes.append(None)
log(m.name + ' votes to kill no one.')
# Shuffle to eliminate max() bias
random.shuffle(victim_votes)
# The victim is the player most voted for by the mafia, with ties broken
# randomly.
victim = max(victim_votes, key=victim_votes.count)
log('The mafia collectively decides to kill {}.'.format(
victim.name if victim is not None else 'no one'))
# COP NIGHT ACTION
# The cop chooses a player to investigate. At the dawn of the next day,
# they are told whether that player is village- or mafia-aligned.
if cop is not None:
cop.add_message('It is night. Who would you like to investigate?')
m_write(cop)
try:
execute(cop)
suspect = name_to_player[m_read(cop)]
log('{} spends the night investigating {}.'.format(
cop.name, suspect.name))
except:
# Investigate no one on invalid input
suspect = None
log('{} chooses not to investigate anyone.'.format(cop.name))
# DOCTOR NIGHT ACTION
# The doctor chooses a player they expect the mafia to try to kill. If they
# are right, the mafia gets no kills that night.
if doctor is not None:
doctor.add_message('It is night. Who would you like to save?')
m_write(doctor)
try:
execute(doctor)
patient = name_to_player[m_read(doctor)]
if patient == victim:
victim = None
log('{} was able to save {} from near-certain death.'.format(
doctor.name, patient.name))
else:
log('{} tried to save {}, but they were not the target.'.format(
doctor.name, patient.name))
except:
# Save no one on invalid input
log('{} took tonight off.'.format(doctor.name))
log('')
day += 1
if mafia:
print 'MAFIA VICTORY'
log('MAFIA VICTORY')
else:
print 'VILLAGE VICTORY'
log('VILLAGE VICTORY')
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:53:58.250",
"Id": "85318",
"Score": "0",
"body": "Love the code looks awesome. You going to compile to exe so we can all play it?"
}
] | [
{
"body": "<p>Overall, it looks pretty good to me. I agree that you have good commenting and variable and function naming. I see just a few things to comment on.</p>\n\n<ul>\n<li><p>You have assign_roles() nested inside get_players(). Is there a reason for doing this? Unless there's a good one, I'd recommend putting assign_roles() at the top level along with everything else.</p></li>\n<li><p>Could you put the log file someplace like '/tmp/log' so it doesn't mess up your list of players? Besides, what if you have a player named 'log'? Also, you might consider looking into python's logging module. It can be a bit complex, but provides a lot of nice features for managing log files.</p></li>\n<li><p>I see an opportunity for further modularizing your main() routine -- maybe routines like day_action(), maybe_lynch_somebody(), mafia_night_action(), cop_night_action(), and doctor_night_action(). It might involve passing your lists around some, but you're already doing that up above, so it shouldn't be an issue.</p></li>\n</ul>\n\n<p>Looks like an interesting game.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:14:55.883",
"Id": "84108",
"Score": "0",
"body": "1. I was under the impression that are only ever called from inside another function are generally kept inside that other function for clarity reasons (with the exception of `main()`, of course). If I'm mistaken, I can fix that easily. 2. That's true, I could. Having `log` under `players/` is an artifact of before I made the `log()` function. I was writing to it with the whole `with open(...` syntax each time and didn't to navigate to a different folder each time. Now that I almost always do it from the function, that wouldn't be an issue at all. I didn't know python had a logging module..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:16:01.683",
"Id": "84109",
"Score": "0",
"body": "...but I'll check it out! 3. That's true, I should do that. If I'm being honest with you, I was starting to near the end of the project when I got there and having it all dumped into `main()` is probably an artifact of me growing lazy. :P Thank you for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:37:17.547",
"Id": "84124",
"Score": "0",
"body": "You're welcome. 1. With regard to nested functions, it may just be a matter of preference on my part. I think it's easier to find things when they're all at the top level. PEP20, The Zen of Python (http://legacy.python.org/dev/peps/pep-0020/) does say, \"Flat is better than nested.\" However, if nesting works well for you to indicate that the subordinate function is only called by its parent, I wouldn't stop doing that just because some guy on the internet says to. Now, if twenty guys on the internet say so, that's something else again. :) Let's see if anybody else has an opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:40:56.790",
"Id": "84125",
"Score": "0",
"body": "2. For putting the log file in /tmp, I didn't mean to suggest that you should os.chdir(\"/tmp\") before opening the file. Just use the full path in the open statement: open('/tmp/log', 'a'). That will work from wherever you are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T12:03:14.507",
"Id": "84136",
"Score": "0",
"body": "re: nested functions: I'm going to be honest and say that the coding style opinions of a guy who *actively posts answers on codereview.SE* probably trumps those of a guy who did a CodeAcademy course and uses reddit. :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:10:41.827",
"Id": "84836",
"Score": "0",
"body": "With regard to nested functions, I just read about closures here: http://en.wikibooks.org/wiki/Python_Programming/Functions#Closures. A closure is a nested function that uses information from the scope in which it was defined. Since functions are objects like everything else in python, the created function can be returned by the outer function and used elsewhere and retains its knowledge of the context in which it was created."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:13:01.763",
"Id": "84837",
"Score": "0",
"body": "In the case of get_players() and assign_roles(), they will work just as well un-nested since you're passing the players list into assign_roles(), so I stand by my recommendation in this case. I just wanted to acknowledge that there are good reasons for nesting functions if the situation calls for it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:59:23.593",
"Id": "47936",
"ParentId": "47836",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47936",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T21:32:26.777",
"Id": "47836",
"Score": "11",
"Tags": [
"python",
"game",
"python-2.x"
],
"Title": "Mafia game simulation engine"
} | 47836 |
<p><a href="https://codereview.stackexchange.com/q/39521/27623">I posted my audio recording program to Code Review before</a>, and received <a href="https://codereview.stackexchange.com/a/47694/27623">a stern review</a> along with the other reviews that caused me to rewrite the entire code base. Here is what I would like reviewed:</p>
<ol>
<li><p><strong>Reusability/Portability</strong> - is this code easy to use for multiple separate projects with minimal modification?</p></li>
<li><p><strong>Optimization</strong> - although I'm not sure there is much room for improvement here, how can I make this code perform more efficiently? Obviously I can't record things any faster, but could I store the file or start the recording process faster than I am currently?</p></li>
<li><p><strong>Dynamics</strong> - are there <a href="http://www.portaudio.com/" rel="nofollow noreferrer">PortAudio</a> or <a href="http://www.mega-nerd.com/libsndfile/" rel="nofollow noreferrer">libsndfile</a> features that I am not taking advantage of that could make my program more powerful?</p></li>
<li><p><strong>Documentation</strong> - are my comments easy to understand? Are there ways that I could expound upon them?</p></li>
</ol>
<hr>
<p><strong><code>audio.h</code></strong>:</p>
<pre><code>/**
* @file audio.h
* @brief Contains AudioData structure, and relevent audio functions.
*/
#include <stdint.h>
#include <string.h>
/**
* Holds all of the necessary information for building an
* audio file.
* @var duration Contains how long the audio file will be in seconds.
* @var formatType Contains the audio formatting type.
* @var numberOfChannels Contains the number of audio channels.
* @var sampleRate Contains the sample rate in Hertz.
* @var frameIndex Contains the current frame to be processed.
* @var maxFrameIndex Contains the number of frames that the audio file will store.
* @var recordedSamples Contains the raw PCM audio data.
*/
typedef struct
{
uint32_t duration;
uint16_t formatType;
uint16_t numberOfChannels;
uint32_t sampleRate;
uint32_t frameIndex;
uint32_t maxFrameIndex;
float* recordedSamples;
} AudioData;
int recordFLAC(AudioData data, const char *fileName);
AudioData initAudioData(uint32_t sample_rate, uint16_t channels, uint32_t duration);
</code></pre>
<p><strong><code>record.c</code></strong>:</p>
<pre><code>/**
* @file record.c
* @brief Records a FLAC audio file
*/
#include <stdio.h>
#include <stdlib.h>
#include <portaudio.h>
#include <sndfile.h>
#include "audio.h"
/**
* @fn initAudioData
* @param sampleRate The sample rate in Hertz in which the audio is to be recorded
* @param channels The number of channels in which the audio is to be recorded
* @param duration How long in seconds the recording will be
* @return a partially initialized structure.
*/
AudioData initAudioData(uint32_t sampleRate, uint16_t channels, uint32_t duration)
{
AudioData data;
data.duration = duration;
data.formatType = 1;
data.numberOfChannels = channels;
data.sampleRate = sampleRate;
data.frameIndex = 0;
data.maxFrameIndex = sampleRate * duration;
return data;
}
/**
* This routine will be called by the PortAudio engine when audio is needed.
* It may be called at interrupt level on some machines so don't do anything
* that could mess up the system like calling malloc() or free().
*/
static int recordCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
{
AudioData* data = (AudioData*) userData;
const float* rptr = (const float*)inputBuffer;
float* wptr = &data->recordedSamples[data->frameIndex * data->numberOfChannels];
long framesToCalc;
int finished;
unsigned long framesLeft = data->maxFrameIndex - data->frameIndex;
(void) outputBuffer; /* Prevent unused variable warnings. */
(void) timeInfo;
(void) statusFlags;
(void) userData;
if(framesLeft < framesPerBuffer)
{
framesToCalc = framesLeft;
finished = paComplete;
}
else
{
framesToCalc = framesPerBuffer;
finished = paContinue;
}
if(!inputBuffer)
{
for(long i = 0; i < framesToCalc; i++)
{
*wptr++ = 0.0f; // left
if(data->numberOfChannels == 2) *wptr++ = 0.0f; // right
}
}
else
{
for(long i = 0; i < framesToCalc; i++)
{
*wptr++ = *rptr++; // left
if(data->numberOfChannels == 2) *wptr++ = *rptr++; // right
}
}
data->frameIndex += framesToCalc;
return finished;
}
/**
* @fn recordFLAC
* @param data An initiallized (with initAudioData()) AudioData structure
* @param fileName The name of the file in which the recording will be stored
* @return Success value
*/
int recordFLAC(AudioData data, const char *fileName)
{
PaStreamParameters inputParameters;
PaStream* stream;
int err = 0;
int numSamples = data.maxFrameIndex * data.numberOfChannels;
int numBytes = numSamples * sizeof(data.recordedSamples[0]);
data.recordedSamples = calloc(numSamples, numBytes); // From now on, recordedSamples is initialised.
if(!data.recordedSamples)
{
fprintf(stderr, "Could not allocate record array.\n");
goto done;
}
if((err = Pa_Initialize())) goto done;
inputParameters.device = Pa_GetDefaultInputDevice();
if (inputParameters.device == paNoDevice)
{
fprintf(stderr,"Error: No default input device.\n");
goto done;
}
inputParameters.channelCount = data.numberOfChannels;
inputParameters.sampleFormat = paFloat32;
inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(&stream, &inputParameters, NULL, data.sampleRate, paFramesPerBufferUnspecified, paClipOff, recordCallback, &data);
if(err) goto done;
if((err = Pa_StartStream(stream))) goto done;
puts("=== Now recording!! Please speak into the microphone. ===");
while(1 == (err = Pa_IsStreamActive(stream)))
{
Pa_Sleep(1000);
printf("index = %d\n", data.frameIndex);
}
if((err = Pa_CloseStream(stream))) goto done;
done:
Pa_Terminate();
if(err)
{
fprintf(stderr, "An error occured while using the portaudio stream: %d\n", err);
fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(err));
err = 1; // Always manually return positive codes.
}
else
{
SF_INFO sfinfo;
sfinfo.channels = data.numberOfChannels;
sfinfo.samplerate = data.sampleRate;
sfinfo.format = SF_FORMAT_FLAC | SF_FORMAT_PCM_16;
SNDFILE* outfile = sf_open(fileName, SFM_WRITE, &sfinfo); // open to file
if (!outfile) return -1;
long wr = sf_write_float(outfile, data.recordedSamples, numSamples); // write the entire buffer to the file
if (wr < numSamples) fprintf(stderr, "Only wrote %lu frames, should have written %d", wr, numSamples);
sf_write_sync(outfile); // force write to disk
sf_close(outfile); // don't forget to close the file
}
free(data.recordedSamples);
return err;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-03T14:16:16.580",
"Id": "452212",
"Score": "0",
"body": "We are not aware of the duration we would like to record until silence. Please suggest ways to modify the code to record until silence of say a given duration."
}
] | [
{
"body": "<p>Few notes.</p>\n\n<p>First, you don't want to copy data in the loop. Call <code>memset()</code>/<code>memcpy()</code> instead. You need some very serious reason to <em>not</em> use standard library. Here is some example code:</p>\n\n<pre><code>dataSize = sizeof(*wptr) * data->numberOfChannels * framesToCalc;\nif (!inputBuffer)\n memset(wptr, dataSize, 0);\nelse\n memcpy(wptr, rptr, dataSize);\n</code></pre>\n\n<p>Second, <code>recordFLAC()</code> still needs some refactoring. As coded, it contains both some essential functionality (such as setup and teardown) along with the code more suitable for a demo purposes (printing error messages, writing data to a file). You want to separate them. This is all the function should be doing:</p>\n\n<pre><code>record(AudioData data, char * buffer)\n{\n if (Pa_Initialize()) goto done;\n if ((inputParameters.device = Pa_GetDefaultInputDevice()) == paNoDevice)\n goto done;\n // Setup the rest of inputParameters\n if (Pa_OpenStream(...)) goto done;\n\n // This is another suspicious moment. I am not familiar with portaudio\n // to suggest an alternative for progress reporting, etc.\n while (Pa_IsStreamActive(stream))\n Pa_Sleep(1000);\n\n if (Pa_CloseStream()) goto done;\ndone:\n Pa_Terminate();\n}\n</code></pre>\n\n<p>Otherwise, looks quite promising.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:13:42.120",
"Id": "83869",
"Score": "0",
"body": "Could you flesh this out a bit? For example, what loop are you talking about? There is only one loop in my program (unless you are talking about the callback), and it is printing out data, not copying it. And could you maybe give some pseudo code for how you would refactor it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:19:26.823",
"Id": "83870",
"Score": "0",
"body": "You're right, I am talking about the callback. Give me few moments for the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:26:17.440",
"Id": "83871",
"Score": "0",
"body": "Interesting. I'd be interested to talk to you about this a bit more in [our chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:36:05.943",
"Id": "83872",
"Score": "0",
"body": "I am there. Is there anything special I shall do?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T03:08:15.567",
"Id": "47844",
"ParentId": "47840",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "47844",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T00:04:12.543",
"Id": "47840",
"Score": "10",
"Tags": [
"performance",
"c",
"audio",
"portability"
],
"Title": "Recording audio in C 2.0"
} | 47840 |
<p>My requirement is to convert a sequence of numbers into a display string as below.</p>
<p>Example </p>
<blockquote>
<p><strong>Input</strong></p>
<p>1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86</p>
<p><strong>Output</strong></p>
<p>1-5,7-8,10-12,15,86-88</p>
</blockquote>
<hr>
<pre><code>void makeDisplayString(std::vector<int>& vector, std::wstring& string)
{
if(vector.empty()) return; // If empty do nothing
std::sort(vector.begin(),vector.end()); // Sort vector first
int& preValue =vector.at(0);
string.append(std::to_wstring(preValue));
bool continueFlag = false; // Flag to check if continuation of value
for(auto const & num : vector)
{
if(preValue ==num) continue; // if same number as previous , Skip it
if(preValue+1 == num) // If number is one more than privious value
{
preValue = num;
continueFlag=true; // set continuation flag and continue rest part
continue;
}
if(continueFlag)
{
// We reach here only if neither number is save as previous nor it is continous of numbering
// But befor this number there was a continous numbering
string.push_back(L'-');
string.append(std::to_wstring(preValue));
string.push_back(L',');
preValue=num;
string.append(std::to_wstring(num));
continueFlag = false;
continue;
}
// We reach here only if neither number is save as previous nor it is continous of numbering
// Also befor this number there was no continous numbering
preValue = num;
string.push_back(L',');
string.append(std::to_wstring(num));
}
// This is to handle a sequence ending with continous number
if(continueFlag)
{
string.push_back(L'-');
string.append(std::to_wstring(*vector.rbegin()));
}
}
</code></pre>
| [] | [
{
"body": "<p>State flags usually indicate a design problem.</p>\n\n<p>How about this instead (after vector is sorted) :</p>\n\n<pre><code>template <typename I>\nI get_sequential_range(I first, I last)\n{\n I end_range = ++first;\n while ((end_range != last) &&(*end_range <= *first + 1)) {\n ++first;\n ++end_range;\n }\n return end_range;\n}\n\ntemplate <typename I>\nstd::stringstream make_display_string(I first, I last)\n{\n std::stringstream out;\n I end_range;\n while(first != last) {\n end_range = find_sequential_range(first, last);\n out << *first << '-' << *(end_range - 1) << ',';\n first = end_range;\n }\n return out;\n}\n</code></pre>\n\n<p>Disclaimer: untested. Consider it a pseudocode. And sorry if I misunderstood your task.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:07:16.750",
"Id": "84203",
"Score": "0",
"body": "@dvp Good point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:16:25.063",
"Id": "84204",
"Score": "0",
"body": "Oops, no, sorry. That algorithm does something completely unrelated D:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:30:24.687",
"Id": "84207",
"Score": "0",
"body": "(It's some kind of negation of `adjacent_find`; you could use a negated predicate but then the corner-cases get ugly. [Redefining some `find_not_adjacent`](http://coliru.stacked-crooked.com/a/6194af33f6d2c4e5) seems to be cleaner.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T05:44:39.507",
"Id": "47850",
"ParentId": "47845",
"Score": "4"
}
},
{
"body": "<p><strong>1. Separate data representation from actual output, using standard algorithms where possible</strong>.</p>\n\n<p><code>make_ranges</code> below takes input sequence <code>array</code> and returns limits of all ranges found, in two different sequences <code>from</code>, <code>to</code>:</p>\n\n<pre><code>template<typename F, typename T, typename A>\nvoid make_ranges(F& from, T& to, A array)\n{\n auto diff = array;\n std::sort(array.begin(), array.end());\n std::adjacent_difference(array.begin(), array.end(), diff.begin());\n\n std::vector<size_t> idx(array.size());\n std::iota(idx.begin(), idx.end(), 0);\n auto sep = [&diff] (size_t i) { return diff[i] > 1; };\n for(auto p = idx.begin(); p != idx.end();)\n {\n from.push_back(array[*p]);\n p = std::find_if(++p, idx.end(), sep);\n to.push_back(array[*(p - 1)]);\n }\n}\n</code></pre>\n\n<p><strong>2. For most generic use, use a stream for output</strong>:</p>\n\n<pre><code>template<typename S, typename I, typename J>\nvoid print_range(S& stream, I i, J j)\n{\n stream << *i;\n if (*j != *i)\n stream << \"-\" << *j;\n}\n\ntemplate<typename S, typename F, typename T>\nvoid print_ranges(S& stream, const F& from, const T& to)\n{\n auto i = from.begin();\n auto j = to.begin();\n if (i != from.end())\n print_range(stream, i++, j++);\n while (i != from.end())\n {\n stream << \",\";\n print_range(stream, i++, j++);\n }\n}\n</code></pre>\n\n<p><strong>3. For convenient use, provide a streaming operator interface:</strong></p>\n\n<pre><code>template<typename S, typename A>\nS& operator<<(S& stream, const array_ranges<A>& ranges)\n{\n typename std::decay<A>::type from, to;\n make_ranges(from, to, std::get<0>(ranges));\n print_ranges(stream, from, to);\n return stream;\n}\n</code></pre>\n\n<p>where <code>array_ranges</code> is a helper struct holding a sequence and indicating that its ranges should be streamed out instead of the sequence itself. Given a sequence, an <code>array_ranges</code> instance is made easily via helper function <code>ranges</code>:</p>\n\n<pre><code>template<typename A>\nstruct array_ranges : std::tuple<A> { using std::tuple<A>::tuple; };\n\ntemplate<typename A>\narray_ranges<A> ranges(A&& a) { return array_ranges<A>{std::forward<A>(a)}; }\n</code></pre>\n\n<p><strong>Example</strong></p>\n\n<p>Now the above can be used as</p>\n\n<pre><code>std::vector<int> arr{1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86};\nstd::cout << arr << std::endl;\nstd::cout << ranges(arr) << std::endl;\n</code></pre>\n\n<p>See <a href=\"http://coliru.stacked-crooked.com/a/cca909833a90328f\" rel=\"nofollow\">live example</a>.</p>\n\n<p>If you want to print the ranges into a string, just use an <code>std::ostringstream</code>.</p>\n\n<p><strong>Discussion</strong></p>\n\n<p>With the above separation, you can do more advanced tasks like extracting ranges from arbitrary sequences, processing them (e.g. filtering or merging two sets of ranges), and finally printing them.</p>\n\n<p>If you don't need any extra processing, this separation is more costly than direct printing since it stores intermediate results in arrays <code>from</code>, <code>to</code>. Using <code>std::adjacent_difference</code> introduces another intermediate result.</p>\n\n<p>It is possible to save the extra cost of \"intermediate results\" while keeping the same design by more advanced techniques like <a href=\"http://en.wikipedia.org/wiki/Expression_templates\" rel=\"nofollow\">expression templates</a>, but this goes way beyond this simple task.</p>\n\n<p>I would personally prefer a clean design to optimal performance for this task. This makes code more readable and maintainable. Also, with a bit more abstraction, you may find that parts of the code above can be reused elsewhere (especially <code>print_ranges</code>, but I don't want to go too far).</p>\n\n<p>Another choice you could follow is to have an <code>std::pair</code> or (better) a dedicated data structure representing one range. A single sequence would then be enough instead of two sequences <code>from</code>, <code>to</code>, but processing such a sequence would be a bit more involved.</p>\n\n<p>Of course, you are free to flat everything into a single call without intermediates if you prefer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:07:20.900",
"Id": "47871",
"ParentId": "47845",
"Score": "8"
}
},
{
"body": "<p>I'm wondering if you might be over thinking it a bit. By keeping track of start value and end value you test the next number against the end value if it's less than 2 it's the new end value otherwise add this range to your string and start a new range:</p>\n\n<pre><code>std::wstring makeDisplayString(std::vector<int>& invect)\n{\n std::wstringstream ss(L\"\");\n if(!invect.empty()) // If empty do nothing\n {\n std::sort(invect.begin(),invect.end()); // Sort vector first\n //start a new range\n int startValue =invect[0];\n int endValue;\n for(auto const & num : invect)\n {\n if((num - endValue) < 2)\n {\n endValue = num;\n }\n else\n {\n if(startValue == endValue)\n ss << startValue << \",\";\n else\n ss << startValue << \"-\" << endValue << \",\";\n startValue = num;\n endValue = num;\n }\n }\n ss << startValue << \"-\" << endValue;\n }\n return ss.str();\n}\n</code></pre>\n\n<p>Rather than trying to change an existing string this returns the string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:04:39.530",
"Id": "47905",
"ParentId": "47845",
"Score": "0"
}
},
{
"body": "<p>I'm late to the party, but here is a nice clean C++11 answer which works with any container supporting <code>begin()</code> and <code>end()</code> iterators (and therefore range-based <code>for</code>) and any contained object meaningfully supporting <code>operator=</code>, <code>operator!=</code>, a stream inserter and <code>operator+</code>. That includes all integer types and character types, of course. Also note that I decided to omit sorting from the algorithm itself, preferring instead to leave that to an external <code>std::sort</code> in the example code.</p>\n\n<pre><code>#include <string>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include <valarray>\n#include <algorithm>\n\ntemplate <typename C>\nstd::string rangeprint(const C &r)\n{\n auto first = r[0];\n auto last = r[0];\n std::stringstream result;\n result << first;\n for (const auto &n : r) {\n if (n != last+1 && n != last) {\n if (last != first)\n result << '-' << last;\n result << ',' << n;\n first = n;\n }\n last = n;\n }\n if (last != first) \n result << '-' << last;\n return result.str();\n}\n\nint main()\n{\n std::vector<int> r{1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86};\n std::sort(r.begin(), r.end());\n std::cout << rangeprint(r) << '\\n';\n\n const std::valarray<char> b{'A','B','C','D','F','G','M','X','Z'};\n std::cout << rangeprint(b) << '\\n';\n}\n</code></pre>\n\n<h2>Update:</h2>\n\n<p>Just for fun, I created a new class to show how this might be used with user-created classes. Here's the class:</p>\n\n<pre><code>class GreekAlphabet {\nprivate:\n const static std::vector<std::string> letterName;\n std::size_t index;\npublic:\n GreekAlphabet(const GreekAlphabet &g) : index(g.index) {}\n GreekAlphabet(const char *s) {\n for (index = 0; index < letterName.size(); ++index)\n if (s == letterName[index])\n break;\n if (index == letterName.size()) {\n throw std::range_error(\"invalid Greek letter\");\n }\n }\n bool operator!=(const GreekAlphabet &b) const { \n return index != b.index; \n }\n GreekAlphabet operator+(int b) const { \n GreekAlphabet c(*this); \n c.index = (c.index+b)%letterName.size(); \n return c; \n }\n friend std::ostream& operator<<(std::ostream& out, \n const GreekAlphabet &a) \n {\n return out << GreekAlphabet::letterName[a.index];\n }\n};\n\nconst std::vector<std::string> GreekAlphabet::letterName{\n \"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\", \n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\", \"nu\", \"xi\",\n \"omicron\", \"pi\", \"rho\", \"sigma\", \"tau\", \"upsilon\", \"phi\", \n \"chi\", \"psi\", \"omega\"};\n</code></pre>\n\n<p>And here's an example of its use with <code>rangeprint()</code>:</p>\n\n<pre><code>int main()\n{\n const std::vector<GreekAlphabet> ga{\"alpha\", \"beta\", \"gamma\",\n \"delta\",\"mu\", \"nu\", \"xi\", \"pi\", \"rho\", \"omega\"};\n std::cout << rangeprint(ga) << '\\n';\n}\n</code></pre>\n\n<p>This prints:</p>\n\n<pre><code>alpha-delta,mu-xi,pi-rho,omega\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:26:03.393",
"Id": "47914",
"ParentId": "47845",
"Score": "3"
}
},
{
"body": "<p>I'll start by reviewing the code as it stands, then add some commentary about how I think I'd do this job instead.</p>\n\n<p>I'd say your code is quite readable--while I personally prefer snake_case variable names over the camelCase you've used, it's at least a decent convention and you've followed it fairly consistently.</p>\n\n<p>The names themselves aren't quite as meaningful as I'd prefer though. The prime example would be using <code>vector</code> as the name of the variable holding the input. I see two problems here. First, you've re-used a name from the standard library for an entirely different purpose (a variable instead of a template). While I'm somewhat more tolerant of re-using names for different purposes than many, it seems ill-advised in this case. Second, and more importantly, <code>vector</code> only tells us about an incidental detail of how the input data happens to be stored. It would be much more useful to give it a name that reflects its purpose and use instead--<code>input</code> for one possible example.</p>\n\n<p>That brings us to another point: I think your code specifies types to an unnecessary degree--to the point that its flexibility is substantially reduced. In some cases you can justify reduced flexibility when the greater specialization makes the code much easier to read and/or use--but at least in this case, we don't seem to be gaining a lot.</p>\n\n<p>Finally, I think the code combines two rather separate tasks:</p>\n\n<ol>\n<li>Breaking a collection of inputs into contiguous ranges, and</li>\n<li>Converting contiguous ranges to readable strings.</li>\n</ol>\n\n<p>It seems to me that the code would benefit from keeping these two operations separate. </p>\n\n<p>For the first of these, I think @iavr had (at least roughly) the right idea: it should be implemented as a generic algorithm that takes input as a pair of iterators. Unlike his solution, I'd also write the output via an iterator rather than directly to a stream (-like object) using an insertion operator.</p>\n\n<p>This makes it trivial to write the output to a string (via a stringstream), or directly to any other sort of stream, or to a collection (e.g., vector or deque) of the right type.</p>\n\n<p>To do this, I'd start by defining a type to hold a range, and handle insertion of that type into a stream:</p>\n\n<pre><code>template <class T>\nclass range_t { \n T begin, end;\npublic:\n range_t(T begin, T end) : begin(begin), end(end) {}\n\n friend std::ostream &operator<<(std::ostream &os, range_t const &r) {\n os << r.begin;\n if (r.end != r.begin)\n os << \"-\" << r.end;\n return os;\n }\n};\n</code></pre>\n\n<p>The stream insertion operator also handles conversion of that object to a string (the second task noted above) by writing to a stringstream. Depending on the situation, it can be beneficial to add a <code>to_string</code> function to carry out that conversion directly. This is largely an optimization though, adding more code to avoid the overhead of a stringstream. I'll leave it out for now, but note that it's generally fairly trivial to add as long as T is a type that itself has a <code>to_string</code> (which it does for the normal integer types in C++11).</p>\n\n<p>Then for the sake of convenience, I'd define a function template to create an object of that type (this allows the type parameter to be deduced from the passed type rather than having to be specified explicitly):</p>\n\n<pre><code>template <class T>\nrange_t<T> range(T begin, T end) { return range_t<T>(begin, end); }\n</code></pre>\n\n<p>With those in place we can get to the real code to create a series of ranges from some input data:</p>\n\n<pre><code>template <typename RIt, typename OutIt>\nvoid contiguous_ranges(RIt begin, RIt end, OutIt result) {\n std::sort(begin, end);\n\n auto pos = begin;\n for (++pos ; pos != end; ++pos) {\n if (*pos > *(pos - 1) + 1) {\n *result++ = range(*begin, *(pos - 1));\n begin = pos;\n }\n }\n *result++ = range(*begin, *(end-1));\n}\n</code></pre>\n\n<p>One minor note: although this uses random-access iterators for the input (thus \"RIt\" for the type name), the random access is needed only for the <code>std::sort</code>. The rest of the algorithm only requires input iterators (and it's fairly easy to use a different sorting algorithm that doesn't require random access iterators, though typically with some loss of efficiency).</p>\n\n<p>You'd put these together something like this:</p>\n\n<pre><code>std::vector<int> input {1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86};\n\ncontiguous_ranges(input.begin(), input.end(), \n infix_ostream_iterator<range_t<int> >(std::cout, \", \"));\n</code></pre>\n\n<p>[To avoid an extra comma at the end of the output, I've used the <code>infix_ostream_iterator</code> from <a href=\"https://codereview.stackexchange.com/q/13176/489\">a previous question</a> though you could substitute a normal <code>std::ostream_iterator</code> if you didn't mind an extra comma after the end of the output.]</p>\n\n<p>At least to me, this seems to combine simplicity in use, readability (especially to anybody already accustomed to standard algorithms) and flexibility--it's able to produce output to a string, a stream, or essentially any collection that's accessible via an output iterator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:04:17.167",
"Id": "84121",
"Score": "0",
"body": "The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std. See [What can and can't I specialize in the std namespace?](http://stackoverflow.com/a/8513497/2644390)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:10:15.253",
"Id": "84168",
"Score": "0",
"body": "@iavr: Good point--one of those things I'm prone to doing when it's late and I'm tired (but fix in the morning)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:24:09.887",
"Id": "47951",
"ParentId": "47845",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T04:20:34.653",
"Id": "47845",
"Score": "7",
"Tags": [
"c++",
"strings",
"c++11",
"converting"
],
"Title": "Convert sequence of number into display string"
} | 47845 |
<p>I've been looking for an implementation of Tarjan's algorithm in C#/C++ for a strongly-connected components in graphs, and couldn't find any implementation without use of additional Stack - most of them just follow <a href="http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm" rel="noreferrer">wikipedia pseudocode</a>. I've decided to create one in case if someone is looking for it. Please take a look and codereview. The main point is that mark the SCC as completed once I'm done with descendand processing, and that any cross-edge towards completed SCC will be ignored.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
public class Graph
{
private int _verticesCount;
private List<int>[] _vertexAdjancedVertices; // i-th element contains info about all adjanced vertices of vertex #i
public Graph(int[,] edges)
{
_verticesCount = edges.Cast<int>().Max() + 1;
_vertexAdjancedVertices = new List<int>[_verticesCount];
for (int i = 0; i < _verticesCount; ++i)
_vertexAdjancedVertices[i] = new List<int>();
for(int i = 0; i < edges.GetLength(0); ++i)
AddDirectedEdge(edges[i, 0], edges[i, 1]);
}
public void AddEdge(int vertex1, int vertex2, bool directed = false)
{
AddDirectedEdge(vertex1, vertex2);
if (!directed)
AddDirectedEdge(vertex2, vertex1);
}
public void AddDirectedEdge(int vertex1, int vertex2)
{
_vertexAdjancedVertices[vertex1].Add(vertex2);
}
public List<List<int>> GetStronglyConnectedComponents()
{
//DFS
var processed = new bool[_verticesCount];
var minConnectedValue = new int[_verticesCount];
var sccCompleted = new bool[_verticesCount];
int currentTime = 0;
for(int startingVertex = 0; startingVertex < _verticesCount; ++startingVertex)
if (!processed[startingVertex])
GetStronglyConnectedComponents(startingVertex, ref currentTime, processed, minConnectedValue, sccCompleted);
var res = minConnectedValue.Select((mcv, i) => new {Vertex = i, MinConnectedValue = mcv})
.GroupBy(vmcv => vmcv.MinConnectedValue)
.Select(g => g.Select(vmcv => vmcv.Vertex).ToList()).ToList();
return res;
}
private void GetStronglyConnectedComponents(int vertex, ref int currentTime, bool[] processed, int[] minConnectedValue, bool[] sccCompleted)
{
processed[vertex] = true;
++currentTime;
//var currentDiscoveryTime = currentTime;
minConnectedValue[vertex] = currentTime; // initialize to current time
sccCompleted[vertex] = false;
foreach (var neighbour in _vertexAdjancedVertices[vertex])
{
if (!processed[neighbour])
{
GetStronglyConnectedComponents(neighbour, ref currentTime, processed, minConnectedValue, sccCompleted);
minConnectedValue[vertex] = Math.Min(minConnectedValue[vertex], minConnectedValue[neighbour]); // if we will ever find cycle
}
else if (!sccCompleted[minConnectedValue[neighbour]]) // ignore references to completed sccs
{
minConnectedValue[vertex] = Math.Min(minConnectedValue[vertex], minConnectedValue[neighbour]); // we've reached processed vertex - use it as a minConnectedValue we could reach to (if smaller)
}
}
if (minConnectedValue[vertex] == vertex) // we are going up to the stack, meaning that we are done with all the descendands
sccCompleted[vertex] = true; // mark as completed in case if we are the root of current scc
}
};
</code></pre>
<p>Usage:</p>
<pre><code> var g = new Graph(new[,] {
{1, 2}, {2, 3}, {2, 4}, {2, 5}, {3, 1}, {4, 1}, {4, 6}, {4, 8}, {5, 6}, {6, 7}, {7, 5}, {8, 6}
});
var sccs = g.GetStronglyConnectedComponents();
Console.WriteLine("g1");
foreach (var scc in sccs)
Console.WriteLine(String.Join(",",scc)); // print out
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:42:25.080",
"Id": "84033",
"Score": "0",
"body": "It appears, upon my admittedly hasty reading of this code, that you've merely replaced an external stack with three external arrays. Is that an accurate observation? If so, I'm confused as to why three arrays would be more-desirable than one stack. Could you elaborate on that at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:46:29.513",
"Id": "84041",
"Score": "1",
"body": "So -- I implemented the algorithm with a stack, as per the wikipedia pseudocode, and the result does not match the result your implementation returns. Have you actually verified, against another known-working implementation, that your implementation is generating correct results?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:00:18.960",
"Id": "84045",
"Score": "0",
"body": "The code works on sample data I tried, could you share yours?\nThe wikipedia keeps the same amount of data: minConnectedValue as .lowLink field, processed as .index field (they use 'undefined') and the only field I introduced is 'completed'. I'm using two bools plus one int per field, wikipedia: two ints per field.\nThe main difference is in the wikipedia there is a call \"w is in S\" which is Stack.Contains, which has linear time. I.e. the direct implementation in the example is O(n*n), in the notes they suggest using additional flag to workaround that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:44:54.733",
"Id": "84056",
"Score": "0",
"body": "The output discrepancy I mentioned above was in my code; sorry for any concern I caused there. Your answer matches that given by [another implementation](https://github.com/danielrbradley/CycleDetection). I'm going to be spending some quality time with your \"going up the stack\" code, though... I'm very suspicious it will work the same as the stack-based code in all cases. That's why I'm curious as to how thoroughly you have/haven't verified it against existing implementations. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:09:17.597",
"Id": "84063",
"Score": "1",
"body": "Your implementation appears to be sensitive to the order the edges are given in. If you use {4, 8}, {1, 2}, {8, 6}, {2, 5}, {3, 1}, {7, 5}, {4, 1}, {2, 4}, {4, 6}, {5, 6}, {6, 7}, {2, 3} instead of your original ordering, it results in a different answer. Neither stack-based implementation is sensitive to edge ordering. I'm not sure if this qualifies the code as \"broken\" or not, but if you know exactly how to characterize the edge ordering requirements of the input, I'd suggest updating your question with that information."
}
] | [
{
"body": "<h1>Brace Usage</h1>\n\n<p>It is generally considered best practice to always use braces with control statements (such as \"if\" and \"for\" statements). If you are concerned with whitespace, consider that placing the opening brace on the same line as the control statement means that the total increase in code size is only 1 line (for the closing brace). It has the added benefit of causing the compiler to complain if you later delete the statement, without deleting the entire block of code attached to it.</p>\n\n<h1>Preincrement vs. Postincrement</h1>\n\n<p>While both preincrement (++i) and postincrement (i++) do the same thing in isolation, I generally prefer to read the latter. The latter also happens to behave the way most people expect when refactoring the code (render the value, then increment), whereas the former tends to be a very special case (increment first, then render the value) which can cause errors and confusion during refactoring and maintenance. As such, I would recommend using preincrement operators only in the rare occasions they are actually needed (they're a flag that you need to slow down and read that chunk of code carefully).</p>\n\n<h1>Algorithm Behavior</h1>\n\n<p>The algorithm's output varies based on the order that the edges are presented to the class. Either the class needs to ensure that its internal edge lists are always in the appropriate order assumed/required by the algorithm, or the algorithm needs to be modified to handle edges in an arbitrary order (which the stack-based algorithm does).</p>\n\n<p>The original question's test vector results in:</p>\n\n<pre>\n0\n1,2,3,4\n5,6,7\n8\n</pre>\n\n<p>Whereas reordering the edges to be:</p>\n\n<pre><code>{4, 8}, {1, 2}, {8, 6}, {2, 5}, {3, 1}, {7, 5}, {4, 1}, {2, 4}, {4, 6}, {5, 6}, {6, 7}, {2, 3}\n</code></pre>\n\n<p>Results in an output of:</p>\n\n<pre>\n0\n1,2,3,4\n5,6,7,8\n</pre>\n\n<p>There may be additional deficiencies/broken cases surrounding this particular implementation. I ceased investigation upon finding this problem, but I would strongly suggest extensive verification against a known-working stack-based implementation after taking any corrective actions on your stackless algorithm.</p>\n\n<h1>Container Types</h1>\n\n<p>As a general rule of thumb, when returning a container, you should return the most-generic container interface type appropriate. It is almost never appropriate to return a concrete container, such as a <code>List<T></code> or <code>Dictionary<T></code>. In the case of <code>public List<List<int>> GetStronglyConnectedComponents()</code>, it should probably return <code>ICollection<ICollection<int>></code> (since knowing how many groups and how many vertices are in each group makes sense enough to not use <code>IEnumerable<T></code>, but all of the <code>IList<T></code> functionality seems overkill).</p>\n\n<h1>Comments</h1>\n\n<p>Comments are far easier to read when they are above the line they are commenting, rather than to the right. Comments on the right of lines tend to contribute to overly-long lines, they tend to not be well-aligned (and come out of alignment upon refactoring), and tend to get lost/pushed off the side of the screen. All of this makes it much more difficult to do a comments-only skim of the code to get the gist of what it's supposed to be doing, prior to analyzing the code proper, or when quickly trying to find the part of the code you need to modify. The only benefit of comments on the right is that they take up less horizontal space -- but the hit to readability, and therefore usefulness, makes this placement unacceptable to me in most cases.</p>\n\n<p>Some of the comments could also use improvement. \"If we will ever find cycle\" is confusing; it's either an incomplete thought, or placed on the wrong line. \"Initialize to current time\" is self-evident; it would be more useful to know why initializing to the current time is important (and possibly comment what currentTime is/does). \"DFS\" I assume means \"depth-first search,\" and if so, should go into the recursive GetStronglyConnectedComponents call (right before the if statement that kicks off the actual depth-first searching), not the root call.</p>\n\n<p>The \"var currentDiscoveryTime[...]\" comment is also dead code, and should be removed.</p>\n\n<h1>Structures</h1>\n\n<p>It would be nice from an aesthetic standpoint to, e.g., pass around a single array of a structure containing your working data, rather than three same-sized arrays.</p>\n\n<h1>Speed</h1>\n\n<p>If you're simply aiming to get to an \\$O(1)\\$ sidestep of the stack lookup, consider the easier alternative of keeping a secondary data structure (such as your <code>List<bool></code>) that you can modify to mirror the stack, allowing you \\$O(1)\\$ insertion and lookup in \\$2N\\$ space. This would eliminate your need to get clever with edge orderings (which will take time to sort) or subtle algorithm alterations (translating the stack to effectively an array), while getting you the speedup you want. It's not as cool or elegant as the algorithmic gymnastics of doing away with the stack altogether, but it's much more likely to be maintainable, fast, and correct in the future. ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:00:36.210",
"Id": "84085",
"Score": "0",
"body": "Derp. I just noticed that the [Wikipedia article](http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#Remarks) even indicates in its Remarks section that \"The test for whether w is on the stack should be done in constant time, for example, by testing a flag stored on each node that indicates whether it is on the stack.\" My suggestion in the \"Speed\" section, therefore, isn't any different from your provided source material. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T00:37:44.083",
"Id": "47939",
"ParentId": "47846",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T04:25:22.573",
"Id": "47846",
"Score": "8",
"Tags": [
"c#",
"algorithm",
"graph"
],
"Title": "Tarjan's algorithm for Strongly Connected Components without keeping SCC in stack"
} | 47846 |
<p>I have a site where user accounts can be created in two ways: by new users (sign up) and by admin users. Since the creation is handled differently in each case, I decided to split the logic into two separate functions. I have a working implementation but I'm pretty new to Rails so I don't know if it is robust and secure. I am looking for feedback on how to improve it.</p>
<p><strong>users_controller.rb</strong></p>
<pre><code>before_action :signed_in_user, only: [:home, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: [:create_by_admin, :destroy]
.
.
.
def new
if !signed_in?
@user = User.new
@user.confirmation_code = User.new_confirmation_code
elsif signed_in? && current_user.admin?
@user = User.new
render 'new_by_admin' # basically a new.html.erb but with a dropdown for the admin setting
else
redirect_to root_url
end
end
def create
if signed_in? && !current_user.admin?
redirect_to root_url
elsif signed_in? && current_user.admin?
create_by_admin
else
create_by_user
end
end
def create_by_user
@user = User.new(user_params)
if @user.save
UserMailer.confirmation_email(@user).deliver
flash[:success] = "Great! Now check your email for activation instructions."
redirect_to root_url
else
render 'new'
end
end
def create_by_admin
@user = User.new(admin_params)
if @user.save
@user.update_attributes(confirmed: true)
flash[:success] = "User for " + @user.name + " created."
redirect_to users_path
else
render 'new_by_admin'
end
end
.
.
.
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
def admin_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, :admin)
end
</code></pre>
<p>Essentially, all create requests are routed to the create action, and from there sent to the appropriate method (depending on whether the requesting user is a new user or an existing user who is an admin). The differences between the methods is that new users receive an email to activate their accounts upon signup and cannot set themselves as admin, whereas admin users create accounts that are already confirmed and can set them as admin.</p>
<p>Is this a silly way to do it? Should I create an <code>admin_controller</code> that handles all administrative requests?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:00:32.817",
"Id": "84019",
"Score": "0",
"body": "You have a bug in your `#create` method: The `elsif` branch will _never_ be reached. If you're signed in, you'll trigger the first branch immediately; if you're not signed in, it'll jump to the `else` branch. It'll never check if you're an admin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:51:16.567",
"Id": "84023",
"Score": "0",
"body": "Thanks, I actually fixed that last night after posting it - I'll make the edit. :)"
}
] | [
{
"body": "<p>It's fine to create 2 methods to break up the logic a bit - however, there are other things I'd look into before tackling the user vs admin stuff:</p>\n\n<p>Firstly: Ruby style prescribes 2-spaces indentation - not tabs, not 4 spaces.</p>\n\n<p>Second, if you're going to use them, make those <code>create_by*</code> methods <em>private</em>. Don't mix 'em with the regular controller actions.</p>\n\n<p>Third: String interpolation:</p>\n\n<pre><code>flash[:success] = \"User for #{@user.name} created.\"\n</code></pre>\n\n<p>But <code>success</code> is an uncommon flash key. You can use the default <code>notice</code> message type directly in your redirect</p>\n\n<pre><code>redirect_to root_url, notice: \"User for #{@user.name} created.\"\n</code></pre>\n\n<p>If you absolutely want to use <code>success</code>, you can use <a href=\"http://api.rubyonrails.org/classes/ActionController/Flash/ClassMethods.html#method-i-add_flash_types\" rel=\"nofollow\"><code>add_flash_types</code></a> to add it, and use <code>redirect_to ..., success: '...'</code>.</p>\n\n<p>And then you have this:</p>\n\n<pre><code>render 'new_by_admin' # basically a new.html.erb but with a dropdown for the admin setting\n</code></pre>\n\n<p>Don't use two templates - that's a giant hassle to maintain. Use a conditional in the view itself to show or not show the dropdown. I'd also add an <code>admin?</code> helper like this</p>\n\n<pre><code># in application_controller.rb\ndef admin?\n current_user.try(:admin?)\nend\nhelper_method :admin?\n</code></pre>\n\n<p>(I'm assuming that <code>current_user</code> is <code>nil</code> if you're not signed in).</p>\n\n<p>So now you can check for admins in one go rather than both check <code>signed_in?</code> and <em>then</em> check <code>current_user.admin?</code> </p>\n\n<p>In the <code>new</code> view you get this:</p>\n\n<pre><code><% if admin? %>\n your dropdown\n<% end %>\n</code></pre>\n\n<p>And you don't need to 2 templates. Your <code>if..elsif..else</code> in <code>#create</code> can also become the more readable:</p>\n\n<pre><code>if admin?\n ...\nelsif signed_in? # regular user\n ...\nelse\n ...\nend\n</code></pre>\n\n<p>Your code also makes me wonder how you handle passwords. If an admin creates a user, I imagine you'll want to send login instructions <em>and</em> password to the new user.</p>\n\n<p>Right now, it looks like the admin picks a password for other people, but you <em>should</em> already have a \"reset password\" method (for users who've forgotten their password) that will create a random password and email it to the user. It shouldn't be the admin's job to make up passwords.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:25:38.243",
"Id": "84035",
"Score": "0",
"body": "Thank you very much for your comment. Your suggestions make sense - I implemented them and they work great. To answer your questions... 1. I have a flash_class method inside application_helpers.rb that assigns a class to the flash div, which Bootstrap then uses to style it appropriately. In this case, :success equates to 'alert alert-success'. 2. passwords: currently there isn't a mechanism to reset them, although that's what I will work on next. Admins won't always create user accounts - that's just a fail-safe in case the regular method (sign-up) fails. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:40:08.913",
"Id": "84119",
"Score": "1",
"body": "@enragedcamel I figured the `success` flash key was to do with Bootstrap. All the more reason to use the `add_flash_types` trick, and make `success` an \"official\" flash type (or use the helper to remap `notice` to the `alert-success` class)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:12:39.703",
"Id": "47917",
"ParentId": "47847",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47917",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T04:30:55.853",
"Id": "47847",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Creating user accounts as an administrative user"
} | 47847 |
<p>I've been learning Java lately and had some great feedback from the previous threads (hangman and guess a number games).
I was challenged by a user to try to get this code done, so I'm posting it here for further review.
Basically my weakeast (among many) points are exception handling and proper documentation.
What do you think about it? How would you improve it?</p>
<p>Code can be found also in <a href="https://github.com/facundop/RandomWord/blob/master/src/app/RandomWord.java">GitHub</a></p>
<pre><code>package app;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class RandomWord {
private String fileName = "src/app/wordlist.txt";
List<String> lines = null;
public static void main(String[] args) {
RandomWord randomWord = new RandomWord();
randomWord.init();
}
private void init() {
try {
lines = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
} catch (IOException e) {
System.out.println("File can't be opened.");
}
int randomWordIndex = getRandomNumber(1, lines.size());
System.out.println(lines.get(randomWordIndex));
}
/**
* Returns a random number in the range of the specified min and max
* parameters.
*
* @param min
* the minimum value to return
* @param max
* the maximum value to return
* @return a random number between the specified range
*/
private int getRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
}
</code></pre>
| [] | [
{
"body": "<p>It's largely fine by me. :)</p>\n\n<p>Just one glaring point: your implementation would not return the first line, as <code>getRandomNumber()</code> will not return <code>0</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T05:15:33.150",
"Id": "47849",
"ParentId": "47848",
"Score": "5"
}
},
{
"body": "<h3>Hardcoding</h3>\n\n<p>The path to the file with words is hardcoded. That's not so good. It would be better to make it a command line argument.</p>\n\n<p>If you <em>must</em> hardcode something, make it a constant, for example:</p>\n\n<pre><code>private static final String PATH = \"src/app/wordlist.txt\";\n</code></pre>\n\n<p><code>fileName</code> was not a good name for a path anyway. A \"file name\" usually refers to the last path segment without parent directories.</p>\n\n<h3>Single responsibility principle</h3>\n\n<p>The class violates the single responsibility principle: it picks a random word, <em>and</em> it reads a file. I would do something like this instead:</p>\n\n<pre><code>class RandomStringPicker {\n private final List<String> list;\n\n public RandomStringPicker(List<String> list) {\n this.list = list;\n }\n\n public String pick() {\n return list.get(pickRandomNumber(list.size()));\n }\n\n private int pickRandomNumber(int max) {\n return (int) (Math.random() * max);\n }\n}\n</code></pre>\n\n<p>This class only does one thing. You could read the file somewhere else and create a <code>RandomStringPicker</code> class from the lines you read. But now you can reuse this class for other purposes too, for example in unit tests.</p>\n\n<p>This implementation also improves the weakness of your <code>init</code> method. If you forget to call <code>init</code>, your program will compile, but not work. In the example above there is no such uncertainty: if the class is not constructed with a list, it will not compile.</p>\n\n<p>Or you could even go one step further and make the class work with <em>anything</em>, not only strings:</p>\n\n<pre><code>class RandomPicker<T> {\n private final List<T> list;\n\n public RandomPicker(List<T> list) {\n this.list = list;\n }\n\n public T pick() {\n return list.get(pickRandomNumber(list.size()));\n }\n\n private int pickRandomNumber(int max) {\n return (int) (Math.random() * max);\n }\n}\n</code></pre>\n\n<h3>Bugs</h3>\n\n<p>If you have 10 lines, the call <code>getRandomNumber(1, lines.size())</code> will return a random number between 1 and 10, inclusive, which has two problems:</p>\n\n<ul>\n<li>The first line (index = 0) will never be picked</li>\n<li>If 10 is picked, that will be beyond the end of your list and throw an exception</li>\n</ul>\n\n<p>Related to this issue is that you don't really need a minimum parameter for your random number picker. So that's an unnecessary detail in your implementation, you could use something more simple like the example above.</p>\n\n<h3>Printing, validating and logging</h3>\n\n<p>It's not good practice to print things on the console. If you want to verify your code works, write unit tests. If you want to log messages during runtime, use a logger.</p>\n\n<h3>Nitpicks</h3>\n\n<ul>\n<li>The code is not well indented</li>\n<li>Unnecessary brackets in <code>(max - min) + 1</code>. This is the same: <code>max - min + 1</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:48:54.410",
"Id": "47853",
"ParentId": "47848",
"Score": "10"
}
},
{
"body": "<p><strong>Exception Handling</strong><br>\nYou wrap the <code>readAllLines</code> with a try catch block, but if an error occurs, you simply write a line to the console, and continue... in the very next line you call <code>line.size()</code>, which will result in a <code>NullPointerException</code>...<br>\nMorale of the story is - if you don't have anything smart to do in your catch block - it is better to let the exception bubble up to where it can be handled, or otherwise stop the application completely, notifying the user what <em>exactly</em> was the problems (that's what exceptions are for...)</p>\n\n<p><strong>Documentation</strong><br>\nThe only documentation you have is for the <code>getRandomNumber(int min, int max)</code> method, and it is full of reiterations on how this methods returns a random number between a min and a max number.<br>\nThis kind of documentation does not help anyone - the signature of the method is self-explanatory. Documentation has a nasty habit of rotting - since you tend not to maintain it as you maintain the code, and it becomes inaccurate and ultimately misleading.</p>\n\n<p>Documentation would be needed when the method's signature does <em>not</em> convey what the method is doing (like in <code>init</code>), but I would sooner change the name (and the content) of the method before writing documentation, as suggested in the other answer here, since I believe that <a href=\"http://memeagora.blogspot.co.il/2008/11/comments-code-smell.html\">comments are a code-smell</a>, and that self-explanatory code is an indicator for better design.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T07:49:16.173",
"Id": "47855",
"ParentId": "47848",
"Score": "8"
}
},
{
"body": "<p>I'll focus on the choice of algorithm. Choose janos' answer for style review, I'd say.</p>\n\n<p>Files can be arbitrarily large. Larger than what can actually fit in your VM's memory. Your algorithm, while simple, does not deal well with a source of numbers of which the size is not known at the start.</p>\n\n<p>So lets devise a better algorithm that can deal with an arbitrarily large number of inputs, of which we do not know the size beforehand.</p>\n\n<p>To abstract this we will act as if our function gets as input an <code>Iterator<T></code> (it could be one that reads from a file, or simply iterates a list, or reads primes from a webservice, ...)</p>\n\n<p>First off, we'll need to handle the case that the <code>Iterator</code> is empty. Your current solution simply throws an <code>IndexOutOfBoundsException</code>, but we can do better, and we'll throw a custom exception.</p>\n\n<p>The idea of the algorithm is that we have a current choice, and for each new input we may take it as our current choice instead. Of course, the odds that we should change our current choice should decrease proportionally to the number of inputs we've seen.</p>\n\n<p>We'll need to keep track of a few things : </p>\n\n<ul>\n<li>the item we would have picked if we'd have seen all inputs : <code>currentPick</code></li>\n<li>the number of inputs we've seen so far : <code>totalInputs</code></li>\n</ul>\n\n<p>When we read the first number it's the only one we can pick so far, so <code>currentPick</code> becomes that number and we increase <code>totalInputs</code>.</p>\n\n<p>Then for every next input, we determine the chance that that number becomes our <code>currentPick</code>, and that chance is 1/<code>totalInputs</code>. So we ask our random source to get the next <code>int</code> in [0, <code>totalInputs</code>[ and if it turns out to be 0, we change our <code>currentPick</code> to the latest item.</p>\n\n<p>so something like this :</p>\n\n<pre><code>public static <T> T pickItem(Iterator<T> inputs) {\n if (!inputs.hasNext()) {\n throw new EmptyInputException();\n }\n\n T currentPick = inputs.next();\n long totalInputs = 1;\n\n Random random = new Random();\n\n while (inputs.hasNext()) {\n T next = inputs.next();\n totalInputs++;\n if (shouldPick(totalInputs, random)) {\n currentPick = next;\n }\n }\n return currentPick;\n}\n\nprivate static boolean shouldPick(long totalInputs, Random random) {\n return nextLong(random, totalInputs) == 0;\n}\n\nprivate static long nextLong(Random random, long bound) {\n return (long) (random.nextDouble() * bound);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:30:24.840",
"Id": "84038",
"Score": "0",
"body": "To complement this answer, [`org.apache.commons.io.LineIterator`](http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/LineIterator.html) would be a handy way to get an `Iterator<String>` over lines of a file."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:47:33.570",
"Id": "47907",
"ParentId": "47848",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T04:44:52.700",
"Id": "47848",
"Score": "8",
"Tags": [
"java",
"random",
"file",
"io"
],
"Title": "Read from a file and pick a random line"
} | 47848 |
<p>I'm trying to make a backend for QuizUp like application: user connects to a server, sends credentials and gets paired up with another user. After that server handles each pair, periodicaly sending server messages to each user in a pair and also redirecting user's mesages between them.</p>
<p>Server class:</p>
<pre><code>private static class Server{
private static final int NUM_THREADS = 2400;
private ExecutorService executorService;
private ServerSocket serverSocket;
private int listeningPort;
public volatile boolean isRunning;
private Thread mainThread;
private volatile Map<String, Conn> playRequests;
public Server(int port){
try {
executorService = Executors.newFixedThreadPool(NUM_THREADS);
listeningPort = port;
serverSocket = new ServerSocket(listeningPort);
isRunning = true;
playRequests = new ConcurrentHashMap<String, Conn>();
mainThread = new Thread(new Runnable(){
@Override
public void run() {
handleIncomingConnections();
}
});
} catch (IOException e) {
System.out.println(e.toString());
}
}
public void run(){
mainThread.start();
}
private void handleIncomingConnections(){
while(isRunning){
try {
final Socket client = serverSocket.accept();
Runnable gameRunnable = new Runnable(){
@Override
public void run() {
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
String read = null;
String id = null;
boolean isRequesting = false;
String rid = null;
while(!(read = reader.readLine()).equals("FIN_1")){
String[] str = read.split("#");
if(str[0].equals("id")){
id = str[1];
}else if(str[0].equals("isRequesting")){
isRequesting = (str[1].equals("1"));
}else if(str[0].equals("rid")){
rid = str[1];
}
}
Conn connection = new Conn(client, isRequesting, id, writer, reader);
if(isRequesting){
playRequests.put(rid, connection);
}else{
if(playRequests.containsKey(id)){
Conn conn = playRequests.get(id);
playRequests.remove(id);
handleGame(conn, connection);
}
}
}catch(Exception e){
System.out.println(e.toString());
}
}
};
executorService.execute(gameRunnable);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void handleGame(Conn a, Conn b){
new GameHandler(a, b).execute();
}
}
</code></pre>
<p>GameHandler class:</p>
<pre><code>private class GameHandler{
private volatile Conn a;
private volatile Conn b;
private Thread aReadThread;
private Thread bReadThread;
private Thread messageThread;
private Runnable aReadRunnable;
private Runnable bReadRunnable;
private Runnable messageRunnable;
private volatile PrintWriter aWriter;
private volatile PrintWriter bWriter;
private volatile BufferedReader aReader;
private volatile BufferedReader bReader;
private volatile boolean aIsReady;
private volatile boolean bIsReady;
private volatile boolean isGameRunning;
public GameHandler(final Conn s1, final Conn s2){
this.a = s1;
this.b = s2;
isGameRunning = true;
try {
aWriter = a.writer;
bWriter = b.writer;
aReader = a.reader;
bReader = b.reader;
} catch (Exception e) {
try {
isGameRunning = false;
a.close();
b.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(e.toString());
}
messageRunnable = new Runnable(){
@Override
public void run() {
System.out.println(a.id + " " + b.id);
messageThread = Thread.currentThread();
for(int i = 0; i < 6; i++){
if(isGameRunning){
try{
Thread.sleep(4000);
}catch(InterruptedException e){
}
}
}
//end game
isGameRunning = false;
try {
a.close();
b.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
aReadRunnable = new Runnable(){
@Override
public void run() {
aReadThread = Thread.currentThread();
String line = null;
try {
while (isGameRunning && (line = aReader.readLine()) != null && !(line = aReader.readLine()).equals("FIN")){
bWriter.println(line);
}
a.close();
System.out.println(a.id + " done");
} catch (Exception e) {
try {
isGameRunning = false;
a.close();
b.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(e.toString());
}
}
};
bReadRunnable = new Runnable(){
@Override
public void run() {
bReadThread = Thread.currentThread();
String line = null;
try {
while (isGameRunning && (line = bReader.readLine()) != null && !(line = bReader.readLine()).equals("FIN")){
aWriter.println(line);
}
b.close();
System.out.println(b.id + " done");
} catch (Exception e) {
try {
isGameRunning = false;
a.close();
b.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(e.toString());
}
}
};
}
public void execute() {
executorService.execute(messageRunnable);
executorService.execute(aReadRunnable);
executorService.execute(bReadRunnable);
}
}
</code></pre>
<p>And a container class for each users to hold open socket, in/out streams, credentials, etc:</p>
<pre><code>private class Conn{
public Socket s;
public boolean isRequesting;
public PrintWriter writer;
public String id;
public BufferedReader reader;
Conn(Socket s, boolean isRequesting, String id, PrintWriter writer, BufferedReader reader){
this.s = s;
this.isRequesting = isRequesting;
this.id = id;
this.writer = writer;
this.reader = reader;
}
public void close() throws IOException{
s.close();
}
}
</code></pre>
<p>The logic is following:</p>
<p>Server has a <code>mainThread</code>, where it accepts incoming connections and creates client sockets. For each new socket it creates a <code>gameRunnable</code>, where it listens for client's credentials (whether this client is the one requesting connection, id of the user it wants to connect to, id of itself). After receiving credentials, server creates a new Conn object, storing all the info(id, and also socket and in/out streams, so it doesn't have to open it again after) there, and than places it in the Map (<code>playRequests</code>) with requested user id as a key. If there is a matching pair in a map, server creates a new <code>GameHandler</code> for these two Conn objects (all this still goes inside the <code>gameRunnable</code>). Each <code>GameHandler</code> contains three Runnables: messageRunnable to send messages from server to both users, and two Runnables (<code>aReadRunnable</code> and <code>bReadRunnable</code>) to read incoming data from both sockets. So basically, each communication session (game) requires 4 threads (1 to get credentials and start a game, and three to maintain the game before the end). Here are the questions I have:</p>
<ol>
<li><p>Are there any design/implementation issues you see here? Please be as picky as possible because I'd really not want it to crash under high load. If you see smth, you are more than welcome to give your solutions</p></li>
<li><p>I know that having large and uncontrolled number of threads is a bad practice, so I'm using an executer with fixed thread pool to execute all the Runnables. However, due to the game features, I can't make users who are requesting connections wait for empty threads in a pool, what is obviously going to happen if I have a lot of incoming connections. So is usage of thread pool reasonable here? If yes, what number of threads should I use, given that I need 4 threads per game, and each game lasts approximately 2 minutes.</p></li>
<li><p>Am I closing all the sockets correctly? Are there any memory leaks?</p></li>
</ol>
<p>Other questions regard server deploying:</p>
<ol>
<li><p>I'm planning to run it on Amazon EC2. Should I use Tomcat server for this, or can I just run it as a plain java program on JVM?</p></li>
<li><p>I tested it on my laptop, and having many simultaneous connections, heap size is not enough to handle all of them. Should I increase heap size before lunch as much as possible, or it may affect performance?</p></li>
</ol>
| [] | [
{
"body": "<h1>Blocking I/O doesn't scale well</h1>\n\n<p>Blocking I/O usually requires a 1:1 coupling between threads and streams. Thin clients can get away with using blocking I/O, because they're not going to have 100+ connections open. For servers with long-lasting connections, it's not workable.</p>\n\n<p>You've already noticed this with your memory requirements spiking. Consider that, if a thread uses just 256KB (or even 1MB) in stack space, and you run 2400 threads, you're running 600MB (or 2400MB) just for your executor.</p>\n\n<h1>Enter non-blocking I/O</h1>\n\n<p>Java 1.4 introduced <strong>non-blocking I/O</strong> (NIO) to get around the 1:1 thread-to-stream coupling. NIO works pretty much like event handling in a GUI: you attach streams to a <em>selector</em>, you poll that selector for interesting events (e.g. stream has unread data, connection is ready), and then you do something with that event. Just like a GUI doesn't need a separate thread per component, NIO allows you to run a server with basically a single worker thread on your end.</p>\n\n<p>Here's a quick & dirty example of something running under NIO, minus the executor and clean-up for brevity:</p>\n\n<pre><code>import java.io.*;\nimport java.nio.*;\nimport java.nio.channels.*;\nimport java.util.*;\n\npublic class Repeater {\n public static void main(String[] args) throws IOException {\n Selector selector = Selector.open();\n ServerSocketChannel server = ServerSocketChannel.open();\n server.configureBlocking(false);\n server.socket().bind(null);\n server.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler());\n System.out.println(\"Listening on \" + server.socket().getInetAddress() + \" @ \" + server.socket().getLocalPort());\n\n while ( selector.select() > 0 ) {\n Iterator<SelectionKey> keys = selector.selectedKeys().iterator();\n while ( keys.hasNext() ) {\n SelectionKey key = keys.next();\n try {\n ((Handler) key.attachment()).handle(selector, key);\n } catch (Exception ex) {\n ex.printStackTrace();\n continue;\n } finally {\n keys.remove(); // [!]\n }\n }\n }\n }\n\n static interface Handler {\n void handle(Selector selector, SelectionKey key) throws IOException;\n }\n\n static final int BUFFER_SIZE_IN_BYTES = 140;\n static class AcceptHandler implements Handler {\n public void handle(Selector selector, SelectionKey key) throws IOException {\n if ( key.isAcceptable() ) {\n ServerSocketChannel server = (ServerSocketChannel) key.channel();\n SocketChannel client = server.accept();\n client.configureBlocking(false);\n client.write(ByteBuffer.wrap((\"Please leave a message no longer than \" + BUFFER_SIZE_IN_BYTES + \" bytes.\\r\\n\").getBytes()));\n\n client.register(selector, SelectionKey.OP_READ, new ReadHandler());\n }\n }\n }\n\n static class ReadHandler implements Handler { \n private final ByteBuffer myStorage = ByteBuffer.allocate(BUFFER_SIZE_IN_BYTES); \n public void handle(Selector selector, SelectionKey key) throws IOException {\n if ( key.isReadable() ) {\n SocketChannel client = (SocketChannel) key.channel();\n client.read(myStorage);\n if ( !myStorage.hasRemaining() || new String(myStorage.array(), 0, myStorage.position()).endsWith(\"\\n\") ) {\n myStorage.flip();\n client.write(myStorage);\n myStorage.clear();\n } else {\n client.register(selector, SelectionKey.OP_READ, this);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>A quick test on a 64-bit JVM had process size on about 22MB for 4000 connections, and 36MB for 10000 connections. Actual use will be a bit more because this example is simplistic, but you get a sense of how it scales.</p>\n\n<p>If you need to do serious processing before sending an answer, you can still delegate the channel handling to an executor.</p>\n\n<h1>...or consider asynchronous I/O</h1>\n\n<p>Java 7 introduced <strong>asynchronous I/O</strong> under the name NIO.2, which looks like it can do away with manually controlling the selector. I haven't used it in any serious manner yet, so I can't comment on how well it handles things or its ease of use, but it's worth taking a look to see which approach better floats your boat.</p>\n\n<h1>Networking libraries</h1>\n\n<p>I'm assuming you're also doing this as an exercise to yourself. If not, consider using <a href=\"https://mina.apache.org\">Apache MINA</a> to shield you from some of the complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T08:38:24.793",
"Id": "97677",
"Score": "0",
"body": "thank you for mentioning asynchronous i/o, that gives me a good starting point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-22T07:19:35.647",
"Id": "349112",
"Score": "0",
"body": "@JvR I am also using socket to send data but in my case I need to make sure that I am not sharing same socket between two threads. I have a question [here](https://codereview.stackexchange.com/questions/179576/do-not-share-same-socket-between-two-threads-at-the-same-time) and wanted to see if you can help me out if possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:48:02.200",
"Id": "47908",
"ParentId": "47851",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47908",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T06:09:36.843",
"Id": "47851",
"Score": "8",
"Tags": [
"java",
"multithreading",
"socket",
"server"
],
"Title": "Multi-threaded socket server high load"
} | 47851 |
<p>In case the table has class <code>'trans'</code> - run <code>dataTable()</code> and <code>columnFilter()</code>; otherwise just run <code>dataTable()</code>.</p>
<p>Is it possible to <strong>not repeat</strong> the <code>dataTable()</code> part?</p>
<pre><code>$('#dt_a').each(function() {
if ($(this).hasClass('trans')) {
$(this).dataTable({
"sDom": "<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap_alt",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
})
.columnFilter({
sPlaceHolder: "head:before",
aoColumns: [
null,
{ type: "text" },
{ type: "text" },
{ type: "date-range" },
{ type: "text" },
{ type: "text" },
null,
null
]
});
} else {
$(this).dataTable({
"sDom": "<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap_alt",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
});
}
});
</code></pre>
<p><strong>NOTE:</strong></p>
<p><code>columnFilter</code> is an extension to <code>dataTable</code>.</p>
| [] | [
{
"body": "<p>Use some variables. You don't need to chain function calls; it's just a neat thing you <em>can</em> do when appropriate, but it's not required.</p>\n\n<pre><code>$('#dt_a').each(function() {\n var target = $(this), // store this \n table = target.dataTable({ // and store this too\n \"sDom\": \"<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>\",\n \"sPaginationType\": \"bootstrap_alt\",\n \"oLanguage\": {\n \"sLengthMenu\": \"_MENU_ records per page\"\n }\n });\n\n if (target.hasClass('trans')) {\n table.columnFilter({\n sPlaceHolder: \"head:before\",\n aoColumns: [\n null,\n { type: \"text\" },\n { type: \"text\" },\n { type: \"date-range\" },\n { type: \"text\" },\n { type: \"text\" },\n null,\n null\n ]\n });\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T09:01:59.167",
"Id": "83893",
"Score": "0",
"body": "Neat! I didn't know chaining function calls wasn't necessary. Now I know. Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:18:24.253",
"Id": "83905",
"Score": "1",
"body": "@gmaggio The reason chaining works, is that one function call returns an object, and then you call the next function in the chain on that object. So for instance `$(...)` returns an object, and you can either call something on that object directly (chaining), or you can stick that object in a variable for later use. In other words, you can always cut a chain in 2 or more pieces."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:12:56.767",
"Id": "47858",
"ParentId": "47857",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47858",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:03:56.540",
"Id": "47857",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"jquery-datatables"
],
"Title": "Making a datatable, maybe also with column filters"
} | 47857 |
<p>A month ago I finished and posted my <a href="https://codereview.stackexchange.com/questions/45091/tic-tac-toe-feedback-requested">first version</a> of my Tic-Tac-Toe, I received a lot of good feedback and refactored it to more closely suit the MVP design pattern. </p>
<p>I've done some further clean-ups and refactoring in the code now but most importantly I have implemented a very primitive AI, that works "fairly well", my goal with the AI was <strong>NOT</strong> to create an AI with perfect play, this has been covered many times before as Tictactoe is a solved game, my goal was to create an AI that would mimick human play more closely. I think the implementation is decent but the code is a mess, it was my first attempt ever at coding a weak AI and it ended up with me having to add quite a large amount of extra methods for searching and sorting the grid just for the AI to work. </p>
<p>Anyhow, any feedback is appreciated, not restricted to the AI only, I have posted the (almost) complete code below:</p>
<p><strong>Grid.cs</strong></p>
<pre><code> class Grid
{
const int MAX_CELLS = 3;
public Cell[,] Cells { get; set; }
private Cell[,] cells = new Cell[MAX_CELLS, MAX_CELLS];
public Cell this[int index, int index2]
{
get
{
return cells[index, index2];
}
set
{
cells[index, index2] = value;
}
}
public Outcome Outcome { get; private set; }
public Grid(IGameViewer viewer)
{
Outcome = Outcome.None;
for (int x = 0; x < MAX_CELLS; x++)
{
for (int y = 0; y < MAX_CELLS; y++)
{
this[x, y] = new Cell(viewer, new Position(x, y));
}
}
}
public bool CheckOutcome(Position coords, Player player)
{
//Check for player wins first
var corners = new Position[] { new Position(0,0), new Position(2,0), new Position(0,2), new Position(2,2) };
var middle = new Position(1,1);
var checkDiagonals = false;
//If the cell is at the corner or the middle we have to check for diagonal wins too
if (corners.Any(e => e.Equals(coords)) || middle.Equals(coords)) { checkDiagonals = true; }
if (player.PlayerWon(this[coords.X, coords.Y], this, checkDiagonals))
{
switch (player.marker)
{
case Mark.Cross:
Outcome = Outcome.CrossWin;
break;
case Mark.Nought:
Outcome = Outcome.NoughtWin;
break;
}
return true;
}
//Now we can check for draws
if (this.GetEmptyCells().Length == 0)
{
Outcome = Outcome.Draw;
return true;
}
//If execution reaches this point then no one has won, return false
return false;
}
public List<Cell[]> GetEmptyLines()
{
var selection = new List<Cell[]>();
for (int i = 0; i < this.cells.GetLength(0); i++)
{
var rows = new List<Cell[]>() { this.HorizontalRelatives(cells[i, i]), this.VerticalRelatives(cells[i, i]) };
if (i == 1)
{
rows.Add(this.DiagonalRelatives(cells[i, i]));
rows.Add(this.DiagonalRelatives2(cells[i, i]));
}
selection.AddRange(rows.FindAll(array => array.Length.Equals(3)));
}
return selection;
}
public Cell[] GetEmptyCells()
{
List<Cell> emptyCells = new List<Cell>();
foreach (Cell cell in cells)
{
if (cell.Mark == Mark.Empty)
{
emptyCells.Add(cell);
}
}
return emptyCells.ToArray();
}
public Position IndexOf(Cell cell)
{
for (int x = 0; x < cells.GetLength(0); x++)
{
for (int y = 0; y < cells.GetLength(1); y++)
{
if (cells[x, y].Equals(cell))
{
return new Position(x, y);
}
}
}
//If code reaches this point, then it didn't find anything, return -1
return new Position(-1, -1);
}
public Cell[] DiagonalRelatives(Cell cell)
{
var relatives = new List<Cell>();
for (int x = 0; x < 3; x++)
{
if (cells[x, x].Mark.Equals(cell.Mark))
{
relatives.Add(cells[x, x]);
}
}
return relatives.ToArray();
}
public Cell[] DiagonalRelatives2(Cell cell)
{
var relatives = new List<Cell>();
for (int x = 0; x < 3; x++)
{
if (cells[x, 2 - x].Mark.Equals(cell.Mark)) { relatives.Add(cells[x, 2 - x]); }
}
return relatives.ToArray();
}
public Cell[] HorizontalRelatives(Cell cell)
{
var relatives = new List<Cell>();
int rowNum = this.IndexOf(cell).Y;
for (int x = 0; x < 3; x++)
{
//Find row of cell
if (cells[x, rowNum].Mark.Equals(cell.Mark)) { relatives.Add(cells[x, rowNum]); }
}
return relatives.ToArray();
}
public Cell[] VerticalRelatives(Cell cell)
{
var relatives = new List<Cell>();
int colNum = this.IndexOf(cell).X;
for (int y = 0; y < 3; y++)
{
//Find row of cell
if (cells[colNum, y].Mark.Equals(cell.Mark)) { relatives.Add(cells[colNum, y]); }
}
return relatives.ToArray();
}
public Cell[] Where(Predicate<Cell> cellSelector)
{
var results = new List<Cell>();
foreach (var cell in cells)
{
if (cellSelector.Invoke(cell))
{
results.Add(cell);
}
}
return results.ToArray();
}
public Cell Find(Predicate<Cell> cellSelector)
{
foreach (var cell in cells)
{
if (cellSelector.Invoke(cell))
{
return cell;
}
}
//If it doesn't find any cell that matches predicate conditions then return null
return null;
}
public void Reset()
{
foreach (Cell cell in cells)
{
cell.Reset();
}
}
public IEnumerator<Cell> GetEnumerator()
{
foreach (Cell cell in cells)
{
yield return cell;
}
}
}
</code></pre>
<p><strong>Position.cs</strong></p>
<pre><code>struct Position
{
public readonly int X;
public readonly int Y;
public Position(int x, int y)
{
this.X = x;
this.Y = y;
}
}
</code></pre>
<p><strong>GameController.cs</strong></p>
<pre><code> class GameController : IGamePresenter
{
public Player[] Players { get; private set; }
public event GameEndHandler GameEnd;
public event PlayedEventHandler Played;
public Grid Grid { get; private set; }
public GameController(IGameViewer viewer)
{
Grid = new Grid(viewer);
Players = new Player[2];
Players[0] = new Player(Mark.Cross); // Always set to human
Players[1] = new AIPlayer(Mark.Nought, this); // Set to AI
}
void IGamePresenter.PlayerChoice(Player player, Position position)
{
//This is so the AI can start playing again when a new round is started
(Players[1] as AIPlayer).DisallowPlay = false;
// Presenter -> Model, place marker at coords
Grid[position.X, position.Y].Mark = player.marker;
// Model -> Presenter, if grid reaches an outcome end the game
if (Grid.CheckOutcome(position, player))
{
GameEnd(Grid.Outcome);
}
//Raise Played Event
Played(Grid[position.X, position.Y], player);
}
void IGamePresenter.RestartGame()
{
// Reset grid
Grid.Reset();
// Reset AIPlayer
(Players[1] as AIPlayer).Reset();
}
}
</code></pre>
<p><strong>Player.cs</strong></p>
<pre><code>class Player
{
public readonly Mark marker;
public int Score { get; set; }
public Player(Mark marker)
{
this.marker = marker;
}
public bool PlayerWon(Cell cell, Grid grid, bool checkDiagonals)
{
return (grid.HorizontalRelatives(cell).Length == 3 || grid.VerticalRelatives(cell).Length == 3) ? true
: (checkDiagonals) ?
(grid.DiagonalRelatives(cell).Length == 3 || grid.DiagonalRelatives2(cell).Length == 3) ? true : false
: false;
}
}
</code></pre>
<p><strong>AIPlayer.cs</strong></p>
<pre><code> class AIPlayer : Player
{
private readonly IGamePresenter presenter;
private readonly DecisionMaker decisionMaker;
public int Turn { get; set; } // We aren't using this right now but it's good for state-based AIs
public bool DisallowPlay { get; set; }
public AIPlayer(Mark marker, IGamePresenter presenter) : base(marker)
{
this.presenter = presenter;
decisionMaker = new DecisionMaker();
Turn = new int();
presenter.Played += DoTurn;
presenter.GameEnd += new GameEndHandler(x => DisallowPlay = true); // Disable play for AI after game has been won
}
private void DoTurn(Cell cell, Player player)
{
//This check is necessary, otherwise we'll cause an infinite loop
if (player is AIPlayer || DisallowPlay)
{
return;
}
var decision = decisionMaker.GetDecision(presenter.Grid, this);
Turn++;
Task.Delay(250).Wait(); // This is just a cosmetic thing, so it'll look like the AI needs some "thinking time"
presenter.PlayerChoice(this, decision);
}
public void Reset()
{
Turn = 0;
decisionMaker.Reset();
}
}
}
class Decision
{
public readonly Position Position;
public readonly int Priority;
public Decision(int priority, Position position)
{
Priority = priority;
Position = position;
}
}
/// <summary>
/// This is a very simple strategy that will first and foremost try to win and secondly try to force a draw.
/// </summary>
class BasicAlgorithm : IDecisionAlgorithm
{
private static Position[] corners = new Position[] { new Position(0, 0), new Position(2, 2) };
private static Position[] corners2 = new Position[] { new Position(0, 2), new Position(2, 0) };
private static Position middle = new Position(1, 1);
private List<int> horizontalWin = new List<int>() { 0, 1, 2 };
private List<int> verticalWin = new List<int>() { 0, 1, 2 };
private bool diagonalWin = true;
private bool diagonalWin2 = true;
Position IDecisionAlgorithm.Invoke(Grid grid, AIPlayer player)
{
var strategies = new Decision[] { StrategyOne(grid, player), StrategyTwo(grid, player) };
return
(strategies[0].Priority == strategies[1].Priority) ?
strategies[new Random().Next(1)].Position
: (strategies[0].Priority > strategies[1].Priority) ?
strategies[0].Position : strategies[1].Position;
}
void IDecisionAlgorithm.Reset()
{
horizontalWin = new List<int>() { 0, 1, 2 };
verticalWin = new List<int>() { 0, 1, 2 };
diagonalWin = true;
diagonalWin2 = true;
}
/// <summary>
/// Tries to win the game, through horizontal, vertical diagonal lines. Priority returned will range from 0(no priority) to
/// 3 (absolute action).
/// </summary>
/// <param name="grid"></param>
/// <param name="player"></param>
/// <returns>Decision</returns>
private Decision StrategyOne(Grid grid, AIPlayer player)
{
// Start by analyzing board state to identify what wins that are possible
foreach (Cell cell in grid)
{
if (cell.Mark.Equals(Mark.Cross))
{
horizontalWin.RemoveAll(n => n.Equals(cell.Position.Y));
verticalWin.RemoveAll(n => n.Equals(cell.Position.X));
//If opponent has his marker in the middle then all diagonal wins are impossible
if (cell.Position.Equals(middle) && cell.Mark.Equals(Mark.Cross))
{
diagonalWin = false;
diagonalWin2 = false;
}
// For other cells different rules apply, as there are 3 horizontal and diagonal wins each
else if (cell.Mark.Equals(Mark.Cross))
{
if (corners.Contains(cell.Position)) // Check if diagonal win is possible
{
diagonalWin = false;
}
if (corners2.Contains(cell.Position))
{
diagonalWin2 = false;
}
}
}
}
//Check if any type of win is possible
if (horizontalWin.Count == 0 && verticalWin.Count == 0 && !diagonalWin && !diagonalWin2)
{
// In this case winning is impossible so we should then always return lowest priority from this strategy
return new Decision(0, new Position());
}
//Now calculate which type of win to prioritize, starting by checking where we already have marks placed
var friendlyCells = grid.Where(cell => cell.Mark.Equals(player.marker));
//If we don't have any friendly marks placed then we will have to base our decision on any row where a win is possible
if (friendlyCells.Length < 1)
{
//Get all empty rows
var options = grid.GetEmptyLines();
var rnd = new Random();
//Since these are all equally viable options just randomize our choice between them all with priority 1.
var decision = options[rnd.Next(options.Count)];
// Each array will always contain 3 cells so cleaner with a static number here
return new Decision(1, decision[rnd.Next(2)].Position);
}
else // Okay if we have friendly cells then we need to how many and assign each a unique priority
{
var options = new List<Tuple<int, Position>>();
foreach (var cell in friendlyCells)
{
var horizontalNeighbours = grid.HorizontalRelatives(cell);
var verticalNeighbours = grid.VerticalRelatives(cell);
var diagonalNeighbours = grid.DiagonalRelatives(cell);
var diagonalNeighbours2 = grid.DiagonalRelatives2(cell);
//Now check if a win can be achieved in Y-axis
if (horizontalWin.Contains(cell.Position.Y))
{
// Okay since horizontal wins are OK at this point then just find the cell and add it to the list
// The priority is calculated as if (number of neighbours == 2) then priority = 3 else priority = 1.
options.Add(Tuple.Create((horizontalNeighbours.Length == 2) ? 3 : 1, grid.Find(
(entry) =>
entry.Position.Y.Equals(cell.Position.Y) &&
entry.Mark.Equals(Mark.Empty))
.Position));
}
//Same thing here but X-axis instead
if (verticalWin.Contains(cell.Position.X))
{
options.Add(Tuple.Create((verticalNeighbours.Length == 2) ? 3 : 1, grid.Find(
(entry) =>
entry.Position.X.Equals(cell.Position.X) &&
entry.Mark.Equals(Mark.Empty))
.Position));
}
if (diagonalWin && corners.Any(pos => pos.Equals(cell.Position)) || diagonalWin && cell.Position.Equals(middle)) //Only check for diagonal wins if cell is in a corner
{
options.Add(Tuple.Create((diagonalNeighbours.Length == 2) ? 3 : 1, grid.Find(
(entry) =>
corners.Any(pos => pos.Equals(entry.Position)) && entry.Mark.Equals(Mark.Empty) ||
entry.Position.Equals(middle) && entry.Mark.Equals(Mark.Empty)).Position));
}
if (diagonalWin2 && corners2.Any(pos => pos.Equals(cell.Position)) || diagonalWin2 && cell.Position.Equals(middle))
{
options.Add(Tuple.Create((diagonalNeighbours2.Length == 2) ? 3 : 1, grid.Find(
(entry) =>
corners2.Any(pos => pos.Equals(entry.Position)) && entry.Mark.Equals(Mark.Empty) ||
entry.Position.Equals(middle) && entry.Mark.Equals(Mark.Empty)).Position));
}
}
//If it doesn't find any neighbouring cells that can win just place marker on an empty valid space
if (options.Count < 1)
{
var emptyRows = grid.GetEmptyLines();
var rnd = new Random();
//Since these are all equally viable options just randomize our choice between them all with priority 1.
var decision = emptyRows[rnd.Next(options.Count)];
// Each array will always contain 3 cells so cleaner with a static number here
return new Decision(1, decision[rnd.Next(2)].Position);
}
//Sort dictionary by key value
var sortedOptions = options.OrderByDescending(entry => entry.Item1);
//Okay now first check if we have more than one entry with the same priority
if (sortedOptions.Where(entry => entry.Item1.Equals(sortedOptions.First().Item1)).Count() > 1)
{
var selection = sortedOptions.Where(entry => entry.Item1.Equals(sortedOptions.First().Item1)).ToList();
return new Decision(sortedOptions.First().Item1, selection[new Random().Next(selection.Count)].Item2);
}
else
{
return new Decision(sortedOptions.First().Item1, sortedOptions.First().Item2);
}
}
}
/// <summary>
/// Will attempt to force a draw by analyzing board state and opponent mark placements and attempting to block them.
/// Priority can never exceed 2 so a high-probability win will always take precedent over this strategy.
/// </summary>
/// <param name="board"></param>
/// <param name="player"></param>
/// <returns>Decision</returns>
private Decision StrategyTwo(Grid grid, AIPlayer player)
{
//Start by getting each X-marked cell
var unfriendlyCells = new List<Tuple<int,Cell>>();
var emptyCells = grid.GetEmptyCells();
foreach (var cell in grid)
{
if (cell.Mark.Equals(Mark.Cross))
{
unfriendlyCells.Add(Tuple.Create(1, cell)); //Set these to priority 1 by default
}
}
var prioritizedOptions = new List<Tuple<int,Position>>();
//Now get all relatives + empty cells of those X-marked cells
foreach (var option in unfriendlyCells)
{
int horizontalNeighbours = grid.HorizontalRelatives(option.Item2).Length;
var emptyHorizontalCells = emptyCells.Where(entry => entry.Position.Y.Equals(option.Item2.Position.Y));
int verticalNeighbours = grid.VerticalRelatives(option.Item2).Length;
var emptyVerticalCells = emptyCells.Where(entry => entry.Position.X.Equals(option.Item2.Position.X));
int diagonalNeighbours = grid.DiagonalRelatives(option.Item2).Length;
var emptyDiagonalCells = emptyCells.Where(entry => corners.Any(corner => corner.Equals(entry.Position)));
int diagonalNeighbours2 = grid.DiagonalRelatives2(option.Item2).Length;
var emptyDiagonalCells2 = emptyCells.Where(entry => corners2.Any(corner => corner.Equals(entry.Position)));
if(horizontalNeighbours > 1 && emptyHorizontalCells.Count() == 1)
{
//If we have 1 neighbouring X-cell + 1 empty cell then we must block them off with the highest priority
prioritizedOptions.Add(Tuple.Create(2, emptyHorizontalCells.First().Position));
}
if (verticalNeighbours > 1 && emptyVerticalCells.Count() == 1)
{
prioritizedOptions.Add(Tuple.Create(2, emptyVerticalCells.First().Position));
}
if (diagonalNeighbours > 1 && emptyDiagonalCells.Count() == 1)
{
prioritizedOptions.Add(Tuple.Create(2, emptyDiagonalCells.First().Position));
}
if (diagonalNeighbours2 > 1 && emptyDiagonalCells2.Count() == 1)
{
prioritizedOptions.Add(Tuple.Create(2, emptyDiagonalCells2.First().Position));
}
}
/*For now if there's more than one prioritized block entry then we just randomly choose one, later on we should use
* extra analysis to determine if one block can succesfully block out two axises. */
if (prioritizedOptions.Count < 1)
{
//If there are no priority 2 options then filter out all empty cells that are within the same axis as a X-marked cell
var options = emptyCells.Where(
(entry) =>
unfriendlyCells.Any(cell => cell.Item2.Position.X.Equals(entry.Position.X)) ||
unfriendlyCells.Any(cell => cell.Item2.Position.Y.Equals(entry.Position.Y))).ToArray();
//Randomly return one of them
return new Decision(1, options[new Random().Next(options.Length)].Position);
}
else
{
return new Decision(2, prioritizedOptions[new Random().Next(prioritizedOptions.Count)].Item2);
}
}
}
</code></pre>
| [] | [
{
"body": "<pre><code>Grid -> public Cell this[int index, int index2]\n</code></pre>\n\n<p>I'm not pro but I think that:</p>\n\n<ul>\n<li>you should create function for checking if index is validate - you use same ugly condition twice.</li>\n<li>you could not check if index is correct at all... Does it matter if you get ArgumentOutOfRangeException or default IndexOutFoRangeException?</li>\n</ul>\n\n<p>Thanks to this change you can remove 15 lines of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:05:42.880",
"Id": "83901",
"Score": "0",
"body": "You're right, I'm gonna change that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:02:40.977",
"Id": "83923",
"Score": "0",
"body": "As you see, no need to be a pro to answer CR questions :) +1!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:02:48.340",
"Id": "47867",
"ParentId": "47861",
"Score": "4"
}
},
{
"body": "<h1>Fields</h1>\n\n<p>I see a property <code>Cells</code> but it is never used either in <code>Grid</code> or any other class (as far as I can tell). </p>\n\n<p>Order your class members like this:</p>\n\n<ul>\n<li>Constants</li>\n<li>Fields</li>\n<li>Properties</li>\n<li>Methods</li>\n</ul>\n\n<p>This makes it easier for people to read the code and have an expectation of where they can find what.</p>\n\n<h1>Naming</h1>\n\n<p><code>index</code> and <code>index2</code> aren't very descriptive names. Consider naming them according to their purpose: <code>row</code> and <code>column</code>.</p>\n\n<p>Your method <code>CheckOutcome</code> returns a <code>bool</code> which is cleared up in the comments inside the method that <code>true</code> means someone won and <code>false</code> nobody won. The current method name would suggest a <code>void</code> return type, perhaps returning a control-variable (like <code>-1</code> or true/false for errors) or an exception. If you change it to, for example, <code>HasWinner</code> then the intent is immediately more clear.</p>\n\n<p>You have a property called <code>DisallowPlay</code>, which is the inversion of <code>AllowPlay</code>. People find it easier to read the positive version and things like <code>AllowPlay = true</code> make more sense than <code>DisallowedPlay = false</code>.</p>\n\n<p>I would change <code>DiagonalWin</code> and <code>DiagonalWin2</code> to <code>DiagonalWinLeftTop</code> and <code>DiagonalWinRightTop</code> (or similar values). That way you know what diagonal it is exactly.</p>\n\n<h1>Magic values</h1>\n\n<p>Magic values are values that look like they're placed there randomly. Consider adding context to make this immediately clear.</p>\n\n<p>For example:</p>\n\n<pre><code>var corners = new Position[] { new Position(0,0), new Position(2,0), new Position(0,2), new Position(2,2) };\n</code></pre>\n\n<p>could become</p>\n\n<pre><code>int boundary = MAX_CELLS - 1;\nvar corners = new Position[] { new Position(0,0), new Position(boundary ,0), new Position(0, boundary ), new Position(boundary , boundary) };\n</code></pre>\n\n<p>Added benefit: now it's also easier to provide support for bigger playfields, you just have to manipulate the <code>MAX_CELLS</code> constant.</p>\n\n<h1>Consistency</h1>\n\n<p>I prefer <code>==</code> over <code>.Equals()</code>. It gives me less the feeling as if the code is all cluttered which makes me feel all happy and fluffy. You use <code>==</code> everywhere as well, so unless you overloaded the operator (which I can't tell), I would change</p>\n\n<pre><code>cells[x, y].Equals(cell)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>cells[x, y] == cell\n</code></pre>\n\n<h1>404 values</h1>\n\n<p><code>-1</code> is a common way to express \"not found\" when you're expecting an integer but using the same approach to fill a referency type's fields is not the intention. How is the programmer supposed to know if he should check <code>position.x</code>? Or <code>position.y</code>? Maybe both?</p>\n\n<p>In rare cases, returning <code>null</code> is an appropriate solution. I would say that this is one of them (method: <code>public Position IndexOf(Cell cell)</code>).</p>\n\n<p>I notice there is never any check done to see if the cell is invalid so I assume you just work with them and let the program flow iterate over it like a valid position. I don't know how the code works in depth but keep in mind that this means some properties might not get initialized because they get skipped somewhere which in turn can cause a <code>NullReferenceException</code> elsewhere where they get read.</p>\n\n<h1>Initialization</h1>\n\n<p>This is not needed:</p>\n\n<pre><code>Turn = new int();\n</code></pre>\n\n<h1>Threading</h1>\n\n<p>I'm not very experienced with multithreading but unless I'm mistaking, you're putting the UI thread to sleep here:</p>\n\n<pre><code>Task.Delay(250).Wait();\n</code></pre>\n\n<p>It's still a low value so it wouldn't matter too much but should you go to higher values I would add some sort of visual feedback so the user can distinguish between the AI \"thinking\" and the program crashing.</p>\n\n<h1>Random</h1>\n\n<p>You're creating a <code>Random</code> object inside a method. This is a dangerous approach because it uses a time-based seed so if there are 2 very close method calls, there will not have enough time passed. Consider creating an instance once on class level and calling <code>.Next()</code> on that field.</p>\n\n<p>You're actually using several <code>Random</code> instances throughout your code so they can all benefit from this.</p>\n\n<hr />\n\n<h2>Conclusion</h2>\n\n<p>Overall the code seems pretty nice. There's still quite a bit of duplication and I think abstracting a few concepts in classes and interfaces might be a solution to remove some duplication, but overall it is good. The main remarks are style-wise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:07:15.877",
"Id": "83925",
"Score": "0",
"body": "+1 for being all happy and fluffy when you see `==`. The world needs more fluffiness ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:16:15.280",
"Id": "84027",
"Score": "0",
"body": "in the `magic value` section, you didn't mention the `var middle = new Position(1,1);` element, and the subsequent test, which effectively prevent from using anything but 3 as a MAX_CELLS value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:22:00.043",
"Id": "84031",
"Score": "0",
"body": "@njzk2: there are multiple \"offenses\" for the *Random*, *Consistency*, *Magic values* and *Naming* sections. It would have been a lot of work and very little added value to sum them all up. There are indeed more places throughout the code that won't immediately work with a different value because they all have a hardcoded dependency on `3`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:53:44.993",
"Id": "47875",
"ParentId": "47861",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47875",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T09:29:55.537",
"Id": "47861",
"Score": "7",
"Tags": [
"c#",
"object-oriented",
"mvp"
],
"Title": "Follow-Up Post Tictactoe now with AI"
} | 47861 |
<p>I have seperated my project into two projects. One is the web forms project and the other is the Model project with contains a generic repository implementation, a service class for each of my entities and a UnitOfWork class. All the code below apart from the last section is in my Model class library project.</p>
<p><strong>Generic repository interface</strong></p>
<pre><code>public interface IRepository<TEntity> : IDisposable where TEntity : class
{
IQueryable<TEntity> GetAll();
IQueryable<TEntity> GetWhere(Expression<Func<TEntity,bool>> predicate);
TEntity GetSingle(Expression<Func<TEntity, bool>> predicate);
TEntity GetSingleOrDefault(Expression<Func<TEntity, bool>> predicate);
void Add(TEntity entity);
void Delete(TEntity entity);
}
</code></pre>
<p>I start of with this Interface which my services will interact with.</p>
<p>A few points about this class:</p>
<ul>
<li>As i am having a service for each of my entity object, I see no reason why I shouldn't use a generic repository as creating a repository for each entity object as-well, would bloat the amount of classes i have and make it harder to manage, when i can just pass a predicate from my service into the Get methods to retrieve the data i need. So instead of creating multiple methods such as "GetById", "GetByName" in a repository specific to each entity i use a generic one and include those methods in the service class. However i have heard many people say the generic repository is an anti-pattern so i'm not sure if this is the right way.</li>
<li>I do not include a save changes methods in the repositories as i want to make any interactions with these only come from the UnitOfWork class (which will expose the service classes as properties). So this should force validation to be done via the service classes as these are the only objects which will interact with repository. In every example i see the repository has a save changes method so i'n not sure if this is a reasonable approach. </li>
</ul>
<p><strong>Generic repository</strong></p>
<p>Below is the implementation of the IRepository for my web app, I think it has a pretty standard structure. I swap this out for another implementation when testing the service classes. I don't think there is much to say about it other than what i mentioned above. </p>
<pre><code>internal class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
{
private bool isDisposed;
private DbSet<TEntity> dbSet;
public DbSet<TEntity> DbSet
{
get { return dbSet; }
}
private RequestboxEntities requestboxContext;
public RepositoryBase(RequestboxEntities requestboxContext)
{
this.requestboxContext = requestboxContext;
this.dbSet = requestboxContext.Set<TEntity>();
}
public IQueryable<TEntity> GetAll()
{
return dbSet;
}
public IQueryable<TEntity> GetWhere(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
{
return dbSet.Where(predicate);
}
public TEntity GetSingle(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
{
return dbSet.Single(predicate);
}
public TEntity GetSingleOrDefault(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
{
return dbSet.SingleOrDefault(predicate);
}
public void Add(TEntity entity)
{
dbSet.Add(entity);
}
public void Delete(TEntity entity)
{
dbSet.Remove(entity);
}
public virtual void Dispose(bool isManuallyDisposing)
{
if (!isDisposed)
{
if (isManuallyDisposing)
requestboxContext.Dispose();
}
isDisposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~RepositoryBase()
{
Dispose(false);
}
}
</code></pre>
<p><strong>Service classes</strong></p>
<p>These are the only classes that will interact with the generic repository and will be used in the UnitOfWork class. Below is part of one of my service classes, i have left out some code to improve readability, all other services are very similar to this one.</p>
<pre><code>public class GroupService
{
IUnitOfWork unitOfWork;
IRepository<Group> groupRepository;
public GroupService(IRepository<Group> groupRepository, IUnitOfWork unitOfWork)
{
this.groupRepository = groupRepository;
this.unitOfWork = unitOfWork;
}
public Group GetById(int id)
{
return groupRepository.GetSingle(g => g.Id == id);
}
public List<Group> GetProductGroupsUserBelongsTo(int instanceId, Guid userId)
{
IQuerable<UserGroup> userGroups = unitOfWork.UserGroupService.GetByUserId(userId);
IQuerable<Group> groupsInInstance = groupRepository.GetWhere(g => g.InstanceId == instanceId);
return groupsInInstance.Join(userGroups, g => g.Id, u => u.GroupId, (g, u) => g).ToList();
}
public void Add(Group group)
{
if(!ExistsInInstance(group.Name,group.InstanceId))
groupRepository.Add(group);
else
throw new Exception("A group with the same name already exists for the instance");
}
public bool ExistsInInstance(string name, int instanceId)
{
return GetAll().SingleOrDefault(g => g.Name == name && g.InstanceId == instanceId) != null;
}
}
</code></pre>
<p>Some points and concerns about these classes </p>
<ul>
<li>I have made these classes require a IUnitOfWork class in the constructor. This is for functions which require interacting with a repository other than it's own. In the "GetProductGroupsUserBelongsTo" method i need to read from my UserService class aswell so instead of creating a new UserService object i use the existing one in the UnitOfWork object passed through to the service. I did this as it ensures I always use the same entity context (set in the UnitOfWork class) when using different services/repositories. Doing it this way also makes sure i don't use the context directly in my service classes, which makes them easier to test.</li>
<li>In my Get Methods i generally use GetSingle() so an error is thrown if an object doesnt exist for the Id. However i am not sure if i should be using GetSingleOrDefault() and then handling the null on the client that consumes the service or if i should expect the client to use the "ExistsInInstance" method to check if it exists before calling the Get Methods.</li>
</ul>
<p><strong>UnitOfWork interface</strong></p>
<p>I have removed some of the services for readability purposes, but there are many more services defined as properties just like the "GroupService".</p>
<pre><code>public interface IUnitOfWork : IDisposable
{
GroupService GroupService { get; }
UserService UserService { get; }
void Commit();
}
</code></pre>
<p><strong>UnitOfWork Class</strong></p>
<pre><code> public class UnitOfWork : IUnitOfWork
{
private bool disposed = false;
private RequestboxEntities requestboxContext = new RequestboxEntities();
private GroupService groupService;
private UserService userService;
public GroupService GroupService
{
get
{
if (groupService == null)
groupService = new GroupService(new RepositoryBase<Group>(requestboxContext));
return groupService;
}
}
public UserService UserService
{
get
{
if (userService == null)
userService = new UserService(new RepositoryBase<User>(requestboxContext));
return userService;
}
}
public UnitOfWork()
{
requestboxContext = new RequestboxEntities();
}
public void Commit()
{
requestboxContext.SaveChanges();
}
public void Refresh()
{
requestboxContext.Dispose();
requestboxContext = new RequestboxEntities();
}
protected virtual void Dispose(bool isManuallyDisposing)
{
if (!this.disposed)
{
if (isManuallyDisposing)
requestboxContext.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~UnitOfWork()
{
Dispose(false);
}
}
</code></pre>
<p>A few points about this class:</p>
<ul>
<li><p>Each service is exposed as a public property. This is so when working with it you can easily call the methods like this "unitOfWork.GroupService.GetById(id)" </p></li>
<li><p>This class shares the same entity context between each service, so to ensure when working with the same unitOfWork object everything is kept in sync. This is the only class that can save the context via the "Commit" method.</p></li>
</ul>
<p><strong>Working with the Model</strong></p>
<p>So that's the structure of my Model project here is an example if how i consume it in a web page. I know this might fit better in an MVC project rather than webforms but that is not a realistic option at the moment and my main concerns are with the structure and use of the Model project not the web app. </p>
<pre><code> public class BasePage : System.Web.UI.Page
{
UnitOfWork uow = new UnitOfWork();
protected override void OnUnload(EventArgs e)
{
uow.Dispose();
base.OnUnload(e);
}
}
</code></pre>
<p>Each page will inherit this class so a unique UnitOfWork will be made for each request and will always be disposed on the "Unload" event. Then to use it in a page i can do something like this. </p>
<pre><code> public class ManageGroupsPage : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
int groupId = (int)dropdown.SelectedItem.Value;
Group group = uow.GroupService.GetById(groupId);
NameTextBox.text = group.Name;
}
}
</code></pre>
<p>I can then easily and quickly work with the UnitOfWOrk object by interacting with it's public properties (The Service classes).</p>
<p><strong>Conclusion and Concerns</strong></p>
<p>My main concerns are with the structure of the Model project and how the layers interact with each other. Whether it is a good idea to use the generic repository, if the service classes should be passed through a IUnitOfWork object as this prevents them from working without this class so it's not as flexible. And if it is a good idea to have evrything rely on the UnitOfWork class.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T10:54:30.993",
"Id": "83900",
"Score": "1",
"body": "Welcome. Nice complete question. Hope you find the answers your looking for."
}
] | [
{
"body": "<p>I've used the Generic repository solution myself in the past. At first I found it really great but after a while as the project got a bit bigger it started to feel a bit restrictive and didn't seem to offer much benefits for the amount of code written. </p>\n\n<p>The more I read the more it appeard Entity framework was already a Repository / UnitofWork. Why did I need another layer? Well I'm sure there are plenty of reasons why but in my projects I couldn't see it.</p>\n\n<p>Instead I found myself starting to use the entity-framework directly within a service layer but abstracting the EF away using interfaces. This allowed me to remove the Repository layer whilst maintaining the level of abstraction I was after between the UI layer and any business or data layer (as well as continuing to easily mock for unit tests).</p>\n\n<p>Using your solution an alternative approach I might consider would be something like:</p>\n\n<pre><code>public interface IUnitOfWork\n{\n public IDbSet<Group> Groups { get; set; }\n // other entity sets here\n\n System.Data.Entity.Database Database { get; }\n DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;\n int SaveChanges();\n}\n</code></pre>\n\n<p>My Unit of work was essentially my Entity framework data context</p>\n\n<pre><code>public class MyDbContext : DbContext, IUnitOfWork\n{\n public DbSet<Group> Groups { get; set; }\n\n // etc\n}\n</code></pre>\n\n<p>I would now only use a service layer directly interacting with the IUnitOfWork. However I would also consider abstracting each service behind an interface itself.</p>\n\n<pre><code>public interface IGroupService : ICrudService<Group> // Maybe, maybe not depending\n{\n Group GetById(int id);\n}\n</code></pre>\n\n<p>If there were a group of interfaces that shared a common theme i.e. CRUD I might consider making those seperate and implementing them where necessary. Or even a base service class to contain common methods.</p>\n\n<pre><code>public interface ICrudService<TEntity>\n{\n TEntity GetById(int id);\n void Update(TEntity entity);\n void Add(TEntity entity);\n void Delete(TEntity entity);\n}\n\npublic class GroupService : IGroupService\n{\n private readonly IUnitOfWork _unitOfWork;\n\n public GroupService(IUnitOfWork unitOfWork)\n {\n _unitOfWork = unitOfWork;\n } \n\n public Group GetById(int id)\n {\n return _unitOfWork.Find(id);\n }\n}\n</code></pre>\n\n<p>If my service required other services I would simply pass those into the constructor. If I found myself passing too many then I would start knowing I had a bit of SRP mis-use and consider creating another service or re-arranging my existing code base.</p>\n\n<p>If you wanted a GOD service class you could still achieve this as you did with your UnitOfWork example by doing something like:</p>\n\n<pre><code>public interface IServiceContext\n{\n IGroupService GroupService { get; private set; }\n // And all your other services\n}\n</code></pre>\n\n<p>Hopefully you get the drift....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:12:59.703",
"Id": "83904",
"Score": "0",
"body": "Thanks for the feedback. I think i understand, so your UnitOfWork class would act like the repository as-well including methods like \"Find\". (For my example i may add \"GetSingle\" and \"GetWhere\" as seen in my original post). Should these methods also be in the IUnitOfWork interface? And then when you come to consume the services you would create an instance of the service and pass through the UOW, instead of interacting with the UnitOfWork directly (via it's properties) as i did. Am I understanding this correctly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:26:57.290",
"Id": "83907",
"Score": "0",
"body": "Ah I see, so you would manually go into the DbContext class and make it implement your IUnitOfWork (I am using db first so this is generated for me, but i could still edit it every time i regenerate the database) So the interface would not need the methods like \"GetWhere\" defined as my original comment suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:55:12.200",
"Id": "84043",
"Score": "1",
"body": "@user2945722 rather than manually edit the auto generated class you could create a partial DbContext and make that one implement your interface"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:56:29.873",
"Id": "84044",
"Score": "0",
"body": "@user2945722 I guess I would have my service layer do most of the logic. So needing a generic GetWhere off that might not be needed as instead it would expose methods like GetActiveGroup and GetRelatedGroupsTo i.e. buiness rule type methods"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T10:52:47.127",
"Id": "47866",
"ParentId": "47865",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47866",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T10:04:36.613",
"Id": "47865",
"Score": "6",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Database first entity framework, repository, service, UnitOfWork pattern"
} | 47865 |
<p>I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes).</p>
<p>Am I over-thinking this? Can you help me minimize the code? I am just not seeing it. ALSO, is there any way to simplify the input of so many variables such as in this situation?</p>
<pre><code>def lindexsplit(List,*lindex):
index = list(lindex)
index.sort()
templist1 = []
templist2 = []
templist3 = []
breakcounter = 0
itemcounter = 0
finalcounter = 0
numberofbreaks = len(index)
totalitems = len(List)
lastindexval = index[(len(index)-1)]
finalcounttrigger = (totalitems-(lastindexval+1))
for item in List:
itemcounter += 1
indexofitem = itemcounter - 1
nextbreakindex = index[breakcounter]
#Less than the last cut
if breakcounter <= numberofbreaks:
if indexofitem < nextbreakindex:
templist1.append(item)
elif breakcounter < (numberofbreaks - 1):
templist1.append(item)
templist2.append(templist1)
templist1 = []
breakcounter +=1
else:
if indexofitem <= lastindexval and indexofitem <= totalitems:
templist1.append(item)
templist2.append(templist1)
templist1 = []
else:
if indexofitem >= lastindexval and indexofitem < totalitems + 1:
finalcounter += 1
templist3.append(item)
if finalcounter == finalcounttrigger:
templist2.append(templist3)
return templist2
</code></pre>
<p>Example:</p>
<pre><code>mylist = [1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15]
lindexsplit(mylist,3,5,8)
return [[1, 2, 3, 4], [5, 6], [7, 8, 9], [0, 10, 11, 12, 13, 14, 15]]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:26:10.060",
"Id": "83906",
"Score": "0",
"body": "Welcome to codereview.stackexchange. In order to make reviewing easier for everyone, can you tell us a bit more about what your function is supposed to do and how it does it ? Also, examples are more than welcome :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:42:27.340",
"Id": "83908",
"Score": "0",
"body": "The function takes a list of any set of objects and slices that list at any number of sorted indexes given as arguments in the second part of the function :) - I noticed that there was no split method for lists, so I made my own"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:46:01.493",
"Id": "83909",
"Score": "1",
"body": "Please edit your answer to include this explanation. Also, if you could add an example, that would make things much easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:58:48.533",
"Id": "83910",
"Score": "0",
"body": "Thanks for your example, this is exactly what I was hoping for. Unfortunately, the output I get is `[[1, 2, 3, 4], [5, 6], [7, 8, 9], [0, 10, 11, 12, 13, 14, 15]]` and not the one you've provided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:02:55.090",
"Id": "83913",
"Score": "0",
"body": "That is the correct output! I had a index problem in the version I used to give the output. I will correct it. Yours is the correct working example of my code. Is there a way to make it more efficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:20:29.577",
"Id": "83916",
"Score": "0",
"body": "Is there anyway to get the python developers to include this a similar method in the next python updates?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:37:34.033",
"Id": "83920",
"Score": "1",
"body": "I don't want to be rude, but this should be a one-liner: `return [seq[i:j] for i, j in zip((0,) + indices, indices + (None,))]`, as shown in the answers to [this Stack Overflow question](http://stackoverflow.com/questions/1198512/split-a-list-into-parts-based-on-a-set-of-indexes-in-python). I'm also not sure why your indices are 1-based rather than 0-based: if I pass `3` as an index to your function, I would expect a split after the third element, not after the fourth."
}
] | [
{
"body": "<p>A few cosmetic changes to makes your code more beautiful/pythonic :</p>\n\n<p><strong>Fix formatting</strong></p>\n\n<ul>\n<li>Remove some line breaks as it makes the code harder to read</li>\n<li>Change variables name to follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a></li>\n<li>Your code lacks documentation making it hard to understand.</li>\n</ul>\n\n<p><strong>Use <a href=\"https://docs.python.org/2/library/functions.html#enumerate\" rel=\"noreferrer\">enumerate</a></strong></p>\n\n<p>Enumerate does exactly what you are trying to achieve : keep track of the index while looping on an iterable. Just use <code>for indexofitem,item in enumerate(List):</code>.</p>\n\n<p><strong>Remove levels of nested logic</strong></p>\n\n<p>Using <code>elif</code>, you could make your code a bit easier to follow. The inside of the <code>for-loop</code> becomes :</p>\n\n<pre><code> if breakcounter <= numberofbreaks:\n if indexofitem < nextbreakindex:\n templist1.append(item)\n elif breakcounter < (numberofbreaks - 1):\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n breakcounter +=1\n elif indexofitem <= lastindexval and indexofitem <= totalitems:\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n elif indexofitem >= lastindexval and indexofitem < totalitems + 1:\n finalcounter += 1\n templist3.append(item)\n if finalcounter == finalcounttrigger:\n templist2.append(templist3)\n</code></pre>\n\n<p><strong>Rewrite your comparisons</strong></p>\n\n<p>In Python, you can write comparisons in a very natural way : <code>indexofitem >= lastindexval and indexofitem < totalitems + 1</code> becomes <code>lastindexval <= indexofitem < totalitems + 1</code>.</p>\n\n<p><strong>Use smart indices to get the last element of array</strong></p>\n\n<p>You can rewrite <code>lastindexval = index[(len(index)-1)]</code> with the much clearer <code>lastindexval = index[-1]</code>.</p>\n\n<p><strong>Rethink your logic</strong></p>\n\n<p>You have <code>totalitems = len(List)</code> and <code>indexofitem</code> going from <code>0</code> to <code>len(List) - 1</code> (included). Thus, <code>indexofitem <= totalitems</code> is not an interesting condition to check. The same goes for <code>indexofitem < totalitems + 1</code>.</p>\n\n<p>Once this is removed, we have :</p>\n\n<pre><code> #Less than the last cut\n if breakcounter <= numberofbreaks:\n if indexofitem < nextbreakindex:\n templist1.append(item)\n elif breakcounter < (numberofbreaks - 1):\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n breakcounter +=1\n elif indexofitem <= lastindexval:\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n elif lastindexval <= indexofitem:\n finalcounter += 1\n templist3.append(item)\n if finalcounter == finalcounttrigger:\n templist2.append(templist3)\n</code></pre>\n\n<p><strong>Re-think your logic (bis)</strong></p>\n\n<p>On the code above, the last 2 <code>elif</code> checks are a bit redundant : if we don't go into the <code>indexofitem <= lastindexval</code> block then we must have <code>lastindexval < indexofitem</code> and ``lastindexval <= indexofitem` must be true.</p>\n\n<p>After cleaning this, the code looks like :</p>\n\n<pre><code> for indexofitem,item in enumerate(List):\n nextbreakindex = index[breakcounter]\n\n #Less than the last cut\n if breakcounter <= numberofbreaks:\n if indexofitem < nextbreakindex:\n templist1.append(item)\n elif breakcounter < (numberofbreaks - 1):\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n breakcounter +=1\n elif indexofitem <= lastindexval:\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n else:\n finalcounter += 1\n templist3.append(item)\n if finalcounter == finalcounttrigger:\n templist2.append(templist3)\n return templist2\n</code></pre>\n\n<p><strong>Re-think your logic (ter)</strong></p>\n\n<p>Nothing happens in the loop if <code>breakcounter > numberofbreaks</code> as <code>breakcounter</code> and <code>numberofbreaks</code> are not changed. If this is really the case, we might as well just break out of the loop. However, things are even better than this : once again we are in a situation that cannot happen. This can be seen in two different ways :</p>\n\n<ul>\n<li><p>if <code>breakcounter</code> was to be bigger than <code>numberofbreaks</code>, <code>nextbreakindex = index[breakcounter]</code> would have thrown an exception.</p></li>\n<li><p><code>breakcounter</code> only gets incremented one element at a time. This happens only if <code>breakcounter < (numberofbreaks - 1)</code>. Thus, once <code>breakcounter</code> reaches <code>numberofbreaks - 1</code>, it stops growing.</p></li>\n</ul>\n\n<p>At the end of this rewriting, your code looks like :</p>\n\n<pre><code>def lindexsplit(List,*lindex):\n index = list(lindex)\n index.sort()\n\n templist1 = []\n templist2 = []\n templist3 = []\n\n breakcounter = 0\n finalcounter = 0\n\n numberofbreaks = len(index)\n\n lastindexval = index[-1]\n finalcounttrigger = (len(List)-(lastindexval+1))\n\n for indexofitem,item in enumerate(List):\n nextbreakindex = index[breakcounter]\n\n if indexofitem < nextbreakindex:\n print \"A\"\n templist1.append(item)\n elif breakcounter < (numberofbreaks - 1):\n print \"B\"\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n breakcounter +=1\n elif indexofitem <= lastindexval:\n print \"C\"\n templist1.append(item)\n templist2.append(templist1)\n templist1 = []\n else:\n print \"D\"\n finalcounter += 1\n templist3.append(item)\n if finalcounter == finalcounttrigger:\n templist2.append(templist3)\n return templist2\n</code></pre>\n\n<p>I reckon there is still a lot more to improve and a much more simple solution could be written (as suggested in the comments). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:02:12.780",
"Id": "47876",
"ParentId": "47868",
"Score": "5"
}
},
{
"body": "<p>There is a lot simpler way to do this. You can use <a href=\"http://forums.udacity.com/questions/2017002/python-101-unit-1-understanding-indices-and-slicing\" rel=\"nofollow noreferrer\">list slicing</a> and the <a href=\"https://docs.python.org/2/library/functions.html#zip\" rel=\"nofollow noreferrer\">zip</a> function.</p>\n\n<p>List slicing essentially cuts up a given list into sections. The general form is <code>list[start:stop:step]</code>. The <code>start</code> section of a slice designates the first index of the list we want to <strong>included</strong> in our slice. The <code>stop</code> section designates the first index of the list we want <strong>excluded</strong> in our slice. The <code>step</code> section defines how many indices we are moving as well as in which direction (based on whether it is positive or negative). An example:</p>\n\n<pre><code>>>> x = [1, 2, 3, 4]\n>>> x[1:3]\n[2, 3]\n>>> x[2:]\n[3, 4]\n>>> x[0:4]\n[1, 2, 3, 4]\n>>> x[0:4:1]\n[1, 2, 3, 4]\n>>> x[0:4:2]\n[1, 3]\n>>> x[0:4:3]\n[1, 4]\n>>> x[0:4:4]\n[1]\n>>> x[0:4:5]\n[1]\n</code></pre>\n\n<hr>\n\n<p>The zip function takes sequences and creates a zip object that contains tuples of their corresponding index elements:</p>\n\n<pre><code>>>> for pair in zip([1, 2, 3], ['a', 'b', 'c']):\n... print(pair)\n(1, 'a')\n(2, 'b')\n(3, 'c')\n</code></pre>\n\n<hr>\n\n<p>You can combine these two strategies to simplify your function. Here is my version of your <code>lindexsplit</code> function: </p>\n\n<pre><code>def lindexsplit(some_list, *args):\n # Checks to see if any extra arguments were passed. If so,\n # prepend the 0th index and append the final index of the \n # passed list. This saves from having to check for the beginning\n # and end of args in the for-loop. Also, increment each value in \n # args to get the desired behavior.\n if args:\n args = (0,) + tuple(data+1 for data in args) + (len(some_list)+1,)\n\n # For a little more brevity, here is the list comprehension of the following\n # statements:\n # return [some_list[start:end] for start, end in zip(args, args[1:])]\n my_list = []\n for start, end in zip(args, args[1:]):\n my_list.append(some_list[start:end])\n return my_list\n</code></pre>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-22T13:09:08.053",
"Id": "47877",
"ParentId": "47868",
"Score": "16"
}
},
{
"body": "<p>For below mention seq. code mentioned below didn't work as expected:</p>\n\n<p>CODE:</p>\n\n<pre><code>def lindexsplit(some_list, *args):\n # Checks to see if any extra arguments were passed. If so,\n # prepend the 0th index and append the final index of the\n # passed list. This saves from having to check for the beginning\n # and end of args in the for-loop. Also, increment each value in\n # args to get the desired behavior.\n if args:\n args = (0,) + tuple(data+1 for data in args) + (len(some_list)+1,)\n\n # For a little more brevity, here is the list comprehension of the following\n # statements:\n # return [some_list[start:end] for start, end in zip(args, args[1:])]\n my_list = []\n for start, end in zip(args, args[1:]):\n my_list.append(some_list[start:end])\n return my_list\n\nl = [1,2,3,4,5,6,7,8,9,0,11,12,13,14,15]\nprint(lindexsplit(l, 4,7,9,11))\n</code></pre>\n\n<p>INPUT 1:</p>\n\n<pre><code>print(lindexsplit(l, 4,7,9,11))\n</code></pre>\n\n<p>OUTPUT 1:</p>\n\n<pre><code>[[1, 2, 3, 4, 5], [6, 7, 8], [9, 0], [11, 12], [13, 14, 15]]\n</code></pre>\n\n<p>INPUT 2:</p>\n\n<pre><code>print(lindexsplit(l, 4,7,9,15))\n</code></pre>\n\n<p>OUTPUT 2:</p>\n\n<pre><code>[[1, 2, 3, 4, 5], [6, 7, 8], [9, 0], [11, 12, 13, 14, 15], []]\n</code></pre>\n\n<p>Please have a look at the simple and updated function which works for all the cases and if it fails somewhere then please let me know.</p>\n\n<p>CODE:</p>\n\n<pre><code>def lindexsplit(List, lindex):\n index_list = lindex\n index_list.sort()\n\n new_list = []\n\n print(index_list)\n\n len_index = len(index_list)\n for idx_index, index in enumerate(index_list):\n if len(index_list) == 1:\n new_list = [List[:index+1], List[index+1:]]\n else:\n if idx_index==0:\n new_list.append(List[:index+1])\n # print('Start', List[:index+1])\n elif idx_index==len_index-1:\n new_list.append(List[index_list[idx_index - 1] + 1:index + 1])\n # print('End', List[index_list[idx_index - 1] + 1:index + 1])\n if List[index+1:]:\n new_list.append(List[index+1:])\n # print('End', List[index+1:])\n else:\n new_list.append(List[index_list[idx_index-1]+1:index+1])\n # print('Between', List[index_list[idx_index-1]+1:index+1])\n\n return new_list\n\n\nl = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\nl = [str(ele) for ele in l]\nprint(lindexsplit(l, [0,1, 8, 14, 15] ))\n</code></pre>\n\n<p>INPUT 1:</p>\n\n<pre><code>print(lindexsplit(l, 4,7,9,11))\n</code></pre>\n\n<p>OUTPUT 1:</p>\n\n<pre><code>[['0', '1', '2', '3', '4'], ['5', '6', '7'], ['8', '9'], ['10', '11'], ['12', '13', '14', '15']]\n</code></pre>\n\n<p>INPUT 2:</p>\n\n<pre><code>print(lindexsplit(l, 4,7,9,15))\n</code></pre>\n\n<p>OUTPUT 2:</p>\n\n<pre><code>[['0', '1', '2', '3', '4'], ['5', '6', '7'], ['8', '9'], ['10', '11', '12', '13', '14', '15']]\n</code></pre>\n\n<p>INPUT 3:</p>\n\n<pre><code>print(lindexsplit(l, 4,7,9,15))\n</code></pre>\n\n<p>OUTPUT 3:</p>\n\n<pre><code>[['0'], ['1'], ['2', '3', '4', '5', '6', '7', '8'], ['9', '10', '11', '12', '13', '14'], ['15']]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:10:55.593",
"Id": "462148",
"Score": "1",
"body": "Welcome to Code Review! This answer doesn't really offer much for the OP. Please (re-) read [The help center page _How do I write a good answer?_](https://codereview.stackexchange.com/help/how-to-answer). Note it states: \"_Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T06:45:16.090",
"Id": "236007",
"ParentId": "47868",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:15:12.413",
"Id": "47868",
"Score": "15",
"Tags": [
"python",
"python-2.x"
],
"Title": "Splitting a list by indexes"
} | 47868 |
<p>I am a fairly new (RubyonRails) developer. I desire to improve my coding skills so I used climate to do some review on my code. It gave me a flag for this method that its complex. Is it characterised as complex because of having several "actions/tasks" in a single method?</p>
<p>Will it be better if I extract some code segments to a different method?</p>
<p>Is there something else I am not seeing?</p>
<pre><code> def search
filter_mapping = {"cost" => "rcost", "quality" => "rquality", "time" => "rtime", "experience" => "rexperience", "communication" => "rcommunication"}
@filters = params[:filter].split(",") rescue []
@sort = params[:sort]
@user_type = params[:s_user_type]
@skills = params[:s_skills]
@location = params[:location]
@max_rate = params[:max_rate]
@availability = params[:availability]
@users = User.scoped.joins(:user_skills)
@users = @users.where('user_type = ?', @user_type) if @user_type.present?
@users = @users.where('user_skills.skill_id in (?)', @skills.map(&:to_i)) if @skills.present? && @skills.size > 0
@users = @users.where('availability = ?', @availability) if @availability.present?
@users = @users.where('location_country = ?', @location) if @location.present?
@users = @users.where('rate < ?', @max_rate.to_i) if @max_rate.present?
@users = @users.page(params[:page]).per(PER_PAGE)
@filters.each do |f|
if filter_mapping.keys.include?(f)
@users = @users.order("#{filter_mapping[f]} desc")
end
end
@users = @users.order('id asc') if @filters.empty?
@advanced_link = @location.blank? && @max_rate.blank? && @availability.blank?
render :index
end
</code></pre>
<p><strong>Update</strong></p>
<p>I figured out that I can extract the scopes into a method like that:</p>
<pre><code> def get_users_where_scopes
@users = User.scoped.joins(:user_skills)
@users = @users.where('user_type = ?', @user_type) if @user_type.present?
@users = @users.where('user_skills.skill_id in (?)', @skills.map(&:to_i)) if @skills.present? && @skills.size > 0
@users = @users.where('availability = ?', @availability) if @availability.present?
@users = @users.where('location_country = ?', @location) if @location.present?
@users = @users.where('rate < ?', @max_rate.to_i) if @max_rate.present?
@users = @users.page(params[:page]).per(PER_PAGE)
end
</code></pre>
<p>and then call it with <code>@users = get_users_where_scopes()</code>. But now the complexity of this method seems wrong to me.</p>
| [] | [
{
"body": "<p>I'd say to first make a service object to keep the controller lean and clean, and to give yourself a place to put all the logic without fear of polluting the controller. Plus: It's reusable!</p>\n\n<pre><code># app/services/user_search.rb\n\nclass UserSearch\n ORDER_MAPPING = {\n \"cost\" => \"rcost\",\n \"quality\" => \"rquality\",\n \"time\" => \"rtime\",\n \"experience\" => \"rexperience\",\n \"communication\" => \"rcommunication\"\n }.freeze\n\n def initialize(params)\n @params = params\n end\n\n def results\n @results ||= begin\n records = User.scoped.joins(:user_skills)\n records = scope(records)\n records = order(records)\n end\n end\n\n private\n\n def param(key)\n @params[key] if @params[key].present?\n end\n\n def scope(scoped)\n scoped = add_scope(scoped, 'user_type = ?', param(:user_type))\n scoped = add_scope(scoped, 'user_skills.skill_id in (?)', skill_ids)\n scoped = add_scope(scoped, 'availability = ?', param(:availability))\n scoped = add_scope(scoped, 'location_country = ?', param(:location))\n scoped = add_scope(scoped, 'rate < ?', max_rate)\n end\n\n def add_scope(scope, sql, *params)\n scope.where(sql, *params) if params.all?(&:present?)\n scope\n end\n\n def order(scope)\n terms = sanitized_order_terms || default_order_terms\n terms.each { |term| scope.order(term) }\n scope\n end\n\n def sanitized_order_terms\n terms = param(:filter).try(:split, \",\")\n terms = terms.map { |term| ORDER_MAPPING[term] }\n terms = terms.compact\n terms if terms.any?\n end\n\n def default_order_terms\n [\"id asc\"]\n end\n\n def skill_ids\n param(:s_skills).try(:map, &:to_i)\n end\n\n def max_rate\n param(:max_rate).try(:to_i)\n end\nend\n</code></pre>\n\n<p>I've intentionally kept the pagination in the controller, as it's pretty independent of the scoping and ordering. However, it'd be simple to add as arguments to the <code>#results</code> method</p>\n\n<p>In your controller:</p>\n\n<pre><code>def search\n @users = UserSearch.new(params).results.page(params[:page]).per(PER_PAGE)\n\n advanced_params = %w(location max_rate availability).map { |p| params[p] }\n @advanced_link = advanced_params.all?(&:blank)\n\n render :index\nend\n</code></pre>\n\n<p>I'd probably pick a more direct way of determining the <code>@advanced_link</code>, such as sending an <code>advanced</code> parameter along, and simply looking at that instead of the implicit state you have now.</p>\n\n<p>I have no idea what Code Climate thinks of the code above, but I imagine it'll be happier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:39:24.800",
"Id": "84112",
"Score": "0",
"body": "what do you think of reusing the same name of variables to hold different values? for me it's a no-no..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:32:57.830",
"Id": "84116",
"Score": "0",
"body": "@tokland If you're referring to the `@advanced_link`-thing in the controller, which is just me being lazy; I'll change that - thanks! But for the `UserSearch` class' methods it was a conscious choice. E.g. in `#scope` the `scoped` var does change, yes, but no more than it would if there was a self-modifying `where!` I could call on it. I just see it as breaking a `where().where().where...` chain up into single links. The value changes quantitatively, not qualitatively, so to speak. If it were anything else, I'd use different vars (like I _should_ have done in the controller code)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:59:56.710",
"Id": "47899",
"ParentId": "47872",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47899",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-22T12:15:17.063",
"Id": "47872",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "Filtering users by criteria in Ruby on Rails"
} | 47872 |
<p>I wrote a script that moves files older than two days over to a network share (via scheduled task). Windows Task Scheduler doesn't seem to like the script so much, but it works well by itself. </p>
<ol>
<li><p>Is there a faster way than what I have?</p></li>
<li><p>Is there a way to programmatically make it a scheduled task or service of some type?</p></li>
</ol>
<p>Backup.ps1</p>
<pre><code>$today = get-date
$tda= $today.addDays(-2) #two days ago
$files = get-childitem d:\source_path | select fullname, lastwritetime | where-object{$_.lastwritetime -lt $tda}
foreach ($file in $files) {
Echo "moving " $file.fullname #just so I know it's still running, get rid of this?
mv $file.fullname 'n:\dest_folder'
Echo 'done'
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:51:07.633",
"Id": "83933",
"Score": "0",
"body": "What happens if the destination folder already has a file with that name ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:15:42.820",
"Id": "83938",
"Score": "0",
"body": "It shouldn't, BUT the whole thing dies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:30:27.217",
"Id": "83946",
"Score": "1",
"body": "I would consider using ` -force` then -> http://technet.microsoft.com/en-us/library/ee176910.aspx"
}
] | [
{
"body": "<p>Okay, I'll start by trying to answer your questions first.</p>\n\n<ol>\n<li><p>If there is a lot of files and you should look into using runspaces to run several copy-jobs in separate threads. Just be careful, you are still limited by the bandwidth of the network.</p></li>\n<li><p>We need to see some kind of error to be certain, but I would start by using PowerShell commands instead of old dos commands. </p></li>\n</ol>\n\n<p>Which leads me to the second part of this answer. The actual code review :)</p>\n\n<p>First thing; if you are going to write a script in PowerShell, use PowerShell commands :) Replace <code>echo</code> with <code>Write-Host</code> and replace <code>mv</code> with <code>Copy-Item</code>.</p>\n\n<p>Second: you don't need <code>| select fullname, lastwritetime</code>. It probably just adds (a little bit of) latency to the execution of the script.</p>\n\n<p>As others have pointed out, you should add some error handling and thinking about what would happen if the destination folder already have a file with the same name. Using <code>-Force</code> is one way, but would overwrite the existing file. So if you don't want this, you will have to handle it differently.</p>\n\n<p>Lastly, if you are new to PowerShell, start commenting your code. You'll thank yourself when you go back to review your scripts 6 months from now :)</p>\n\n<hr>\n\n<p>Oh, by the way, If you read up on <code>Copy-Item</code>, there is a <code>-Filter</code> parameter that might make the whole <code>Get-ChildItem</code> part of the script redundant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-15T11:53:00.990",
"Id": "60126",
"ParentId": "47873",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "60126",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T12:15:42.187",
"Id": "47873",
"Score": "6",
"Tags": [
"file",
"windows",
"powershell"
],
"Title": "Fastest Windows script to move files from one did to a network dir"
} | 47873 |
<p>Important fact: the number of the input is greater than 1. How do I use this fact to speed up this solution?</p>
<pre><code>public class subSetSumR{
// Solving Subset sum using recursion
public static boolean subSetSumRecur(int [] mySet, int n, int goal){
if (goal ==0){
return true;}
if ((goal<0)|(n>=mySet.length))
return false;
if (subSetSumRecur(mySet,n+1,goal - mySet[n])){
System.out.print(mySet[n]+" ");
return true;}
if (subSetSumRecur(mySet,n+1,goal))
return true;
return false;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:51:45.473",
"Id": "84042",
"Score": "0",
"body": "Consider switching to a [dynamic programming solution](http://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution)."
}
] | [
{
"body": "<p>At times to speed up a recursion you can use <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoization</a> to cache the results of your previous known calculations, trading memory for speed. (Memoization is slightly different to dynamic programming.)</p>\n\n<blockquote>\n <p>A memoized function \"remembers\" the results corresponding to some set\n of specific inputs. Subsequent calls with remembered inputs return the\n remembered result rather than recalculating it, thus eliminating the\n primary cost of a call with given parameters from all but the first\n call made to the function with those parameters.</p>\n</blockquote>\n\n<p>Here's an example, after I took the liberty to simplify the number of arguments a bit for sake of clarity,</p>\n\n<pre><code>public static Map<List<Integer>, Boolean> cache = new HashMap<List<Integer>, Boolean>();\n\npublic static boolean subSetSum(List<Integer> S, int sum) {\n if (sum == 0) return true;\n if (S.size() == 0 || sum < 0) return false;\n\n List<Integer> key = new ArrayList<Integer>(S); // composite (set, sum) memoization key\n key.add(sum);\n // let x be the first element of S, then there is either a solution with\n // the set S - {x} without the first element considered, or there is a\n // solution where x is accounted for, ie with the set S - {x} and sum - x\n if (!cache.containsKey(key)) {\n List<Integer> forwardSet = S.subList(1, S.size());\n cache.put(key, subSetSum(forwardSet, sum) || subSetSum(forwardSet, sum - S.get(0)));\n }\n return cache.get(key);\n}\n// Example: subSetSum(Arrays.asList(new Integer[] { -7, -3, -2, 5, 8 }), 1);\n</code></pre>\n\n<p>Note the caveat that the example outlines the trade-off described above, it may or may not be faster than your specific example. For example, notice that the list of integers that constitutes the key is cloned, which is suboptimal. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:12:45.393",
"Id": "83937",
"Score": "0",
"body": "@user3527406 Also see this question: http://codereview.stackexchange.com/questions/45910/optimizing-unique-partitions-of-integers . The answers has some guidelines on how to remember previous calculations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:30:09.263",
"Id": "84037",
"Score": "0",
"body": "@user3527406 You should still have a look at the Python code and maybe learn a bit about Python. IMHO as a programmer you should always be able to understand the basics of any programming language using a bit of common sense (and a reference manual)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:36:36.260",
"Id": "47880",
"ParentId": "47878",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47880",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:18:19.403",
"Id": "47878",
"Score": "8",
"Tags": [
"java",
"algorithm",
"performance",
"recursion",
"combinatorics"
],
"Title": "Speeding up subset sum implementation"
} | 47878 |
<p>Based on the reply of this <a href="https://stackoverflow.com/questions/23111868/unit-of-work-pattern-implementation">question</a> I have created the following code. I need to check whether it's good or not.</p>
<p>Here is my entity class:</p>
<pre><code>public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Designation { get; set; }
}
</code></pre>
<p>This is my db context implementation:</p>
<pre><code> public class MyDataContext<T> : DbContext where T:class
{
private IDbSet<T> _dbSet;
public MyDataContext() : base("name=DefaultConnectionString")
{
_dbSet = this.Set<T>();
}
public MyDataContext(IDbSet<T> dbSet )
: base("name=DefaultConnectionString")
{
this._dbSet = dbSet;
}
public IDbSet<T> DbSetOjbect
{
get { return _dbSet; }
}
}
</code></pre>
<p>Now I have implemented the <code>EmployeeService</code> business logic class and the <code>IEmployee</code> service class:</p>
<pre><code> public interface IEmployeeService
{
List<Employee> GetEmployees();
}
</code></pre>
<p>Here is the implementation:</p>
<pre><code>public class EmployeeService : IEmployeeService
{
private IDbSet<Employee> employee;
public EmployeeService()
{
var employeeContext = new MyDataContext<Employee>();
employee = employeeContext.DbSetOjbect;
}
public EmployeeService(IDbSet<Employee> employee)
{
this.employee = employee;
}
public List<Employee> GetEmployees()
{
return employee.ToList();
}
}
</code></pre>
<p>The following is my controller code in ASP.NET MVC controller.</p>
<pre><code> public class EmployeeController : Controller
{
private readonly IEmployeeService _employeeService;
public EmployeeController()
{
_employeeService = new EmployeeService();
}
public EmployeeController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
public ActionResult Index()
{
return View(_employeeService.GetEmployees());
}
}
</code></pre>
<p>I want to check whether it is a good approach for TDD Test Driven Development or not.</p>
| [] | [
{
"body": "<p>The <code>Context</code> in this situation isn't correct. The <code>Context</code> should have all your <code>dbSets</code>. With the <code>UnitOfWork</code> pattern there is only 1 instance of the <code>Context</code>. It is used by your repositories (<code>DbSet</code>s) and by the <code>UnitOfWork</code>. Since there is only a single instance it allows you to call many services, each of which update your context, before calling <code>UnitOfWork.Commit()</code>. When you call <code>UnitOfWork.Commit()</code> all the changes you've made will get submitted together. In your above implementation you are creating a new <code>Context</code> in the <code>EmployeeService</code> which means in another service you will end up creating another instance of the <code>Context</code> and that is incorrect. The idea behind the <code>UnitOfWork</code> pattern is that you can chain together services before committing and the data gets saved as a single <code>UnitOfWork</code>. </p>\n\n<p>Here's my context from a recent project, reduced in size. My <code>IDataContext</code> has some additional definitions for what I need to use from <code>DbContext</code> like:</p>\n\n<pre><code>public interface IDataContext : IDisposable\n {\n DbChangeTracker ChangeTracker { get; }\n int SaveChanges();\n DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;\n DbSet<TEntity> Set<TEntity>() where TEntity : class;\n DbSet Set(Type entityType);\n int> SaveChanges();\n public IDbSet<Function> Functions { get; set; }\n public IDbSet<PlaceHolder> PlaceHolders { get; set; }\n public IDbSet<Configuration> Configurations { get; set; }\n public IDbSet<Client> Clients { get; set; }\n public IDbSet<ParentClient> ParentClients { get; set; }\n}\n\n public class DataContext : DbContext, IDataContext\n {\n public DataContext()\n {\n Configurations = Set<Configuration>();\n Clients = Set<Client>();\n ParentClients = Set<ParentClient>();\n }\n\n public IDbSet<Function> Functions { get; set; }\n public IDbSet<PlaceHolder> PlaceHolders { get; set; }\n public IDbSet<Configuration> Configurations { get; set; }\n public IDbSet<Client> Clients { get; set; }\n public IDbSet<ParentClient> ParentClients { get; set; }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n new UserConfiguration().AddConfiguration(modelBuilder.Configurations);\n new ParentClientConfiguration().AddConfiguration(modelBuilder.Configurations);\n new ClientConfiguration().AddConfiguration(modelBuilder.Configurations);\n new EmailConfiguration().AddConfiguration(modelBuilder.Configurations);\n Configuration.LazyLoadingEnabled = false;\n }\n }\n</code></pre>\n\n<p>Here's my <code>UnitOfWork</code>. There are different ways of doing this. In some cases people expose all the repositories (<code>DbSet</code>s) here, and then inject the <code>UnitOfWork</code> into their classes and extract whatever repositories they need. Personally I don't like having something in my services that exposes the entire data store so I follow the hiding approach. As you can see the approach I'm following only has a <code>Commit()</code>. Since the <code>UnitOfWork</code> and all the repositories (<code>DbSet</code>s) share the same single instance of the <code>Context</code> they are all acting on the same data.</p>\n\n<pre><code>public interface IUnitOfWork : IDisposable\n {\n ICollection<ValidationResult> Commit();\n }\n\n public class UnitOfWork : IUnitOfWork\n {\n private readonly IDataContext _context;\n\n public UnitOfWork(IDataContext context)\n {\n _context = context;\n }\n\n public ICollection<ValidationResult> Commit()\n {\n var validationResults = new List<ValidationResult>();\n\n try\n {\n _context.SaveChanges();\n }\n catch (DbEntityValidationException dbe)\n {\n foreach (DbEntityValidationResult validation in dbe.EntityValidationErrors)\n {\n IEnumerable<ValidationResult> validations = validation.ValidationErrors.Select(\n error => new ValidationResult(\n error.ErrorMessage,\n new[]\n {\n error.PropertyName\n }));\n\n validationResults.AddRange(validations);\n\n return validationResults;\n }\n }\n return validationResults;\n }\n\n public void Dispose()\n {\n _context.Dispose();\n }\n }\n</code></pre>\n\n<p>This brings us to your service classes. The catch here is that if you choose to inject <code>IDbSet</code>s then you have to extract them from the context and inject them because you can't create them directly. Using Unity as the IOC (I recommend Autofac but had to use Unity for this project) it looks like this:</p>\n\n<pre><code>var context = container.Resolve<IDataContext>();\ncontainer.RegisterInstance(context.Functions, manager(typeof (ContainerControlledLifetimeManager)));\ncontainer.RegisterInstance(context.AuditRounds, manager(typeof (ContainerControlledLifetimeManager)));\ncontainer.RegisterInstance(context.Clients, manager(typeof (ContainerControlledLifetimeManager)));\n</code></pre>\n\n<p>In order to support this kind of code you'll need to something like what is above:</p>\n\n<pre><code>public EmployeeService(IDbSet<Employee> employee) \n {\n this.employee = employee;\n }\n</code></pre>\n\n<p>Per your original concern you were not wanting to do something for \"every\" entity. Personally the effort is so small I don't concern myself with it but if that's important to you then there is the <code>GenericRepository</code> approach. In that approach we inject that single instance of the <code>IContext</code> and the repository extracts the <code>IDbSet</code> from the context using some EF functionality and you have a class like:</p>\n\n<pre><code>public GenericRepository<T> : IGenericRespository<T>\n{\n private SchoolContext _context;\n\n public GenericRepository(IContext context)\n {\n _context = context;\n }\n\n public Get(int id)\n {\n return _context.Set<T>().Find(id);\n }\n}\n</code></pre>\n\n<p>Then the service class looks like this:</p>\n\n<pre><code>public EmployeeService(IGenericRespository<Employee> employee) \n{\n this.employee = employee;\n}\n</code></pre>\n\n<p>The problem with the generic repository is that you have to create your implementations for Create, Insert, and Delete as well Fetch. This can get ugly quickly if you try to start using <code>DbEntity</code> and attaching entities to the context through the repository. For example if you didn't want to load the record before updating it you would have to know how to attach it and set it's state in the context. This can be tedious and troublesome because it's just not that straight forward. Once you add in some child relationships and managing child collections things really go to hell fast. If you're not needing to Mock your repositories for testing I would advise against this approach unless you find an implementation online that you understand.</p>\n\n<p>With all these solutions the key is understanding how IOC works and configuring your IOC container accordingly. Depending on the container you use it can get really confusing how to register stuff, especially when generics are involved. I use Autofac whenever I can because of it's simplicity. I would never Unity except when the client insists.</p>\n\n<p>The most important point when choosing your approach is to make sure it's in line with what you need. I would always say it's good to use the pattern to some degree. However if you are not writing unit tests and not needing to Mock classes for testing then you could skip the <code>UnitOfWork</code> and just use your <code>IContext</code> and skip the Repositories and just use <code>DbSet</code>s. They accomplish the same things. As long as you are injecting things properly you get the other benefits of the pattern and the cleanliness in your design but you lose the ability to Mock the objects for testing.</p>\n\n<p>Then your code would look like this which is as simple as it can get:</p>\n\n<pre><code>public EmployeeService(IContext context) \n{\n this.employees = context.Employees;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:59:57.527",
"Id": "84002",
"Score": "0",
"body": "Did you see question link I have posted with question. In that its clearly mentioned that unit of work internally already implemented by the entity framework 6.0. The solution you given was correct till entity framework 5.0 but not any more with 6.0"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:11:53.107",
"Id": "47891",
"ParentId": "47879",
"Score": "8"
}
},
{
"body": "<p>I've never TDD'd, but don't do that:</p>\n\n<blockquote>\n<pre><code>public class MyDataContext<T> : DbContext where T : class\n</code></pre>\n</blockquote>\n\n<p>This gives you a context-per-entity, which might work for ultra-simplistic CRUD scenarios, but doesn't scale very well and will quickly give you headaches as soon as you need to deal with more than a single entity type in a single <em>transaction</em> - because that's what a <em>unit-of-work</em> encapsulates: a <em>transaction</em>.</p>\n\n<p><code>DbContext</code> <em>is</em> a unit-of-work, and <code>IDbSet<T></code> <em>is</em> a repository; they <em>are</em> an abstraction; by wrapping it with your own, you're making an <em>abstraction over an abstraction</em>, and you gain nothing but complexity.</p>\n\n<p><a href=\"http://www.wekeroad.com/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/\" rel=\"noreferrer\">This blog entry</a> sums it up pretty well. In a nutshell: <strong>embrace DbContext, don't fight it.</strong></p>\n\n<p>If you really want/need an abstraction, make your <code>DbContext</code> class implement some <code>IUnitOfWork</code> interface; expose a <code>Commit</code> or <code>SaveChanges</code> method and a way to get the entities:</p>\n\n<pre><code>public interface IUnitOfWork\n{\n void Commit();\n IDbSet<T> Set<T>() where T : class;\n}\n</code></pre>\n\n<p>Then you can easily implement it:</p>\n\n<pre><code>public class MyDataContext : DbContext, IUnitOfWork\n{\n public void Commit()\n {\n SaveChanges();\n }\n}\n</code></pre>\n\n<p>I don't like <code>IEmployeeService</code> either. This looks like an interface that can grow hair and tentacles and become quite a monster (<code>GetByName</code>, <code>FindByEmailAddress</code>, etc.) - and the last thing you want is an interface that needs to change all the time.</p>\n\n<p>I'd do it something like this, but I'm reluctant to use the entity types directly in the views, I'd probably have the service expose <code>EmployeeModel</code> or <code>IEmployee</code> instead (see <a href=\"https://codereview.stackexchange.com/questions/30769/converting-between-data-and-presentation-types\">this question for more details</a> - it's WPF, but I think lots of it applies to ASP.NET/MVC), so as to only have the service class aware of the <code>Employee</code> class, leaving the controller and the view working off some <code>IEmployee</code> implementation, probably some <code>EmployeeModel</code> class, idea being to separate the <em>data model</em> from the <em>domain model</em>.</p>\n\n<pre><code>public class EmployeeService\n{\n private readonly IUnitOfWork _unitOfWork;\n\n public EmployeeService(IUnitOfWork unitOfWork)\n {\n _unitOfWork = unitOfWork;\n }\n\n IEnumerable<Employee> GetEmployees()\n {\n return _unitOfWork.Set<Employee>().ToList();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:04:59.240",
"Id": "84013",
"Score": "0",
"body": "Entity framework 6.0 has inbuilt unit of work representation see the link I have posted with question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:12:32.467",
"Id": "84014",
"Score": "0",
"body": "I did. And I don't agree with creating a generic `IRepository<T>` interface, even less so with a generic `DbContext<T>`, for the reasons described in this answer and in the linked blog."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:39:07.777",
"Id": "84018",
"Score": "0",
"body": "ok understood thanks!! I will check whether it will work with TDD or not"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T06:30:35.297",
"Id": "84105",
"Score": "0",
"body": "Its not working in Iunit of work also as you can not define generic property in interace"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:25:05.553",
"Id": "84148",
"Score": "0",
"body": "@Jalpesh `Set<T>()` is a generic method, `Set<T>() where T : class;` should compile without any problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:09:59.963",
"Id": "84255",
"Score": "0",
"body": "Yes I know but its not working its giving error like Employee is not part of current context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:01:41.290",
"Id": "84274",
"Score": "0",
"body": "Sorry I over-simplified, the example was just showing how `Commit` is implemented; you still configure your model in `OnModelCreating` and have `IDbSet<TEntity>` *on the implementation* - it's just the interface doesn't need to expose them and change as the implementation does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:17:11.783",
"Id": "84277",
"Score": "0",
"body": "No problem thanks. So I should write on model creating with tables that I have right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:32:08.073",
"Id": "84279",
"Score": "1",
"body": "Just like public IDbSet<Employee> Employees { get; set; } right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:45:27.957",
"Id": "84286",
"Score": "0",
"body": "or on model creating something like this what you prefer? modelBuilder.Entity<Employee>().ToTable(\"Employees\");"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T13:41:04.917",
"Id": "84645",
"Score": "0",
"body": "I like the automagic conventions, but I also like explicitness of configurations. EF itself seems to prefer convention over configuration - at the end of the day it's your decision, ..as long as you're consistent. I think if you declare an IDbSet property you don't need to declare the mappings, EF will do them by convention"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T20:56:20.860",
"Id": "283316",
"Score": "1",
"body": "If you have an application where everything is hosted in a single MS SQL database, this answer is correct. Don't do that. \n\nHowever, the repository isn't always in a MS SQL database. Hence the onset of Microservices, where one context per entity is desired, allowing an entity to exist anywhere: cloud service, database, SAP, Salesforce, NoSQL, Xml, Excel, wherever. \n\nThe navigation properties are handled not by EF, but by a separate separate JSON calls or a CompoundMicroservice (that rolls up two or more Microservices). \n\nIn a Microservice Architecure, this design could be desired."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T20:59:53.523",
"Id": "283318",
"Score": "0",
"body": "@Rhyous fine, have a context per *connection string* / data source. But a context per entity is outright nuts. Also, EF isn't a silver bullet: if your application needs to play SSIS and integrate and query 20 data sources (Excel as a database, seriously??), then IMO you're using the wrong hammer for the job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T21:18:27.257",
"Id": "283326",
"Score": "0",
"body": "I build software for business integration. A business might be running two dozen business apps, each its own db, api. And some Excel apps.\n\nI'm implementing an architecture with one REST Microservice and IRepository per entity, with every entity having the ability to use the generic repo, which is a generic DbContext for a single entity, or a custom IRepository.\n\nIn my situation, a repo per entity is not nuts. It provides code reuse features through generics that far outweigh the benefits of coupled entities. The result is an extremely small code base that support infinite entities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:19:16.227",
"Id": "420156",
"Score": "0",
"body": "Since we inject `EmployeeService` we actually DO need `IEmployeeService` interface for DI. Because it's commonplace to depend upon abstractions rather than on concrete implemenations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:30:56.023",
"Id": "420159",
"Score": "0",
"body": "@AlexHerman You're quoting the *Dependency Inversion Principle* (code to abstractions..), and ignoring the *Interface Segregation Principle* - SOLID falls apart if either part takes a beating, as is the case with an interface that's constanty being edited with new members. Been a while since I used Ninject, but pretty sure it lets you bind a concrete type `.ToSelf()` - so no, you don't need the interface for DI. And you don't *want* an interface that's literally designed to require changes for every new feature you're going to code against it. Principles are just that: *principles* - not laws."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:33:16.403",
"Id": "420160",
"Score": "0",
"body": "> and ignoring the Interface Segregation Principle -\nbut again according to this one we still must provide multiple smaller interfaces"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:34:04.257",
"Id": "420161",
"Score": "0",
"body": "And that is exactly the opposite of an interface with members such as `GetByName`, `FindByEmailAddress`, and whatnot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:35:17.190",
"Id": "420162",
"Score": "0",
"body": "@MathieuGuindon And yes, almost any DI framework allows you to register just the class and inject it. I've done that a lot too. My post on reddit from a few days ago https://www.reddit.com/r/csharp/comments/b9u8cf/dependency_injection_and_interfaces/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:05:16.420",
"Id": "420164",
"Score": "0",
"body": "@MathieuGuindon so they mention that interfaces are still useful with unit testing > `It helps in testing. You mock the interface set up some behaviours and pass the mocked instance into what ever you're testing.`"
}
],
"meta_data": {
"CommentCount": "20",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:53:38.500",
"Id": "47904",
"ParentId": "47879",
"Score": "54"
}
}
] | {
"AcceptedAnswerId": "47904",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T13:18:44.260",
"Id": "47879",
"Score": "46",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc"
],
"Title": "Unit of Work and Repository with Entity Framework 6"
} | 47879 |
<p>I have a collection of phrases in a <code>List</code>. Each phrase is a <code>String Array</code> where each element in the array is a word.</p>
<p>I create a <code>List<Entry<String, Integer>></code> which holds the <code>words</code> as keys and the <code>times used</code> as value. Everything is sorted by value in descending order. </p>
<p>Then what I do is print the top <code>X</code> words that were used along with how many times they were used. What I want to know is if there is a better/simpler way of doing it and generally anything you want to add to make my code look or perform better. </p>
<p><strong>Here is my code:</strong></p>
<pre><code>public class WordCounting {
public static void printTopWords(final int numberOfWords, List<String[]> phrases) {
List<Entry<String, Integer>> wordsMap = entriesSortedByValues(wordCount(phrases));
Iterator entries = wordsMap.iterator();
int wordsCounter = 1;
while (entries.hasNext() && wordsCounter <= numberOfWords) {
Entry entry = (Entry) entries.next();
String key = (String) entry.getKey();
int value = (int) entry.getValue();
System.out.println(wordsCounter + ": " + key + " - " + value);
wordsCounter++;
}
}
private static Map<String, Integer> wordCount(List<String[]> phrases) {
Map<String, Integer> wordCounter = new TreeMap<>();
for (String[] strings : phrases) {
for (String string : strings) {
wordCounter.put(string, wordCounter.get(string) == null
? 1 : wordCounter.get(string) + 1);
}
}
return wordCounter;
}
static <K, V extends Comparable<? super V>>
List<Entry<K, V>> entriesSortedByValues(Map<K, V> map) {
List<Entry<K, V>> sortedEntries = new ArrayList<>(map.entrySet());
Collections.sort(sortedEntries,
new Comparator<Entry<K, V>>() {
@Override
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return e2.getValue().compareTo(e1.getValue());
}
}
);
return sortedEntries;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:28:26.837",
"Id": "83945",
"Score": "2",
"body": "Any special reason you are using a `List<Entry<...>>` instead of a `Map`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:30:36.560",
"Id": "83947",
"Score": "0",
"body": "@RoToRa because I've read that a Map wouldn't handle the equal valued correctly because of the `entriesSortedByValues` which I just posted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:31:17.667",
"Id": "83948",
"Score": "0",
"body": "@SilliconTouch To be honest you are not doing anything noteworthy in that while loop, except you are explicitly using an iterator instead of a `for (Entry enty: map) {` loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:32:30.937",
"Id": "83949",
"Score": "0",
"body": "I wanted a `for loop` but I thought it would be better to use a `while` since I have two conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:35:58.453",
"Id": "83950",
"Score": "0",
"body": "See http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java about how to sort a map by value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:40:37.860",
"Id": "83951",
"Score": "0",
"body": "@RoToRa That's one of the solutions I found and as I said it has implications with equal values that's why I used a `List<Entry<...>>`."
}
] | [
{
"body": "<p>A few notes for now:</p>\n\n<p>You're not using generics for your iterator, if you use</p>\n\n<pre><code>Iterator<Entry<String, Integer>> entries = wordsMap.iterator();\n</code></pre>\n\n<p>and <code>Entry<String, Integer> entry = entries.next();</code></p>\n\n<p>you won't have to typecast anything.</p>\n\n<hr>\n\n<p>You could use an <code>AtomicInteger</code> instead of an <code>Integer</code> to avoid having to use <code>.put</code>. By using <code>AtomicInteger</code> you could call <code>.incrementAndGet()</code> on it to increase the value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:52:11.223",
"Id": "47888",
"ParentId": "47884",
"Score": "7"
}
},
{
"body": "<p>In <code>wordCount</code> you don't need a <code>TreeMap</code>. A <code>TreeMap</code> orders entries by keys, but you don't need it at all. The purpose of this method is to return a map of word counts, the ordering of entries doesn't matter. It's not an error to use a <code>TreeMap</code>, it's just pointless. A <code>HashMap</code> would have been better.</p>\n\n<p>In <code>printTopWords</code> you are using iterators without type. That's not a good practice, and the casts inside the loop are ugly. The loop would have been better like this, using the iterator pattern:</p>\n\n<pre><code>int wordsCounter = 1;\nfor (Entry<String, Integer> entry : wordsMap) {\n String key = entry.getKey();\n int value = entry.getValue();\n System.out.println(wordsCounter + \": \" + key + \" - \" + value);\n if (++wordsCounter > numberOfWords) {\n break;\n }\n}\n</code></pre>\n\n<p>Your program doesn't separate responsibilities well. You should not sort-and-print in the same method. It would be better to separate that to 2 methods, one to sort and another to print. That way unit testing will be easier too, as your test cases could be based on what the sorting method returns.</p>\n\n<p>A somewhat simpler method to sort by values would have been using a <code>Comparator</code> with a <code>TreeSet</code>, for example:</p>\n\n<pre><code>static class WordCountComparator implements Comparator<String> {\n Map<String, Integer> base;\n public WordCountComparator(Map<String, Integer> base) {\n this.base = base;\n }\n\n public int compare(String a, String b) {\n if (base.get(a) >= base.get(b)) {\n return -1;\n }\n return 1;\n }\n}\n\npublic static List<String> printTopWords(final int numberOfWords, List<String[]> phrases) {\n Map<String, Integer> wordCountMap = wordCount(phrases);\n Map<String, Integer> wordsSortedByCount = new TreeMap<String, Integer>(new WordCountComparator(wordCountMap));\n wordsSortedByCount.putAll(wordCountMap);\n // ...\n}\n</code></pre>\n\n<p>You could iterate over entries in <code>wordsSortedByCount</code>, they are sorted by the word count.</p>\n\n<p>Keep in mind that you did not specify the ordering of words that have the same count, so the ordering of those will be unspecified.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:17:05.717",
"Id": "84028",
"Score": "0",
"body": "In `for (Entry<String, Integer> entry : wordsMap) {` you should loop over the `wordsMap.entrySet()` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:20:01.470",
"Id": "84030",
"Score": "2",
"body": "@skiwi his `wordsMap` is actually a `List`, not a `Map`, that's why. He has several naming issues, hence the confusion..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:20:39.647",
"Id": "47898",
"ParentId": "47884",
"Score": "10"
}
},
{
"body": "<p>As others have pointed out the most obvious improvements already, I would like to talk about Java 8. Maybe you cannot use it yet, but I would recommend looking into it and this answer should proivde useful for anyone reading this.</p>\n\n<p>My main focus point here will be designing the code such that it will logically do what it is supposed to do.</p>\n\n<p>You have a method in which you take a <code>List<String[]></code> as argument, and you want to return the top x occurences, that is all you want, in order that means:</p>\n\n<ol>\n<li>Put all <code>String</code>s together in some structure.</li>\n<li>Keep track of how many occurences they have.</li>\n<li>Sort the list to have the words with the highest amount of occurences first.</li>\n<li>Return the top x occurences.</li>\n<li>Then decide what you want to do with it.</li>\n</ol>\n\n<p>Issue 4 and 5 are seperated explicitely here, because that is what you ought to do. Every method should serve one purpose, and doing something <em>and</em> printing it is not one purpose.</p>\n\n<p>Another improvement is that as input I want a structure consisting of <code>String</code>s, and not your (ugly) <code>List<String[]></code>, I will also deal with that. The code will be fully explained below. While we are at it, I'll also improve the error checking.</p>\n\n<p>The code:</p>\n\n<pre><code>public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) {\n if (topX < 1) {\n throw new IllegalArgumentException(\"invalid value for topX: \" + topX);\n }\n Objects.requireNonNull(words);\n Comparator<Map.Entry<String, Long>> comparator = Comparator.comparingLong(Map.Entry::getValue);\n return words.collect(Collectors.groupingBy(i -> i, Collectors.counting()))\n .entrySet().stream()\n .sorted(comparator.reversed())\n .limit(topX);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>List<String[]> phrases = Arrays.asList(new String[]{\"a\", \"b\", \"c\"}, new String[]{\"a\", \"a\", \"b\", \"d\"});\nList<Map.Entry<String, Long>> topEntries = getTopWords(2, phrases.stream().flatMap(Arrays::stream))\n .collect(Collectors.toList());\nint counter = 1;\nfor (Map.Entry<String, Long> entry : topEntries) {\n System.out.println(counter + \": \" + entry.getKey() + \" - \" + entry.getValue());\n counter++;\n}\n</code></pre>\n\n<p>The output:</p>\n\n<blockquote>\n <p>1: a - 3<br>\n 2: b - 2</p>\n</blockquote>\n\n<p>The explanation:</p>\n\n<ol>\n<li>You have your <code>List<String[]></code> phrases first, you want to simply have an object that holds your <code>String</code>s. Here a <code>Stream<String></code> is a suitable object, because you only need to have a <em>view</em> on your <code>phrases</code> object, there is no point in actually storing the new data. You do this by calling <code>phrases.stream().flatMap(Arrays::stream)</code>.\n<ol>\n<li>This will first turn your <code>List<String[]></code> in a <code>Stream<String[]></code>.</li>\n<li>Then you use a method reference that describes the lambda <code>stringArray -> Arrays.stream(stringArray)</code> to acquire a <code>Stream<String></code>.</li>\n<li>Then with the <code>flatMap</code> you add all elements of the resulting <code>Stream<String></code> back into the original <code>Stream<String></code>.</li>\n</ol></li>\n<li>Then you start at the <code>getTopWords</code> method, which returns a <code>Stream<Map.Entry<String, Long>></code>, again to offer the flexibility to do what you want with the results, they are <strong>not</strong> stored yet at the point where it gets returned.</li>\n<li>First I added some error checking.</li>\n<li>Then I obtain a <code>Comparator<Map.Entry<String, Long>></code> that will compare what the entry is with the <strong>lowest</strong> number of occurences. This is done by using a <code>Comparator.comparingLong</code> on the value of the entry, which is obtained with the method reference <code>Map.Entry::getValue</code>.</li>\n<li>Then I start the chain of operations on the input <code>Stream<String></code>:\n<ol>\n<li>First group the results by their identity, which normally produces a <code>Map<String, List<String>></code>.</li>\n<li>The trick here is that I also used a <em>downstream</em> <code>Collector</code>, which counts the number of times the string occurs, hence it is called <code>Collectors.counting()</code>.</li>\n<li>At this point I have a <code>Map<String, Long></code> denoting the word and the number of occurences. It uses a <code>Long</code>, because this is what <code>Collectors.counting()</code> returns.</li>\n<li>Then I obtain a <code>Set<Map.Entry<String, Long>></code> and convert it into a stream.</li>\n<li>Then I call <code>sorted()</code> on the <code>Stream<Map.Entry<String, Long>></code> with the <strong>reversed</strong> comparator. This is done here, because type interference is not strong enough to use <code>Comparator.comparingLong(Map.Entry::getValue).reversed()</code>.</li>\n<li>Then I <code>limit()</code> the stream by the top x elements.</li>\n</ol></li>\n<li>Now we have the <code>Stream<Map.Entry<String, Long>></code>, and here we decide to collect it into a <code>List<Map.Entry<String, Long>></code>.</li>\n<li>Here we continue with your old logic of having a counter attached to it.</li>\n</ol>\n\n<p>A few points that are worth to note:</p>\n\n<ol>\n<li>The explicit <code>comparator.reversed()</code> is ugly, but neccessary to not result in type casting, which is even more ugly, it is a limitation of the current type interference. It might be only an issue in IDE's and the <em>javac</em> compiler might actually compile it though.</li>\n<li>The usage of <code>Map.Entry<String, Long></code> is pretty bloated, but our most reasonable option, besides creating a <code>Pair</code> class ourselves and using <code>Pair<String, Long></code>. This will hopefully be easier if Java 9 includes tuples (which logically include pairs) as more or less first-class citizens.</li>\n<li>In the whole method <code>getTopWords</code> we end up storing all the entries in memory once, with the <code>Map<String, Long></code>, I am pretty sure there are ways around that, but not worth the effort here, only optimize this if it becomes a real bottleneck.</li>\n<li>I was hoping to use the <code>Stream.forEach()</code> method when processing the results, however this is not possible with the requirement that you want to have a <em>counter</em>. Again, more possibilities open up in Java 9 when we hopefully have <code>BiStream</code>s and tuples.</li>\n</ol>\n\n<p>I hope this review has been helpful for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:49:29.443",
"Id": "84175",
"Score": "0",
"body": "Very good and detailed answer with new stuff for me to learn. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:01:37.747",
"Id": "84465",
"Score": "0",
"body": "I have a question. Some of the phrases are an empty string and I want to filter out the empty ones using the '.filter()' function. Do I need to create another comparator for this purpose or can I get away with just having something like '.filter(isEmpty())' in one line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:05:15.767",
"Id": "84467",
"Score": "0",
"body": "@SilliconTouch You'd want to use `.filter(str -> !str.isEmpty())`, the *filter* method actually describes which elements you wish to keep, and not which ones you want to throw out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:00:58.123",
"Id": "47919",
"ParentId": "47884",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "47919",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:14:25.530",
"Id": "47884",
"Score": "11",
"Tags": [
"java",
"performance"
],
"Title": "Printing the most used words from phrases"
} | 47884 |
<p>Below is a simple Trade class with minimal business logic: primarily a method to get market value associated with the trade. But the trade needs the following pieces of <em>core</em> functionality, orthogonal to any business logic:</p>
<ul>
<li>Need to be serializable to/from JSON (<code>toJson</code>/<code>fromJson</code>)</li>
<li>Need to be sorted in lists by date (<code>compareTo</code>)</li>
<li>Need to be copyable (<em>copy</em> with <code>TradeBuilder</code> to make copy more useful)</li>
<li>Need to be stored as key in map (<code>hashCode</code> and <em>operator==</em>)</li>
</ul>
<p>Notes:</p>
<ul>
<li>The Date class is just a wrapper that wraps DateTime</li>
<li>ebisu_utils provides very basic support for JSON serialization</li>
<li>The code was code generated - and given the boilerplate it is understandable why</li>
</ul>
<p>In this context trades do not have unique id's, so storing them as keys in a map may be suspect. While it is possible to have two trades with all the same fields actually be unique - ignore that for this purpose and assume it can not happen.</p>
<p>I believe the functionality works fine as is. But, here are some questions:</p>
<ul>
<li><p>What are better approaches for any of these functions?</p></li>
<li><p>With reflection could some/much of this boilerplate code could be removed?</p>
<ul>
<li>If so - can it be done with no runtime cost for both Dart and transpiled JavaScript?</li>
</ul></li>
<li><p>What are the performance considerations of these implementations?</p></li>
<li><p>I think there are not ways to guarantee true immutability in Dart objects. Making all fields final is a signal that trades are intended/effectively immutable. Are there many holes in this?</p></li>
<li><p>Is the <code>TradeBuilder</code> overkill? It is there because of the
<em>quasi-immutability</em> aspect of Trade. So if you wanted to unwind a buy,
creating a comparable sell would be:</p>
<pre><code>final sell = (new TradeBuilder.copyFrom(buy)
..tradeType = SELL).buildInstance();
</code></pre></li>
</ul>
<p>Finally, in terms of clutter, would it be better to move much/some of this code out of the class and into a separate set of related functions within the library?</p>
<pre><code>class Trade implements Comparable<Trade> {
const Trade(this.date, this.symbol, this.tradeType, this.quantity, this.price);
bool operator==(Trade other) =>
identical(this, other) ||
date == other.date &&
symbol == other.symbol &&
tradeType == other.tradeType &&
quantity == other.quantity &&
price == other.price;
int get hashCode {
int result = 17;
final int prime = 23;
result = result*prime + date.hashCode;
result = result*prime + symbol.hashCode;
result = result*prime + tradeType.hashCode;
result = result*prime + quantity.hashCode;
result = result*prime + price.hashCode;
return result;
}
int compareTo(Trade other) {
int result = 0;
((result = date.compareTo(other.date)) == 0) &&
((result = symbol.compareTo(other.symbol)) == 0) &&
((result = tradeType.compareTo(other.tradeType)) == 0) &&
((result = quantity.compareTo(other.quantity)) == 0) &&
((result = price.compareTo(other.price)) == 0);
return result;
}
copy() => new Trade._copy(this);
final Date date;
final String symbol;
final TradeType tradeType;
final double quantity;
final double price;
// custom <class Trade>
get signedQuantity => tradeType == BUY? quantity : -quantity;
get marketValue => quantity * price;
toString() => '($_symbolTxt$_buyOrSellTxt $quantity@$price $date)';
get _symbolTxt => symbol == null? '' : '$symbol: ';
get _buyOrSellTxt => tradeType == BUY? 'B' : 'S';
// end <class Trade>
Map toJson() {
return {
"date": ebisu_utils.toJson(date),
"symbol": ebisu_utils.toJson(symbol),
"tradeType": ebisu_utils.toJson(tradeType),
"quantity": ebisu_utils.toJson(quantity),
"price": ebisu_utils.toJson(price),
};
}
static Trade fromJson(Object json) {
if(json == null) return null;
if(json is String) {
json = convert.JSON.decode(json);
}
assert(json is Map);
return new Trade._fromJsonMapImpl(json);
}
Trade._fromJsonMapImpl(Map jsonMap) :
date = Date.fromJson(jsonMap["date"]),
symbol = jsonMap["symbol"],
tradeType = TradeType.fromJson(jsonMap["tradeType"]),
quantity = jsonMap["quantity"],
price = jsonMap["price"];
Trade._copy(Trade other) :
date = other.date,
symbol = other.symbol,
tradeType = other.tradeType == null? null : other.tradeType.copy(),
quantity = other.quantity,
price = other.price;
}
class TradeBuilder {
TradeBuilder();
Date date;
String symbol;
TradeType tradeType;
double quantity;
double price;
// custom <class TradeBuilder>
// end <class TradeBuilder>
Trade buildInstance() => new Trade(
date, symbol, tradeType, quantity, price);
factory TradeBuilder.copyFrom(Trade _) =>
new TradeBuilder._copyImpl(_.copy());
TradeBuilder._copyImpl(Trade _) :
date = _.date,
symbol = _.symbol,
tradeType = _.tradeType,
quantity = _.quantity,
price = _.price;
}
class TradeType implements Comparable<TradeType> {
static const BUY = const TradeType._(0);
static const SELL = const TradeType._(1);
static get values => [
BUY,
SELL
];
final int value;
int get hashCode => value;
const TradeType._(this.value);
copy() => this;
int compareTo(TradeType other) => value.compareTo(other.value);
String toString() {
switch(this) {
case BUY: return "Buy";
case SELL: return "Sell";
}
return null;
}
static TradeType fromString(String s) {
if(s == null) return null;
switch(s) {
case "Buy": return BUY;
case "Sell": return SELL;
default: return null;
}
}
int toJson() => value;
static TradeType fromJson(int v) {
return v==null? null : values[v];
}
}
const BUY = TradeType.BUY;
const SELL = TradeType.SELL;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:47:14.830",
"Id": "85292",
"Score": "0",
"body": "Alex Tatumizer pointed out an issue with hashCode. It needs to apply mask to prevent going beyond smi. \n\nconst MASK=(1<<31)-1;\nresult = ((result*prime)&MASK + date.hashCode)&MASK;\n\nThis is tedious - so a better solution is to use pub package quiver to help generate the hash."
}
] | [
{
"body": "<p>Here are some first pass thoughts:</p>\n\n<p>Initial thoughts...</p>\n\n<ul>\n<li><p>Your whitespace isnt consistent with the dart<a href=\"https://www.dartlang.org/articles/style-guide/\" rel=\"nofollow noreferrer\">style guide</a>.</p></li>\n<li><p>reflection probably is overkill here and has significant binary size implications when complied to JS.</p></li>\n<li><p>Trade wont benefit from a const constructor as I suspect you will encounter new trades during the life of the app and I believe that const constructor executions must be known at compile time. (See: <a href=\"https://stackoverflow.com/questions/21744677/dartlang-const-constructor-how-is-it-different-to-regular-constructor\">https://stackoverflow.com/questions/21744677/dartlang-const-constructor-how-is-it-different-to-regular-constructor</a>)</p></li>\n<li><p>final is a strong immutability guarantee - though keep in mind once compiled to js it wont protect you 100% from determined malicious code on the same page</p></li>\n<li><p>Move your fields to the top of your class</p></li>\n<li><p>Put your constructors one after another</p></li>\n<li><p>your getters dont appear to have return types whereas most of your other methods do, was that intentional? Dart style guide would suggest that public methods should declare return types.</p></li>\n<li><p>Your Trade.toString format may be an issue when debugging because if either of the the fields are empty you may not be obvious. If you need this particular format for something else to consume then you are stuck. Normally I like to label each field so it is unambiguous. </p></li>\n<li><p>Map.toJson should use => since it is a single line return function. Also, why dont you just call ebisu_utils.toJson(this) ?</p></li>\n<li><p>I would use constants to define these fields so you dont have to repeat them everywhere.</p></li>\n<li><p>the fromJson constructor should probably be a named constructor or at least a factory constructor</p></li>\n<li><p>TradeBuilder seems like overkill when you could just use a factory constructor on Trade with optional params</p></li>\n<li><p>your trade type enum should include a name field as well as the value/ordinal so that you dont have to switch in the toString</p></li>\n<li><p>I dont think you need to copy a enum, they are considered constants.</p></li>\n<li><p>I dont understand why you are exporting BUY and SELL as consts when the are already enums</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:37:52.000",
"Id": "85290",
"Score": "0",
"body": "Regarding 'constructors one after another', private constructors are toward the bottom. If public fields go at top is recommended I'll change. A const ctor can be used with new (dynamic) or const (compile time) - so is more flexible? Not understanding using 'constants to not repeat fields' bit. Enum needs copy because the generator creating Trade does not know TradeType is an Enum and special so it copies like it would non-primitives - so therefore uniformity. BUY/SELL exported so can be referenced without type. I will work on your other suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T01:02:23.803",
"Id": "48534",
"ParentId": "47887",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:22:45.413",
"Id": "47887",
"Score": "2",
"Tags": [
"dart"
],
"Title": "Providing core functionality orthogonal to business logic in Dart"
} | 47887 |
<p>JavaScript's <code>setTimeout()</code> and <code>setInterval()</code> are evil and not precise:</p>
<ol>
<li><p><a href="https://andrewduthie.com/2013/12/31/creating-a-self-correcting-alternative-to-javascripts-setinterval/" rel="nofollow noreferrer">Both functions have a delay of a varying quantity of milliseconds.</a></p></li>
<li><p>Both functions are very resource-intensive because they execute several times every second.</p></li>
</ol>
<p>A new alternative is <code>window.requestAnimationFrame()</code>, which is less resource-intensive, disabled on page blur, and does not slow down other stuff. This makes it the perfect substitute for a modern <code>setTimeout()</code> and <code>setInterval()</code>.</p>
<p><strong>Description</strong></p>
<p>These functions use <code>requestAnimationframe()</code> to check if the time has passed
based on the elapsed Time calculated from <code>Date.now()</code>. The time passed is more precise than the native functions and theoretically less resource-intensive. Another advantage (or disadvantage) is that the functions are not executed on page blur.</p>
<p>Good for: animations, visual effects</p>
<p>Bad for: timers, clock</p>
<p><strong><code>RafTimeout</code></strong></p>
<pre><code>window.rtimeOut=function(callback,delay){
var dateNow=Date.now,
requestAnimation=window.requestAnimationFrame,
start=dateNow(),
stop,
timeoutFunc=function(){
dateNow()-start<delay?stop||requestAnimation(timeoutFunc):callback()
};
requestAnimation(timeoutFunc);
return{
clear:function(){stop=1}
}
}
</code></pre>
<p><strong><code>RafInterval</code></strong></p>
<pre><code>window.rInterval=function(callback,delay){
var dateNow=Date.now,
requestAnimation=window.requestAnimationFrame,
start=dateNow(),
stop,
intervalFunc=function(){
dateNow()-start<delay||(start+=delay,callback());
stop||requestAnimation(intervalFunc)
}
requestAnimation(intervalFunc);
return{
clear:function(){stop=1}
}
}
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>var interval1,timeout1;
window.onload=function(){
interval1=window.rInterval(function(){console.log('interval1')},2000);
timeout1=window.rtimeOut(function(){console.log('timeout1')},5000);
}
/* to clear
interval1.clear();
timeout1.clear();
*/
</code></pre>
<p><strong>Demo</strong></p>
<p><a href="http://jsfiddle.net/wZ9Z6/" rel="nofollow noreferrer">jsFiddle</a></p>
<p><strong>Questions</strong></p>
<ol>
<li><p>Normally I don't write functions inside functions, but in this case it's probably a good solution. What about memory leaks if I create hundreds of these time-based functions?</p></li>
<li><p>Is there a better solution to clear those functions?</p></li>
<li><p>For heavy animations and multiple intervals and timeouts, I was thinking to activate a single <code>requestAnimationFrame()</code> loop which would check for intervals and timeouts inside a previously stored array... (but I think there should be no difference if there is just one <code>requestAnimationframe</code> or multiple). So how do the browsers handle those multiple <code>requestAnimationframes()</code>?</p></li>
</ol>
<p><strong>Note:</strong></p>
<p>If the code above does not work here is the original code:</p>
<pre><code>window.rInterval=function(a,b){var c=Date.now,d=window.requestAnimationFrame,e=c(),f,g=function(){c()-e<b||(e+=b,a());f||d(g)};d(g);return{clear:function(){f=1}}}//callback,delay
window.rtimeOut=function(a,b){var c=Date.now,d=window.requestAnimationFrame,e=c(),f,g=function(){c()-e<b?f||d(g):a()};d(g);return{clear:function(){f=1}}}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:09:50.127",
"Id": "83958",
"Score": "4",
"body": "`requestAnimationFrame` is called on average 60 times per second.. At first sight, your code is far eviler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:14:06.133",
"Id": "83960",
"Score": "0",
"body": "oh konijn, i see you like my posts ;), but i never get the sense of your answers. I know that requestAnimationframe is executed 60 times per seconds. But setTimeout checks more often if the delay is passed.. anyway .. explain yourself. Why is my code evil?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:16:35.140",
"Id": "83962",
"Score": "0",
"body": "Do you have a link that says that `setTimeout` checks more often, that is the first I hear of that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:23:17.247",
"Id": "83964",
"Score": "0",
"body": "simple setInterval(func,10) <- works... this is faster than 60fps 60HZ ... 60fps == 17ms"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:28:28.030",
"Id": "83967",
"Score": "0",
"body": "As far as I can read your code, if I want to wait 170 ms, then your code will have executed `requestAnimation` 10 times, it would have executed `setTimeout` once, right ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:29:24.987",
"Id": "83969",
"Score": "0",
"body": "yeah but it checks every 4ms (if the 170ms are passed) or more or less... depends on cpu and js engine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:31:09.823",
"Id": "83972",
"Score": "0",
"body": "last comment, ( thanks SE ), do you have a link that talks about this 4ms ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:32:03.863",
"Id": "83973",
"Score": "0",
"body": "http://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:25:59.627",
"Id": "84375",
"Score": "0",
"body": "I've rolled back Rev 5 → 3. We have instituted a [new policy](http://meta.codereview.stackexchange.com/a/1765/9357) that follow-ups should either be an answer to your own question, or a new question altogether if you want to have the new code reviewed. Thanks for your cooperation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:28:57.503",
"Id": "84941",
"Score": "0",
"body": "ok here is the new version with namespace. http://jsfiddle.net/G34Sr/"
}
] | [
{
"body": "<h1>Update 4/23/2014:</h1>\n<p>Okay then, off to your updated code. Nothing much I can do here now. Here are some generic code optimization tips:</p>\n<ul>\n<li><p>Name stuff verbosely. It's one issue I find with others' code. They tend to name it like <code>t</code> for time, or <code>l</code> for length. Unless it's something implied, like <code>i</code>,<code>j</code> and <code>k</code> for counters (and we do see loops), please name them verbosely.</p>\n</li>\n<li><p>Don't ever worry about long code. That's what minifiers are for. Name them verbosely, structure them properly. Don't even bother using the "comma-separated <code>var</code>s". Minifiers do that.</p>\n</li>\n<li><p>Ternaries tend to be messy and unreadable. If possible, use <code>if-else</code>. Again, minifiers also convert them to ternaries to be shorter.</p>\n</li>\n<li><p>As for possible bottlenecks, <code>splice</code> is an overhead because it resizes the array, shifting the contents around. It's much avoided like <code>unshift</code> and <code>shift</code> for the same reason. I don't know if keeping a "hole" in the array is a performance benefit either, so let's leave it as is.</p>\n</li>\n<li><p>A general performance tip is just to avoid creating objects inside the loops. If it can't be avoided, just make sure you free them up when done (free references).</p>\n</li>\n</ul>\n<p>So far, that's about it. I'll leave the fine-tuning to you.</p>\n<h1>Previous answer:</h1>\n<blockquote>\n<p>Normally i don't write functions inside functions, but in this case it's prolly a good solution. What about memory leaks if i create hundreds of this timebased functions?</p>\n</blockquote>\n<p>That wouldn't be an issue. Besides, how many functions do you think the FB homepage, or any site for that matter, creates? What you should be wary about, though, is when your timers create functions on every iteration. That's what you should look out for. Along the lines of this:</p>\n<pre><code>function tick(){\n requestAnimationFrame(tick);\n\n // Oh...\n var aFunctionMadeOnEachTick = function(){...};\n aFunctionMadeOnEachTick();\n}\n</code></pre>\n<p>Although some JS engines are smart enough to figure this out and pull out the function, I have seen performance decreases when doing this in some of my projects.</p>\n<blockquote>\n<p>Is there a better solution to clear those functions?</p>\n</blockquote>\n<p>I was thinking about something along the lines of a common function that can be referenced by each API function to generate a runner. This way, we have one function sitting internally waiting to be called, instead of one created each call.</p>\n<pre><code>;(function (ns) {\n \n // An array of references/ids/booleans/whatever that can be used to clear off running timers\n var timers = [];\n\n // The common function\n // Haven't figured out how the cb and delay gets called on the next tick, but\n // this should be a good template to think about.\n function runningFn(cb,delay) {\n if(iShouldStillRun) requestAnimationFrame(runningFn);\n if(Date.now() > something) execute();\n }\n\n // Your API functions\n ns.setTimeOut = function (callback, delay) {\n runningFn(callback,delay);\n }\n ns.setInterval = function (callback, delay) {...}\n ns.clearInterval = function (callback, delay) {...}\n ns.clearTimeout = function (callback, delay) {...}\n\n}(this.Timers = this.Timers || {}));\n</code></pre>\n<blockquote>\n<p>For heavy animations and multiple intervals,timeouts i was thinking to activate a single requestAnimationFrame loop which check for intervals and timeouts inside a previously stored array...</p>\n</blockquote>\n<p>The last time I checked, looping through an array with 700+ items caused stuttering in the UI. Also, by the nature of timers, they can actually be delayed by these operations. Again, JS is single-threaded, and timers also live in that thread. If JS is busy churning, it can delay async tasks and that includes timers.</p>\n<h2><code>rAF</code> at a glance</h2>\n<p>One thing about <code>rAF</code> is that it's built for animation. It strives to give you a 60fps. However, when it can't, it isn't any different from <code>setInterval</code> and <code>setTimeout</code>. Also, it depends on browser implementation. Some browsers throttle timers according to different situations, like unfocused windows/tabs.</p>\n<h2>Let's start cherry-picking</h2>\n<p>Now here are some interesting things about your implementation:</p>\n<ul>\n<li>You have an internal function in each instance of a timer. Looks like the root of your worries.</li>\n<li>But you also return an object for each instance for the <code>clear</code>. Why not store some sort of reference to running timers, and create another global function that clears them?</li>\n<li>Like you found out, 60fps is 16ms per draw. However, <a href=\"http://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers/\" rel=\"nofollow noreferrer\">timers are as fast as 4ms</a>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:26:28.917",
"Id": "83965",
"Score": "0",
"body": "yeah i knew it :(... i was just trying to keep one global variable per function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:28:34.600",
"Id": "83968",
"Score": "0",
"body": "so basically i should define those 2 functions (intervalFunc,clear) outside and pass it as reference..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:29:36.287",
"Id": "83970",
"Score": "0",
"body": "@cocco If you wanted to avoid globals, then you could create a single global namespace for your functions. There, you can define 2 timer, and 2 clearer functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:36:33.323",
"Id": "83975",
"Score": "0",
"body": "mh... yeah thats a problem... i didn't want to use a namespace.. in that case everything changes...then the 3rd question is the most appropriate.. create a namespace wich contains the functions and an array of active intervals and timeouts and a single requestAnimationframe.right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:39:11.780",
"Id": "83976",
"Score": "1",
"body": "and yeah i'm using rAF exactly because of those 60fps vs much more.else the same function can be writtten with setTimout"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:44:28.227",
"Id": "83977",
"Score": "0",
"body": "\"timers create functions on every iteration\" ...requestAnimation(timeoutFunc) this is just a reference.. it does pass the reference every iteration..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:48:18.947",
"Id": "83981",
"Score": "0",
"body": "what to say.. perfect answer... as prolly the namespace is the only solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:53:59.943",
"Id": "83983",
"Score": "0",
"body": "yeah sure..i don't create functions inside the animationframe.(your first example)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:52:44.443",
"Id": "84201",
"Score": "0",
"body": "I added a new version based on your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:26:43.013",
"Id": "84220",
"Score": "0",
"body": "4. splice cause the timercount is based on the array length, 5. what objects?1,2,3 Minifiers don't reuse static variables, they don't convert in a proper way to bitwise,shorthand and tenerary.here are some of many basic examples.\nhttp://stackoverflow.com/a/21353032/2450730\nAnd the short names are just some temp variables.\n\"pre optimization is the root of all evil\" <- i don't belive that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:47:38.980",
"Id": "84222",
"Score": "0",
"body": "http://jsfiddle.net/G34Sr/ this one has no extra log..."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:15:28.933",
"Id": "47892",
"ParentId": "47889",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47892",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-22T14:54:23.100",
"Id": "47889",
"Score": "17",
"Tags": [
"javascript",
"memory-management",
"datetime",
"animation"
],
"Title": "Alternative to setInterval and setTimeout"
} | 47889 |
<p>I feel like just because the below works doesn't mean it is correct, I want to improve it but I can't really figure out how. Besides the fact it is down right ugly I feel the performance could be increased a lot also.</p>
<p>Am I even using the Entity Framework and/or LINQ the way it is supposed to be used?</p>
<p>So I have these classes:</p>
<pre><code>[Table("OrderInfo")]
public class OrderInfo
{
public long ID {get; set;}
public long OrderID {get; set;}
public virtual Order Order { get; set; }
public long ItemID {get; set;}
public double Qty { get; set; }
public virtual Item Item { get; set; }
}
[Table("Items")]
public class Item
{
public Item()
{
this.Orders = new List<OrderInfo>();
}
#region Strings
public string Color { get; set; }
public string FullName { get; set; }
[Column(@"Sheet/Roll")]
public string Type { get; set; }
public string PrimaryMachine { get; set; }
public string Alias { get; set; }
public string Brand { get; set; }
#endregion
#region Long
public long ID { get; set; }
public long? Weight { get; set; }
#endregion
#region Doubles
public double? Size1 { get; set; }
public double? Size2 { get; set; }
public double? Size3 { get; set; }
#endregion.
public virtual ICollection<OrderInfo> Orders { get; set; }
}
</code></pre>
<p>below is the code calling the data:</p>
<pre><code> private void dgvOrders_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.SelectedRows.Count > 0)
{
if (dgvOrderItems.DataSource != null)
dgvOrderItems.DataSource = null;
int ID = Convert.ToInt32(dgv["ID", dgv.SelectedRows[0].Index].Value);
List<OrderInfo> OrderInfo = new List<OrderInfo>();
OrderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();
if(OrderInfo.Count <= 0)
{
MessageBox.Show("No Info Found For This Order!");
ClearForm();
return;
}
lblPO.Text = "P.O. # " + OrderInfo[0].ID.ToString();
lblRequestedBy.Text = "Requested By: " + OrderInfo[0].Order.RequestedBy;
lblOrderDate.Text = "Ordered On: " + OrderInfo[0].Order.Date.ToShortDateString();
dgvOrderItems.DataSource = OrderInfo.Select(x => new { x.ItemID, x.Qty, x.Item.FullName, x.Item.Brand, x.Item.Color }).ToList();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:12:21.187",
"Id": "506618",
"Score": "1",
"body": "I [changed the title](https://codereview.stackexchange.com/posts/47890/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] | [
{
"body": "<h1>Architecture</h1>\n<p>One thing that jumps forward is that you're going straight from the UI to your datasource. In a three-layer design (UI, Model, Persistence) or MVC (Model, View, Controller) there is always a layer between the UI and your datasource.</p>\n<p>A samplesetup would be this:</p>\n<pre><code>interface IOrderRepository {\n IEnumerable<OrderInfo> GetOrderById(int id);\n}\n\nclass OrderRepository : IOrderRepository {\n public IEnumerable<OrderInfo> GetOrderById(int id){\n using(var context = new MyDataContext()){\n return context.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();\n }\n }\n}\n\nclass UIController {\n private IOrderRepository _orderRepository;\n \n public void OnOrdersSelectionChanged(DataGridView view){\n _orderRepository.GetOrderById(Convert.ToInt32(dgv["ID", dgv.SelectedRows[0].Index].Value));\n }\n}\n</code></pre>\n<p>Now your view is coupled loose from your datasource through the intermediate repository. You might be interested in reading up on the repository pattern, for example <a href=\"https://docs.microsoft.com/en-us/archive/blogs/wriju/using-repository-pattern-in-entity-framework\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h1>Resources</h1>\n<p>I don't see a <code>using</code> statement in your code so I assume that your <code>DataContext</code> is held as a private field. This context class is explicitly made to be disposed after using it once so you should use it as such.</p>\n<p>In the MSDN blog I linked just before the repository is disposed instead which is also an option although I have found that wrapping all calls to the <code>DataContext</code> is more often used.</p>\n<h1>Braces</h1>\n<p>Always add your braces to your <code>if</code> statements, even when it's just one line. It's simply too easy to make mistakes.</p>\n<h1>Inline declaration</h1>\n<p>This snippet</p>\n<pre><code>List<OrderInfo> OrderInfo = new List<OrderInfo>();\nOrderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();\n</code></pre>\n<p>is an elaborate way of writing</p>\n<pre><code>var orderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();\n</code></pre>\n<p>Notice also how I made <code>orderInfo</code> lowercase. Keep naming conventions in mind!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:01:25.067",
"Id": "84224",
"Score": "0",
"body": "Do you have any more links? I have been trying to implement the Repository system, and keepo having issues like from that link when I try to use the `IQueryable<Order> AllIncluding(params Expression<Func<Order, object>>[] includeProperties);` method I get an error `query = query.Include(includeProperty);` that Include is not part of Context.Order. Any additional links would be great"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:11:31.250",
"Id": "84226",
"Score": "0",
"body": "[Google](https://www.google.be/search?q=repository+pattern+entity+framework&oq=repository+pat&aqs=chrome.0.69i59j69i57j0j69i61j0l2.4168j0j7&sourceid=chrome&es_sm=122&ie=UTF-8) yields many results, all of them which look pretty good. If you need assistance with not-working code, don't forget to visit Stack Overflow!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-22T18:58:58.463",
"Id": "47909",
"ParentId": "47890",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47909",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-22T15:09:28.347",
"Id": "47890",
"Score": "5",
"Tags": [
"c#",
"design-patterns",
".net",
"linq",
"entity-framework"
],
"Title": "Displaying information about an order when selection changes"
} | 47890 |
<p>I needed a super simple parser to get HTML attributes and their values. I didn’t want to load a big library or anything so I made this.</p>
<p>I realize I am making assumptions here, mainly:</p>
<ul>
<li>Attribute values will be surrounded with either single or double
quotes.</li>
<li>The input string will end with <code>></code> or <code>/></code>.</li>
</ul>
<p>Besides those assumptions are there any other glaring issues here?</p>
<pre><code>Dictionary<string, string> HTMLAttributes(string tag)
{
Dictionary<string, string> attr = new Dictionary<string, string>();
MatchCollection matches =
Regex.Matches(tag, @"([^\t\n\f \/>""'=]+)(?:=)('.*?'|"".*?"")(?:\s|\/>|\>)");
foreach (Match match in matches)
{
attr.Add(match.Groups[1].Value,
match.Groups[2].Value.Substring(1, match.Groups[2].Value.Length - 2)
);
}
return attr;
}
</code></pre>
<p>Running:</p>
<pre><code>HTMLAttributes("<body class=\" something \" hello='world' />");
</code></pre>
<p>Returns:</p>
<pre><code>{
class: " something ",
hello: "world"
}
</code></pre>
<p>Sample:</p>
<p><a href="http://ideone.com/ZBaBhB" rel="nofollow">http://ideone.com/ZBaBhB</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:51:09.633",
"Id": "83982",
"Score": "1",
"body": "“I didn't want to load a big library” Are you sure that's more work than an unreadable line-long regex that you're not sure actually works correctly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:00:54.670",
"Id": "83985",
"Score": "0",
"body": "My concern wasn't my work load but my web app having to load a big library for 1 simple operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:04:03.167",
"Id": "83986",
"Score": "0",
"body": "Why does that concern you? Are you worried about the small time it takes to load a library (which is done once when the app starts)? Or about the small amount of memory it will require? Both sound like premature optimizations to me. Or do you have another reason?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:05:11.230",
"Id": "83987",
"Score": "0",
"body": "It is overkill to load a library for a single function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:09:43.800",
"Id": "83988",
"Score": "2",
"body": "It's not if that function is something that's actually quite complicated like HTML parsing. [You can't parse HTML with regex.](http://stackoverflow.com/a/1732454/41071)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:11:28.747",
"Id": "83989",
"Score": "1",
"body": "If that's such a big concern you should probably be looking at something like c++ instead of any of the .net languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T14:14:38.700",
"Id": "159475",
"Score": "1",
"body": "Maintaining libraries is often more difficult than maintaining a small piece of code. When the platform changes, and the library has not been updated, you are stuck. The argument can go the other way as well. When parsing requirements change, one can simply update the library and be done. In my experience, the problems happen more than the benefits, so I agree with OP in this case, but for maintenance reasons, not performance reasons."
}
] | [
{
"body": "<ol>\n<li>Whitespace around <code>=</code> is allowed, your regex won't handle that.</li>\n<li>Characters in HTML can be encoded, some characters (like <code>&</code>) have to be encoded. For example <code>name=\"AT&amp;T\"</code> should return that the value of <code>name</code> is <code>AT&T</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:00:23.403",
"Id": "47896",
"ParentId": "47893",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47896",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T15:27:14.737",
"Id": "47893",
"Score": "1",
"Tags": [
"c#",
"html",
"parsing",
"regex"
],
"Title": "Is this a safe way to parse out HTML tag attributes?"
} | 47893 |
<p>A manager for a speedy async saving objects to isolated storage, using serialization from Newtonsoft.Json. A project to play with is <a href="https://isostoragemanager.codeplex.com/" rel="nofollow">here</a>.</p>
<pre><code>public static async Task<T> ReadJsonEx<T>(String filepath)
{
if (String.IsNullOrEmpty(filepath))
return default(T);
return await await Task.Factory.StartNew(async () =>
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filepath, FileMode.Open, store))
using (var sr = new StreamReader(stream))
using (var jr = new JsonTextReader(sr))
return await jr.ReadJsonAsyncTask<T>();
});
}
public static async Task<bool> WriteJsonEx<T>(String filepath, T content)
{
if (String.IsNullOrEmpty(filepath))
return false;
return await await Task.Factory.StartNew(async () =>
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filepath, FileMode.Create, store))
using (var sw = new StreamWriter(stream))
using (var jw = new JsonTextWriter(sw))
await jw.WriteJsonAsyncTask(content);
return true;
});
}
</code></pre>
<p>Where extensions are</p>
<pre><code>private static readonly JsonSerializer JsonSerializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore };
public static async Task<bool> WriteJsonAsyncTask<T>(this JsonTextWriter writer, T content)
{
writer.Formatting = Formatting.Indented;
return await TaskEx.Run(() =>
{
try { JsonSerializer.Serialize(writer, content); }
catch (Exception) { return false; }
return true;
});
}
public static async Task<T> ReadJsonAsyncTask<T>(this JsonTextReader reader)
{
return await TaskEx.Run(() => JsonSerializer.Deserialize<T>(reader));
}
</code></pre>
<p>I'm just wondering if this code is secure and if it can be used in the real app.
Is the current approach safe enough? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:23:16.767",
"Id": "84972",
"Score": "2",
"body": "These edits can probably earn you some rep if you word them into an answer / \"selfie\" review ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:25:46.007",
"Id": "84981",
"Score": "0",
"body": "@Mat'sMug fair enough :) Thanks, would move them there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:09:48.670",
"Id": "85003",
"Score": "0",
"body": "Also, please don't edit the code in the question. I've rolled back Rev 14 → 13."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:33:40.517",
"Id": "85012",
"Score": "0",
"body": "@200_success it was almost the same, just with extra CreateFolderIfNecessary() call. Though, i got your point: code samples should stay original."
}
] | [
{
"body": "<p>This is very neat. Just a few code formatting nitpicks:</p>\n\n<blockquote>\n<pre><code> if (String.IsNullOrEmpty(filepath))\n return default(T);\n\n return await await Task.Factory.StartNew(async () =>\n {\n using (var store = IsolatedStorageFile.GetUserStoreForApplication())\n using (var stream = new IsolatedStorageFileStream(filepath, FileMode.Open, store))\n using (var sr = new StreamReader(stream))\n using (var jr = new JsonTextReader(sr))\n return await jr.ReadJsonAsyncTask<T>();\n });\n</code></pre>\n</blockquote>\n\n<p>Call me over-zealous, I think it would be best to specify the scopes with curly braces - I like the stacked <code>using</code> blocks though, so like this:</p>\n\n<pre><code> if (String.IsNullOrEmpty(filepath))\n {\n return default(T);\n }\n\n return await await Task.Factory.StartNew(async () =>\n {\n using (var store = IsolatedStorageFile.GetUserStoreForApplication())\n using (var stream = new IsolatedStorageFileStream(filepath, FileMode.Open, store))\n using (var sr = new StreamReader(stream))\n using (var jr = new JsonTextReader(sr))\n {\n return await jr.ReadJsonAsyncTask<T>();\n }\n });\n</code></pre>\n\n<p>And here too:</p>\n\n<blockquote>\n<pre><code>public static async Task<bool> WriteJsonAsyncTask<T>(this JsonTextWriter writer, T content)\n{\n writer.Formatting = Formatting.Indented;\n return await TaskEx.Run(() =>\n {\n try { JsonSerializer.Serialize(writer, content); }\n catch (Exception) { return false; }\n return true;\n });\n}\n</code></pre>\n</blockquote>\n\n<p>I find code reads better going down than going across:</p>\n\n<pre><code>public static async Task<bool> WriteJsonAsyncTask<T>(this JsonTextWriter writer, T content)\n{\n writer.Formatting = Formatting.Indented;\n return await TaskEx.Run(() =>\n {\n try \n {\n JsonSerializer.Serialize(writer, content);\n return true;\n }\n catch (Exception) \n { \n return false; \n }\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:14:11.620",
"Id": "84978",
"Score": "2",
"body": "As a matter of style, I'd also put the `return true;` within the `catch` block to show the entire \"happy path\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:15:02.210",
"Id": "84979",
"Score": "0",
"body": "@JesseC.Slicer good point - I put it in the `try` block though ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:29:43.610",
"Id": "84982",
"Score": "0",
"body": "@Mat'sMug Thanks for a review. However, it is indeed only a matter of style :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:35:41.963",
"Id": "84983",
"Score": "0",
"body": "@VitaliiVasylenko Meh, the downside of reviewing nice code ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:48:05.617",
"Id": "84984",
"Score": "0",
"body": "@Mat'sMug well.. agree :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:41:21.560",
"Id": "84994",
"Score": "0",
"body": "@JesseC.Slicer Thanks for idea, i'll use it either."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:46:30.897",
"Id": "48418",
"ParentId": "47897",
"Score": "3"
}
},
{
"body": "<p>Talking about code stability, I had found several issues so far:</p>\n<ol>\n<li><p>I tried to call <code>WriteJsonEx()</code> from the <code>Application_Deactivated()</code> to save some data - sometimes it works, but several times it failed to finish writing before app deactivates.</p>\n<p>I found an answer <a href=\"https://stackoverflow.com/questions/14936279/cant-save-data-to-storagefile-while-app-is-being-deactivated?rq=1\">here</a>. In a short: calling async during app deactivation is a bad idea. Sync calls should be used instead (app has several seconds to store data, so sync calls should works fine).</p>\n</li>\n<li><p>No folder autocreation</p>\n<p>Just call <code>DirectoryExists()</code> and <code>CreateDirectory()</code> if needed. Will update sample in a while.</p>\n</li>\n<li><p>Is it thread-safe?</p>\n<p>Probably adding <code>lock()</code> would help, should test it deeper.</p>\n</li>\n</ol>\n<p>EDIT: I'm doing some crash-tests <a href=\"https://stackoverflow.com/questions/23582262/async-reader-writer-locker\">here</a>. Will publish the results in this thread either.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:27:46.350",
"Id": "48426",
"ParentId": "47897",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T16:20:08.963",
"Id": "47897",
"Score": "4",
"Tags": [
"c#",
"json",
"async-await",
"windows-phone",
"windows-phone-7"
],
"Title": "IsoStorageManager"
} | 47897 |
<p>I just wrote this short little program to increment up the build number for my projects every time I build them.</p>
<p>After compiling this exe, I just call it in the pre-build command line.</p>
<p>I did take out the filename string because I used it thrice, and I figured I'd get some flack if I didn't.</p>
<pre><code>static void Main()
{
int num;
string file = "AssemblyInfo.cs";
if (File.Exists(file))
File.WriteAllLines(file, File.ReadAllLines(file).Select(s => !s.Trim().StartsWith("[assembly: AssemblyFileVersion(") ? s : string.Join(".", s.Trim(']').Trim(')').Trim('"').Split('.').Select((n, i) => i != 3 ? n : !int.TryParse(n, out num) ? n : (num + 1).ToString())) + "\")]"));
}
</code></pre>
<p>I realize this is complex, and the average person wont be able to read it. I use magic numbers, and I do some things specifically to keep the glory on 1 line. Feel free to bask in the presence of psychedelic code (which just wants to be your friend).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:16:34.520",
"Id": "84006",
"Score": "0",
"body": "How about just having `[assembly: AssemblyVersion(\"1.0.*\")]` in your *AssemblyInfo.cs* file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:22:22.620",
"Id": "84007",
"Score": "1",
"body": "@Mat'sMug Last I checked(years ago), that didn't work as I'd liked. The numbers weren't incrementing, but instead being eradic and random, I probably should have checked again before writing this :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:24:52.257",
"Id": "84008",
"Score": "0",
"body": "You're right, the build number does look somewhat random, but a new build will always have a higher build number than the previous. What need is there to have it exactly incremental?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:01:55.380",
"Id": "84011",
"Score": "0",
"body": "@Mat'sMug for cleanliness sake, however I feel that there are certain circumstances which actually cause that number to go down, which I certainly didn't want. VS should def fix that, then I would use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:04:43.263",
"Id": "84012",
"Score": "2",
"body": "Is it possible that the *revision* number went up when the *build* number went down?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:26:41.867",
"Id": "84017",
"Score": "0",
"body": "It had to do with the way the numbers were generated based on the day and time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:30:19.550",
"Id": "84094",
"Score": "1",
"body": "I suggest using the [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) class (Version.Parse, then create an incremented object, then call Version.ToString) to reduce the string gymnastics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:28:36.023",
"Id": "84230",
"Score": "0",
"body": "Minor nitpick - call the variable by the more descriptive `filename` instead of `file`."
}
] | [
{
"body": "<p>There is way too much code in that last line. I'm not a stickler for wrapping at 80 character, but 280 characters seems like a bit much. Just because this is a build step script doesn't mean you code doesn't have to be readable. Write a real function to do this operation so I don't have to trust that you are writing the line back the correct way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:24:06.193",
"Id": "47901",
"ParentId": "47900",
"Score": "10"
}
},
{
"body": "<p>I think it's not completely terrible to cram a lot of stuff in a single chain of instructions. But, for the love of god, you have to break that line. Perhaps something like this:</p>\n\n<pre><code>if (File.Exists(file)) {\n File.WriteAllLines(file,\n File.ReadAllLines(file)\n .Select(s => !s.Trim().StartsWith(\"[assembly: AssemblyFileVersion(\")\n ? s\n : string.Join(\".\", s.Trim(']').Trim(')').Trim('\"').Split('.')\n .Select((n, i) => i != 3\n ? n\n : !int.TryParse(n, out num)\n ? n\n : (num + 1).ToString())) + \"\\\")]\"));\n}\n</code></pre>\n\n<p>I don't have a Visual Studio with me. I used the auto-format function of IntelliJ to get this one (sort of). I'm sure Visual Studio too has something to reformat this nicely. Use it!</p>\n\n<hr>\n\n<p>In addition to the above, to put it simply, you want to change this:</p>\n\n<pre><code>[assembly: AssemblyVersion(\"x.y.z\")]\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>[assembly: AssemblyVersion(\"x.y.z+1\")]\n</code></pre>\n\n<p>In addition to expanding the long chain to multiple lines, I would point out that this part is ugly:</p>\n\n<pre><code>string.Join(\".\", s.Trim(']').Trim(')').Trim('\"').Split('.')\n</code></pre>\n\n<p>It would be better to use an approach like this, sorry for the Perl implementation:</p>\n\n<pre><code>sub increment_version {\n my ($before, $minor, $after) = @_;\n $before . ($minor + 1) . $after;\n}\ns/(\\[assembly: AssemblyFileVersion\\(\"\\d+\\.\\d+\\.)(\\d+)(\"\\)\\])/&increment_version($1, $2, $3)/e;\n</code></pre>\n\n<p>The idea here is to use a regular expression to extract the part you want to change, the part before and after it, and replace the whole thing with the middle part changed as you wish.</p>\n\n<p>Finally, but perhaps most importantly, you definitely want to unit test the middle part that replaces the text. When you do that, you will have to extract the entire first <code>Select</code> into its own method, which will do you a lot of good, and make your implementation more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:29:54.037",
"Id": "47902",
"ParentId": "47900",
"Score": "10"
}
},
{
"body": "<pre><code>i != 3 ? n : !int.TryParse(n, out num) ? n : code\n</code></pre>\n\n<p>Could be</p>\n\n<pre><code>i != 3 || !int.TryParse(n, out num) ? n : code\n</code></pre>\n\n<p>...saves 3 characters, and makes more logical sense.</p>\n\n<p>Also, instead of checking that index, it could be re-written to store the result, then only modify the 3rd indexed location and <code>TryParse</code> that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T18:16:02.187",
"Id": "47906",
"ParentId": "47900",
"Score": "3"
}
},
{
"body": "<p><s>Why not use <code>Regex.Match</code> instead of using those confusing joins/splits? Unless you are purposely trying to code golf this, doing it using regular expression is much easier to follow logically.</s></p>\n\n<p>After taking into account delegates used with <code>Regex.Replace</code> (as explained in svick's comment), here is a functionally superior solution to the previous answer I posted. This eliminates much of the unnecessary lambda pieces. The original solution is arguably not a good use of <code>LINQ</code> because of the changes being made to the collection (ie. not a very strong use of queries, despite lambdas having that functionality).</p>\n\n<pre><code>static void Main()\n{\n string file = \"AssemblyInfo.cs\";\n if (File.Exists(file))\n File.WriteAllText(file,\n Regex.Replace(\n File.ReadAllText(file),\n @\"(?<=\\[assembly: AssemblyFileVersion\\(\"\"[0-9]*.[0-9]*.)[0-9]*(?=.[0-9]*\"\"\\)\\])\",\n m => (Convert.ToInt16(m.Value) + 1).ToString()\n )\n );\n }\n}\n</code></pre>\n\n<p>Still only one semi-colon, but at least it's possible to look at it and recognize each piece for what it does. Note I split the parentheses onto separate lines here for parameter readability, but some programmers disagree with this style of line-breaking.</p>\n\n<p>It basically works similar to your original solution, but it basically finds and replaces the <code>Regex.Match</code> with an incremented value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:10:22.140",
"Id": "84026",
"Score": "0",
"body": "Wouldn't this be even better by using `Regex.Replace`? That way, you wouldn't have to do anything with parts that don't change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:19:12.467",
"Id": "84029",
"Score": "0",
"body": "@svick: I'm not sure the `Regex` engine is able to perform number increments like that within `Regex.Replace`. Maybe you can accomplish this by using a delegate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:33:38.447",
"Id": "84039",
"Score": "0",
"body": "@CodesInChaos: `foreach` uses an enumerator. How would you modify the value of the line in this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:30:41.757",
"Id": "84048",
"Score": "0",
"body": "Yeah, delegate, along with look-ahead and look-behind: `string expr = @\"(?<=\\[assembly: AssemblyFileVersion\\(\"\"[0-9]*.[0-9]*.)[0-9]*(?=.[0-9]*\"\"\\)\\])\"; file[i] = Regex.Replace(file[i], expr, m => (Convert.ToInt16(m.Value) + 1).ToString());`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T01:04:38.950",
"Id": "84073",
"Score": "0",
"body": "@svick: Nice, I like that. Feel free to edit it directly into my post if you'd like (I don't have access to a compiler right now to test)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:02:40.620",
"Id": "47910",
"ParentId": "47900",
"Score": "16"
}
},
{
"body": "<p>Don't try to be a badass cowboy. ☺</p>\n\n<p>Stuffing everything onto one line of code is trying to be badass. You could improve clarity simply by adding whitespace.</p>\n\n<p>Producing an incremented version number by careless string processing is trying to be a cowboy. I suggest introducing some kind of abstraction, such as this <a href=\"https://github.com/maxhauser/semver\"><code>SemVer</code> class</a>. If you don't want to introduce an external dependency, it wouldn't be that hard to incorporate just the routines you need into your own code.</p>\n\n<p>A regular expression substitution with a callback would be the way to go, I think.</p>\n\n<pre><code>static string IncrVersion(Match m)\n{\n SemVersion version = SemVersion.Parse(match.Groups[1].Value);\n return version.Change(patch: 1 + version.Patch).ToString();\n}\n\nstatic void Main()\n{\n string file = \"AssemblyInfo.cs\";\n var versionRx = new Regex(@\"\\[assembly: AssemblyFileVersion\\((.*)\\)\\]\");\n if (File.Exists(file)) \n {\n File.WriteAllLines(file,\n File.ReadAllLines(file).Select(s =>\n versionRx.Replace(s, new MatchEvaluator(IncrVersion))\n ) \n ); \n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:19:34.797",
"Id": "84067",
"Score": "0",
"body": "I'm no C# programmer. Please feel free to correct the code above."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:18:32.660",
"Id": "47933",
"ParentId": "47900",
"Score": "13"
}
},
{
"body": "<p>Well, you could also use a custom build target that increments the build number automatically.</p>\n\n<p>Using MSBuild.Community.Tasks, this is pretty easy:</p>\n\n<pre><code><Version VersionFile=\"Version.txt\" BuildType=\"Incremental\">\n <Output TaskParameter=\"Major\" PropertyName=\"Major\" />\n <Output TaskParameter=\"Minor\" PropertyName=\"Minor\" />\n <Output TaskParameter=\"Build\" PropertyName=\"Build\" />\n <Output TaskParameter=\"Revision\" PropertyName=\"Revision\" />\n</Version>\n<AssemblyInfo \n AssemblyVersion=\"$(Major).$(Minor).$(Build).$(Revision)\"\n AssemblyFileVersion=\"$(Major).$(Minor).$(Build).$(Revision)\" \n CodeLanguage=\"CS\" ComVisible=\"False\" />\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:17:16.800",
"Id": "84228",
"Score": "1",
"body": "While it doesn't review the code in the OP itself, this certainly strikes towards the OP's goal, using a different part of the same technology. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:24:42.010",
"Id": "47952",
"ParentId": "47900",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47910",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T17:07:28.650",
"Id": "47900",
"Score": "19",
"Tags": [
"c#",
"linq",
"lambda"
],
"Title": "Increment up the build number in AssemblyInfo.cs on every build"
} | 47900 |
<p>The goal here is to create a Top Level Menu that automatically pulls child pages without the need to manually add them to said menu. I didn't know any other way to accomplish this without a walker, of which I'm not very familiar with. </p>
<p>I was playing around with it and was able to get the submenus to work with this. The submenu gets added at the bottom of <code>start_el</code></p>
<pre><code>/** The Walker **/
class fitz_and_the_tantrums extends Walker_Nav_Menu {
// add main/sub classes to li's and links
function start_el( &$output, $item, $depth, $args ) {
global $wp_query;
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
// passed classes
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
// build html
$output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $class_names . '">';
// link attributes
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';
$item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
$args->before,
$attributes,
$args->link_before,
apply_filters( 'the_title', $item->title, $item->ID ),
$args->link_after,
$args->after
);
// build html
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
if(nav_hasChildren($item->object_id)){
$output .= '<ul class="submenu">';
ob_start();
wp_list_pages(
array(
'child_of' => $item->object_id,
'depth' => 1,
'title_li' => ''
)
);
$output .= ob_get_clean();
$output .= '</ul>';
}
}
}
/** Check if item has Children **/
function nav_hasChildren($pid) {
$children = get_pages('child_of='.$pid);
if($children)
return true;
else
return false;
}
</code></pre>
<p>Is there a way to minimize the needed code, or do I absolutely need to set everything so that the Walker can function properly?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T14:52:51.273",
"Id": "47903",
"Score": "2",
"Tags": [
"php",
"wordpress"
],
"Title": "Automatic submenu"
} | 47903 |
<p>Here is another portion of the <a href="https://codereview.stackexchange.com/questions/47789/civilization-5-mod-validator">same program</a> that I would like optimizing (85-95% of the time running the program is spent within this class!!!) so that it runs faster, especially for users who have less powerful computers.</p>
<p>Any optimizations for this section of the code would be greatly appreciated! I have done my best again to comment my code to help you understand it and I will post a short
paragraph introducing the data system. Please note, that although I acknowledge that using braces on the same like as the statement is convention, I find it very hard to read code in this form and so I use the brace on the next line style!</p>
<p>As promised here is the way the data is stored:</p>
<blockquote>
<p>Table class contains a <code>HashMap</code> of <code>Table</code> instances paired with their
name, which are accessed by <code>getTable(String name)</code> or <code>getRegister()</code> for
everything</p>
<p>A Table contains a <code>HashMap <String, Vector<Row>></code> which stores Rows,
grouped by their primary tag's name (which is the tag that they define, if they don't define a tag their name is "")</p>
<p>a Row contains an <code>LinkedHashMap</code> of <code>Tag <?></code>s which can be varying types
such as int or String mapped to their name.</p>
<p>The <code>Tag</code> has a name and a ? data field.</p>
</blockquote>
<p>and the code in question:</p>
<pre><code>public class ReferenceDetector
{
private HashMap<String, Table> register; //a variable which contains all the data
public ReferenceDetector(HashMap<String, Table> register)
{
this.register = register;
}
/*
* Here our main job is to find any tags in the register that:
* contain a body of a String
* is not excluded by the program as an ignored tag
* and check to see if they are defined as existing in the primary tables
*/
void findReferences(boolean store)
{
Table dump = new Table("Dump", true, true); //the dump table is used to define any references that are errors in the Base Game,
//they clearly work so the mod should be able to use them! (typically these references exist in the DLL or Lua
for (Table table : register.values()) // for every table in the register
{
for (ArrayList<Row> rowReferences : table.getRows().values()) //for every group of same named rows in the table
{
for (Row row : rowReferences) // for every row in this group
{
for (Tag<?> tag : row.getTags()) // for every tag in this row
{
if (tag.get() instanceof String && !Excludes.checkExcludedTag((String) tag.get())) // are we a String and not to be ignored?
{
String tableTarget = determineTable(tag.getName()); //determine the table name (see below)
// attempt to resolve the reference, to check if it was defined, so if we have the tag CIVILIZATION_NEPAL, does it exist in the primary table Civilizations?
// the boolean argument for resolveReference is used in case of no found table!
boolean passed = !tableTarget.equals("") ? resolveReference(new Reference(tableTarget, (String) tag.get()), false) : resolveReference(new Reference(tableTarget, (String) tag.get()), true);
if (!passed && !store) // we didn't succeed and we are not checking the base game
{
System.out.println(String.format("MISSING REFERENCE: %s %sin %s references %s in tag %s, this object doesn't exist"
, !row.getIdentifier().isEmpty() ? "Row with type" : String.format("Entry with %s = %s", row.getTags().toArray(new Tag<?> [] {})[0].getName(), row.getTags().toArray(new Tag<?> [] {})[0].get())
, !row.getIdentifier().isEmpty() ? row.getIdentifier() + " " : ""
, table.getIdentifier()
, tag.get()
, tag.getName())); //print out the diagnosis to the user
}
else if (!passed && store) // if we are checking the base game, no body cares about this error! Just a DLL definition, just create the definition in the dump so that it can be used by mods
{
dump.addDumpRow((String) tag.get());
}
}
}
}
}
}
dump.register(); //add the dump table to the register itself!
}
/*
* Let's run through the targetTable, or the whole register (if bruteForce is true) for this tag's definition
* a Reference simply contains the targetTable name (or null) and the actual tag we are looking for (as object)
*/
boolean resolveReference(Reference ref, boolean bruteForce)
{
boolean regexSearch = ref.object.contains("%");
/*
* The above line is important.
* Some tags represent text, and in-game any random dialog or stuff used in the in-game pedia is written in this form:
* TXT_KEY_..._n (where n represents the variants so 1, 2, 3, 4 etc)
* Then in the xml, where they are needed the code is instructed to accept anything with the form TXT_KEY_..._% to denote any of these tags
* hence why we need to do the same! if there is a % chances are it could be defined as something slightly different!
*/
Pattern search = Pattern.compile(ref.object.replace(".", "\\.").replace("%", ".+")); //convert any . into regex literals, and convert the % into a regex of: any character at least once (for times when we are looking in the dump)
if (!bruteForce && register.get(ref.targetTable).getRows().containsKey(ref.object)) { return true; } // we looked in the targetTable and found the definition, success!
else // looks like we need to go through everything... (from bruteForce or unable to find in the targetTable)
{
for (Table table : register.values()) //for every table
{
if (table.isPrimary()) //if it is primary (definitions of keys are only ever primary)
{
if (regexSearch) //if we detect the use of %
{
for (String key : table.getRows().keySet()) //for every row group name
{
if (search.matcher(key).matches()) //if this matches, the primary key is the one we were looking for!
{
return true;
}
}
}
else
{
if (table.getRows().containsKey(ref.object)) // is the key we are looking for the name of a row group (if it is, then we know it is a primary key definition)
{
return true;
}
}
}
}
return false;
}
}
String determineTable(String tagName)
{
// Try to identify the table based on Convention
if (tagName.contains("Type") && register.containsKey(tagName.substring(0, tagName.length() - 4) + "s")) //are we of the form ____Type ? if so then cut off the Type and add s, this usually is another table
{
if (Table.getTable(tagName.substring(0, tagName.length() - 4) + "s").isPrimary()) // is the table that we have found primary (and therefore defines the reference)
{
return tagName.substring(0, tagName.length() - 4) + "s"; // yes, let's assume it is the right table!
}
}
// We failed... send notice for brute force
return "";
}
private class Reference
{
private String targetTable, object;
Reference(String targetTable, String object)
{
this.targetTable = targetTable;
this.object = object;
}
}
}
</code></pre>
<p>Also, here is a quick overview of what the code has to achieve and some background:</p>
<p>This part of the program is responsible for ensuring that any tags that are defined in the mods do actually exist somewhere else in the mod/any dependency mods/the base game itself. </p>
<p>For example, my mod has a tag which says that England's unique unit should be UNIT_LONGBOWMAN. This code will then check that UNIT_LONGBOWMAN does in fact exist. It first attempts to work out the table where it might have been defined (The tag itself exists like this in xml: <code><UnitType>UNIT_LONGBOWMAN</UnitType></code>, we should take UnitType->Unit->Units as our table name) and then searches there (if it actually is a table known by that name) for a row which has an identifier that matches this tag content (which indicates that row is responsible for defining UNIT_LONGBOWMAN, otherwise it's name would be ""). If it couldn't find a table that could contain the definition, it performs brute force and checks every table in the data for a row group that defines this tag!</p>
<p>If you have any questions do not hesitate to ask!</p>
<p><strong>EDIT (for Table class + children):</strong></p>
<pre><code>public class Table implements Serializable //the register is serialised to be used next runtime, easier that way :)
{
private static final long serialVersionUID = 1L;
private boolean primary;
private boolean nonUnique = false;
private static HashMap<String, Table> register = new HashMap<String, Table> ();
private HashMap<String, ArrayList<Row>> rows = new HashMap<String, ArrayList<Row>> ();
private String tableIdentifier;
public static HashMap<String, Table> getRegister() { return register; }
public boolean isPrimary() { return primary; }
public void setIsPrimary(boolean value) { primary = value; }
public boolean isNonUnique() { return nonUnique; }
public void setIsNonUnique(boolean value) { nonUnique = value; }
// Constructor called from Table.getTable(String)
private Table(String identifier, boolean primary)
{
tableIdentifier = identifier;
this.primary = primary;
register();
}
// Called where ever we need to create a table but not register it!
public Table(String identifier, boolean primary, boolean preprepare)
{
tableIdentifier = identifier;
this.primary = primary;
}
public void register()
{
register.put(tableIdentifier, this);
}
public String getIdentifier() { return tableIdentifier; }
// get or define and get a table
public static Table getTable(String identifier)
{
return getRegister().containsKey(identifier) ? getRegister().get(identifier) : new Table(identifier, MainLauncher.reader.isPrimaryTable(identifier));
}
public ArrayList<Row> getRows(String identifier)
{
return rows.get(identifier);
}
public HashMap<String, ArrayList<Row>> getRowGroups() { return rows; }
// add row to this table, then return it (or return the any row that is identical in contents and name)
public Row addRow(Row row, boolean ignore)
{
String rowIdentifier = row.getIdentifier();
if (!rows.containsKey(rowIdentifier)) rows.put(rowIdentifier, new ArrayList<Row> ());
if (!primary || nonUnique)
{
if (rows.get(rowIdentifier).isEmpty())
{
rows.get(rowIdentifier).add(row);
}
else
{
out: for (Row loopRow : rows.get(rowIdentifier))
{
for (Tag<?> loopTag : loopRow.getTags())
{
if (row.getTag(loopTag.getName()) == null || (!row.getTag(loopTag.getName()).get().equals(loopTag.get())))
{
rows.get(rowIdentifier).add(row);
break out;
}
}
return loopRow;
}
}
}
else
{
if (!rows.get(rowIdentifier).isEmpty())
{
rows.get(rowIdentifier).clear();
if (!ignore) System.out.println(String.format("WARNING: Cannot have more than one of same type: %s in %s", rowIdentifier, tableIdentifier));
}
rows.get(rowIdentifier).add(row);
}
return row;
}
// used for dumping base game problems
public void addDumpRow(String identifier)
{
if (!rows.containsKey(identifier)) rows.put(identifier, new ArrayList<Row> ());
if (!rows.get(identifier).isEmpty())
{
rows.get(identifier).clear();
}
rows.get(identifier).add(new Row(identifier));
}
// called from the XML readers, if the delete tag was identified. just removes rows from the table that have tables that match all "wheres"
public <T> void deleteRow(HashMap<String, T> wheres)
{
HashMap<String, Vector<Row>> deletes = new HashMap<String, Vector<Row>> ();
for (String rowName : rows.keySet())
{
for (Row row : rows.get(rowName))
{
boolean matches = true;
for (String identifier : wheres.keySet())
{
T content = wheres.get(identifier);
if (row.getTags().stream().anyMatch(tag -> !tag.get().equals(content) && tag.getName().equals(identifier)))
{
matches = false;
break;
}
}
if (matches)
{
if (!deletes.containsKey(rowName))
{
deletes.put(rowName, new Vector<Row> ());
}
deletes.get(rowName).add(row);
}
}
}
for (String name : deletes.keySet())
{
ArrayList<Row> group = rows.get(name);
deletes.get(name).stream().forEach(group::remove);
if (group.isEmpty()) rows.remove(name);
}
}
// similar to deleteRow(), replaces the contents of any rows that match all wheres with the updates
public <T, U> void updateRow(HashMap<String, T> wheres, HashMap<String, U> updates)
{
for (ArrayList<Row> rowGroup : rows.values())
{
for (Row row : rowGroup)
{
Vector<String> updatesToApply = new Vector<String> ();
boolean matches = false;
for (Tag<?> tag : row.getTags())
{
matches = true;
if (wheres.keySet().stream().anyMatch(tagName -> !tag.getName().equals(tagName) || !tag.get().equals(wheres.get(tagName))))
{
matches = false;
break;
}
if (matches)
{
updates.keySet().stream().forEach(updatesToApply::add);
}
}
for (String updateName : updatesToApply)
{
if (row.getTag(updateName) != null)
{
row.removeTag(row.getTag(updateName));
}
row.addTag(updateName, new Tag<U>(updateName, updates.get(updateName)));
}
}
}
}
public static class Row implements Serializable
{
private static final long serialVersionUID = 1L;
private String rowIdentifier;
private LinkedHashMap<String, Tag<?>> tags;
Row(String identifier)
{
tags = new LinkedHashMap<String, Tag<?>> ();
rowIdentifier = identifier;
}
public void removeTag(Tag<?> tag)
{
tags.remove(tag.getName());
}
public void addTag(String identifier, Tag<?> tag)
{
tags.put(identifier, tag);
}
public Tag<?> getTag(String identifier) { return tags.get(identifier); }
public Collection<Tag<?>> getTags() { return tags.values(); }
public String getIdentifier() { return rowIdentifier; }
public static class Tag<T> implements Serializable
{
private static final long serialVersionUID = 1L;
private T data;
private String tagIdentifier;
Tag(String identifier, T data)
{
tagIdentifier = identifier;
this.data = data;
}
public T get() { return data; }
public String getName() { return tagIdentifier; }
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Without the full program, I can't profile runs to prove where issues are and that my suggestions will improve them, so I'm guessing a bit. Further, I have no knowledge of Civilization 5's file structure so please gloss over misuse of terms. That said, I do have some suggestions and an angle or two to explore.</p>\n\n<hr>\n\n<h2><code>boolean resolveReference(Reference ref, boolean bruteForce)</code></h2>\n\n<p>You're basically doing a full scan over all of your data when you resort to brute force. For a bit more memory use, you can build an index to help speed things up. To do this, you'll need to make your <code>HashMap<String, Table> register</code> a first-class citizen by giving it its own class, <code>Register</code>.</p>\n\n<p>For brevity, I'm going to use the Multimap from the <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">guava libraries</a>. It feels like it will make a difference here.</p>\n\n<pre><code>// Register.java\npublic class Register {\n private static final Register global = new Register();\n public static Register global() {\n return global;\n }\n\n SetMultimap<String, Table> keysToTable = HashMultimap.create();\n Map<String, Table> tablesByName = new HashMap<>();\n\n public boolean resolveReference(Reference ref) {\n return keysToTable.containsKey(ref.object);\n }\n\n public Table getOrCreateTable(String name) {\n Table table = tablesByName.get(name);\n if ( table == null ) {\n table = new Table(name);\n tablesByName.put(name, table);\n }\n return table;\n }\n\n static <V> void addPrefixes(String key, V value, Multimap<String, V> multimap) {\n for (int end = key.length(); end >= 0; end-- ) {\n multimap.put(key.substring(0, end) + \"%\", value);\n }\n }\n\n public class Table {\n String name;\n ListMultimap<String, Row> rowsByPrimaryTag = ArrayListMultimap.create();\n\n Table(String name) {\n this.name = name;\n }\n\n public void addRow(String key, Row row) {\n keysToTable.put(key, this);\n addPrefixes(key, this, keysToTable);\n\n // add to rowsByPrimaryTag as needed\n }\n\n public Register getRegister() {\n return Register.this;\n }\n }\n}\n</code></pre>\n\n<p><code>addPrefixes</code> assumes that the <code>%</code> expansion wildcard only happens at the very end of a specifier. The method could be made to account for other uses, if necessary. What it does is basically:</p>\n\n<pre><code>addPrefixes(\"ARCHER\", table, mm) {\n mm.put(\"ARCHER%\", table)\n mm.put(\"ARCHE%\", table)\n mm.put(\"ARCH%\", table)\n mm.put(\"ARC%\", table)\n mm.put(\"AR%\", table)\n mm.put(\"A%\", table)\n mm.put(\"%\", table)\n}\n</code></pre>\n\n<p>So that, if you later add a key \"ARCHON\" to another table (or the same), \"ARCH%\" will find both tables immediately. That should take care of the brute force issues and remove the need for regexes, I think.</p>\n\n<hr>\n\n<h2><code>String determineTable(String tagName)</code></h2>\n\n<p>The expression <code>tagName.substring(0, tagName.length() - 4) + \"s\"</code> appears often in here. Consider extracting it and replacing it with a local final variable:</p>\n\n<pre><code>String determineTable(String tagName) {\n // unit_type -> units\n final String tableName = tagName.substring(0, tagName.length() - 4) + \"s\";\n // Try to identify the table based on Convention \n if (tagName.contains(\"Type\") && register.containsKey(tableName)) { //are we of the form ____Type ? if so then cut off the Type and add s, this usually is another table\n if (Table.getTable(tableName).isPrimary()) { // is the table that we have found primary (and therefore defines the reference)\n return tableName; // yes, let's assume it is the right table!\n }\n }\n // We failed... send notice for brute force\n return \"\";\n}\n</code></pre>\n\n<p>It will shave off a few operations, and improve the method's robustness to change.</p>\n\n<hr>\n\n<h2><code>private class Reference</code></h2>\n\n<p>Do you need this one? Since the class holds no logic, only data, and sees use only once, maybe it's better to flatten it out:</p>\n\n<pre><code> public boolean resolveReference(Reference ref)\n-> public boolean resolveReference(String object, String targetTable)\n</code></pre>\n\n<p>Removes some allocations and field lookups. That's slim pickings, though: if you do use it elsewhere, or you feel it makes things less readable, or you intend to flesh it out later, just leave it be.</p>\n\n<hr>\n\n<h2><code>void findReferences(boolean store)</code></h2>\n\n<pre><code>boolean passed = !tableTarget.equals(\"\") ?\n resolveReference(new Reference(tableTarget, (String) tag.get()), false) :\n resolveReference(new Reference(tableTarget, (String) tag.get()), true);\n</code></pre>\n\n<p>can be shortened to:</p>\n\n<pre><code>boolean passed = resolveReference(\n new Reference(tableTarget, (String) tag.get()),\n tableTarget.equals(\"\"));\n</code></pre>\n\n<hr>\n\n<p>On a stylistic note, your code feels overdocumented. You did provide useful comments (pointing out special casing on '%', for instance), but some lines were superfluous, like on the iteration in <code>findReferences</code>.</p>\n\n<p>Aim for self-documenting code through the naming of variables, classes, and methods. If that's not enough, add javadoc to the methods or fields troubling you.</p>\n\n<pre><code>String guessTableName(String tagName) {\n if ( tagName.endsWith(\"Type\") ) {\n final String tableName = tagName.substring(0, tagName.length() - \"Type\".length()) + \"s\";\n final Table table = register.getTable(tableName);\n if ( table != null && table.isPrimary() ) {\n return tableName;\n }\n }\n return \"\";\n}\n</code></pre>\n\n<p>Add comments when:</p>\n\n<ul>\n<li><p>You need to explain intent in a way that is not obvious from your code.</p>\n\n<pre><code>/* We're starting on the left side of the tree because production data indicates\n * about 80% of the time, queried nodes are in the left half. */\n\n/* In Civ V, a '%' is a wildcard, so detect if this string has a '%' character. */\n</code></pre></li>\n<li><p>A part of your code is counter-intuitive or fragile, or to document code smells.</p>\n\n<pre><code>array[index] = 5; // null-checked by array.length before\n\nif ( end = reachedEOF() ) // boolean assignment\n\n// don't call this recursively because it changes global context\n\n/* Copied from XYZ#refineMyCoffee */\n</code></pre></li>\n<li><p>Naming or code assumes domain knowledge.</p>\n\n<pre><code>/**\n * <p>Holds rows grouped by tags.\n * <p>A <dfn>Row</dfn> is a ...\n */\npublic class Table {\n</code></pre></li>\n</ul>\n\n<p>In the end, it's as much a matter of personal style as it is a science or discipline. You are the developer and later maintainer of the project, so pick something you're comfortable with. When in doubt, err on the side of slightly over-documenting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:22:13.590",
"Id": "84883",
"Score": "0",
"body": "A lot to read over here ;). With the over-documenting, be assured it doesn't normally look like that! I put in more for this post, as I felt it was a hard piece of code to understand, but I do see your point :). Nice catch on the `findReference()` and `determineTable()` stuff! I will fix it. Reference was beefed out, but only for my own optimisations (whilst I was waiting for an answer here, I put the whole register into a set of references and another of primary keys, then check to see that all references are in the primaryKey set, but I will look into yours to see if it is faster)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:29:19.983",
"Id": "84884",
"Score": "0",
"body": "also, just in case it makes a difference, the register map comes from calling `Table.getRegister()`, so all the tables are kept in the Table class (I will update the opening post with the structure, so you can better understand what is going on there)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T21:46:01.923",
"Id": "48368",
"ParentId": "47911",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48368",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:21:03.433",
"Id": "47911",
"Score": "5",
"Tags": [
"java",
"optimization"
],
"Title": "Civilization 5 Mod validator part 2"
} | 47911 |
<p>Dart is an open-source, class-based, optionally-typed programming language for building web applications--on both the client and server--created by <a href="/questions/tagged/google" class="post-tag" title="show questions tagged 'google'" rel="tag">google</a>. Dart’s design goals are:</p>
<ul>
<li>Create a structured yet flexible language for web programming.</li>
<li>Make Dart feel familiar and natural to programmers and thus easy to learn.</li>
<li>Ensure that Dart delivers high performance on all modern web browsers and environments ranging from small handheld devices to server-side execution.</li>
</ul>
<p>Dart targets a wide range of development scenarios, from a one-person project without much structure to a large-scale project needing formal types in the code to state programmer intent. </p>
<p>To support this wide range of projects, Dart provides the following features and tools:</p>
<ul>
<li>Optional types; this means you can start coding without types and add them later as needed. </li>
<li>Isolates: concurrent programming on server and client</li>
<li>Easy access to DOM the way jQuery does it</li>
<li>Dart Editor: an Eclipse based IDE</li>
<li>Dartium: a build of the Chromium Web Browser with a built-in Dart Virtual Machine</li>
</ul>
<h2>Links</h2>
<ul>
<li><a href="http://www.dartlang.org" rel="nofollow">The Dart Homepage</a></li>
<li><a href="http://news.dartlang.org" rel="nofollow">Official Dart News & Updates</a></li>
<li><a href="http://www.dartosphere.org" rel="nofollow">The Dartosphere</a> - A collection of recent Dart blog posts</li>
<li><a href="https://plus.google.com/communities/114566943291919232850" rel="nofollow">Dartisans</a> Dartisans community on Google+</li>
<li><a href="https://groups.google.com/a/dartlang.org/forum/#!forum/web" rel="nofollow">Dart Google Groups Page</a></li>
</ul>
<h2>Documentation</h2>
<ul>
<li><a href="http://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html" rel="nofollow">Tour of the Dart Language</a></li>
<li><a href="http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html" rel="nofollow">Tour of the Dart Libraries</a></li>
<li><a href="http://try.dartlang.org/" rel="nofollow">Dart Code samples</a></li>
<li><a href="http://api.dartlang.org/docs/releases/latest/" rel="nofollow">Dart API Reference</a></li>
</ul>
<h2>FAQ</h2>
<ul>
<li><a href="https://www.dartlang.org/support/faq.html" rel="nofollow">Frequently Asked Questions</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:22:36.213",
"Id": "47912",
"Score": "0",
"Tags": null,
"Title": null
} | 47912 |
Dart is a class-based, optionally-typed programming language for building web and command-line applications. Dart compiles to modern JavaScript to run on the client and runs natively on the Dart VM for server-side apps. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:22:36.213",
"Id": "47913",
"Score": "0",
"Tags": null,
"Title": null
} | 47913 |
<p>I am trying to make this code that creates accounts in a cpanel/whm account more secure.</p>
<p>Could someone please let me know what needs to be done to make this more secure?</p>
<pre><code><?php
/////// YOUR WHM LOGIN DATA
$whm_user = "username"; // reseller username
$whm_pass = "password"; // the password you use to login to WHM
#####################################################################################
############## END OF SETTINGS. DO NOT EDIT BELOW #######################
#####################################################################################
$whm_host = $_SERVER['HTTP_HOST'];
function getVar($name, $def = '') {
if (isset($_REQUEST[$name]))
return $_REQUEST[$name];
else
return $def;
}
// Domain name of new hosting account
// To create subdomain just pass full subdomain name
// Example: newuser.zubrag.com
if (!isset($user_domain)) {
$user_domain = getVar('domain');
}
// Username of the new hosting account
if (!isset($user_name)) {
$user_name = getVar('user');
}
// Password for the new hosting account
if (!isset($user_pass)) {
$user_pass = getVar('password');
}
// New hosting account Package
if (!isset($user_plan)) {
$user_plan = getVar('package');
}
// Contact email
if (!isset($user_email)) {
$user_email = getVar('email');
}
// if parameters passed then create account
if (!empty($user_name)) {
// create account on the cPanel server
$script = "http://{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct";
$params = "?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}";
$result = file_get_contents($script.$params);
}
// otherwise show input form
else {
$frm = <<<EOD
EOD;
echo $frm;
}
?>
</code></pre>
<p>EDIT:</p>
<p>This works:</p>
<pre><code>$whm_host = $_SERVER['SERVER_NAME'];
function getVar($name, $def = '', $sg_method = 'POST') {
switch($sg_method){
case 'POST' : return isset($_POST[$name]) ? $_POST[$name] : $def;
break;
case 'GET' : return isset($_GET[$name]) ? $_GET[$name] : $def;
break;
case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;
break;
default : return $def;
}
}
// Domain name of new hosting account
// To create subdomain just pass full subdomain name
// Example: newuser.zubrag.com
if (!isset($user_domain)) {
$user_domain = getVar('domain');
}
// Username of the new hosting account
if (!isset($user_name)) {
$user_name = getVar('user');
}
// Password for the new hosting account
if (!isset($user_pass)) {
$user_pass = getVar('password');
}
// New hosting account Package
if (!isset($user_plan)) {
$user_plan = getVar('package');
}
// Contact email
if (!isset($user_email)) {
$user_email = getVar('email');
}
// if parameters passed then create account
if (!empty($user_name)) {
// create account on the cPanel server
$script = "http://{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct";
$params = "?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}";
$result = file_get_contents($script.$params);
}
// otherwise show input form
else {
$frm = <<<EOD
EOD;
echo $frm;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:33:51.473",
"Id": "84020",
"Score": "0",
"body": "@Jamal, I don't see the reason behind your edit! the code already creates accounts so that works fine. I just need to make it more secure!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:35:31.320",
"Id": "84021",
"Score": "2",
"body": "I know, but we prefer titles that state the purpose of the code. The request is already given in the body and the tags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:40:25.690",
"Id": "84022",
"Score": "0",
"body": "@Jamal, fair enough. so any suggestion on the security of the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:51:27.260",
"Id": "84024",
"Score": "0",
"body": "I'm not experienced in PHP, so I have nothing to say about it. There are others on this site who should be able to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:52:58.207",
"Id": "84025",
"Score": "0",
"body": "@Jamal, okay mate... Thanks. fingers crossed someone's gonna chip in and help."
}
] | [
{
"body": "<p>Let's start with the easy fish - <code>$_REQUEST</code>. Going by the <a href=\"http://www.php.net/manual/en/reserved.variables.request.php\" rel=\"nofollow noreferrer\">PHP manual</a>, <code>$_REQUEST</code> is a combination of <code>$_POST</code>, <code>$_GET</code>, and <code>$_COOKIE</code>. </p>\n\n<p>In your <code>getVar(...)</code> function, you reference the request superglobal, and in the following lines, you use it to get a password. Using the request superglobal would allow a password to be given in via insecure methods like GET and COOKIE. Ideally, you want to POST any sensitive data like a password, so let's modify the code to just grab from POST by default, and let's add a third parameter in case we need to get certain values from GET or COOKIE. </p>\n\n<pre><code>function getVar($name, $def = '', $sg_method = 'POST') {\n switch($sg_method){\n case 'POST' : return isset($_POST[$name]) ? $_POST[$name] : $def;\n break;\n case 'GET' : return isset($_GET[$name]) ? $_GET[$name] : $def;\n break;\n case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;\n break;\n default : return $def;\n }\n}\n</code></pre>\n\n<p>One glaring security issue is the following line:</p>\n\n<pre><code>$whm_host = $_SERVER['HTTP_HOST'];\n</code></pre>\n\n<p>You have to remember that HTTP_HOST is gotten from a user-defined header. Unless a business requirement dictates it, you should use SERVER_NAME. See <a href=\"https://stackoverflow.com/questions/2297403/http-host-vs-server-name\">HTTP_HOST vs. SERVER_NAME</a> on Stack Overflow for a better explanation - specifically <a href=\"https://stackoverflow.com/a/2297421/1753963\">this answer by BalusC</a>. </p>\n\n<p>Now, we can compress the multiple IF statements into a simpler foreach, as follows:</p>\n\n<pre><code>$user_data = array(\n \"domain\" => array($user_domain, 'user_domain'),\n \"user\" => array($user_name, 'user_name'),\n \"password\" => array($user_pass, 'user_pass'),\n \"package\" => array($user_plan, 'user_plan'),\n \"email\" => array($user_email, 'user_email')\n);\n\nforeach($user_data as $key => $val){\n if(empty($val[0])){\n $$val[1] = getVar($key);\n }\n}\n</code></pre>\n\n<p>Below is how I've modified your code:</p>\n\n<pre><code># Your WHM login data\n$whm_user = \"username\"; # reseller username\n$whm_pass = \"password\"; # the password you use to login to WHM\n\n#####################################################################################\n############## END OF SETTINGS. DO NOT EDIT BELOW #######################\n#####################################################################################\n\n$whm_host = $_SERVER['HTTP_HOST'];\n\nfunction getVar($name, $def = '', $sg_method = 'POST') {\n switch($sg_method){\n case 'POST' : return isset($_POST[$name]) ? $_POST[$name] : $def;\n break;\n case 'GET' : return isset($_GET[$name]) ? $_GET[$name] : $def;\n break;\n case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;\n }\n}\n\n# Domain name of new hosting account\n# To create subdomain just pass full subdomain name\n# Example: newuser.zubrag.com\n$user_data = array(\n \"domain\" => array($user_domain, 'user_domain'),\n \"user\" => array($user_name, 'user_name'),\n \"password\" => array($user_pass, 'user_pass'),\n \"package\" => array($user_plan, 'user_plan'),\n \"email\" => array($user_email, 'user_email')\n);\n\nforeach($user_data as $key => $val){\n if(empty($val[0])){\n $$val[1] = getVar($key);\n }\n}\n\n# if parameters passed then create account\nif (!empty($user_name)) {\n # create account on the cPanel server\n $script = \"http:#{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct\";\n $params = \"?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}\";\n $result = file_get_contents($script.$params);\n} else {\n $frm = <<<EOD\nEOD;\n echo $frm;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:20:30.813",
"Id": "84132",
"Score": "0",
"body": "Thank you for taking the time to answer this question. however, using this code, I get an error it also has a syntax error in the second line from the bottom!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:30:12.713",
"Id": "84152",
"Score": "0",
"body": "That's because of the newdoc. Notice that I wrote it on one line as `<<<EOD \\EOD` where the backslash means everything after the backslash goes on a new string (the stackexchange editor would break the code if the EOD was left aligned). I'll edit it to try and show how it's *supposed* to go. Unless you're getting another error, in which case, please copy and paste it into a comment here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:11:02.320",
"Id": "47920",
"ParentId": "47915",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T19:26:32.143",
"Id": "47915",
"Score": "1",
"Tags": [
"php",
"security"
],
"Title": "Creating accounts in a cpanel/whm account"
} | 47915 |
<p>Looking for help refactoring the following code to follow a Functional Programming paradigm.</p>
<p>The first function builds a configuration object with default settings and optional presets, while the <code>buildResourcePath</code> will assemble a URL for the image service.</p>
<p><code>getSizedUrl</code> and <code>getSizedSkuUrl</code> returns a URL that will be used for an image tag.</p>
<pre><code>var imgSvcPath = './imageSizer.svc';
/**
* configureImg
* Build a configurtion object with sane defaults applied that can be used to construct a url for the ImageResizer service
*/
function configureImg( options ){
options = options || {};
var defaults = {
type: null,
src: '',
width: 120,
height: null
},
// use Image presets if an option.type provided
presets = options.type ? Images.getPresets( options.type ) : {};
return $.extend( defaults, options, presets );
};
/**
* buildResourcePath
* Construct a url for the ImageResize service to be used for the src of <img />
*/
function buildResourcePath( svcName, options ){
// imageSizer.svc/GetResizedImage?path=[path]&size=[size]&quality=[quality]
var resourcePath = [],
conf = configureImg( options ),
src = ( conf.skuId !== undefined )
? '?sku=' + conf.skuId
: '?path=' + encodeURI( conf.src ),
size = '&size=' + ( conf.height ? 'h|' + conf.height : 'w|' + conf.width ),
quality = conf.quality ? '&quality=' + conf.quality : '';
resourcePath.push( imgSvcPath, svcName, src, size, quality );
return resourcePath.join( '' );
};
/**
* getSizedUrl
* return src of <img /> for GetResizedImage
*/
var getSizedUrl = function( options ){
if( 'undefined' === typeof options.src ) {
console.error( 'upi.Services.Image::getSizedUrl configuration options must provide an image src string' );
}
return buildResourcePath( 'GetResizedImage', options );
};
/**
* getSizedSkuUrl
* return src for an <img /> for GetResizedSkuImage
*/
var getSizedUrlForSku = function( skuId, options ){
if( 'undefined' === typeof skuId ) {
console.error( 'upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID' );
}
options = options || {};
options[ 'skuId' ] = skuId;
return buildResourcePath( 'GetResizedSkuImage', options );
};
Image = {
getSizedUrlForSku: getSizedUrlForSku,
getSizedUrl: getSizedUrl
};
</code></pre>
| [] | [
{
"body": "<pre><code>// Store everything in a scope. It's to preven you from polluting the global\n// scope as well as protect your code from collisions.\n;(function(ns) {\n\n // Pulling out constants into this scope. They only need to be declared once.\n var imgSvcPath = './imageSizer.svc';\n var defaults = {\n type: null,\n src: '',\n width: 120,\n height: null\n };\n\n function configureImg(options) {\n var options = options || {};\n var presets = options.type ? Images.getPresets(options.type) : {};\n\n // It's best if you extend to a blank object. Don't override the defaults.\n return $.extend({}, defaults, options, presets);\n }\n\n function buildResourcePath(svcName, options) {\n\n var conf = configureImg(options);\n\n // I assume you use jQuery because of $.extend so I introduce $.param\n // which takes a map and converts it into a serialized parameter list\n\n var params = {};\n\n // And ternaries can be very messy and unreadable. Now using if-else instead.\n if (conf.skuId !== undefined) params.sku = conf.skuId;\n else params.path = conf.src;\n\n if (conf.height) params.size = 'h|' + conf.height;\n else params.size = 'w|' + conf.width;\n\n if (conf.quality) params.quality = conf.quality;\n\n return imgSvcPath + '?' + $.param(params);\n }\n\n // Let's append our API to the namespace\n\n ns.getSizedUrl = function(options) {\n if ('undefined' === typeof options.src) {\n console.error('upi.Services.Image::getSizedUrl configuration options must provide an image src string')\n }\n return buildResourcePath('GetResizedImage', options)\n };\n\n ns.getSizedUrlForSku = function(skuId, options) {\n if ('undefined' === typeof skuId) {\n console.error('upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID')\n }\n options = options || {};\n options['skuId'] = skuId;\n return buildResourcePath('GetResizedSkuImage', options)\n };\n\n // Change your namespace to something else. Image is already taken.\n // Image is the constructor for making image elements with JS.\n}(this.MyImage = this.MyImage || {}))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:04:53.467",
"Id": "47922",
"ParentId": "47918",
"Score": "5"
}
},
{
"body": "<p>Immutability is one of the cornerstones of functional programming.</p>\n\n<p><code>getSizedUrlForSku</code> mutates it's argument and hence violates immutability. It's better to make a copy of <code>options</code> here.</p>\n\n<pre><code>var getSizedUrlForSku = function( skuId, options ){\n // ...\n optionsCopy = $.extend( {skuId: skuId}, options )\n return buildResourcePath( 'GetResizedSkuImage', optionsCopy );\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:53:21.527",
"Id": "47953",
"ParentId": "47918",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T20:50:53.737",
"Id": "47918",
"Score": "6",
"Tags": [
"javascript",
"functional-programming",
"url"
],
"Title": "Refactor module for calls to internal image service"
} | 47918 |
<p>I have a question regarding a program that is to run an alarm clock and display the time (HH:MM AM/PM) and also trigger the alarm and display "ringing" at 12:00 AM.</p>
<p>I am a beginner in Java and I am a little lost. I believe I have most of the skeletal work done. This is much like another question asked on here but I could not find an answer to my problems. So I apologize for the similarity. I am also to create a "dummy driver" in order to test the method as one of the requirements for this program is to be able to be read by a general driver someone else has created. Therefore, all of my variables and methods must be left the way I have them in order to be read by said driver. I wish I could be a little more specific in what I need assistance with but any feedback you can give me is much appreciated.</p>
<p>This is what I've got so far:</p>
<pre><code>//dummy driver
package program5;
public class Program5 {
public static void main(String[] args) {
AlarmClock alarm = new AlarmClock();
System.out.println(alarm.getHour() + ":" + alarm.getMinute() + alarm.getAmOrPM());
System.out.println(alarm.getAlarmHour() + ":" + alarm.getAlarmMinute() + alarm.getAlarmAmOrPm());
System.out.println(alarm.isIsAlarmRinging());
}
}
package program5;
public class AlarmClock {
private int hour;
private int minute;
private String amOrPm;
private int alarmHour;
private int alarmMinute;
private String alarmAmOrPm;
private boolean isAlarmRinging;
//constructor:
AlarmClock() {
hour = 12;
alarmHour = 12;
minute = 0;
alarmMinute = 0;
alarmAmOrPm = new String();
amOrPm = new String();
isAlarmRinging = false;
}
//getters:
public int getHour() {
if ((hour >= 1) && (hour <= 12)) {
}
return hour;
}
public int getMinute() {
if ((minute >= 0) && (minute <= 59)) {
}
return minute;
}
public String getAmOrPM() {
return amOrPm;
}
public int getAlarmHour() {
return alarmHour;
}
public int getAlarmMinute() {
return alarmMinute;
}
public String getAlarmAmOrPm() {
return alarmAmOrPm;
}
public boolean isIsAlarmRinging() {
if (hour >= 12){
isAlarmRinging = true;
}
return isAlarmRinging;
}
//setters
public void setHour(int newHour) {
if ((newHour >= 1) && (newHour <= 12)) {
hour = newHour;
}
}
public void setMinute(int newMinute) {
if ((newMinute >= 0) && (newMinute <= 59)) {
minute = newMinute;
}
}
public void setAmOrPM(String newAmOrPm) {
amOrPm = newAmOrPm;
}
public void setAlarmHour(int newAlarmHour) {
if ((newAlarmHour >= 1) && (newAlarmHour <= 12)) {
alarmHour = newAlarmHour;
}
}
public void setAlarmMinute(int newAlarmMinute) {
if ((newAlarmMinute >= 0) && (newAlarmMinute <= 59)) {
alarmMinute = newAlarmMinute;
}
}
public void setAlarmAmOrPm(String newAlarmAmOrPm) {
alarmAmOrPm = newAlarmAmOrPm;
}
public void setIsAlarmRinging(boolean isAlarmRinging) {
if (isAlarmRinging = true) {
System.out.println("Ringing!");
}
}
public void advanceOneMinute() {
minute++;
if (minute == 59) {
hour++;
}
}
public void advanceMinutes(int minutesToAdvance) {
}
public void advanceOneHour() {
hour++;
if (hour > 12) {
hour = 1;
}
}
public void advanceHours(int hoursToAdvance) {
}
public void setTime(int newHour, int newMinute, String newAmOrPm) {
hour = newHour;
amOrPm = newAmOrPm;
}
public void setAlarmTime(int newAlarmHour, int newAlarmMinute, String newAlarmAmOrPm) {
if(hour >=0 && hour <= 23 && minute >=0 && minute <= 59) {
newAlarmHour = hour;
newAlarmMinute = minute;
}
}
public void turnOffAlarm() {
isAlarmRinging = false;
}
public void displayTime() {
}
public void displayAlarmTime() {
}
}
</code></pre>
<p>It's far from done but it's a start. If you can tell me anything I can do, I'll be very thankful. I'm not sure exactly what my question is. Just if I'm on the right track and what I'm doing wrong. Sorry it's not a short, concise, clear-cut question.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:04:55.480",
"Id": "84046",
"Score": "2",
"body": "Here on [codereview.se] we are used to long questions don't worry too much about it. Welcome, btw. I hereby also invite you to our [chat], feel free to drop in now and then ;)"
}
] | [
{
"body": "<p>One bug is that your constructor initializes the clock to an invalid state: <code>amOrPm</code> is set to an empty string.</p>\n\n<p>You keep a seven state variables: <code>hour</code>, <code>minute</code>, <code>amOrPm</code>, <code>alarmHour</code>, <code>alarmMinute</code>, <code>alarmAmOrPm</code>, <code>isAlarmRinging</code>. Maintaining <code>hour</code> and <code>minute</code> separately, doing the carrying manually, is troublesome.</p>\n\n<p>I suggest paring that down to three: <code>time</code>, <code>alarmTime</code>, <code>isAlarmRinging</code>. Keep time as the number of minutes since midnight.</p>\n\n<pre><code>public class AlarmClock {\n // Time, in minutes since midnight\n private int time;\n\n private static final int MINUTES_PER_12_HOURS = 12 * 60,\n MINUTES_PER_DAY = 24 * 60;\n\n /**\n * Returns the hour, between 1 and 12 inclusive.\n */\n public int getHour() {\n int h = (this.time / 60) % 12;\n return (h == 0) ? 12 : h;\n }\n\n public int getMinute() {\n return this.time % 60;\n }\n\n public String getAmOrPm() {\n return (this.time < MINUTES_PER_12_HOURS) ? \"AM\" : \"PM\";\n }\n\n public void advanceOneHour() {\n this.time = (this.time + 60) % MINUTES_PER_DAY;\n }\n\n …\n}\n</code></pre>\n\n<p>You don't even need an explicit constructor! The default values will cause the time to be initialized to midnight.</p>\n\n<p>I'll leave it to you to fill in the rest.</p>\n\n<p>Watch the consistency of your capitalization in <code>getAmOrPM()</code>. Either <code>getAMOrPM()</code> or <code>getAmOrPm()</code> would be acceptable; I prefer the latter, especially since it matches the way you named your <code>amOrPm</code> variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:41:12.433",
"Id": "47928",
"ParentId": "47921",
"Score": "3"
}
},
{
"body": "<p>I'm not too familiar with Java, so I won't review any specific aspect of that. I just want to address the lack of indentation in this code, which is very important.</p>\n\n<p>Let's take the first portion of your code:</p>\n\n<pre><code>public class Program5 {\n\npublic static void main(String[] args) {\nAlarmClock alarm = new AlarmClock();\nSystem.out.println(alarm.getHour() + \":\" + alarm.getMinute() + alarm.getAmOrPM());\nSystem.out.println(alarm.getAlarmHour() + \":\" + alarm.getAlarmMinute() + alarm.getAlarmAmOrPm());\nSystem.out.println(alarm.isIsAlarmRinging());\n}\n}\n</code></pre>\n\n<p>Whenever you have something inside of <code>{}</code> that are on multiple lines, the code within the <code>{}</code> should be indented so that readers will know that the code belongs in this block. In this code portion, it's hard to tell what belongs inside of what because everything is aligned towards the side.</p>\n\n<p>In this portion, when you have a line that opens with a <code>{</code>, such as</p>\n\n<pre><code>public class Program5 {\n</code></pre>\n\n<p>the code within this containment should be indented. The number of spaces to indent by is not concrete and mostly depends on the environment and language. In this answer, I will use four spaces.</p>\n\n<p>If we follow this idea of indentation, that code portion should look like this:</p>\n\n<pre><code>public class Program5 {\n\n public static void main(String[] args) {\n AlarmClock alarm = new AlarmClock();\n System.out.println(alarm.getHour() + \":\" + alarm.getMinute() + alarm.getAmOrPM());\n System.out.println(alarm.getAlarmHour() + \":\" + alarm.getAlarmMinute() + alarm.getAlarmAmOrPm());\n System.out.println(alarm.isIsAlarmRinging());\n }\n}\n</code></pre>\n\n<p>There are two <code>{</code>, so the following code for each of those statements is indented. You can now see what belongs to what, thereby increasing readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:46:02.483",
"Id": "47929",
"ParentId": "47921",
"Score": "3"
}
},
{
"body": "<h1>Calendar</h1>\n\n<p>You created an alarmclock, which is really just a time-representation. A <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html\"><code>Calendar</code></a> has both a date and time component. I strongly, strongly suggest you use that so you can let your user define how he wants his date represented and let the API handle fancy stuff like timezones, summer hours, etc.</p>\n\n<p>You can also look into the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/\">Java 8 time API</a> but I think that might not be appropriate yet.</p>\n\n<h1>Enums</h1>\n\n<p>When you have a limited set of different possibilities, your mind should immediately wander to <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\">enums</a>. This way you can represent your AM/PM by saying <code>DayPart.AM</code> and <code>DayPart.PM</code> instead of the literal string \"AM\" which could mistakenly be used as \"aM\", \"am\", \"AX\", etc. It will provide compile-time safety and is a lot more pleasant to work with.</p>\n\n<h1>Indentation</h1>\n\n<p>Stick to conventions. Some people indent a block with one tab (or 4 spaces), <a href=\"http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.2-block-indentation\">some with 2 spaces</a>. This will keep the code readable for everyone.</p>\n\n<h1>Methods without a meaningful body</h1>\n\n<p>Look at your code here:</p>\n\n<pre><code>public int getHour() {\nif ((hour >= 1) && (hour <= 12)) {\n}\nreturn hour;\n}\n</code></pre>\n\n<p>With formatting this becomes this:</p>\n\n<pre><code>public int getHour() {\n if ((hour >= 1) && (hour <= 12)) {\n }\n\n return hour;\n}\n</code></pre>\n\n<p>Can you tell what's wrong here? Note that there are several methods that have this construct!</p>\n\n<h1>Assignment vs Comparison</h1>\n\n<p>This is a very common mistake:</p>\n\n<pre><code>if (isAlarmRinging = true)\n</code></pre>\n\n<p>What you do here is set <code>isAlarmRinging</code> to <code>true</code>, you never compare it. </p>\n\n<p>Keep in mind:</p>\n\n<ul>\n<li>Comparison: <code>==</code>.</li>\n<li>Assignment: <code>=</code>.</li>\n</ul>\n\n<h1>Unused parameters</h1>\n\n<p>In your method <code>setTime</code> you never use the parameter <code>newMinute</code>.<br>\nLikewise in method <code>setAlarmTime</code> you never use <code>newAlarmAmOrPm</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:28:45.643",
"Id": "84068",
"Score": "0",
"body": "A `Calendar` represents a datetime. Here, we want a time without any specific date."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:31:15.040",
"Id": "84069",
"Score": "0",
"body": "Yeah, but in essence that doesn't make a difference. You want the time of the next day (or however much you look into the future with your alarm). Just because the user doesn't explicitly state the day, doesn't mean it's not appropriate. It shouldn't change the functionality at all but it will make handling times, timezones, representations, etc a lot easier."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:46:51.103",
"Id": "47930",
"ParentId": "47921",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T21:51:03.340",
"Id": "47921",
"Score": "7",
"Tags": [
"java",
"beginner",
"datetime"
],
"Title": "Alarm clock with \"ringing\" functionality"
} | 47921 |
<p>Please be super brutal, and treat this as a top technical interview.</p>
<p>Worst case analysis: \$O(n)\$ (please confirm)</p>
<p>Space complexity: \$O(n)\$</p>
<blockquote>
<p><strong>Problem:</strong></p>
<p>Given an absolute path for a file (Unix-style), simplify it.</p>
<p>For example:</p>
<pre><code>path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"
</code></pre>
<p>Corner Cases: Did you consider the case where path = <code>/../</code>? In this
case, you should return <code>/</code>. Another corner case is the path might
contain multiple slashes <code>/</code> together, such as <code>/home//foo/</code>. In this
case, you should ignore redundant slashes and return <code>/home/foo</code>.</p>
</blockquote>
<p>My attempt:</p>
<pre><code>private static String simplifyPath(String path) {
Deque<String> pathDeterminer = new ArrayDeque<String>();
String[] pathSplitter = path.split("/");
StringBuilder absolutePath = new StringBuilder();
for(String term : pathSplitter){
if(term == null || term.length() == 0 || term.equals(".")){
/*ignore these guys*/
}else if(term.equals("..")){
if(pathDeterminer.size() > 0){
pathDeterminer.removeLast();
}
}else{
pathDeterminer.addLast(term);
}
}
if(pathDeterminer.isEmpty()){
return "/";
}
while(! pathDeterminer.isEmpty()){
absolutePath.insert(0, pathDeterminer.removeLast());
absolutePath.insert(0, "/");
}
return absolutePath.toString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:59:05.220",
"Id": "84061",
"Score": "0",
"body": "Have you though of 'cd /;cd ../../A/AA/' Where does that go? Or more specifically '/../../A/AA/'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:01:43.820",
"Id": "84062",
"Score": "0",
"body": "Rather than build a string. Build an array of path segments. If you hit a path segment of '.' (or the empty segment) don't add it. If you hit a path segment of '..' pop the last element (if one exists). Once you have parsed all the path segments and added them to the array you can just pull them back together into a string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:47:28.457",
"Id": "84070",
"Score": "0",
"body": "It might be worth adding a pre-check for some of the cases you handle. I am thinking scanning the string for . or // before making any copies will give you a very quick return on paths that are not complex. Reading through a string is much faster than copying it every case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:48:39.680",
"Id": "84128",
"Score": "0",
"body": "Not sure what being \"super brutal\" means, but in an interview, I'd repsond to this with something based on `URI.create(path).normalize().getPath()`..."
}
] | [
{
"body": "<p>Overall, it is very easy to read and understand your code. I think that you make good choices of data structures.</p>\n\n<p>A few things:</p>\n\n<ul>\n<li><p>I'm not very fond of your spacing formatting, but at least you're consistent which makes this a minor issue. I prefer, and the Java styling conventions is, <code>while (!pathDeterminer.isEmpty()) {</code></p></li>\n<li><p><code>if(term == null</code> will never happen. As <code>pathSplitter</code> is a String array acquired from using <code>.split</code> on a regular string, there will be no null entries in the array.</p></li>\n<li><p><code>term.length() == 0</code> and <code>if(pathDeterminer.size() > 0){</code> - use <code>.isEmpty()</code> instead.</p></li>\n<li><p><code>/*ignore these guys*/</code> I would use a <code>continue;</code> to make it more clear that they really should be ignored, or use this:</p>\n\n<pre><code>if (term.equals(\"..\")) {\n if (!pathDeterminer.isEmpty())\n pathDeterminer.removeLast();\n}\nelse if (!term.isEmpty() && !term.equals(\".\")) {\n pathDeterminer.addLast(term);\n}\n</code></pre></li>\n</ul>\n\n<p>Regarding the complexities: Yes, I agree that those are \\$O(n)\\$.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:30:53.240",
"Id": "47926",
"ParentId": "47923",
"Score": "6"
}
},
{
"body": "<p>Within the limits of the instructions, this is a good solution, but could do with some tweaks.</p>\n\n<p>I would start with challenging the assumptions a little bit. Even if you don't handle the odd cases, I would still mention them. The things I am think of, when I hear <em>\"Given an absolute path for a file (Unix-style)\"</em> are:</p>\n\n<ul>\n<li>escaped slashes <code>path/to/file\\/with\\/slash.in.name</code></li>\n<li>well, that's about it, actually... other unix-like special cases probably would not affect this code.</li>\n</ul>\n\n<p>So, I would probably handle the escaped-backslash, probably with a negative-look-behind on the split regex <code>path.split(\"(?!\\\\\\\\)/\")</code>....</p>\n\n<p>Then, I dislike the <code>insert(0, ...)</code> use of the StringBuilder. Because I know the internals of StringBuilder, I know that it is faster to append. I would treat the StringBuilder differently to you in 2 ways:</p>\n\n<ol>\n<li><p>Set the initial size:</p>\n\n<pre><code>StringBuilder absolutePath = new StringBuilder(path.length());\n</code></pre></li>\n<li><p>Append values from the other end of the Deque</p>\n\n<pre><code>while(! pathDeterminer.isEmpty()){\n absolutePath.append(\"/\");\n absolutePath.append(0, pathDeterminer.removeFirst());\n} \n</code></pre></li>\n</ol>\n\n<p>Because your code uses the StringBuilder.insert(0, ...) mechanism, and because that is an \\$O(n)\\$ operation (because it has to move all the other characters that come after the inserted value), the overall complexity of the code is not \\$O(n)\\$, but rather \\$O(n^2)\\$. Changing to an append will bring the code back (closer) to \\$O(n)\\$, where each character is copied only once....</p>\n\n<p>See the differences between:</p>\n\n<ul>\n<li><a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28java.lang.String%29\">StringBuilder.append()</a></li>\n<li><a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.insert%28int,java.lang.String%29\">StringBuilder.insert(0, ...)</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:44:28.220",
"Id": "84055",
"Score": "0",
"body": "how does your stringbuilder approach improve performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:47:49.357",
"Id": "84057",
"Score": "1",
"body": "Compare the [insert logic](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.insert%28int%2Cjava.lang.String%29) which does a System.arrayCopy() to move the characters, to the [append logic](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28java.lang.String%29) which does not. Essentially, the insert adds an order of complexity"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T01:49:31.347",
"Id": "84078",
"Score": "0",
"body": "I did not know that, wow!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:34:05.767",
"Id": "47927",
"ParentId": "47923",
"Score": "7"
}
},
{
"body": "<p>I would expect the function to work with either absolute or relative paths. If I pass it a relative path as a parameter, I expect a relative path returned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:53:09.987",
"Id": "47934",
"ParentId": "47923",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47927",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:11:05.660",
"Id": "47923",
"Score": "7",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Simplifying a path"
} | 47923 |
<blockquote>
<p>We shall say that an n-digit number is pandigital if it makes use of
all the digits 1 to n exactly once; for example, the 5-digit number,
15234, is 1 through 5 pandigital.</p>
<p>The product 7254 is unusual, as the identity, 39 × 186 = 7254,
containing multiplicand, multiplier, and product is 1 through 9
pandigital.</p>
<p>Find the sum of all products whose multiplicand/multiplier/product
identity can be written as a 1 through 9 pandigital.</p>
<p>HINT: Some products can be obtained in more than one way so be sure to
only include it once in your sum.</p>
</blockquote>
<p>I need help on making this code faster. Right now I'm using double nested for-loops; is there a way I can change that?</p>
<pre><code>from timeit import default_timer as timer
start = timer()
products = set()
for a in range(12, 100):
for b in range(102, 1000): # to get 9-digit: 2-digit * 3-digit
product = a * b
digits = list(str(a) + str(b) + str(product))
digits = [int(x) for x in digits]
if sorted(digits, key = int) == range(1, 10):
products.add(product)
for a in range(1, 10):
for b in range(1023, 10000): # other option is 1-digit * 4-digit
product = a * b
digits = list(str(a) + str(b) + str(product))
digits = [int(x) for x in digits]
if sorted(digits, key = int) == range(1, 10):
products.add(product)
ans = sum(list(products))
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [] | [
{
"body": "<p>As far as I know Project Euler problems, a brute force approach just doesn't work. So, we shouldn't code code, but rather an algorithm review.</p>\n\n<p>An immediate thing coming to mind is that you test too many knowingly impossible combinations of <code>a</code> and <code>b</code>. They together must be composed of different digits, which you may test prior to multiplication.</p>\n\n<p>My suggestion would be to create an iterator supplying numbers composed by different digits (from a given set - for <code>b</code> the digit set doesn't include digits used in <code>a</code>), and test the product being composed by what's left. </p>\n\n<p>That <em>may</em> give you a significant speedup. May be, more math insight is required.</p>\n\n<p>PS: once digits for <code>a</code> are selected, you may limit the range in which a product may fall, which in turn limits the possible range for <code>b</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T00:54:59.180",
"Id": "47940",
"ParentId": "47931",
"Score": "3"
}
},
{
"body": "<p>Since you know that all of the non-zero digits must be present in the answer, you can skip most of the numbers in the range. That is, it's pointless to do a test multiplication of 22*3333 because those both repeat digits. </p>\n\n<p>So what is needed is an efficient way to run through all of the permutations of digits quickly, and fortunately, Python's <code>itertools</code> provides exactly that.</p>\n\n<pre><code>import itertools\nstart = timer()\nproducts = set()\ndef makeint(n):\n return int(''.join(map(str,n)))\n\ntarget = range(1,10)\nd = itertools.permutations(target, 5)\nfor a in d:\n product = makeint(a[:2])*makeint(a[2:])\n if sorted(list(a)+map(int,str(product))) == target:\n products.add(product)\n product = makeint(a[:1])*makeint(a[1:])\n if sorted(list(a)+map(int,str(product))) == target:\n products.add(product)\n\nans = sum(list(products))\n</code></pre>\n\n<p>The way this works is to pick off permutations 5 digits at a time and then group as 2 and 3 or as 1, 4 as you have done. There are other refinements one can make, such as skipping every number which ends in a 5 (because 5*n will always end in either 0, which is not in the range, or 5 which would be a duplicate digit), but I'll leave such refinements to you.</p>\n\n<p>As it stands, this code runs almost 8x faster than the original.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T01:06:33.763",
"Id": "47941",
"ParentId": "47931",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:59:04.880",
"Id": "47931",
"Score": "4",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "How to make Project Euler 32 in Python faster?"
} | 47931 |
<p>Some recursive code is part of a particularly slow path of a project. Out of curiosity I was playing around with reimplementing the code using stack context iteration instead of recursion. Below are snippets reduced to just the iteration patterns of tree elements using a DOM structure for simplicity. </p>
<p>I was surprised <a href="http://jsperf.com/recursion-vs-iteration-852/4">when benchmarking the code</a> that the recursive variant was faster than iterative approaches. Is there a flaw in my implementations (they each iterate the same number of elements to the same depth)? The snippets aren't strictly equivalent in the order they touch the elements though I doubt that effects the performance.</p>
<hr>
<p><strong>Recursive depth first approach</strong></p>
<pre><code>function iterate(current, depth) {
var children = current.childNodes;
for (var i = 0, len = children.length; i < len; i++) {
iterate(children[i], depth + 1);
}
}
iterate(parentElement, 0);
</code></pre>
<p><strong>Iterative breadth first forwards</strong></p>
<pre><code>var stack = [{
depth: 0,
element: treeHeadNode
}];
var stackItem = 0;
var current;
var children, i, len;
var depth;
while (current = stack[stackItem++]) {
//get the arguments
depth = current.depth;
current = current.element;
children = current.childNodes;
for (i = 0, len = children.length; i < len; i++) {
stack.push({ //pass args via object or array
element: children[i],
depth: depth + 1
});
}
}
</code></pre>
<p><strong>Iterative breadth first backwards approach</strong></p>
<pre><code>var stack = [{
depth: 0,
element: treeHeadNode
}];
var current;
var children, i, len;
var depth;
while (current = stack.pop()) {
//get the arguments
depth = current.depth;
current = current.element;
children = current.childNodes;
for (i = 0, len = children.length; i < len; i++) {
stack.push({ //pass args via object or array
element: children[i],
depth: depth + 1
});
}
}
</code></pre>
<hr>
<p>I was expecting the second snippet to be fastest in JS (no array popping), is there opportunity for further optimization to improve the performance of the iterative approach? I believe part of the slowness is creating the arguments in an object (i.e. <code>{depth: depth+1,element: someElement}</code>). The recursive snippet is more intuitive and explicit and may benefit from tail recursion in ES6 interpretors.</p>
<p>Repeating myself, is there a more performant way to iterate <code>tree</code> data structures in JavaScript than recursively?</p>
<p><a href="http://jsperf.com/recursion-vs-iteration-852/4"><strong>JSPerf comparing the snippets</strong></a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T00:13:35.967",
"Id": "84072",
"Score": "0",
"body": "Have you tried profiling the routines, perhaps with Google Chrome's developer tools or something like that? That should tell you where most of the time is being spent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:29:29.510",
"Id": "84093",
"Score": "0",
"body": "One thing the v8 developers mentioned as a particular performance pain point was altering the \"shape\" of an object by adding/removing properties. They found it much faster to set a property to `null` which simply changes the property's value than `delete` it which removes it from the object entirely, altering its shape. The object the property references is garbage collected either way, so there's no memory penalty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:42:55.077",
"Id": "84126",
"Score": "0",
"body": "What is `depth` for? I see no use of it, besides adding up while it runs through the tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:49:09.643",
"Id": "84129",
"Score": "0",
"body": "@JosephtheDreamer its just a random variable there to make the solution more useful than passing only one state variable to the next operation. Haven't profiled the operations in much depth, only checked memory, thanks for the suggestion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-10T11:45:24.633",
"Id": "119703",
"Score": "1",
"body": "Perhaps the recursive version performance is due to compiler tail recursion optimization?\nhttp://taylodl.wordpress.com/2013/06/07/functional-javascript-tail-call-optimization-and-trampolines/"
}
] | [
{
"body": "<p>I would have completely agreed with the idea that iterative should be faster than recursive, I have seen proof to that effect many times in other languages. It is however harder to read. Here however, in JavaScript perhaps it is not, at least the benchmarks seem to suggest that the necessary object creation outweighs the function call overhead.</p>\n\n<p>To that end these two examples based on yours illustrate that it is the object creation, and array manipulation that lead to the lower performance of the iterative approach. These two examples leverage the objects being iterated to create a linked list of those objects. This has the downside that it modifies each object traversed and so may not be desirable, beyond illustrating the performance difference.</p>\n\n<p>Within a margin of error, these methods outperform the optimized recursive algorithm.</p>\n\n<p>Breadth-First </p>\n\n<pre><code>// simulates operations for walking through tree using iteration\nparentElement.depth = 0;\nparentElement.next = null;\n\nvar children, i, len;\nvar depth;\ncurrent = parentElement;\nwhile (current) {\n depth = current.depth;\n children = current.childNodes;\n //removes this item from the linked list\n current = current.next;\n for (i = 0, len = children.length; i < len; i++) {\n child = children[i];\n child.depth = depth+1;\n //place new item at the head of the list\n child.next = current;\n current = child;\n }\n}\n</code></pre>\n\n<p>Depth-First</p>\n\n<pre><code>// simulates operations for walking through tree using iteration\nparentElement.depth = 0;\nparentElement.next = null;\n\nvar children, i, len;\nvar depth;\nvar current,last;\ncurrent = parentElement;\nlast = current;\n\nwhile (current) {\n children = current.childNodes;\n for (i = 0, len = children.length; i < len; i++) {\n child = children[i];\n child.depth = current.depth+1;\n child.next = null;\n //place new item at the tail of the list\n last.next = child;\n last = child;\n }\n //removes this item from the linked list\n current = current.next;\n}\n</code></pre>\n\n<p><a href=\"http://jsperf.com/recursion-vs-iteration-852/5\">JSPerf Comparison</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:44:17.703",
"Id": "84081",
"Score": "0",
"body": "You have a couple global variables (`current`) in the jsperf which may be hurting the performance a tad. I'm not sure creating a sll on top of the nodes is fair for the users as they may not be expecting the `next` property on their tree objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:04:17.673",
"Id": "84086",
"Score": "2",
"body": "Globals were as in the original jsperf. I noted the modification of the elements as the problem with this approach and suggested it only for demonstration purposes, as I do not think you can beat the performance of the recursive approach otherwise. The function stacks are far to optimized to be beat by an array used as a stack with new objects being created on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:29:03.417",
"Id": "84092",
"Score": "0",
"body": "Ya, probably true - I'm actually amazed your iterative approach doesn't beat recursion (even in ie8!)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:33:01.360",
"Id": "84095",
"Score": "0",
"body": "The results might vary depending on actual code, for instance, the recursive example here has very few local variables which reduces the function stack overhead. A function that was actually processing each node might have significantly more overhead. This overhead might be enough to change performance characteristics between the two implementations. Further, the recursive approach will likely use a greater amount of memory, as recursion depth increases, and as those local vars cannot be reused by each iteration."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:27:30.143",
"Id": "47943",
"ParentId": "47932",
"Score": "11"
}
},
{
"body": "<p>This question is a couple of years old but it came up in Google and I don't see a satisfying answer, so here goes.</p>\n\n<p>The recursive version is fast because the only overhead it has is the function call. When recursion is slower than iteration that small overhead is usually the reason. However in this case the iterative version has to do a lot of extra work as the data is in a recursive shape.</p>\n\n<p>To optimize the execution of any code that depends on a recursive data structure you should look into replacing the structure or - in case that is infeasible - caching the data into an array for faster iteration. When even that is not possible recursion is likely your best bet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-15T16:36:37.407",
"Id": "150000",
"ParentId": "47932",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:01:05.667",
"Id": "47932",
"Score": "29",
"Tags": [
"javascript",
"performance",
"recursion",
"tree",
"iteration"
],
"Title": "Recursion vs iteration of tree structure"
} | 47932 |
<p>I am creating a converter for use in a Windows 8 XAML app (MVVM). As you can see in the code below, the converter is used to convert a bool into one of two strings from a language resource file.<br>
My question is, is it better to create one instance of <code>ResourceLoader</code> for the converter class or should I continue creating new instances each time the method is called?</p>
<pre><code>class BooleanToBudgetYearStringConverter : IValueConverter
{
private const string CALENDAR = "BudgetCycle_Calendar",
FISCAL = "BudgetCycle_Fiscal";
private Windows.ApplicationModel.Resources.ResourceLoader loader;
public object Convert(object value, Type targetType, object parameter, string language)
{
string entryName = (value is bool && (bool)value) ? CALENDAR : FISCAL; //The name of the entry desired from the entry file.
return new Windows.ApplicationModel.Resources.ResourceLoader().GetString(entryName);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return (value is string && (string)value == new Windows.ApplicationModel.Resources.ResourceLoader().GetString(CALENDAR));
}
}
</code></pre>
<p>I am specifically concerned about speed and memory use.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T01:39:58.003",
"Id": "84077",
"Score": "2",
"body": "Are you sure you should be newing up ResourceLoader objects at all? It seems like [Windows.ApplicationModel.Resources.ResourceLoader](http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.resources.resourceloader.aspx) has static methods on it for getting access to ResourceLoader objects in a singleton manner already. Have you tried using Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView().GetString(entryName) instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:22:52.557",
"Id": "84090",
"Score": "0",
"body": "If the tools support it, neither: let the framework manage and provide instances as appropriate. Not only is this better for client code; it also supports encapsulation, performance, and testing. If not, consider the cost of instantiation (probably negligible) before picking the better choice."
}
] | [
{
"body": "<h1>Use an Attribute</h1>\n\n<p>The class should be tagged with:</p>\n\n<pre><code>[ValueConversion(typeof(Boolean), typeof(String))]\n</code></pre>\n\n<p>If it's of the normal, old-school .NET variety (desktop, client profile, WP8). Windows store apps don't appear to have an analogous attribute in their .NET libraries, and thus this recommendation can be ignored when compiling such a program.</p>\n\n<h1>Drop Type Checks</h1>\n\n<p>If the passed-in value is not of the expected type, you should not do your conversion; you should allow an exception to be thrown, so that you know an invalid binding has taken place (and you can go correct the offending code). This applies to both conversion and back-conversion.</p>\n\n<h1>Explicit Back Conversion</h1>\n\n<p>Check for an explicit match -- don't default to returning \"false\" on a non-match with the CALENDAR string. Instead, check that the input string matches with the FISCAL string. Throw an exception if the input string matches neither acceptable string.</p>\n\n<h1>Use a Singleton</h1>\n\n<p>The documentation for <code><a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.resources.resourceloader.aspx\" rel=\"nofollow\">Windows.ApplicationModel.Resources.ResourceLoader</a></code> implies that the <a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/br206020.aspx\" rel=\"nofollow\">default constructor</a> you're using should result in an object that is identical in function to the one available from the static <code><a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/dn297371.aspx\" rel=\"nofollow\">GetForCurrentView()</a></code> function. If not, then set up your own singleton pattern to ensure that you have at most one shared copy of the resource object around at any given time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:32:01.590",
"Id": "84079",
"Score": "0",
"body": "+1 nice answer. I think the converter will still work without the attribute, care to expand on what the role of the `ValueConversionAttribute` is?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:40:36.843",
"Id": "84080",
"Score": "1",
"body": "@Mat'sMug It's a clear (and machine readable) declaration of intent, so nobody has to guess. From [the documentation](http://msdn.microsoft.com/en-us/library/system.windows.data.valueconversionattribute.aspx), \"When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion[...].\" Now, as to what specific tools use it, and how they use it, I don't know. I would assume it helps prevent bogus bindings. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:14:22.263",
"Id": "84181",
"Score": "0",
"body": "For some reason `System.Windows.Data` and hence `ValueConversion` is not available in my Windows 8.1 app."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:04:29.180",
"Id": "84190",
"Score": "0",
"body": "@Trisped Well, that's confusing, because [IValueConverter](http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=vs.110%29.aspx) is in System.Windows.Data. Are you referencing the PresentationFramework assembly from your project? Can you provide the fully-qualified name of the IValueConverter you're deriving from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:16:38.750",
"Id": "84191",
"Score": "0",
"body": "@TravisSnoozy `Windows.UI.Xaml.Data.IValueConverter`. My project is referencing \".NET for Windows Store apps\" and \"Windows\" which are the only two things I can reference in this type of application (except for other solutions and third party dlls)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:37:55.440",
"Id": "84197",
"Score": "2",
"body": "@Trisped Ah, right, _that_ little nightmare. It doesn't appear that they ported that attribute over to the new flavor of .NET libraries. My apologies; I didn't realize you meant Metro (er... \"windows store\") app when you said \"Windows 8.\" It's even more confusing in that the (non-store-app) MSDN page says this attribute is supported in the Win8 phone, as well as in the client profile... so it's a mystery to me why it's dropped from the windows store app API. :/"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:13:58.423",
"Id": "47942",
"ParentId": "47938",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code>private const string CALENDAR = \"BudgetCycle_Calendar\",\n FISCAL = \"BudgetCycle_Fiscal\";\n</code></pre>\n</blockquote>\n\n<p>Would be much prettier as two instructions:</p>\n\n<pre><code>private const string CALENDAR = \"BudgetCycle_Calendar\";\nprivate const string FISCAL = \"BudgetCycle_Fiscal\";\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>private Windows.ApplicationModel.Resources.ResourceLoader loader;\n</code></pre>\n</blockquote>\n\n<p>Given <code>using Windows.ApplicationModel.Resources;</code>, the above declaration can be simplified to:</p>\n\n<pre><code>private ResourceLoader loader;\n</code></pre>\n\n<p>The variable is declared, but never assigned, and isn't used anywhere.</p>\n\n<p>I'd take <a href=\"https://codereview.stackexchange.com/questions/47938/is-it-better-to-create-a-class-instance-or-create-an-instance-each-time-a-metho#comment84077_47938\">@Travis' advice</a> and assign it like this:</p>\n\n<pre><code>private ResourceLoader loader = ResourceLoader.GetForCurrentView();\n</code></pre>\n\n<p>This greatly improves the readability of your <code>return</code> statements:</p>\n\n<pre><code>return loader.GetString(entryName);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>return (value is string && value.ToString() == loader.GetString(CALENDAR));\n</code></pre>\n\n<p><sub>(follow <a href=\"https://codereview.stackexchange.com/a/47942/23788\">@Travis' advice here too</a>, about explicit back conversion / well, his entire answer actually)</sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T02:32:26.263",
"Id": "47944",
"ParentId": "47938",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47942",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T00:11:40.253",
"Id": "47938",
"Score": "3",
"Tags": [
"c#",
"performance"
],
"Title": "Is it better to create a class instance, or create an instance each time a method is called?"
} | 47938 |
<p>I somehow acquired the idea that I should reduce the number of trips to the database as much as possible and so I use a lot of very long queries. </p>
<p>For example, I had a function that does this:</p>
<pre><code>$shelf = get_shelves($shop_id)
foreach($shelf)
{
$weight = get_weight($shelf);
}
</code></pre>
<p>Everytime a user "view shop" it will list all the shelves, and when I see the loop, I thought I should "optimise" this, so that I only go to the database once. But I ended up with a long query:</p>
<pre><code>$shelf = "SELECT * FROM shelf WHERE shop_id=?";
$weight = "SELECT tray.shelf_id, SUM(egg.weight) AS total_weight FROM tray LEFT JOIN egg WHERE egg.tray_id=tray.tray_id GROUP BY shelf_id";
$query = "SELECT * FROM ($shelf) AS shelf LEFT JOIN ($weight) AS weight ON shelf.shelf_id=weight.shelf_id";
</code></pre>
<p>With this, I didn't have to <code>get_weight()</code> anymore.</p>
<p>Is this "optimisation" at all, is it acceptable? Is there a rule of thumb so that programmers and <a href="http://www.mysqlperformanceblog.com/2013/07/19/what-kind-of-queries-are-bad-for-mysql/" rel="nofollow">DBA</a> can be happy at the same time?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T04:49:18.547",
"Id": "84101",
"Score": "0",
"body": "If this is an optimization can only be decided by profiling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T05:17:59.777",
"Id": "84104",
"Score": "0",
"body": "@MrSmith42 maybe \"Optimisation\" is not a good word. Maybe what I am looking for are some pitfall to look out for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T10:29:27.400",
"Id": "84272",
"Score": "0",
"body": "Somehow, I can't believe, that the complex query with subselects will be faster than those 2 simple queries. Could you show us some results please? For example running 2 simple queries took ?? ms and running 1 complex query took ?? ms."
}
] | [
{
"body": "<p>You are on the right track about trying to reduce trips to the database. I think the rule of thumb would be: whatever gives the best overall performance ;-)</p>\n\n<p>A single query will almost always outperform <code>N</code> queries. Sometimes you may have the choice between two single queries: one that's extremely complex but loads exactly the data you need, and another that's simple but loads more data than you need and you have to filter the result yourself in code. When the database is heavily loaded, the simple query can be faster.</p>\n\n<p>That said, your final <code>$query</code> is not optimal. This would be better:</p>\n\n<pre><code>SELECT col1, col2 FROM shelf\nLEFT JOIN (\n SELECT tray.shelf_id, SUM(egg.weight) AS total_weight FROM tray\n LEFT JOIN egg USING (tray_id)\n GROUP BY shelf_id\n) AS weight USING (shelf_id)\nWHERE shop_id = ?\n</code></pre>\n\n<p>Of course <code>col1</code> and <code>col2</code> are not real columns, I just wanted to emphasize that you should always write the column names explicitly. It's faster to load only what you really need. It also protects you from changes in the column order.</p>\n\n<p>Also notice that I removed one sub-query, which should also make it faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T05:01:42.760",
"Id": "47948",
"ParentId": "47947",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>I somehow acquired the idea that I should reduce the number of trips\n to the database as much as possible and so I use a lot of very long\n queries.</p>\n</blockquote>\n\n<p>This basically says, that you are worried about response time of database. This matters when the database is not on the same machine as your application, but your application is for example in USA and your database is in Australia. In this case it might be (but does not have to be) better to use one complex query instead of a couple of simple queries.</p>\n\n<p>Optimization of your queries should be done in that way that you actually measure time the queries take to execute. There is no golden rule like: \"putting all simple queries into one complex query is always better\". The result of such \"rule\" can be:</p>\n\n<ul>\n<li>overly complex query</li>\n<li>slow query</li>\n<li>queries which are hard to maintain</li>\n<li>queries which are hard to understand by other developers</li>\n</ul>\n\n<p>Janos mentioned a good point with using <code>SELECT col1, col2, ...</code>, you can find more in depth information about it here: <a href=\"https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful\">Why is SELECT * considered harmful?</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T11:30:47.867",
"Id": "88091",
"Score": "0",
"body": "I deal with applications where the app is in the Americas and the DBs are in Australia. They are not my worst performers. That accolade goes to the chatty apps which constantly bombard the server for the same reference data again and again and again and again. Number of calls *does* matter; but it is only one consideration."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T10:48:43.950",
"Id": "48033",
"ParentId": "47947",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47948",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T04:27:16.227",
"Id": "47947",
"Score": "2",
"Tags": [
"sql",
"mysql",
"mysqli"
],
"Title": "Abusive use of long database query?"
} | 47947 |
<p>Recently, I wrote a Sudoku solver in C++. My program is very hard and was solved in a few seconds. In my opinion, this is slow.</p>
<pre><code>#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int tab_in[9][9] = {{0,0,0,0,0,0,0,1,0},
{4,0,0,0,0,0,0,0,0},
{0,2,0,0,0,0,0,0,0},
{0,0,0,0,5,0,4,0,7},
{0,0,8,0,0,0,3,0,0},
{0,0,1,0,9,0,0,0,0},
{3,0,0,4,0,0,2,0,0},
{0,5,0,1,0,0,0,0,0},
{0,0,0,8,0,6,0,0,0}};
int squares[9][9] = {{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{3,3,3,3,3,3,3,3,3},
{3,3,3,3,3,3,3,3,3},
{3,3,3,3,3,3,3,3,3},
{6,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,6,6,6}};
int tab_out[9][9];
int tab[9][9];
int tab_insert[9][9][10];
int iter=0;
void output_solve();
void load();
bool check(int x, int y, int value);
bool next(int x, int y);
bool solve(int x, int y);
void can_insert();
int main()
{
//load();
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
tab_out[i][j]=tab_in[i][j];
}
}
can_insert();
int a = clock();
if(!solve(0, 0))
{
cout<<"This sudoku is unsolvable!"<<endl;
}
else
{
output_solve();
cout<<"\n"<<iter<<endl;
}
int b = clock();
cout<<(b-a)<<"ms"<<endl;
cout<<iter;
getch();
return 0;
}
bool check(int x, int y, int value)
{
for(int i = 0; i < 9; i++)
{
if (value == tab_out[x][i] || value == tab_out[i][y])
{
return false;
}
}
for (int i = squares[x][y]; i <= squares[x][y]+2; i++)
{
for (int j = squares[y][x]; j <= squares[y][x]+2; j++)
{
/*for (int i = (x/3)*3; i <= ((x/3)*3)+2; i++)
{
for (int j = (y/3)*3; j <= ((y/3)*3)+2; j++)
{*/
if (tab_out[i][j] == value)
{
return false;
}
}
}
return true;
}
bool next(int x, int y)
{
if (x == 8 && y == 8) return true;
else if (x == 8) return solve(0, y + 1);
else return solve(x + 1, y);
}
bool solve(int x, int y)
{
if (tab_in[x][y] == 0)
{
int max = tab_insert[x][y][9];
for(int i = 0; i<max; i++)
{
int val = tab_insert[x][y][i];
if (check(x, y, val))
{
tab_out[x][y] = val;
if (next(x, y)) return true;
}
}
iter++;
tab_out[x][y] = 0;
return false;
}
return next(x, y);
}
void load()
{
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
{
cout<<i+1<<", "<<j+1<<endl;
cin>>tab_in[i][j];
}
}
void output_solve()
{
for(int i=0; i<9; i++)
{ cout<<endl;
if(i%3==0 &&i>0)
{
cout<<"---------------\n";
}
for(int j=0; j<9; j++)
{
if(j%3==0 && j>0) cout<<" | ";
cout<<tab_out[i][j];
}
}
}
void can_insert()
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
for(int k=0; k<9; k++)
{
tab_insert[i][j][k]=0;
}
}
}
for(int i = 0; i<9; i++)
{
for(int j = 0; j<9; j++)
{
if(tab_in[i][j]==0)
{
int count = 0;
for(int k = 1; k<=9; k++)
{
if(check(i, j, k))
{
tab_insert[i][j][count] = k;
count++;
}
}
tab_insert[i][j][9]=count;
}
}
}
}
</code></pre>
<p>How can I optimize this? Where can I find a good Sudoku solver implementation in C/C++?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:10:53.147",
"Id": "84107",
"Score": "1",
"body": "First step is to profile, where the time is spent. Do not waste your time in optimizing parts that are not the bottleneck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:41:35.407",
"Id": "84113",
"Score": "0",
"body": "How can I check?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:10:21.017",
"Id": "84115",
"Score": "1",
"body": "I asked google for you: Linux:http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux WINDOWS: http://stackoverflow.com/questions/67554/whats-the-best-free-c-profiler-for-windows"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:22:47.397",
"Id": "84147",
"Score": "0",
"body": "Do you have to use C++? Another language might be more naturally suited for solving this sort of problem. For example, I've previously written a Sudoku solver in [Jess](http://www.jessrules.com/), which takes care of the optimization problems presented by repeatedly applying multiple strategies to a dataset for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:30:05.280",
"Id": "84151",
"Score": "0",
"body": "@TravisSnoozy: it's not the language. I've implemented a C++ solver that runs about 200x faster than this one, even with much more I/O for showing intermediate results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:55:16.243",
"Id": "84156",
"Score": "0",
"body": "@Edward In short \"you can\" doesn't mean \"it's best\" :). Saying you *can* do it in C++, and you *can* do it faster than this implementation in C++ doesn't negate the fact that C++ is not a DSL for logic. IMHO, a rules-based system implementing, e.g., the [Rete algorithm](http://en.wikipedia.org/wiki/Rete_algorithm), is a superior way to express a sudoku solver. If you want C/C++ to be the backend, that's fine -- use [CLIPS](http://clipsrules.sourceforge.net/). You'll still express rules in the DSL, not C/C++, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:57:49.367",
"Id": "84158",
"Score": "1",
"body": "@TravisSnoozy: I'm sure one could code it in Prolog, too, but that wasn't the question. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:00:09.910",
"Id": "84161",
"Score": "0",
"body": "@Edward Which is why I asked the _author_ if he is bound to C/C++. There are better tools specifically for logic problems just like this one, and knowing if/why he has to use C++ is a legitimate question to have answered."
}
] | [
{
"body": "<p>Here are some comments that will help you write a better program.</p>\n\n<h2>If you're writing C++, use C++</h2>\n\n<p>You have included a number of plain C headers, one of which (<code>conio.h</code>) isn't even a Posix standard. Instead, write C++ instead of C++ in a C style. There are many books that can help with this. I usually recommend <em>The C++ Programming Language, 4th ed.</em> by Bjarne Stroustrup. Generally, though, it involves the use of objects instead of just functions, which brings us to the next point.</p>\n\n<h2>Use classes</h2>\n\n<p>C++ is an object oriented language, and much of its expressiveness derives from that. When you have multiple functions all using the same data structure, as in this code, it's usually a very good hint that the data structure should probably be a <code>class</code> and that the functions should be member functions. </p>\n\n<h2>Avoid global variables</h2>\n\n<p>Global variables are generally <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">a bad idea</a>. They make your code fragile, difficult to understand, maintain and reuse and impossible to multithread. There is no reason that all of the global variables in your program couldn't be gathered neatly together into an object and then the object a local variable within <code>main</code>.</p>\n\n<h2>Comment your code</h2>\n\n<p>It's not very easy to read your code and figure out what algorithm is being used to solve the puzzle. Comments help with that and they also describe the purpose and use of individual functions and variables. Uncommented code is usually not easy to maintain.</p>\n\n<h2>Name functions well</h2>\n\n<p>You have functions called <code>solve</code> and <code>output_solve</code> which give some hint as to their purpose by their name. That's good and just what you want. However, you also have some much more opaque names such as <code>check</code> and <code>can_insert</code> which I might be able to figure out, but without comments the <em>only</em> hint is the function name. Both well-chosen function name and comments are an essential part of the code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting that line in every program is a <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad habit</a> that you should avoid. </p>\n\n<h2>Profile your code</h2>\n\n<p>Finally, after you've cleaned things up, then profile your code. That is, measure which parts are slow and think about the underlying algorithm(s) you're using. Are there better ways of solving the problem? Can you reduce the number of operations or the amount of memory needed? All of these are general ways to speed up a program, but with that said, it's important to make it <strong>correct</strong> first, and then work on speed optimizations. You have the benefit in that you already have a correct, but slow, implementation.</p>\n\n<h2>Think about the user</h2>\n\n<p>In order to solve a different puzzle, one has to encode it and recompile. I see that you wrote a <code>load()</code> function so you were thinking about being able to read in a new puzzle, but that's not implemented, and the way that it's written requires a space between every digit and will spin off into an infinite loop if the user accidentally enters a letter. Think about making that a little more durable and then use it instead of a hard-coded data structure. As a bit of a head start, here's a rewritten <code>load()</code> that will work with your exising program.</p>\n\n<pre><code>void load()\n{\n std::string line;\n for(int i=0; i<9; i++) {\n std::getline(std::cin, line);\n for(int j=0; j<9; j++) {\n int ch = line[j]-'0';\n if ((ch >= 1) && (ch <= 9))\n tab_in[i][j] = ch;\n }\n }\n}\n</code></pre>\n\n<p>If you uncomment your <code>load()</code> within <code>main</code>, you can read this file from the command line:</p>\n\n<pre><code>.......1.\n4........\n.2.......\n....5.4.7\n..8...3..\n..1.9....\n3..4..2..\n.5.1.....\n...8.6...\n</code></pre>\n\n<p>which is identical to your hard-coded puzzle. When you get that all working, consider how your code might solve this one which the current code (incorrectly) states is not solvable.</p>\n\n<pre><code>5.2..6...\n...8...41\n...4.2...\n.7....568\n..9...4..\n483....9.\n...2.3...\n93...4...\n...9..3.7\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:30:48.863",
"Id": "47976",
"ParentId": "47949",
"Score": "9"
}
},
{
"body": "<p>If you actually wanted to solve Sudoku instances as quickly as possible, you should consider a SAT solver or a CSP solver. They can work as a black box; just model your Sudoku instance in either formalism, feed it to a solver, and press go.</p>\n\n<p>As far as I can tell, your solver does a brute-force search: pick some variable, try a value, see what happens, and backtrack if you hit a dead-end. There's a very effective heuristic you can use that comes from the domain of CSP solvers. Instead of choosing a \"random\" cell to assign a value to, choose the variable that has that the <em>fewest legal values</em>. This is a so-called \"fail-first heuristic\", and the intuition is that this choice is most likely to fail soon, and it thereby prunes the search tree. This heuristic alone should allow you to solve any 9x9 puzzles in a second or two on modern hardware.</p>\n\n<p>This is not a C++-specific answer, but simply an answer from an algorithmic perspective.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T11:30:53.780",
"Id": "48393",
"ParentId": "47949",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T06:40:50.267",
"Id": "47949",
"Score": "9",
"Tags": [
"c++",
"beginner",
"sudoku"
],
"Title": "Optimizing Sudoku solver in C++"
} | 47949 |
<p>The title is somewhat a misnomer; my apologies. The goal of the procedure is to partition a range of <code>first, last</code> by <code>mid</code> for the postcondition</p>
<pre><code>max(first, mid) <= min(mid, last)
</code></pre>
<p>The actual code (<code>best_n.h</code>):</p>
<pre><code>#include <algorithm>
#include <iterator>
#if !defined(BidirectionalIterator)
#define BidirectionalIterator typename
#endif
template <BidirectionalIterator I>
void select_best(I first, I mid, I last) {
using T = typename I::value_type;
while (first != mid) {
T pivot = *first;
I pp = std::partition(first, last, [pivot](T elt) { return elt < pivot; });
if (pp == first) std::advance(pp, 1);
if (std::distance(first, pp) > std::distance(first, mid)) last = pp;
else first = pp;
}
}
</code></pre>
<p>Works fine if I didn't mistype anything.</p>
<p>Questions:</p>
<ul>
<li>Seeking overall improvements.</li>
<li>What is a right name?</li>
<li>Currently <code>void</code>. Is there anything useful to return?</li>
<li>I don't like passing lambda to <code>std::partition</code>. Any suggestions to avoid it?</li>
<li>A performance is weird. Regardless of a pivot selection strategy, an execution time stays pretty much constant as a function of <code>mid</code>. Obviously outperforms <code>std::partial_sort</code> for somewhat sizable initial ranges, but loses badly for short ones. Any suggestions?</li>
</ul>
<p>PS: I have benchmarks if anybody's interested.</p>
<p>PPS: I am well aware of the beautiful <a href="https://github.com/rjernst/stepanov-components-course/blob/master/code/lecture11/">best 2</a> Stepanov's approach. Challenging everybody to generalize it.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-18T09:27:01.833",
"Id": "95293",
"Score": "0",
"body": "As I understand the algorithm the output is not sorted, it is only guaranteed to have the best n elements in some arbitrary order in the first n positions of the range. A fair comparison should therefore be against [`std::nth_element`](http://en.cppreference.com/w/cpp/algorithm/nth_element) instead of `std::partial_sort`."
}
] | [
{
"body": "<p>A couple of points on the style rather than the algorithm itself. </p>\n\n<p>First, I find the <code>#ifdef</code> for the typename peculiar, it detracts from clarity, and is a pointless use of macros, it may be fine for a small snippet but in a large project or a library header such a thing can wreak havoc. Consider simply,</p>\n\n<pre><code>template <class BidirectionalIterator>\n</code></pre>\n\n<p>That said, note that C++11 relaxes <code>std::partition</code> to a ForwardIterator, so I would simply say,</p>\n\n<pre><code>template <class ForwardIterator>\nvoid select_best(ForwardIterator first, ForwardIterator mid, ForwardIterator last);\n</code></pre>\n\n<p>The type <code>T</code> is also a bad choice to denote a <code>value_type</code>, it has too much baggage as a template parameter. Simply say,</p>\n\n<pre><code>using value_type = typename I::value_type;\n</code></pre>\n\n<p>Then consider avoiding the inadvertent copy of the value by changing the code to take a const reference of the pivot,</p>\n\n<pre><code>const T& pivot = *first;\n</code></pre>\n\n<p>The lambdas are arguably the preferred way to write the predicate (let's not venture into <code>std::bind</code> and <code>std::min</code> territory), but again I would capture the value by a reference to avoid a copy, and be less verbose, </p>\n\n<pre><code>[&](const T& elt) { return elt < pivot; }\n</code></pre>\n\n<p>Consider either using brackets with if-else clauses or at least put the conditional statement on a separate line.</p>\n\n<pre><code>if ( ... )\n statement;\nelse \n</code></pre>\n\n<p>note that using <code>std::distance</code> implies that complexity of your function can blow up to <code>O(n)</code> for that use only (where <code>n</code> is the <code>pp</code>, somewhere around <code>N/2</code>), and if you want <code>O(1)</code> for the distance calculation you have to make sure your iterators are random access.</p>\n\n<p>and last, please get rid of the ghastly space in <code>else first = pp;</code>.</p>\n\n<p>For your question on the return value, would it be useful to return <code>pp</code> itself?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:24:21.230",
"Id": "47968",
"ParentId": "47950",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47968",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T06:56:49.813",
"Id": "47950",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"c++11"
],
"Title": "select_best: yet another partitioning algorithm"
} | 47950 |
<pre><code>private void log(MethodExecutionArgs args, string message, LogLevel level)
{
var calling_ip = ((System.Web.Services.WebService)args.Instance).Context.Request.UserHostAddress;
string method = args.Method.Name;
LogEventInfo logInfo = new LogEventInfo(level, logger.Name, message);
logInfo.Properties.Add("method", method);
logInfo.Properties.Add("calling_ip", calling_ip);
logger.Log(logInfo);
}
</code></pre>
<p>I have written this method to log the ip address of the caller. The <code>calling_ip</code> value is accessed in the NLog.config via the event_context <code>${event-context:item=calling_ip}</code></p>
<p>Can this code be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:17:57.260",
"Id": "84131",
"Score": "0",
"body": "What kind of improvements are you looking for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:38:17.797",
"Id": "84134",
"Score": "0",
"body": "svick, this works. But I was curious to know if there were other ways of doing this."
}
] | [
{
"body": "<p>One possible change would be to use object initializer to set up the properties:</p>\n\n<pre><code>var logInfo = new LogEventInfo(level, logger.Name, message)\n{\n Properties = { { \"method\", method }, { \"calling_ip\", calling_ip } }\n};\n</code></pre>\n\n<p>But I'm not sure this actually improves the code much, especially since using this syntax this way is uncommon, so it can be confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:24:53.790",
"Id": "47969",
"ParentId": "47954",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:53:23.817",
"Id": "47954",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Logging the caller ip in a asmx web service using NLog"
} | 47954 |
<p>I find myself frequently trying to build up Seq's based on some conditionals, but the code I end up with feels verbose and clunky. An example:</p>
<pre><code>def generateSeq(foo: Option[String]) = {
Map("bar" -> "baz") ++ ( if (foo.isDefined) {
Map("foo" -> foo.get)
} else {
Nil
} )
}
</code></pre>
<p>If it were Python, I would simply do:</p>
<pre><code>def generateObject(foo):
obj = {}
obj["bar"] = "baz"
if foo: obj["foo"] = foo
return obj
</code></pre>
<p>Is there a cleaner way to write the Scala code (especially as I add more logic and conditionals involved in building the map)?</p>
| [] | [
{
"body": "<p>It is completely possible to write your Python code in the same style in Scala, just because you have an immutable collection doesn't mean you can't add elements to it - the syntax just looks differently.</p>\n\n<p>One example to rewrite your function:</p>\n\n<pre><code>def generateObject(foo: Option[String]) = {\n var m = Map(\"bar\" -> \"baz\")\n foo foreach { elem => m += (\"foo\" -> elem) }\n m\n}\n</code></pre>\n\n<p>Another example which doesn't need the <code>var</code>:</p>\n\n<pre><code>def generateObject(foo: Option[String]) = {\n val m = Map(\"bar\" -> \"baz\")\n foo map (elem => m + (\"foo\" -> elem)) getOrElse m\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:48:32.547",
"Id": "47962",
"ParentId": "47955",
"Score": "1"
}
},
{
"body": "<p>You can use the fact that <code>Map() ++ None == Map()</code> along with <code>Map() ++ Some((k,v)) == Map((k,v))</code> and <code>Option.map</code> to get the following pattern: </p>\n\n<pre><code>def generateObject(foo: Option[String]) = {\n Map(\"bar\" -> \"baz\") ++ foo.map(\"foo\" -> _)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:55:14.367",
"Id": "48007",
"ParentId": "47955",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T07:59:32.573",
"Id": "47955",
"Score": "4",
"Tags": [
"scala"
],
"Title": "What is the best way to conditionally add to an immutable collection in Scala?"
} | 47955 |
<p>Please verify security from SQL injection attacks.</p>
<p><strong>homepage.php</strong></p>
<pre><code><html>
<head>
</head>
<body>
<ul id="list">
<li><h3><a href="search.php?name=women-top">tops</a></h3></li>
<li><h3><a href="#">suits</a></h3></li>
<li><h3><a href="#">jeans</a></h3></li>
<li><h3><a href="search.php?name=women">more</a></h3></li>
</ul>
</body>
</html>
</code></pre>
<p><strong>second.php</strong></p>
<pre><code><?php
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
session_start();
$lcSearchVal=$_GET['name'];
//echo "hi";
$lcSearcharr=explode("-",$lcSearchVal);
$result=count($lcSearchVal);
//echo $result;
$parts = array();
$parts1=array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = '`PNAME` LIKE "%'.$lcSearchWord.'%"';
$parts1[] = '`TAGS` LIKE "%'.$lcSearchWord.'%"';
//$parts[] = '`CATEGORY` LIKE "%'.$lcSearchWord.'%"';
}
$stmt = $mysqli->prepare("SELECT * FROM xml where ('.implode ('AND',:name).')");
$stmt->bind_Param(':name',$parts);
$list=array();
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$list[]=$row;
}
}
$stmt->close();
$mysqli->close();
foreach($list as $array)
{
?>
<div class="image">
<img src="<?php echo $array['IMAGEURL']?>" width="200px" height="200px"/></a>
<?php
}
?>
</div>
</body>
</html>
</code></pre>
<p>When I click on a link in homepage.php, it will search from XML for the products related
to the clicked link. Please verify whether the SQL statement is secured from a Google bot's attack and whether it's handling the data securely or not.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:34:19.760",
"Id": "84110",
"Score": "0",
"body": "Is `$parts1` used at all ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:35:12.810",
"Id": "84111",
"Score": "0",
"body": "no sir.its not used till now.can delete $parts1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:08:31.457",
"Id": "84114",
"Score": "0",
"body": "@Josay-please help on this.i m not able to correct it."
}
] | [
{
"body": "<p>You are not validating and not escaping <code>$_GET['name']</code>.</p>\n\n<p>Although <a href=\"https://codereview.stackexchange.com/users/20270/wouter-j\">@wouter-j</a> pointed out in a comment that the prepared statement should protect you, <a href=\"https://security.stackexchange.com/questions/15214/are-prepared-statements-100-safe-against-sql-injection\">this post on Security SE</a> argues otherwise, so I don't think you should count on it.</p>\n\n<p>And I think you have some errors too. For example if this works, it looks like <em>magic</em> to me:</p>\n\n<pre><code>$stmt = $mysqli->prepare(\"SELECT * FROM xml where ('.implode ('AND',:name).')\");\n$stmt->bind_Param(':name',$parts);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:36:00.433",
"Id": "84123",
"Score": "0",
"body": "no.its not working sir.Thats why i m looking for help.please correct my code.its giving me serious headache.@Janos"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:45:16.387",
"Id": "84127",
"Score": "4",
"body": "@user3545382 You might be better of asking stack overflow this question my friend"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:00:08.120",
"Id": "84160",
"Score": "0",
"body": "Since he is using prepared statements, he doesn't have to escape `$_GET['name']` anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:18:19.850",
"Id": "84193",
"Score": "1",
"body": "@WouterJ would you disagree with this post: http://security.stackexchange.com/questions/15214/are-prepared-statements-100-safe-against-sql-injection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:05:04.433",
"Id": "84236",
"Score": "0",
"body": "@janos - I for one would disagree with your linked post. All I read was a bunch of \"if this\" and \"if that\" then \"maybe\" something bad might happen. I'd be interested in reading anything that shows an actual exploit especially in the context of mysql and simple sql statements. Not trying to be hostile but I'd like to see some facts."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:48:14.700",
"Id": "47961",
"ParentId": "47956",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:21:31.603",
"Id": "47956",
"Score": "-1",
"Tags": [
"php",
"sql",
"mysql",
"security"
],
"Title": "Is this shopping site safe from SQL injection attacks?"
} | 47956 |
<p>I have defined some <code>DataTemplates</code> are similar. The templates are like this:</p>
<pre><code> <DataTemplate x:Key="DefaultCellTemplate">
<TextBlock Text="{Binding Value}">
<i:Interaction.Behaviors>
<beh:AddErrorButtonAdornerToControlsBehavior
DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="TimeCellTemplate">
<TextBlock Text="{Binding Value, Converter={StaticResource TimeConverter}}">
<i:Interaction.Behaviors>
<beh:AddErrorButtonAdornerToControlsBehavior
DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="StationCellTemplate">
<TextBlock Text="{Binding Value, Converter={StaticResource StationConverter}}">
<i:Interaction.Behaviors>
<beh:AddErrorButtonAdornerToControlsBehavior
DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="ProductionCategoryCellTemplate">
<TextBlock Text="{Binding Value, Converter={StaticResource ProductionCategoryConverter}}">
<i:Interaction.Behaviors>
<beh:AddErrorButtonAdornerToControlsBehavior
DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
</code></pre>
<p>I don't know, if I can define a template base. The template base should be a <code>TextBlock</code> with the behavior and the derived templates should be use a converter for the <code>TextBlock</code> value. Any idea?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T08:23:58.797",
"Id": "101021",
"Score": "0",
"body": "Is there any difference expected between the data templates?"
}
] | [
{
"body": "<p>Real inheritance is not possible in <code>DataTemplate</code> through XAML, as far as I know. What you can do with is use a nested construction of <code>DataTemplate</code>s.</p>\n\n<p>The method boils down to using a <code>ContentPresenter</code> and setting the <code>ContentTemplate</code> property in order to achieve your nesting.</p>\n\n<p>Solutions are already presented on SO and Google; both give a good bit of information:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5918132/in-wpf-can-you-base-one-datatemplate-on-another-like-you-can-with-a-style\">Stack Overflow</a></li>\n<li><a href=\"https://stackoverflow.com/questions/4443600/is-there-a-way-to-use-data-template-inheritance-in-wpf\">Stack Overflow</a></li>\n<li><a href=\"http://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/\" rel=\"nofollow noreferrer\">Google</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-17T08:41:59.213",
"Id": "57282",
"ParentId": "47957",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T08:43:17.393",
"Id": "47957",
"Score": "0",
"Tags": [
"wpf",
"xaml"
],
"Title": "Defining a DataTemplateBase"
} | 47957 |
<p>I’m trying to improve my code’s "signal to noise ratio", hence would appreciate any tips on improving this, what appears to be smelly code. Perhaps there could also be potential performance improvements to be made here:</p>
<pre><code>public class PricingInfoDto
{
[DataMember]
public decimal ListPrice { get; set; }
[DataMember]
public decimal Contribution
{
get
{
var contributionAmount = (1 + TaxRate) * (float)ListPrice * (ContributionPercentage / 100);
return Convert.ToDecimal(Math.Round(Math.Min(ContributionMaximumAmount, contributionAmount), 2));
}
private set
{
// For NHibernate Map
}
}
public float TaxRate { get; set; }
public double ContributionMaximumAmount { get; set; }
public float ContributionPercentage { get; set; }
}
</code></pre>
<p>Unfortunately, I don’t have control over the types of properties, as the types of <code>ContributionMaximumAmount</code> & <code>ContributionPercentage</code> are enforced by the <code>ADO.NET</code> and the public <code>DataMember</code> is expected to be <code>Decimal</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:42:47.033",
"Id": "84135",
"Score": "2",
"body": "I'm not sure if `decimal` is actually going to help you when the source data is in `float`s and `double`s."
}
] | [
{
"body": "<p>You are ignoring the whole point of decimals. Which is to avoid rounding errors from floating point caclulations.</p>\n\n<p>You must cast <code>TaxRate</code>, <code>ListPrice</code>, <code>ContributionPercentage</code>, etc. to <code>Decimal</code> and only then do your calculations using <code>Decimal</code> values. Casting at some point is unavoidable, if you have no control over signatures. You can, however, implement a wrapper, which would do the casting and expose <code>Decimal</code> properties. That will make your code more pretty.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:51:01.530",
"Id": "84120",
"Score": "0",
"body": "thanks, up-voted for decimal suggestion, please see the revised code. Any more comments appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:26:47.013",
"Id": "84133",
"Score": "0",
"body": "ah, changed my mind entirely in the end and created a `SetContribution` extension method for the `PricingInfoDto`. Now it (dto) looks nice & flat and I'm all **green**. Good time to break for lunch)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T12:23:56.337",
"Id": "84138",
"Score": "1",
"body": "@Chuck, i think it is a bad idea. You should not move *core* logic to extension methods. Initialization should be done in constructor. Or inside of the getter, thats fine too. But surely not inside some extension method noone knows about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:03:49.677",
"Id": "84142",
"Score": "0",
"body": "that's the intention: dto is part of the API Contract and nobody needs to know what the internal workings out are. This is a service response data DTO and the extension method is internal to the contract namespace."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:15:19.643",
"Id": "84146",
"Score": "2",
"body": "@Chuck, that is what `private` memebers are for. To hide the implemetation details. In my opinion \"flat look\" is not good enough reason to break the encapsulation (which you do by changing `private` to `internal`). It might not matter much in your case, but it is a bad practice nonetheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:25:53.387",
"Id": "84149",
"Score": "0",
"body": "OK, you're right mate. I'm gonna refactor the query so that it selects the ContributionMaximumAmount and ContributionPercentage into some internal class and then work out the Contribution` amount and set it on the DTO in the query class. Cпасибо за помощь!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:35:55.097",
"Id": "47960",
"ParentId": "47958",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47960",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T09:13:45.947",
"Id": "47958",
"Score": "4",
"Tags": [
"c#",
".net"
],
"Title": "Excessive number casting & conversion?"
} | 47958 |
<p>I have implemented quickly the quick sort algorithm in JavaScript using prototype based style.</p>
<p>The code is rather short (<a href="http://jsfiddle.net/b8mfY/" rel="nofollow">http://jsfiddle.net/b8mfY/</a>):</p>
<pre><code><script>
"use strict";
var Sort = function( inputArray ) {
this.arrayTest = undefined;
this.init( inputArray );
};
Sort.prototype.init = function( inputArray ) {
if ( inputArray instanceof Array && inputArray.length > 0 ) {
this.arrayTest = inputArray;
this.DumpArray( this.arrayTest );
this.QuickSort( this.arrayTest, 0, this.arrayTest.length - 1 );
this.DumpArray( this.arrayTest );
}
else console.log( 'Input argument isn\'t an array object or its length equals zero.' );
};
Sort.prototype.QuickSort = function( data, first, last ) {
var i = first;
var j = last;
var x = data[ Math.ceil( ( first + last ) / 2 ) ];
do {
while ( data[ i ] < x ) i++;
while ( data[ j ] > x ) j--;
if ( i <= j ) {
if ( i < j ) {
if ( data[ i ] !== data[ j ] ) {
var tempItem = data[ i ];
data[ i ] = data[ j ];
data[ j ] = tempItem;
}
}
i++;
j--;
}
} while ( i <= j );
if ( i < last ) this.QuickSort( data, i, last );
if ( first < j ) this.QuickSort( data, first, j );
}
Sort.prototype.DumpArray = function() {
var output = 'The content of array: [ ';
if ( this.arrayTest instanceof Array && this.arrayTest.length > 0 ) {
this.arrayTest.forEach( function( item ) {
output = output.concat( [ item, ', ' ].join( '' ) );
});
}
else console.log( 'Can\'t dump the input array. It\'s not an array object or its length equals zero.' );
output = output.substring( 0, output.length - 2 );
output = output.concat( ' ].' );
console.log( output );
};
window.onload = new Sort([
10,
1,
27,
4090,
100000,
2222,
4934
]);
</script>
</code></pre>
<p>I'm asking for a code review of the quick sort implementation part more than other details.</p>
| [] | [
{
"body": "<p>Looks okay to me.</p>\n\n<ul>\n<li>I would probably go for <code>if ( i != j ) {</code> which could be faster than <code>if ( i < j ) {</code></li>\n<li>You have a ton of short variable names, I guess that's ok for a sorting routine, though I would still rename <code>x</code> to <code>m</code>(iddle).</li>\n<li>I would have declared <code>tempItem</code> right under <code>i</code> and <code>j</code></li>\n</ul>\n\n<p>For the part you are not so interested in;</p>\n\n<ul>\n<li>Capital S in <code>Sort</code> is reserved for constructors</li>\n<li>I think <code>reduce</code> is more appropriate than <code>forEach</code> in <code>DumpArray</code></li>\n<li>You should not put code on the same line after an <code>else</code> statement</li>\n<li><p>Now that I think about it the dump routine could be reduced to</p>\n\n<pre><code>Sort.prototype.DumpArray = function() {\n\nvar prefix = 'The content of array: [ ';\n//Duck typing, just test for join\nif( this.arrayTest.join )\n console.log( prefix + this.arrayTest.join(', ') + ' ]' )\nelse\n console.log( \"Input: \" , this.arrayTest );\n};\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:54:18.130",
"Id": "47985",
"ParentId": "47963",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:11:17.770",
"Id": "47963",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"sorting",
"quick-sort",
"prototypal-class-design"
],
"Title": "Quick sort implementation in JavaScript in prototype style"
} | 47963 |
<p><strong>Background</strong></p>
<p>I'm using MS Exchange 2013 in my environment, and have a separate siem box which analyze logs produced by different systems (i.e exchange). The logs for Exchange are internally stored and can however be extracted such as </p>
<blockquote>
<pre><code>Get-MailboxAuditLog -Identity test-mailbox-1 -LogonTypes
Admin,Delegate –ShowDetails -StartDate mm/dd/2014 -EndDate mm/dd/2014
| Export-Csv “c:\test-Audit-Results.csv”
</code></pre>
</blockquote>
<p><strong>Steps taken so far</strong></p>
<ul>
<li>Enabling audit on Exchange</li>
<li>Got the command Google which needs to put in a script (above)</li>
</ul>
<p><strong>My requirements (in algorithm)</strong> </p>
<ol>
<li>check presence of properties file with last collect time. </li>
<li><p>If file is absent query the data from some period of time before till the current moment:</p>
<ol>
<li><code>Search-AdminAuditLog -StartDate (get-date).adddays(-30) -EndDate (get-date) | Export-Csv "c:\admin-results-temp.csv"</code></li>
<li>remember "get-date" value to properties file</li>
<li>copy "admin-results-temp.csv" file contents to the final file to be forwarder by ALE</li>
</ol></li>
<li><p><strong>If file is present:</strong></p>
<ol>
<li>Get last collect time calculate difference in time from present time. If time-difference is more then 1 hours ...pull the log again</li>
<li>execute Search-AdminAuditLog with StartDate = date from props file, EndDate = current </li>
<li>remember current time to the props file</li>
<li>copy "admin-results-temp.csv" file contents to the final file to be forwarder by ALE</li>
</ol></li>
<li>You can clean up final file once a week to avoid over-grow. ALE will forward it from the beginning at that case.</li>
<li>Schedule the script/code described above to run each minute</li>
<li>Configure ALE in a File Forwarder mode to send file</li>
</ol>
<p>Note: On part of ALE that part is already automated. No need for file-forwarding required.</p>
<p>I want the above algorithm in a power shell script.</p>
<p>Current code:</p>
<pre><code><#
#>
#...................................
# Variables
#...................................
$check_collect_last
#...................................
# Initialize
#...................................
#Set recipient scope
$2007snapin = Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin
if ($2007snapin)
{
$AdminSessionADSettings.ViewEntireForest = 1
}
else
{
$2010snapin = Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010
if ($2010snapin)
{
Set-ADServerSettings -ViewEntireForest $true
}
}
#If no filename specified, generate report file name with random strings for uniqueness
$source=c:\results-audit
$check_last = (ls $source).LastWriteTime
#...................................
# Script
#...................................
#Add dependencies
Import-Module ActiveDirectory
#Get the mailbox list
$mailboxcount = $mailboxes.count
$i = 0
$mailboxdatabases = @(Get-MailboxDatabase)
$directoryInfo = Get-ChildItem C:\Mail-audit-results | Measure-Object
$directoryInfo.count #Returns the count of all of the files in the directory
If $directoryInfo.count -eq 0
{
#Loop through mailbox list
foreach ($mb in $mailboxes)
{
$i = $i + 1
$pct = $i/$mailboxcount * 100
Write-Progress -Activity "Collecting audit details for Mail admin" -Status "Processing mailbox $i of $mailboxcount - $mb" -PercentComplete $pct
$Startdate=((Get-Date).adddays(-30)).ToShortDateString()
$Enddate=(Get-Date).ToShortDateString()
$check_collect_last=Get-Date -format HH:mm:ss
$auditAdmin_search = $mb | Search-MailboxAuditLog -Identity $i -LogonTypes Admin,Delegate –ShowDetails -StartDate $Startdate -EndDate $Enddate | Export-Csv “c:\Mail-audit-results\Temp-Audit-Results.csv”
#appending file to final audit csv file
[System.IO.File]::ReadAllText("c:\Mail-audit-results\Temp-Audit-Results.csv") | Out-File c:\Mail-audit-results\Final-mail-admin.csv -Append -Encoding Unicode
}
}
else
# if difference between last collect time and present is more then #1 hours collect logs in cycle / hrs
$Now = Get-Date -format HH:mm:ss
$check_collect_last = New-TimeSpan $check_collect_last $Now
if ($check_collect_last.Hours -gt 1)
{
foreach ($mb in $mailboxes)
{
$i = $i + 1
$pct = $i/$mailboxcount * 100
Write-Progress -Activity "Collecting audit details for Mail admin" -Status "Processing mailbox $i of $mailboxcount - $mb" -PercentComplete $pct
$Startdate=((Get-Date).ToShortDateString()
$Enddate=(Get-Date).ToShortDateString()
$auditAdmin_search = $mb | Search-MailboxAuditLog -Identity $i -LogonTypes Admin,Delegate –ShowDetails -StartDate -EndDate $Enddate | Export-Csv “c:\Mail-audit-results\Temp-Audit-Results.csv
$check_collect_last=$Startdate
}
}
else
return 0
</code></pre>
<p>This is my first powershell script. I'd appreciate it if someone can suggest/review if possible, especially in regard to date functions.</p>
| [] | [
{
"body": "<p>You have multiple syntax errors. As a start, I would fix those. Also, fix up the indenting to make it easier to see what is going on. Which editor are you using? You could try using the PowerShell ISE. It will show you some of your errors with red wiggly lines.</p>\n\n<p>As a general strategy, I would suggest writing your code step-by-step. Get one thing working before moving on to the next. Break your code up into functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T00:05:28.503",
"Id": "49286",
"ParentId": "47964",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:22:24.307",
"Id": "47964",
"Score": "2",
"Tags": [
"windows",
"powershell"
],
"Title": "Writing a small script to extract MS Exchange audit logs in .csv format"
} | 47964 |
<p>I've realized JS callback hell and I started looking into Promises libraries.
After reading some articles I decided to start with <a href="https://github.com/petkaantonov/bluebird" rel="nofollow">BluebirdJS</a>. I didn't realise how to properly use them yet, because documentation written with API examples, not real usage.</p>
<p>I have two files (NodeJS environment):</p>
<pre><code>#monitor.js
Promise = require("bluebird")
class Monitor
constructor: (@api) ->
getServerInfo: ->
return new Promise((resolve, reject) =>
@api.query("messages.getLongPollServer", { use_ssl: 1}).then(
(result) =>
@key = result.response.key
@server = result.response.server
@ts = result.response.ts
resolve(@)
reject
)
)
printDetails: ->
console.log(@key, @server, @ts)
module.exports = Monitor
#app.js
Api = require("./api")
Monitor = require("./monitor")
api = new Api("6de61129da290c3edf9c699ad25638156266e7b6bdbcc00407efb630e5c62f2d4c71974c7bdba52a03dbd")
monitor = new Monitor(api)
monitor.getServerInfo().then((monitor) -> monitor.printDetails())
</code></pre>
<p>What I wanted to achieve is something like this:</p>
<pre><code>monitor.getServerInfo().then().printDetails()
</code></pre>
<p>because <code>getServerInfo</code> runs asynchronously.</p>
<p>Am I using promises correctly?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:23:33.150",
"Id": "84196",
"Score": "0",
"body": "what is Api? Why are you creating new Promise when api.query already returns a promise?"
}
] | [
{
"body": "<ol>\n<li>Don't use explicit returns in CoffeeScript unless you have to (and you don't here)</li>\n<li>CoffeeScript may do automatic comma insertion, but I certainly didn't right away (i.e. add a comma yourself, right before <code>reject</code> - anything to make it easier to read)</li>\n</ol>\n\n<p>Anyway: You can't get this code</p>\n\n<pre><code>monitor.getServerInfo().then().printDetails()\n</code></pre>\n\n<p>because that would be <em>synchronous</em>, not asynchronous. The interpreter would have to wait in the middle of the chain before it could call <code>printDetails</code>. And it doesn't wait - that's the point of asynchronicity.</p>\n\n<p>And that's why <code>then()</code> always returns a promise object (and nothing else), because it can return that right away without any waiting.</p>\n\n<p>So your current code</p>\n\n<pre><code>monitor.getServerInfo().then((monitor) -> monitor.printDetails())\n</code></pre>\n\n<p>is the way to do it. Of course, it doesn't make much sense to have a <code>printDetails</code> method in your <code>Monitor</code>, if it doesn't always work. Right now, you can just call</p>\n\n<pre><code>(new Monitor(api)).printDetails()\n</code></pre>\n\n<p>and get</p>\n\n<pre><code>undefined, undefined, undefined\n</code></pre>\n\n<p>printed. Or, if you just happened to call it <em>after</em> the API query has run, <code>printDetails</code> will suddenly print actual values. The method is almost random at that point because there's nothing guaranteeing that things happen in the right order.</p>\n\n<p>I'd just skip the <code>Monitor</code> class entirely, since it's not really contributing much - at least not right now. But, given the name \"monitor\", I imagine the point is to get the server info, so you can then set up a polling system of some kind.</p>\n\n<p>In that case, you could make a factory method that returns its product via a promise:</p>\n\n<pre><code>Promise = require \"bluebird\"\n\nclass Monitor\n constructor: (@server, @key, @ts) ->\n # I don't know if a Monitor instance needs an api object\n # for anything. If it does, add it as an argument to\n # this constructor\n\n startPolling: ->\n # ... or something\n\n stopPolling: -> \n # ... or something\n\n printDetails: ->\n console.log @server, @key, @ts\n\n# factory function\nMonitor.create = (api) ->\n # internal function that actually runs the query\n createMonitor = (resolveCallback, rejectCallback) ->\n success = (data) ->\n {server, key, ts} = data.response # CoffeeScript destructuring\n resolveCallback new Monitor(server, key, ts) # also pass in the api obj, if needed\n\n api.query(\"messages.getLongPollServer\", use_ssl: 1).then success, rejectCallback\n\n # return a promise that'll resolve with \n # a new Monitor instance (or fail,\n # presumably with an error of some sort)\n new Promise createMonitor\n\nmodule.exports = Monitor\n</code></pre>\n\n<p>If you already have the <code>server</code>, <code>key</code> and <code>ts</code> values from somewhere, then great; just call <code>new Monitor(server, key, ts)</code> and you're done.</p>\n\n<p>But if you don't, you can do this:</p>\n\n<pre><code>Api = require(\"./api\")\nMonitor = require(\"./monitor\")\n\napi = new Api(\"6de61....\")\n\nsuccess = (monitor) -> monitor.printDetails() # or whatever else you need\nfailure = (args...) -> console.warn args...\n\nMonitor.create(api).then success, failure\n</code></pre>\n\n<p>This is basically turning the process inside out: Instead of instantiating a <code>Monitor</code> object, and making <em>it</em> fetch the data it needs, the factory method is doing the fetching, and only creating the instance when it's time to do so.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:16:03.160",
"Id": "48009",
"ParentId": "47965",
"Score": "2"
}
},
{
"body": "<p>Bluebird has the concept of Promisification that converts any library into a Promise. Maybe it did not exist at the time the chosen answer was written, but I wanted to add this so people coming into this answer should look into that option before anything else. You can use this without changing your existing library code.</p>\n\n<p><a href=\"https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification\" rel=\"nofollow\">https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification</a></p>\n\n<pre><code>var Promise = require('bluebird');\nvar Monitor = Promise.promisifyAll(require('Monitor'));\n</code></pre>\n\n<p>Then something like:</p>\n\n<pre><code>//using getServerInfoAsync to show that you could have written \n//getServerInfo without returning a Promise, as if it were to be used as a callback\nmonitor.getServerInfoAsync().then(monitor.printDetailsAsync)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-15T16:14:20.313",
"Id": "57103",
"ParentId": "47965",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48009",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T10:37:57.997",
"Id": "47965",
"Score": "1",
"Tags": [
"node.js",
"asynchronous",
"coffeescript",
"promise"
],
"Title": "Promises and chained calls"
} | 47965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.