body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I need to add logging functionality for an existing code, based on a result of an operation. I was thinking of creating a class that, when constructed, receives a condition function and a function for execution. Based on the result of the condition, the code will be executed. </p> <p>Example:</p> <pre><code>class auto_logger{ public: auto_logger(const std::function&lt;bool()&gt;&amp; cond, const std::function&lt;void()&gt;&amp; func): _cond(cond), _func(func) {} virtual ~auto_logger() { try { if (_cond()) { _func(); } } catch (...) { } } private: std::function&lt;bool()&gt; _cond; std::function&lt;void()&gt; _func; }; </code></pre> <p>I will use this class like this:</p> <pre><code>int existing_func() { int res = FAILURE; // this is the only additional code auto_logger logger([&amp;](){ return res == SUCCESS; }, [](){ print_to_log(); }); do_some_stuff_that_may_throw(); res = perform_operation(); return res; } </code></pre> <p>I would be happy to get some comments on this code. Are there any problem I am not seeing in this solution? Are there any better solutions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T18:20:29.013", "Id": "57520", "Score": "1", "body": "I don't think the type erasure (`std::function`) is necessary, if you use C++11's auto and a function to create the logger. Additionally, the exception handler in the dtor might hide problems. Note boost has a library for this: [Boost.ScopeExit](http://www.boost.org/doc/libs/1_55_0/libs/scope_exit/doc/html/index.html) (with C++11 support)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:00:21.823", "Id": "57524", "Score": "1", "body": "boost has a scope exit construct for something exactly like this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:57:19.487", "Id": "57539", "Score": "0", "body": "Agreed; the benefits of separating the condition and the function do not outweigh the cost of reading two lambdas. One lambda that evaluates the condition before doing the rest should be plenty, and then existing scope guards work fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T21:59:40.173", "Id": "57549", "Score": "2", "body": "Prefer not to prefix your identifiers with `_`. You need to be careful not to fall into the trap of using a reserved identifier. http://stackoverflow.com/a/228797/14065 and it looks ugly." } ]
[ { "body": "<p>Echoing the comments from the question, the usual design for these sort of things, often called a <a href=\"http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Scope_Guard\" rel=\"nofollow\">scope guard</a>, is to have a function that is called when it no longer needs to be run (frequenlty called <code>dismiss</code> or <code>release</code>.</p>\n\n<pre><code>int existing_func()\n{\n int res = FAILURE;\n\n auto_logger logger([](){\n print_to_log();\n });\n\n do_some_stuff_that_may_throw();\n\n res = perform_operation();\n\n dismiss_logger(logger, res);\n\n return res;\n}\n\nvoid dismiss_logger(auto_logger&amp; logger, int result) {\n if (res != SUCCESS) {\n logger.dont_log();\n }\n}\n</code></pre>\n\n<blockquote>\n <p><code>virtual ~auto_logger()</code></p>\n</blockquote>\n\n<p>Is the expectation that there will be derived classes destroyed via base pointers or via base references? If not, a non-virtual destructor is a common way to signal that a class is not designed to be inherited from.</p>\n\n<blockquote>\n <p><code>} catch (...) {</code></p>\n</blockquote>\n\n<p>Note that Visual C++ (at least) can be configured via the /EHa switch (this is usually a misguided configuration, IMHO) to catch structured exceptions (things like access violations/segmentation faults) in a <code>catch (...)</code> handler.</p>\n\n<p>A common technique to hedge against this configuration is to catch <code>std::exception&amp;</code> <em>under the assumption that all sensible exceptions will derive from it</em>. Anything else being caught (e.g, an int, a structured exception) is likely indicative of a bug in the program so egregious that termination is the only safe recourse, as there's likely some corrupt state somewhere that prevents any further cleanup.</p>\n\n<p>This assumption may or may not be valid. Say this code needs to work in an environment where it is normal and okay to throw and catch things that don't derive from <code>std::exception</code>. (E.g., a framework that has its own base exception class is being used.) If Visual C++ isn't being used of /EHa will never be used, this recommendation may come off as paranoid. :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T21:57:56.730", "Id": "57548", "Score": "1", "body": "Yes the catch must by `...`. Destructors should be designed to never leak any exceptions. If a destructor calls a function you should have a guarantee that it will not throw or you catch everything. http://stackoverflow.com/a/130123/14065 I also believe you are confusing C++ exceptions and structured exceptions of Windows (these are completely different and not caught by the same mechanism)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T22:20:33.400", "Id": "57551", "Score": "0", "body": "@LokiAstari, thanks. Clarified and scoped more to Visual C++." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T20:32:11.553", "Id": "35494", "ParentId": "35482", "Score": "7" } } ]
{ "AcceptedAnswerId": "35494", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T15:16:33.233", "Id": "35482", "Score": "10", "Tags": [ "c++", "c++11" ], "Title": "Automatic function call on scope exit" }
35482
<p>I wrote a simple utility script to process source code files, extract and pretty print braces. It could be very useful for spotting the ugliest files in a code repository. So, I tidied it up a little bit and open-sourced it <a href="https://github.com/muratdozen/playground/blob/master/scripts/pretty_print_braces/__main__.py" rel="nofollow">here</a>.</p> <p>I would very like to have your suggestions and comments on how to make this Python code better in any way.</p> <pre><code>__author__ = 'Murat Derya Ozen' PROGRAM_DESCRIPTION = """ Spot the ugliest files in a code repository. Given a path to a file or a directory, this program parses source files to extract, pretty print and calculate the number of curly brackets, i.e braces. *** Samples usages *** &gt; python pretty_print_braces file --path /root/repo/svn/trunk/SomeJavaClass.java Assuming SomeJavaClass.java is a simple Java source file containing the following code: public class SomeJavaClass { public static void main(String[] args) { if (args != null &amp;&amp; args.length &gt; 2) { System.out.println("Hello"); } } } The program would output: /root/repo/svn/trunk/SomeJavaClass.java { { { } } } Depths: [1, 1, 1] Max depth: 3 The output starts with the file name, followed by the braces in the file pretty-printed, followed by the number of braces at each level, finally followed by the maximum depth. This means that the source file contains at most 3 levels of nested braces. Furthermore; we see that at there is 1 opening and closing brace for each level (i.e 1 for the class declaration, 1 for the static main method declaration and 1 for the if statement). &gt; python pretty_print_braces file --path /root/repo/svn/trunk/SomeJavaClass.java -q Adding '-q' or '--quiet' switches to quite mode where pretty-printing of the braces are not included in the output. &gt; python pretty_print_braces dir -p /root/repo/svn/trunk This command process the whole directory (recursively) as opposed to a single file. It processes each source file and prints the ugliest 5. Ugliness is defined by having the most depth of nested braces. &gt; python pretty_print_braces dir -p /root/repo/svn/trunk --nonrecursive --extensions=cpp,c,h -q -n 3 Process the source files with extensions cpp, c or h in the directory at /root/repo/svn/trunk. Output the ugliest 3 source files in quiet mode. --nonrecursive indicates that subdirectories of trunk will not be traversed. """ import argparse import heapq import re import os INDENT = ' ' * 4 LINE_SEPARATOR = os.linesep def extract_braces(source_code, filename, quiet): """ Parses and extracts the braces from source_code string. Returns a tuple (max_depth, depths, braces, filename). max_depth is the maximum depth of the braces; the deepest level found. depths is a list of integers such that depths[i] is the number of opening braces at depth i. braces is a string containing all braces in source_code pretty printed. """ current_depth, depths, braces = 0, [0], [] def increment_depth_occurence(d): if d &lt; len(depths): depths[d] += 1 else: depths.append(1) for char in source_code: if '{' == char: if not quiet: braces.append((INDENT * current_depth) + '{') current_depth += 1 increment_depth_occurence(current_depth) elif '}' == char: current_depth -= 1 if not quiet: braces.append((INDENT * current_depth) + '}') max_depth = len(depths) - 1 return max_depth, depths[1:], LINE_SEPARATOR.join(braces), filename def analyze_file(filename, quiet): """ Open the file named filename, parse it and return the extract_braces(file_content)'s result. """ file = open(filename, 'r') content = file.read() result = extract_braces(content, filename, quiet) file.close() return result def walk_through_directory(rootpath, recursive, n, file_extensions, quiet): """ Taverse the directory rooted at rootpath. Analyze each file. Store the greatest n results inside a heap. Only files within file_extensions are processed, other are skipped. If recursive is True, traversal will include subdirectories of rootpath as well. Returns the heap containing at most n results. Each element is a tuple returned by extract_braces(source_code). Elements are compared according to the tuple' first element. """ heap_max_size = n def heappush(h, element): """ Insert element into h iff heap's max size has not been reached or element is greater than the lowest element in the heap. """ if len(h) &lt; heap_max_size: heapq.heappush(h, element) else: heapq.heappushpop(h, element) file_extension_regex = '^.+\\.(' + '|'.join(file_extensions) + ')$' file_extension_supported = lambda filename: bool(re.match(file_extension_regex, filename, re.I)) join = os.path.join h = [] # heap to keep track of the greatest n items. def process_directory(dirpath, filenames): """ Process the files rooted immediately in dirpath, without going into dirpath's subdirectories. """ for filename in filenames: if not file_extension_supported(filename): continue absolute_file_path = join(dirpath, filename) result = analyze_file(absolute_file_path, quiet) heappush(h, result) if recursive: for dirpath, _, filenames in os.walk(rootpath): process_directory(dirpath, filenames) else: process_directory(rootpath, os.listdir(rootpath)) return h def get_argparser(): """ Defines and returns the ArgumentParser for this program. """ parser = argparse.ArgumentParser(description=PROGRAM_DESCRIPTION) sub_parsers = parser.add_subparsers() file_sub_parser = sub_parsers.add_parser('file') file_sub_parser.add_argument('-p', '--path', required=True, help='Parse this file to extract and pretty print braces.') file_sub_parser.add_argument('-q', '--quiet', action='store_true', help='Increase output quietness. By default, ' + 'this program prints the file name, maximum depth (deepest level), ' + 'number of opening braces for each depth and the braces pretty ' + 'printed. Supplying \'-q\' will omit pretty printing of the braces') file_sub_parser.set_defaults(func=pretty_print_file) dir_sub_parser = sub_parsers.add_parser('dir') dir_sub_parser.add_argument('-p', '--path', required=True, help='Traverse the files rooted in this directory and all its subdirectories ' + 'and parse each file to extract and pretty print braces.') dir_sub_parser.add_argument('--nonrecursive', action='store_true', help='Traverse only the files in dir but not in subdirectories of dir. By ' + 'default, directories are traversed recursively.') dir_sub_parser.add_argument('--extensions', default='java,cpp,c,h', help='Only the files with these file extensions are parsed. This optional ' + 'argument can take a single extension or a comma separated list. ' + 'Default is \'java,cpp,c,h\'.') dir_sub_parser.add_argument('-n', type=int, default=5, help='Resulting output includes the ugliest \'n\' files. Ugliness is defined by ' + 'the depth of braces. For instance, the Java class defined as ' + '\'class A { void method() { if(true) {return;} } }\' would have a ' + ' depth of 3 as it\'s curly braces go 3 levels deep. By default n=5.') dir_sub_parser.add_argument('-q', '--quiet', action='store_true', help='Increase output quietness. By default, ' + 'this program prints the file name, maximum depth (deepest level), ' + 'number of opening braces for each depth and the braces pretty ' + 'printed. Supplying \'-q\' will omit pretty printing of the braces') dir_sub_parser.set_defaults(func=pretty_print_dir) return parser def print_result(analysis_result, quiet): """ Print analysis_result to STDOUT """ max_depth, depths, braces, filename = analysis_result print filename if not quiet: print braces print 'Depths:', depths print 'Max depth:', max_depth def pretty_print_dir(args): heap = walk_through_directory(args.path, not args.nonrecursive, args.n, args.extensions.split(','), args.quiet) for i in range(min(len(heap), args.n)): analysis_result = heapq.heappop(heap) print_result(analysis_result, args.quiet) print def pretty_print_file(args): analysis_result = analyze_file(args.path, args.quiet) print_result(analysis_result, args.quiet) def main(): parser = get_argparser() args = parser.parse_args() args.func(args) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>Over all, the code is quite readable, and extensively documented both as docstrings and as command line help. Great!</p>\n\n<p>I found no real problems with the code, but here are a few minor nitpicks:</p>\n\n<ul>\n<li>Your script produces wrong (misleading) results if there are braces inside of strings and comments. You are probably aware that, but the user of the script likely is not. This should be mentioned in the documentation.</li>\n<li>Why use regular expressions to match extensions? Use <code>os.path.splitext</code> instead.</li>\n<li>Why is <code>file_extension_supported</code> a lambda instead of a <code>def</code>? In other cases, you used <code>def</code> to define inner helper functions.</li>\n<li>Btw, the name <code>file_extension_supported</code> doesn't really convey the purpose to me.</li>\n<li>The return value of <code>extract_braces</code> places a key role in the program, as can be seen from the fact that it is passed around a lot. Maybe it deserves to be a real class instead of a tuple, so that you don't depend on the order of tuple elements everywhere. This would also require being more explicit on which value you are using as ordering criteria for the heap. That's a good thing.</li>\n<li>There are too many single-letter identifiers for my taste. In particular, single-letter parameter names for functions without docstrings are not quite self-explaining.</li>\n<li>\"Inverted\" comparisons, where one puts the constant to the left of the comparison operator (<code>if '{' == char:</code>) are used in some languages to avoid the pitfall where you by accident write an assignment instead of a comparison (<code>if char = '{':</code>). However, in Python, this is not necessary, as assignment would be a syntax error.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:56:10.303", "Id": "57671", "Score": "0", "body": "I didn't expect such a detailed answer, thank you very much. Here are my comments: 1) Very good point, I hadn't thought about it. Fixed it 2) Good point, wasn't aware of such a method. Will fix it. 3) Because it's the only short one-liner function in this code. Others wouldn't fit into a single line or would be too long for my taste. 4) I thought about this and you're right. But being a Java programmer, I find Python classes ugly:) 5) I can only see `n`, `h`, `q` which I think all are self-explanatory. But I will have a look again. 6) Good point, fixed it. Once again, thank you very much:)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T22:34:52.653", "Id": "35498", "ParentId": "35484", "Score": "4" } } ]
{ "AcceptedAnswerId": "35498", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T16:55:17.703", "Id": "35484", "Score": "2", "Tags": [ "python", "file-system" ], "Title": "Pretty print braces for source code analyzer" }
35484
<p>So I have this simple code in Java. It <code>enqueue</code> (adds) and element to the end of the queue (implemented by an <code>ArrayList</code>) without changing the original queue.</p> <pre><code>public class MyQueue&lt;T&gt;{ private List&lt;T&gt; body; // some constructors and helper functions. //copy constructor public MyQueue(List&lt;T&gt; list){ this.body = list; } //this is the function public MyQueue&lt;T&gt; enqueue(T obj){ List&lt;T&gt; temp = new ArrayList&lt;T&gt;(body); temp.add(obj); return new Queue&lt;T&gt;(temp); } </code></pre> <p>The whole idea is to make <code>enqueue</code> faster and more efficient, and again, as you notice, without changing the value of the original queue. Any ideas?</p> <p><strong>UPDATE</strong> For the sake of completing the idea. </p> <p>1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).</p> <p>2- As for the helper functions, they are simple:</p> <pre><code>public T peek(){ if(body.isEmpty()){ thrown new NoSuchElementException(); } return body.get(0); } public int size(){ return body.size(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T17:28:58.753", "Id": "57518", "Score": "4", "body": "What is the sense of doing so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:00:52.170", "Id": "57525", "Score": "0", "body": "`public Queue(List<T> list){` is not a constructor at all. It's more a compiler error. I guess it should be `public MyQueue(List<T> list){`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:05:23.227", "Id": "57527", "Score": "0", "body": "It's rather hard to \"answer\" this question without knowing how you are using your `MyQueue` class, or what the hidden constructors and helper methods are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:19:59.517", "Id": "58523", "Score": "0", "body": "I am confused, it's not to be changed but you want to make it faster?" } ]
[ { "body": "<p>It seems like what you are trying to accomplish here is to make your Queue class <strong>immutable</strong>. That in itself is good, but there are a couple of issues with your approach:</p>\n\n<ul>\n<li>Creating a new class for this is not needed. There already exists classes for that. Use <code>Collections.unmodifiableList</code> to create one.</li>\n<li>Your class does not implement the <code>List</code> interface (or the <code>Queue</code> interface for that matter). I guess there is a way to access the embedded <code>List&lt;T&gt;</code> such as <code>getList</code> hidden among \"some constructors and helper functions\", but if all that does is to <code>return this.body;</code> then your entire list is still accessible and modifiable.</li>\n<li>The <code>List&lt;T&gt; body</code> field could be, and <em>should</em> be, declared <strong>final</strong>.</li>\n</ul>\n\n<p>Instead of your entire <code>Queue</code> class, you might want to use this static method:</p>\n\n<pre><code>public static &lt;E&gt; List&lt;E&gt; addToList(List&lt;E&gt; oldList, E newElement) {\n List&lt;E&gt; temp = new ArrayList&lt;E&gt;(oldList);\n temp.add(newElement);\n return Collections.unmodifiableList(temp);\n}\n</code></pre>\n\n<p>I should add however, that there is a difference between an unmodifiable list and what I understood about your approach. An unmodifiable list in Java <strong>does not allow any change to the list at all, such as list.set(index, obj).</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:11:49.027", "Id": "57531", "Score": "0", "body": "I think your code example was meant to have `List<E> temp = new ArrayList<E>(oldList);`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T18:56:58.257", "Id": "35489", "ParentId": "35485", "Score": "2" } }, { "body": "<p>I doubt with this implementation. Queue is a very basic data structure -- by \"enqueue\" I would assume that the element is going be added to the original queue. Now as you mentioned you wanted to make this faster, but to achieve that you are copying the original queue. So both time and space will suffer due to a temp array created every time when enqueue is called. Did you execute a performance test on your implementation to see how actually this could be beneficial? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T20:11:27.040", "Id": "35493", "ParentId": "35485", "Score": "2" } }, { "body": "<p>Basically you are trying to improve a basic and common data structure that is <code>Queue</code>. You have two choices available to implement queue - using linked list and other one is using array (here you have used similar by java's <code>ArrayList</code>).</p>\n\n<p>A very brief compassion of two different type of implementation -</p>\n\n<p>Using linked list</p>\n\n<ul>\n<li><p>enqueue has constant time 0(1) and dequeue has 0(n) complexity in worst case</p></li>\n<li><p>Uses extra time and space to deal with the links</p></li>\n</ul>\n\n<p>Using Array </p>\n\n<ul>\n<li><p>enqueue operation takes constant time 0(1) in amortized array.(amortized array is - resizing array as per need for efficiently using space) </p></li>\n<li><p>Less wasted space.</p></li>\n</ul>\n\n<p>First off, you are trying to improve an operation which already has a good performance whether it is array or linked list. </p>\n\n<p>If you had used <code>array</code>, then you had to maintain <code>resize array</code> functionality yourself to achieve amortized time. But since you are using <code>Arralist</code> so you do not have to write extra code to resize array because <code>ArraList</code> inherently provides this functionality.</p>\n\n<p>I suggest that you implement another <code>Queue</code> class using basic <code>array</code> instead of <code>ArrayList</code>. Now start profiling both the implementation and see how they differ in terms of execution time. </p>\n\n<p>While testing, create \"very large\" queue and perform different operation on it. I feel using a basic array on a large queue may have some advantage over ArrayList. I can not claim this statement but profiling two different implementation will give better conclusion. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:01:16.887", "Id": "57608", "Score": "0", "body": "\"Every operation takes constant time 0(1) in worst case\" - Really? Since when is lookup by index a constant time operation on a linked list? Also less wasted space is not quite correct: typically array based structures resize the backing array by doubling the capacity when it's full. So your wasted space is `(n/2) - 1` bytes in worst case (which can be a lot)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:14:10.270", "Id": "57617", "Score": "0", "body": "I think the trick here is to somehow work around the need for 2 stages of copying. since the original should never be changed. and the type returned should be MyQueue. But I cannot seem to work around that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:35:33.410", "Id": "57620", "Score": "0", "body": "@ChrisWue - you are right, let me edit my answer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:37:35.537", "Id": "35519", "ParentId": "35485", "Score": "1" } }, { "body": "<p>The problem with your <code>enqueue</code> approach is that it copies the existing content into a new list. Assuming you enqueue <code>n</code> elements this would result in <code>1 + 2 + 3 + 4 + .. + n</code> copy operations - which is (if you know your ole Gauss) <code>n * (n + 1) / 2</code> or in other words <code>O(n^2)</code>. This is not very efficient.</p>\n<p>Getting immutable data structures right and efficient is not always a trivial task. The best advise I can give is to point you to Eric Lipperts blog who has written a whole series about <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"nofollow noreferrer\">immutable data structures</a> - I found that an extremely interesting read (queues are discussed starting part 4). He uses C# (no surprise there) but I'm sure the ideas can be applied to Java just as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-11-17T07:18:36.127", "Id": "35523", "ParentId": "35485", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T17:00:39.723", "Id": "35485", "Score": "3", "Tags": [ "java", "optimization", "array", "queue" ], "Title": "A more efficient enqueue algorithm in Java" }
35485
<p>I have a library that's parsing some expressions, part of which is a CSS selector. More accurately, it's a jQuery-compatible selector. The selector itself is opaque to my library - I don't need to pick it apart, and I don't need to verify that tag and attribute names are valid HTML, or that its pseudo-selectors exist in the current spec. For now, I just need it to match all syntactically valid CSS selectors and not match the rest of the expression, which is delimited by characters that would not be valid in a selector unless escaped or put in a string in an attribute selector. I would use a <code>RegExp</code> and <code>split</code> the string if CSS had no escapes or quoted values, but it started looking write-only really fast.</p> <p>Does this PEG.js grammar cover all the other edge cases as defined by the CSS standard and jQuery documentation? Could it be more readable? Better in some other way?</p> <pre><code> { /* * glom the array contents returned by the parser * into a string recursively. */ function collapse(stuff) { if (typeof stuff === "string") { return stuff; } else if (stuff instanceof Array) { return stuff.reduce(function (a, item) { return a.concat(collapse(item)); }, "") } else { return ""; } } /* * Replace superfluous white space with a single space. */ function trimWs(present) { if (present) { if (present instanceof Array) { return !!present.length ? " " : ""; } else { return " "; } } else { return ""; } } } start = jqSelector ws "white space" = whites:(" " / "\r" / "\n" / "\t" / "\f")+ { return collapse(whites); } iws "ignored white space" = ws? { return ""; } cws "collapsed white space" = ws:ws { return trimWs(ws); } jqSelector "jquery-compatible selector" = element:(tagIdClassSelector / cssFunctional / cssAttrExpr)+ more:(iws [\+>~,] iws jqSelector / cws jqSelector)? { return collapse([element, more]); } tagIdClassSelector "tag, id, or class selector" = [#\.]? cssIdentifier / "*" cssIdentifier "CSS identifier" = start:cssIdStart rest:cssIdChar* { return collapse([start, rest]); } cssIdStart "start of CSS identifier" = [a-zA-Z_] / escapedChar / "-" ([a-zA-Z_] / escapedChar) cssIdChar "rest of CSS identifier" = [-a-zA-Z0-9_] / escapedChar escapedChar "escape sequence" = "\\" (escapedUnicode / .) escapedUnicode "1-6 hexadecimal digits (unicode escape)" = d0:hexd (d1:hexd (d2:hexd (d3:hexd (d4:hexd d5:hexd?)?)?)?)? { return [d0, d1, d2, d3, d4, d5].join(""); } hexd "hexadecimal digit" = [0-9a-fA-F] cssFunctional "pseudo-selector or functional selector" = ":" cssIdentifier ( "(" cssArg ")" )? cssAttrExpr "attribute selector" = "[" cssIdentifier ( [|~\*^$]? "=" (cssIdentifier / quotedString) )? "]" quotedString "quoted string" = "'" (escapedChar / [^\'])* "'" / '"' (escapedChar / [^\"])* '"' cssArg "functional selector argument" = anpbOddEven / uint / jqSelector anpbOddEven "'an+b' expression, 'odd', 'even', or integer" = [-\+]? uint? [nN] (ws* [-\+] ws* uint)? / [-\+] uint / "even" / "odd" uint "unsigned integer" = [1-9][0-9]* / "0" </code></pre> <p>Compiled JS parser &amp; minimal interactive tester is here: <a href="http://jsfiddle.net/np6BD/" rel="nofollow">http://jsfiddle.net/np6BD/</a></p> <p><strong>UPDATE</strong></p> <p>Incorporating suggestions regarding the JS:</p> <pre><code> { /* * glom the array contents returned by the parser * into a string recursively. * Elses aren't logically necessary to perform this function, * but if I use code folding in my IDE, it still looks like it * does what it does if I include the elses. * Changed name from "collapse" to prevent confusion about * the other sense of the word in the cws token. * Changed reduce/concat to map/join. */ function serialize(stuff) { if (typeof stuff === "string") { return stuff; } else if (stuff instanceof Array) { return stuff.map(serialize).join(""); } else { return ""; } } /* * Replace superfluous white space with a single space. * Function moved to the cws token */ } start = jqSelector ws "white space" = whites:(" " / "\r" / "\n" / "\t" / "\f")+ { return serialize(whites); } iws "ignored white space" = ws? { return ""; } cws "collapsed white space" = ws:ws { if (ws) { if (ws instanceof Array) { return !!ws.length ? " " : ""; } else { return " "; } } else { return ""; } } jqSelector "jquery-compatible selector" = element:(tagIdClassSelector / cssFunctional / cssAttrExpr)+ more:(iws [\+>~,] iws jqSelector / cws jqSelector)? { return serialize([element, more]); } tagIdClassSelector "tag, id, or class selector" = [#\.]? cssIdentifier / "*" cssIdentifier "CSS identifier" = start:cssIdStart rest:cssIdChar* { return serialize([start, rest]); } cssIdStart "start of CSS identifier" = [a-zA-Z_] / escapedChar / "-" ([a-zA-Z_] / escapedChar) cssIdChar "rest of CSS identifier" = [-a-zA-Z0-9_] / escapedChar escapedChar "escape sequence" = "\\" (escapedUnicode / .) escapedUnicode "1-6 hexadecimal digits (unicode escape)" = d0:hexd (d1:hexd (d2:hexd (d3:hexd (d4:hexd d5:hexd?)?)?)?)? { return [d0, d1, d2, d3, d4, d5].join(""); } hexd "hexadecimal digit" = [0-9a-fA-F] cssFunctional "pseudo-selector or functional selector" = ":" cssIdentifier ( "(" cssArg ")" )? cssAttrExpr "attribute selector" = "[" cssIdentifier ( [|~\*^$]? "=" (cssIdentifier / quotedString) )? "]" quotedString "quoted string" = "'" (escapedChar / [^\'])* "'" / '"' (escapedChar / [^\"])* '"' cssArg "functional selector argument" = anpbOddEven / uint / jqSelector anpbOddEven "'an+b' expression, 'odd', 'even', or integer" = [-\+]? uint? [nN] (ws* [-\+] ws* uint)? / [-\+] uint / "even" / "odd" uint "unsigned integer" = [1-9][0-9]* / "0" </code></pre>
[]
[ { "body": "<p>I can only review the JS part, <a href=\"https://codereview.meta.stackexchange.com/q/1345/14625\">I am not sure that grammar reviews are part of CR</a>.</p>\n\n<p><strong>collapse</strong></p>\n\n<ul>\n<li><code>else</code> branches after a <code>return</code> do not make sense.</li>\n<li>I would propose <code>map</code>/<code>join</code> instead of <code>reduce</code>/<code>concat</code></li>\n</ul>\n\n<p>Something likes this: </p>\n\n<pre><code>function collapse(stuff) {\n if (typeof stuff === \"string\")\n return stuff;\n if (stuff instanceof Array) \n return stuff.map(function ( value ) {\n return collapse( value );\n }).join(\"\");\n return \"\";\n}\n</code></pre>\n\n<p><strong>trimWs</strong></p>\n\n<p>The function does not match the comment, and I cannot see what it is supposed to do. You need a better function name, a better parameter name and a proper comment explaining what it does and how it is used.</p>\n\n<p><strong>Update</strong></p>\n\n<pre><code>trimWs( \"abc\" ) -&gt; Returns \" \"\ntrimWs( \" \" ) -&gt; Returns \" \"\ntrimWs( \" \" ) -&gt; Returns \" \"\ntrimWs( \"\\t\" ) -&gt; Returns \" \"\ntrimWs( \"\" ) -&gt; Returns \"\"\ntrimWs( \" abc \" ) -&gt; Returns \" \"\nIf this function were trimming, it would return \"abc\" for the last call\n</code></pre>\n\n<p>Basically it returns a space except for provided empty strings and empty arrays. The code could very well be:</p>\n\n<pre><code>function reduceToSingleSpace( x ) {\n return ( !x || ( x &amp;&amp; x instanceof Array &amp;&amp; !x.length ) )?\"\":\" \";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T05:52:40.080", "Id": "63467", "Score": "0", "body": "`trimWs` = `trim` `W`hite `s`pace. It determines if any white space is `present` by examining its parameter and returns a single space or nothing. In CSS, `a#foo p.bar` is the same as `a#foo p.bar` but not the same as `a#foop.bar`. Can't get rid of the spaces altogether, but there's no point in holding onto more than one. Can you give me an example of a more appropriate name? Good call on map/join, will do, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T11:23:20.517", "Id": "63488", "Score": "0", "body": "In the above comment, the second `a#foo p.bar` was supposed to have many spaces. Not sure where they went. Ironically, that's exactly what the function does - get rid of extraneous white space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T14:40:56.533", "Id": "63502", "Score": "0", "body": "Updated the answer, not too excited by `reduceToSingleSpace`, but that's the best I could come up with so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-28T05:04:39.277", "Id": "63604", "Score": "0", "body": "`trimWs(\" abc \")` is where the PEG is important; `trimWs` is only called to process the `cws` (for `c`ollapsed `w`hite `s`pace) token. I suppose I should probably both rename `collapse` to `serialize` (to avoid confusion about the two senses of the word collapse) and move the body of `trimWs` to be an anonymous function in the `cws` token? What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-28T17:27:00.270", "Id": "63638", "Score": "0", "body": "It sounds better than what you have now or what I proposed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-29T03:26:11.530", "Id": "63671", "Score": "0", "body": "Alright, updating with revision, and waiting for either feedback on the PEG or a determination that it's OT for accept." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T02:16:56.183", "Id": "38146", "ParentId": "35487", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T18:19:06.153", "Id": "35487", "Score": "4", "Tags": [ "javascript", "css", "parsing", "grammar", "peg.js" ], "Title": "PEG.js grammar for parsing CSS selectors" }
35487
<p>This is my first foray into the wild world of jQuery plugin development. The plugin "ajaxifies" forms, which isn't particularly spectacular: </p> <ul> <li>It gets the basics (action, method) from the form itself, serializes the form's fields, and sends the request. </li> <li>Users can provide (via its options) callback functions for the local ajax events (beforeSend, complete, success and error). </li> <li>The dataType can also be set from a custom data attribute, which - if present - takes precedence.</li> </ul> <p>Everything seems to be working as expected (<a href="https://github.com/yrizos/ajaxForm" rel="nofollow">repo</a>, with a <a href="https://github.com/yrizos/ajaxForm/tree/master/demo" rel="nofollow">simple demo</a>). Since this is my first plugin, I'd be particularly interested in critiques of its structure. That said, as always in reviews, any aspect of the code is fair game for criticism. </p> <p><strong>The plugin code:</strong></p> <pre><code>(function ($) { $.fn.ajaxForm = function (options) { var settings = $.extend({}, $.fn.ajaxForm.defaults, options); return this.each(function () { var $form = $(this); dataType = $form.attr("data-dataType"); if (typeof dataType != "undefined") dataType = settings.dataType; $form.on("submit", function (event) { event.preventDefault(); $.ajax({ type: $form.attr("method"), url: $form.attr("action"), data: $form.serialize(), cache: false, dataType: dataType, beforeSend: function () { $form.addClass("ajaxForm-loading"); if (typeof settings.beforeSend == "function") settings.beforeSend.call($form); }, complete: function () { $form.removeClass("ajaxForm-loading"); if (typeof settings.complete == "function") settings.complete.call($form); }, success: function (response) { if (typeof settings.success == "function") settings.success.call($form, response); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (typeof settings.error == "function") settings.error.call($form, XMLHttpRequest, textStatus, errorThrown); } }); }); }); }; $.fn.ajaxForm.defaults = { dataType: "json", beforeSend: function () {}, complete: function () {}, success: function () {}, error: function () {} }; })(jQuery); </code></pre> <p><strong>Initialization:</strong></p> <pre><code>$(document).ready(function () { $("form").ajaxForm({ dataType: "html", success: function (response) { console.log(response); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log("Oops: " + errorThrown); } }); }); </code></pre>
[]
[ { "body": "<p>Structure and style looks fine, although I have some general notes:</p>\n\n<ul>\n<li>Prefer the strong (in)equality operators (<code>!==</code> and <code>===</code>) whenever possible</li>\n<li>Always use braces, even for one-line \"blocks\". It's nice to save a few keystrokes, but personally I prefer the consistency of always using braces</li>\n<li>You could skip the defaults for the <code>beforeSend</code>, <code>complete</code>, etc. callbacks and leave them undefined. Defining them as empty functions is fine, but not necessary with the checks you're doing.</li>\n</ul>\n\n<p>In terms of features/behavior:</p>\n\n<p>I'd highly suggest simply modifying the user's settings, and then passing them to <code>$.ajax()</code>, rather than declare a new object. That way, users can set whatever extra ajax options they want, and not see them ignored. In other words, let your plugin fill in the blanks in the settings the user passes in, not the other way around.</p>\n\n<p>Besides that:</p>\n\n<ul>\n<li>You may want to skip elements that aren't actually forms</li>\n<li>It'd probably be wise to use <code>$form.data(\"dataType\")</code> instead of <code>$form.attr()</code> in case the data type was set using <code>.data()</code> and isn't a real attribute.</li>\n<li>Speaking of data type, you should check if it's a string specifically, since that's the only thing jQuery wants anyway.</li>\n<li>Lastly about the data type: I don't think your plugin should define a <code>\"json\"</code> default. Better to let the be defined explicitly by whomever is using the plugin, or leave it at jQuery's default.</li>\n</ul>\n\n<p>Most importantly: Please forward any and all arguments to the callbacks. For instance, the regular <code>beforeSend</code> receives the XHR object and its settings, but if I specify a <code>beforeSend</code> using this plugin, I won't get those. Since the name's the same, I'd expect it to receive the same arguments. I like to use <code>beforeSend</code> to grab the XHR so I can use it as a Deferred/Promise object, but I can't do that here.</p>\n\n<p>By the way, it'd be in the spirit of jQuery to invoke the callbacks in the <em>element's</em> context, not in the context of the jQuery wrapper around the element. But if you follow my suggestion of modifying the settings rather than replacing them, be sure to note in your documentation that this context-switching only applies to those four callbacks. E.g. if I declare a dynamic <code>201</code> callback to handle the <code>201 Created</code> status code, it won't be called in the element's context (and I can think of a clean way to make it happen).</p>\n\n<p>You may also want to get some of the form's attributes using <code>.prop()</code> instead of <code>.attr()</code>. For instance, a <code>method</code> attribute is not required (it'll default to \"GET\" in that case). Also, the <code>accept</code> attribute is worth checking and carrying over to the ajax options, if present.</p>\n\n<p>Here's what I came up with (untested)</p>\n\n<pre><code>(function ($) {\n $.fn.ajaxForm = function (options) {\n options = $.extend({}, $.fn.ajaxForm.defaults, options);\n\n // A simple helper function\n function callHandler(name, form, args) {\n if(typeof options[name] === \"function\") {\n options[name].apply(form, [].slice.call(args, 0));\n }\n }\n\n return this.each(function () {\n var settings,\n form = this;\n\n settings = $.extend({}, {\n action: $form.prop(\"action\"),\n method: $form.prop(\"method\"),\n accepts: $form.attr(\"accept\"),\n dataType: $form.data(\"dataType\")\n }, options);\n\n settings.beforeSend = function () {\n $form.addClass(\"ajaxForm-loading\");\n callHandler(\"beforeSend\", form, arguments);\n };\n\n settings.complete = function () {\n $form.removeClass(\"ajaxForm-loading\");\n callHandler(\"complete\", form, arguments);\n };\n\n settings.success = function () {\n callHandler(\"success\", form, arguments);\n };\n\n settings.error = function () {\n callHandler(\"error\", form, arguments);\n };\n\n $(this).on(\"submit\", function (event) {\n event.preventDefault();\n $.ajax(settings);\n });\n });\n };\n\n $.fn.ajaxForm.defaults = {};\n\n})(jQuery);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:26:16.953", "Id": "57642", "Score": "0", "body": "Thanks! I've already applied some of your fixes, you can see the result [here](https://github.com/yrizos/ajaxForm/blob/master/ajaxForm/ajaxForm.js). The one thing I ignored (for the moment) is `$.data()`, will need to look into it a bit more (had no idea what it was). When I get around to writing a readme.md, would it be ok to point to your answer from it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T15:13:58.280", "Id": "57648", "Score": "0", "body": "The [`.data()`](http://api.jquery.com/data/) stuff is an edge case concern, but yes, do look into it (it's useful regardless). The point is just that `.data()` will transparently _read_ `data-*` attributes on the element, but it won't _write_ them. See [this fiddle](http://jsfiddle.net/d3ejc/). And sure, you can link to this, if you want. Everything we add here is automatically Creative Commons licensed anyway. But do try writing it yourself - it's always a good exercise and sometimes makes you rethink stuff." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:31:12.637", "Id": "35508", "ParentId": "35488", "Score": "4" } } ]
{ "AcceptedAnswerId": "35508", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T18:40:02.790", "Id": "35488", "Score": "4", "Tags": [ "javascript", "jquery", "ajax", "plugin" ], "Title": "jQuery plugin to ajaxify forms" }
35488
<p>I've answered <a href="https://stackoverflow.com/questions/20020300/validate-excel-imported-data/20021825#20021825">this</a> question on Stack Overflow. The problem is - there are 30 columns in an Excel sheet and I need to validate each of the fields with different validation logic. The code should avoid a lot of if-else blocks. I have used strategy pattern to solve this. I would like to get a review of this code.</p> <pre><code>interface IValidator&lt;T&gt; { boolean validate(T field); } class SomeFieldOne&lt;T&gt; implements IValidator&lt;T&gt; { public boolean validate(T field) { System.out.println("SomeFieldOne validation"); return true; // return true/false based on validation } } class SomeFieldTwo&lt;T&gt; implements IValidator&lt;T&gt; { public boolean validate(T field) { System.out.println("SomeFieldTwo validate"); return true; // return true/false based on validation } } class Context { private IValidator validator; public Context(IValidator validator) { this.validator = validator; } public boolean validate(String field) { return this.validator.validate(field); } } public class TestValidation { public static void main(String[] args) { Context context; context = new Context(new SomeFieldOne()); System.out.println(context.validate("some field one")); context = new Context(new SomeFieldTwo()); System.out.println(context.validate("some field two")); // test other fields .... // ......... } } </code></pre>
[]
[ { "body": "<p>First of all, you're not using your generics properly here: </p>\n\n<pre><code>private IValidator validator;\n</code></pre>\n\n<p>I would change this to </p>\n\n<pre><code>private final IValidator&lt;String&gt; validator;\n</code></pre>\n\n<p>Because:</p>\n\n<ol>\n<li><strong>final</strong> because the value does not change, and should not change. The field should be <strong>immutable</strong></li>\n<li><code>&lt;String&gt;</code> to use generics properly. Otherwise you should get a compiler warning saying <code>IValidator is a raw type. References to generic type IValidator&lt;E&gt; should be parameterized</code></li>\n</ol>\n\n<p>However, I think your <code>Context</code> is not very useful. I don't see any reason for why you need it. You can accomplish the exact same things by using:</p>\n\n<pre><code>public class TestValidation {\n public static void main(String[] args) {\n IValidator&lt;String&gt; context;\n context = new SomeFieldOne();\n System.out.println(context.validate(\"some field one\"));\n context = new SomeFieldTwo();\n System.out.println(context.validate(\"some field two\"));\n // test other fields ....\n // .........\n }\n}\n</code></pre>\n\n<p>This is less code and has the same effect. And it also looks better and improves readability as changing strategy now calls only one constructor instead of two.</p>\n\n<p>I assume you're compiling with Java 1.6 or above, and therefore your classes that implements the <code>IValidator</code> interface should mark the <code>validate</code> method with <code>@Override</code> to comply with the Java coding conventions. (Marking methods with @Override that overrides interface methods was not supported at all in previous Java versions)</p>\n\n<pre><code>@Override\npublic boolean validate(T field) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T20:09:27.897", "Id": "35492", "ParentId": "35491", "Score": "10" } }, { "body": "<p>At times using pattern may overkill the structure. I am not saying that the pattern you used here is not good, but I wanted show that there is also another way where you can pass different block of code to achieve validation for different type of fields. </p>\n\n<pre><code>interface Block&lt;T&gt; {\n public boolean value(T arg);\n}\n\nclass FieldValidator {\n public static &lt;T&gt; boolean validate(T element, Block&lt;T&gt; block) {\n return block.value(element);\n }\n}\n\npublic class UnitTest {\n public static void main(String[] args) {\n // some int field validattion\n System.out.println(FieldValidator.validate(2, new Block&lt;Integer&gt;() {\n public boolean value(Integer arg) {\n System.out.println(\"validating - \" + arg);\n return true; // return true/false \n }\n }));\n\n // some string field validation\n System.out.println(FieldValidator.validate(\"some field 1\", new Block&lt;String&gt;() {\n public boolean value(String arg) {\n System.out.println(\"validating - \" + arg);\n return true; // return true/false \n }\n }));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:16:46.450", "Id": "57636", "Score": "1", "body": "`return block.value(element) ? true : false;` can be simplified to `return block.value(element);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T15:30:29.393", "Id": "57651", "Score": "0", "body": "yes, I missed that, let me edit it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T21:35:04.773", "Id": "35496", "ParentId": "35491", "Score": "4" } }, { "body": "<p>I have heard from some people that you don't want to use design patterns as templates for writing code, the patterns are meant to show you how different pieces of code fit together, on a larger scale you may use many different Patterns by the time you are done with an application. so don't just pick a pattern and try to make your idea fit that pattern, it may or may not work the way that you want or need it to. keep thinking outside the box.</p>\n\n<p>not really a code review, but I think that the question warranted an answer that talked about patterns even if I only floated on the surface</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T07:51:46.657", "Id": "58535", "Score": "0", "body": "@Ravi Kumar's implementation looks more like trying to \"fit\" Strategy Pattern into Validation class.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:15:53.433", "Id": "35896", "ParentId": "35491", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:48:07.520", "Id": "35491", "Score": "12", "Tags": [ "java", "design-patterns" ], "Title": "Validation class to avoid ugly if-else blocks" }
35491
<p>I have implemented a solution to <a href="http://projecteuler.net/problem=5" rel="nofollow">Project Euler problem 5</a>:</p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>My solution uses Python 2.7, and consists of a module I created that finds prime factors of numbers - the <code>factorization</code> module. It contains the functions <code>factors()</code> and <code>primegen()</code> which are implemented in the eponymous Python source files. At the top level of the project, I define a function <code>smallest_multiple()</code> that uses <code>factors()</code> and in that same file a <code>main()</code> function to drive it.</p> <p><strong><code>factorization</code> module</strong>:</p> <p>primegen.py:</p> <pre><code>import itertools def primegen(upper): """Return generator yielding all primes less than upper &gt;&gt;&gt; list(primegen(10)) [2, 3, 5, 7] &gt;&gt;&gt; list(primegen(30)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] """ # http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes marked = [False] * (upper - 2) # using generator here lets us lazily evaluate whether # a number has been marked def next_p(): for i,v in enumerate(marked): if not v: yield i def generate_primes(): for p_idx in next_p(): p = p_idx + 2 cursor = p while True: cursor = cursor + p try: marked[cursor-2] = True except IndexError: break yield p return generate_primes() </code></pre> <p>factors.py:</p> <pre><code>from factorization.primegen import primegen def factors(n): """generator function yielding the prime factors of n Heavily derived from http://en.wikipedia.org/wiki/Trial_division &gt;&gt;&gt; list(factors(14)) [2, 7] &gt;&gt;&gt; list(factors(13195)) [5, 7, 13, 29] &gt;&gt;&gt; list(factors(8)) [2, 2, 2] """ for p in primegen(int(n**0.5) + 1): # sqrt(n) &lt; p =&gt; n = q * (p^k), where k is 0 or 1, and q is product of each element of factors if p*p &gt; n: break # append factor for each time it appears while not n%p: yield p n = n / p if n &gt; 1: yield n </code></pre> <p><strong>Top-level</strong>:</p> <p>e5.py:</p> <pre><code>#!/usr/bin/env python from factorization.factors import factors def smallest_multiple(n): """Returns smallest multiple evenly divisble by each 1..n in N &gt;&gt;&gt; smallest_multiple(10) 2520 """ # for each number &lt;= n, find its prime factors p1^k1, p2^k2, ... # store as prime =&gt; exponent # replace existing stored exponents only if the replacement is greater # for each prime=&gt;exponent # result = result * prime^exponent factor_exp_map = {} for i in xrange(n,0,-1): facs = list(factors(i)) for factor in facs: fact_count = facs.count(factor) cur_fact_count = factor_exp_map.get(factor,0) if (fact_count &gt; cur_fact_count): factor_exp_map[factor] = fact_count result = 1 for factor, exponent in factor_exp_map.iteritems(): result = result * factor**exponent return result def main(): print('result = {0}'.format(smallest_multiple(20))) if __name__ == '__main__': main() </code></pre> <p>The entire project can be found <a href="https://github.com/cveazey/ProjectEuler/tree/master/5" rel="nofollow">on Github</a>. Its only additions are a Sublime Text 2 project and some scripts to enable running the doctests from within the editor.</p> <p>I do have some specific concerns about this code. I find that <code>smallest_multiple()</code> is weird and clunky - especially iterating through each element of factors and asking for its count. It seems there should be some more elegant way to aggregate the factors and their exponents. I wonder if my docstrings and doctests are reasonably correct, and if my module organization is coherent. I'm also wondering if I'm abusing generators, particularly in the doctests where I call <code>list()</code> on each generator to get the result, and the nested generator functions in <code>primegen()</code>.</p> <p>Generally, I'd also like feedback on how Pythonic this code is. I've tried to keep <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> in mind, but any deviations I've hastily overlooked would be good to know about. I also didn't do much in terms of input validation and robustness, so general advice on the idiomatic ways of doing so would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T00:09:04.780", "Id": "57552", "Score": "0", "body": "The problem with your approach is on the maths side: you are being asked, with other words, what's the least common multiple of range (1..20)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:18:15.690", "Id": "57569", "Score": "0", "body": "@tokland Thanks. To be clear, I don't believe there is any trouble with this code doing what I want - the program successfully answered the problem. I'm looking for a code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T15:23:11.380", "Id": "57649", "Score": "0", "body": "Carl Veazy Have a look at J.F.Sebastian's answer to [this SO question](http://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers) to see what tokland means." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:10:49.160", "Id": "57704", "Score": "0", "body": "@steenslag thanks - solved the problem on paper first using prime factorization so hadn't thought to investigate a different approach. I appreciate the explanation!" } ]
[ { "body": "<p>Let me put what @tokland said in another way. In the Zen of Python there is a sentence <code>If the implementation is hard to explain, it's a bad idea.</code>. The same thing that you are doing can be done <strong>much</strong> more efficiently and <strong>clearly</strong> by changing the algorithm used. </p>\n\n<p>Unless you wanted to make a prime generator for some other thing and used this exercise as an excuse to get on with making it, using prime generation here is a bad idea. Bad according to Python's readability view because <code>Simple is better than complex.</code>. For efficiency just try running your code and <a href=\"https://github.com/anshbansal/general/blob/9ed2beac825f38d45e0e66caecdda4d28f39d8c7/Python27/project_euler/001_050/005.py\" rel=\"nofollow\">this code</a> for 1000.</p>\n\n<p>Now getting with your code itself. </p>\n\n<p><strong>primegen.py</strong><br>\nWhy didn't you make the <code>generate_primes</code> as your top level function with a nested <code>next_p</code>? For all intents and purposes it is doing everything. The initialization of <code>marked</code> could have been easily done inside the function and it would have become a lot clearer what you are doing. Currently you are returning a generator from the function call which is yielding required values while you could have directly called the generator itself which would have yielded values. There is an unnecessary level of indirection here.</p>\n\n<p><strong>factors.py</strong><br>\n<strike>The calculation of square root should have been done before the loop. It is calculated at every iteration of the loop while it is actually used once as the function being called here is a generator.</strike> That's what I thought when I saw your code the first time. Ignore that because that's not happening here. Just telling you what kind of confusion you have created in <code>primegen.py</code></p>\n\n<p>Just to be clear, nested generators aren't the problem here.</p>\n\n<ul>\n<li>If you are writing for efficiency alone then <code>while not n%p</code> is perfectly ok. </li>\n<li>Go for <code>while n % p != 0</code> if you want a middle ground between efficiency and readability.</li>\n<li><strike>For readability <code>while n % p is not 0</code> is the preferable one. Its basically English.</strike> As has been said in the comments, this isn't the correct way to do it.</li>\n</ul>\n\n<p>I am leaving the top module for now. Myabe review it later.</p>\n\n<p>I hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:08:15.757", "Id": "57703", "Score": "0", "body": "Thanks for your feedback! When I figured out lcm by prime factorization I ended up re using the factorization code from a previous problem hence them being in their own module. Hadn't thought to pursue a different algorithm but research shows you're right. Could you clarify a bit about the square root comments - and particularly the \"ignore that\" comment?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:01:03.350", "Id": "57711", "Score": "1", "body": "\" while n % p is not 0\": no. `is` tests identity, not equality, and should never be used for numerical comparisons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T14:50:10.887", "Id": "57938", "Score": "0", "body": "@DSM Yeah, it checks for identity but if just used for numbers then it will give the same results as equality. For objects (and hence composite data types) it should not be used as equality. Here the check is for numbers only. So is that still a problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:40:52.080", "Id": "58112", "Score": "1", "body": "`is` only works for a certain range of small integers (try `501 is 500+1` for a counter-example), and even that is an implementation detail of CPython." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T16:51:34.347", "Id": "58372", "Score": "0", "body": "@CarlVeazey The ignore that line (now struck through) was what I had thought when I first saw your code. But my thought was incorrect and your code was correct. I added my incorrect thought to show that the code's design could create confusion. That or maybe I am just a Python noob :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T11:47:48.673", "Id": "35531", "ParentId": "35499", "Score": "1" } }, { "body": "<p>It's pretty good Python. My opinions are:</p>\n\n<ul>\n<li>It might be slightly over-engineered. For a small problem like this, simplicity would be preferable to scalability. For example, you could do without the Sieve of Eratosthenes.</li>\n<li>Gathering repeated prime factors into exponents should probably be considered the responsibility of the <code>factors()</code> function.</li>\n<li>Your code would be more compact if you used a more functional (instead of procedural) style, and clearer if you used more mathematical vocabulary (e.g. \"product\" and \"least common multiple\").</li>\n</ul>\n\n<p>A <a href=\"https://codereview.stackexchange.com/a/33752/9357\">previous review</a> illustrates these principles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T04:55:11.950", "Id": "58064", "Score": "0", "body": "I did re-use some code for another prime generation hence the presence of the sieve and the over-engineering. Could you explain what you mean a 'functional' approach? Could you give a specific example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:36:28.410", "Id": "58068", "Score": "0", "body": "Functional programming in 600 chars? [Start](http://docs.python.org/2/howto/functional.html#built-in-functions) with [examples](http://ibm.com/developerworks/linux/library/l-prog/). Think in big-picture terms of pushing data through transformations. Use list comprehensions, recursion, `lambda`, `map()`, `filter()`, `reduce()`. Pass functions as parameters to functions. Avoid mutation (assigning a value to a variable then changing it) and loops. Read and do [tag:sicp] (chapters 1 and 2). Realize the [limits](http://stackoverflow.com/q/1017621) of functional programming in Python." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:41:33.903", "Id": "35711", "ParentId": "35499", "Score": "1" } }, { "body": "<p>A couple of things that stick in my eye:</p>\n\n<ol>\n<li>Each call to <code>factors</code> runs the sieve of Eratosthenes again from scratch. </li>\n<li><p>This...</p>\n\n<pre><code>cursor = p\nwhile True:\n cursor = cursor + p\n try:\n marked[cursor-2] = True\n except IndexError:\n break\n</code></pre>\n\n<p>...is a rather clunky substitute for a <code>for</code> loop like this:</p>\n\n<pre><code>for cursor in xrange(2*p-2, len(marked), p):\n marked[cursor] = True\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:32:16.770", "Id": "35779", "ParentId": "35499", "Score": "1" } } ]
{ "AcceptedAnswerId": "35531", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T22:43:49.740", "Id": "35499", "Score": "4", "Tags": [ "python", "programming-challenge", "primes" ], "Title": "Project Euler #5 (LCM of [1, 2, …, 20])" }
35499
<p>Can you please take a look at the following x86-64 C++ code which should implement a multi consumer/produce lockfree stack? Do you think I have missed anything?</p> <pre><code>namespace lockfree { // NOTE: this lock-free stack uses the highest 2 bytes // of each pointer to store a 'counter' (an "id") to // ensure that the ABA problem doesn't happen in case // of multiple consumers. // If the stack was to be read by _one only_ consumer // the ABA problem wouldn't manifest and the code would // not need the 'counter' escamotage. // Using an unsigned short is ok-ish because 65536 values // might not be enough in some cases. Ideally we should // be using 32+ bits. template&lt;typename T&gt; class stack { struct element { element *next; const T data; element(const T&amp; data_) : data(data_) { } private: element(const element&amp;); element&amp; operator=(const element&amp;); }; // NOTE: we use the highest 16 bits as counter // this trick should perform ok for quite // _a while_ on Linux 64-bit... static const unsigned short get_ptr_cnt(element** p) { unsigned short *us_p = (unsigned short *)p; return us_p[3]; } // NOTE: same as above! static void set_ptr_cnt(element** p, const unsigned short cnt) { unsigned short *us_p = (unsigned short *)p; us_p[3] = cnt; } element *_head; public: // this lockfree stack can only be initialised and destroyed // in single threaded contexts stack() : _head(0) { } // clean the stack (only in single threaded context!) ~stack() { element *head_ptr = _head; set_ptr_cnt(&amp;head_ptr, 0); while(head_ptr) { element *next = head_ptr-&gt;next; delete head_ptr; head_ptr = next; set_ptr_cnt(&amp;head_ptr, 0); } _head = 0; } void push(const T&amp; data) { // first create an element to be pushed element *to_be_pushed = new element(data); // make sure the highest 16 bits are always // 0 and not part of the address. This check // should always return _false_ on modern x86-64 if(0 != get_ptr_cnt(&amp;to_be_pushed)) { int* p = 0; *p = 1; } while(1) { // get current head in local variable element *local_head = _head; to_be_pushed-&gt;next = local_head; // adjust the pointers and add counter const unsigned short cur_cnt = get_ptr_cnt(&amp;local_head) + 1; set_ptr_cnt(&amp;to_be_pushed, cur_cnt); // compare and swap if(__sync_bool_compare_and_swap(&amp;_head, local_head, to_be_pushed)) return; // otherwise reset the counter to 0 and prepare for another round set_ptr_cnt(&amp;to_be_pushed, 0); } } bool pop(T&amp; data) { while(1) { // get the current head and next head // important to get from local_head variable! element *local_head = _head; // get the counter const unsigned short head_cnt = get_ptr_cnt(&amp;local_head); // reset the counter to get real pointer set_ptr_cnt(&amp;local_head, 0); if(!local_head) break; element *next_head = local_head-&gt;next; // set again original counter and next head set_ptr_cnt(&amp;local_head, head_cnt); set_ptr_cnt(&amp;next_head, head_cnt+1); // compare and swap the local head with head if(__sync_bool_compare_and_swap(&amp;_head, local_head, next_head)) { // reset the counter once more set_ptr_cnt(&amp;local_head, 0); data = local_head-&gt;data; delete local_head; return true; } } return false; } }; } </code></pre> <p>I've written even the version which stores the counter in another 64 bit <code>size_t</code> and implicitly uses <code>cmpxchg16b</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T09:39:40.100", "Id": "57625", "Score": "0", "body": "Please note that there's a question related to this one, http://codereview.stackexchange.com/questions/35518/is-throughput-performance-of-lockfree-stack-in-line-with-expectations , about the throughput of such container (don't _really_ mind about code review in that one)." } ]
[ { "body": "<p>I don't see any problem with the locking, although it is usually quite difficult to see race conditions (which is why you posted it I guess). The code is clearly non-portable (but maybe that is not important), with regard to endian-ness and because <code>unsigned short</code> is not guaranteed to be 16 bits (uint16_t is). </p>\n\n<p>I did wonder about two lines that seem unnecessary. Firstly, setting the count after the swap in <code>push</code>: </p>\n\n<pre><code>if(__sync_bool_compare_and_swap(&amp;_head, local_head, to_be_pushed))\n return;\nset_ptr_cnt(&amp;to_be_pushed, 0); // this line\n</code></pre>\n\n<p>Secondly setting the count on <code>next_head</code> in <code>pop</code></p>\n\n<pre><code>set_ptr_cnt(&amp;local_head, head_cnt);\nset_ptr_cnt(&amp;next_head, head_cnt+1); // this line\nif(__sync_bool_compare_and_swap(&amp;_head, local_head, next_head)) {\n</code></pre>\n\n<p><hr>\n<strong>EDIT</strong> - after discussion with Emanuele, it is clear that the first of these (resetting the <code>to_be_pushed</code> pointer's counter) is absolutely necessary. The second however (<code>set_ptr_cnt(&amp;next_head, head_cnt+1);</code>) is not, but instead is currently (but not reliably) causing the compiler to generate code that 'works'. The reason, I think, is that the stack is really volatile - meaning that the compiler cannot assume that pointer or data values do not change and cannot optimize access to these locations.</p>\n\n<p>So <code>_head</code> maybe should be declared </p>\n\n<pre><code>volatile element *_head;\n</code></pre>\n\n<p>and other references to the stack maybe too. Having said that, I have modified the code to use <code>volatile</code> for <code>_head</code> and elsewhere (see previous edit) but have been unable to make the compiler take any notice - in other words the assembler code generated with <code>volatile</code> has been the same as that without (gcc -S -O3 using gcc 4.2.1 and 4.4.5). So maybe volatile is not the answer...</p>\n\n<hr>\n\n<p>As regards coding style, I think the code is heavily over-commented. Most of the comments are not very useful and could be omitted. Also the variable names are verbose or cryptic. To make the code more readable, I did a global deletion of <code>_ptr</code>, and a global replace of:</p>\n\n<ul>\n<li><code>local_head</code> -> <code>head</code> </li>\n<li><code>next_head</code> -> <code>next</code> </li>\n<li><code>_head</code> -> <code>stack_head</code> (leading underscores should be avoided as they are, I think, reserved, and in any case add nothing).</li>\n<li><code>head_cnt</code> -> <code>count</code> </li>\n<li><code>*_cnt</code> -> <code>*_count</code></li>\n</ul>\n\n<p>Finally, the compiler warns (-Wignored-qualifiers) against the <code>const</code> in:</p>\n\n<pre><code>static const unsigned short get_ptr_cnt(element** p) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:39:56.363", "Id": "58185", "Score": "0", "body": "About first point, agreed, might remove it. Not performing `set_ptr_cnt(&next_head, head_cnt+1);` was making ABA problem (or similar) appear because probably of an optimisation? Should look at generated code though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:28:06.360", "Id": "58187", "Score": "0", "body": "No entry can get onto the stack without its counter value being set. And it is the fact that there is a unique count that prevents the ABA problem. So changing the count in `next_head` during `pop` seems to me to have no purpose - but I could easily believe that I am mistaken :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T23:48:15.970", "Id": "58214", "Score": "0", "body": "Was forgetting, as for the first point `set_ptr_cnt(&to_be_pushed, 0);` you need to reset to 0, because you _need_ to use the pointer at each loop!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T00:36:59.243", "Id": "58219", "Score": "0", "body": "Oh, yes! It is obvious now you point it out..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T00:42:46.293", "Id": "58221", "Score": "0", "body": "I've got an explanation for `set_ptr_cnt(&next_head, head_cnt+1);`. I've generated _asm_ (with -S option); seems like this is forcing g++ 4.6.3 to store on the local stack the `next_head` value (which *is* what I wanted), so when _cas_ occurs the generated code won't go and fetch it from memory (which could be changed by another thread), but will use what was stored on the stack as first read. Does it make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:46:02.720", "Id": "58329", "Score": "0", "body": "I think the problem you have (which that `set_ptr_cnt` call is masking) is that `_head` is essentially `volatile` (as is the whole stack). I'll edit my answer accordingly..." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T02:39:49.787", "Id": "35741", "ParentId": "35502", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T01:49:25.963", "Id": "35502", "Score": "4", "Tags": [ "c++", "multithreading", "stack", "lock-free" ], "Title": "Multi producer/consumers lockfree stack" }
35502
<p>I have written a slideshow application and I am looking for some reviews:</p> <pre><code>import sys import os import utils from PyQt4 import QtGui,QtCore class SlideShowPics(QtGui.QMainWindow): """ SlideShowPics class defines the methods for UI and working logic """ def __init__(self, imgLst, parent=None): super(SlideShowPics, self).__init__(parent) # self._path = path self._imageCache = [] self._imagesInList = imgLst self._pause = False self._count = 0 self.animFlag = True self.updateTimer = QtCore.QTimer() self.connect(self.updateTimer, QtCore.SIGNAL("timeout()"), self.nextImage) self.prepairWindow() self.nextImage() def prepairWindow(self): # Centre UI screen = QtGui.QDesktopWidget().screenGeometry(self) size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) self.setStyleSheet("QWidget{background-color: #000000;}") self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.buildUi() self.showFullScreen() self.playPause() def buildUi(self): self.label = QtGui.QLabel() self.label.setAlignment(QtCore.Qt.AlignCenter) self.setCentralWidget(self.label) def nextImage(self): """ switch to next image or previous image """ if self._imagesInList: if self._count == len(self._imagesInList): self._count = 0 self.showImageByPath( self._imagesInList[self._count]) if self.animFlag: self._count += 1 else: self._count -= 1 def showImageByPath(self, path): if path: image = QtGui.QImage(path) pp = QtGui.QPixmap.fromImage(image) self.label.setPixmap(pp.scaled( self.label.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)) def playPause(self): if not self._pause: self._pause = True self.updateTimer.start(2500) return self._pause else: self._pause = False self.updateTimer.stop() def keyPressEvent(self, keyevent): """ Capture key to exit, next image, previous image, on Escape , Key Right and key left respectively. """ event = keyevent.key() if event == QtCore.Qt.Key_Escape: self.close() if event == QtCore.Qt.Key_Left: self.animFlag = False self.nextImage() if event == QtCore.Qt.Key_Right: self.animFlag = True self.nextImage() if event == 32: self._pause = self.playPause() def main(paths): if isinstance(paths, list): imgLst = utils.imageFilePaths(paths) elif isinstance(paths, str): imgLst = utils.imageFilePaths([paths]) else: print " You can either enter a list of paths or single path" app = QtGui.QApplication(sys.argv) if imgLst: window = SlideShowPics(imgLst) window.show() window.raise_() app.exec_() else: msgBox = QtGui.QMessageBox() msgBox.setText("No Image found in any of the paths below\n\n%s" % paths) msgBox.setStandardButtons(msgBox.Cancel | msgBox.Open); if msgBox.exec_() == msgBox.Open: main(str(QtGui.QFileDialog.getExistingDirectory(None, "Select Directory to SlideShow", os.getcwd()))) if __name__ == '__main__': curntPaths = os.getcwd() if len(sys.argv) &gt; 1: curntPaths = sys.argv[1:] main(curntPaths) </code></pre> <p><strong>utils.py</strong> module:</p> <pre><code>import os def isExtensionSupported(filename): """ Supported extensions viewable in SlideShow """ if filename.endswith('PNG') or filename.endswith('png') or\ filename.endswith('JPG') or filename.endswith('jpg'): return True def imageFilePaths(paths): imagesWithPath = [] for _path in paths: try: dirContent = os.listdir(_path) except OSError: raise OSError("Provided path '%s' doesn't exists." % _path) for each in dirContent: selFile = os.path.join(_path, each) if os.path.isfile(selFile) and isExtensionSupported(selFile): imagesWithPath.append(selFile) return list(set(imagesWithPath)) </code></pre> <ul> <li>Pressing <kbd>←</kbd> will move the slideshow backwards</li> <li>Pressing <kbd>→</kbd> will move the slideshow forward, which is also default</li> <li>Pressing <kbd>spacebar</kbd> will pause</li> <li>Pressing <kbd>Esc</kbd> will exit</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:08:51.400", "Id": "58159", "Score": "0", "body": "I am thinking to pass list if valid image paths to the SlideShowPics class at the time of initialization so i do not have to have getAllImages method. any opinion?" } ]
[ { "body": "<ul>\n<li>When there are no images to show, you print a message to console and exit without showing the GUI. The problem is that a GUI user probably won't see the console and is left wondering why the program won't start. You could show your window with the text in a label, instead.</li>\n<li>The list of images gets loaded in an indirect way when <code>nextImage</code> sees the list is empty. It would be clearer to pass the list in explicitly, like you already propose in your recent comment.</li>\n<li>You filter filenames for png and jpg endings in two places. If you would introduce another format, it would be easy forget to update both functions. Also, I think it would be better to let Qt decide what it is able to display. So, try to show every file and skip quietly to the next one in case of error.</li>\n<li><code>_openFolder</code> is not used. Please delete dead code before submitting for review.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:20:24.490", "Id": "58383", "Score": "0", "body": "I have updated code as per your suggestions except for the third which I guess will leave it for now. I have also moved two public methods to a separate module `utils.py`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:45:48.500", "Id": "35770", "ParentId": "35506", "Score": "2" } } ]
{ "AcceptedAnswerId": "35770", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:26:35.253", "Id": "35506", "Score": "4", "Tags": [ "python", "image", "pyqt" ], "Title": "Simple PyQt4 image slide show player" }
35506
<p>I've written C# code for solving a maze problem. It works, but I want to optimize it so that it could give me all paths. To solve the maze, I walk on the zeros and assumed that the final is reaching -3. </p> <pre><code>const int MAZE_SIZE = 6; static int[] allowed_move_row = { 0, -1, 0, 1 }; static int[] allowed_move_col = { 1, 0, -1, 0 }; const int MAX_ALLOWED_MOVES = 4; static int[,] Optmaze = new int[MAZE_SIZE, MAZE_SIZE]; static int[,] maze = new int[MAZE_SIZE, MAZE_SIZE] { { -2 , 0 , 0 , 0 , 0 , -1 }, { -1 , 0 , -1 , 0 , -1 , 0 } , { -1 , -1 , -1 , 0 , 0 , 0 } , { -1 , 0 , -1 , -1 , 0 , -1 }, { -1 , -1 , -1 , 0 , 0 , 0 } , { -1 , 0 , -1 , -3 , 0 , 0 } }; static bool Solve(int previous_row, int previous_col, int next_step_no) { for (int i = 0; i &lt; MAX_ALLOWED_MOVES; i++) { int col = previous_col + allowed_move_col[i]; int row = previous_row + allowed_move_row[i]; if (col &lt; 0 || col &gt;= MAZE_SIZE) continue; if (row &lt; 0 || row &gt;= MAZE_SIZE) continue; if (maze[row, col] == -3) return true; if (maze[row, col] != 0) continue; maze[row, col] = next_step_no; if (Solve(row, col, next_step_no + 1)) return true; else maze[row, col] = 0; } return false; } static void Main(string[] args) { Print(maze); Console.WriteLine("-----------Solve-------------"); if (Solve (0, 0, 1) ) Print( maze); else Console.WriteLine("No Result"); } static void Print(int[,] maze) { for (int i = 0; i &lt; maze.GetLength(0); i++) { for (int j = 0; j &lt; maze.GetLength(1); j++) { Console.Write(" " + String.Format("{0,3}",maze[i, j]) + " "); } Console.WriteLine(); } } </code></pre> <p><strong>Outputting:</strong></p> <blockquote> <pre><code> -2 0 0 0 0 -1 -1 0 -1 0 -1 0 -1 -1 -1 0 0 0 -1 0 -1 -1 0 -1 -1 -1 -1 0 0 0 -1 0 -1 -3 0 0 -----------Solve------------- -2 1 2 3 0 -1 -1 0 -1 4 -1 0 -1 -1 -1 5 6 0 -1 0 -1 -1 7 -1 -1 -1 -1 0 8 9 -1 0 -1 -3 11 10 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:20:32.197", "Id": "57573", "Score": "0", "body": "I would parallelize the algorithm to make it search from both ends of the maze and stop when they meet half way. More of a brute force optimization than anything cleaver." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:24:21.897", "Id": "57574", "Score": "4", "body": "You need to fully define \"all paths.\" I could loop around the same two positions a few billion times and then get back on a path that actually finds a solution and this would be a \"path.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:32:16.750", "Id": "57575", "Score": "0", "body": "You can use pathing or search algorithms for this such as [A*](http://en.wikipedia.org/wiki/A*_search_algorithm), [B*](http://en.wikipedia.org/wiki/B*) etc. See wikipedia's the side bar for different approaches to solve pathing problems like this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:37:00.120", "Id": "57576", "Score": "0", "body": "A helpful answer could be: http://stackoverflow.com/a/1523678/1445661" } ]
[ { "body": "<p>Walking all zeros is indeed suboptimal. A good first optimization is to preferentially walk on the zeros that bring you closer to the end point.</p>\n<p>To do this, at each step calculate the Pythagorean distance between the x,y coordinates of the array entry you're considering walking to, and the x,y coordinates of the array entry containing -3. This will be the cost of walking to that square. Store all calculated costs so you don't have to recalculate them.</p>\n<p>Then, continue to preferentially choose lowest-cost next squares until you reach the end or a dead end. In cases of dead ends, simply go back and choose the next lowest-cost square that has yet to be traversed. To do this, you will need to keep some notion of path hierarchy, i.e. which steps lead to which next potential steps. A custom node type will do this for you.</p>\n<p>If you've made it this far, then congratulations! You have a rudimentary A* path-finding algorithm. For a helpful guide to implementing this algorithm I recommend <a href=\"https://web.archive.org/web/20171022224528/http://www.policyalmanac.org:80/games/aStarTutorial.htm\" rel=\"nofollow noreferrer\">this resource</a>.</p>\n<p>There are further enhancements to A* efficiency, such as the Jump Point Search algorithm, which is best for more open spaces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-09-08T16:15:44.503", "Id": "62318", "ParentId": "35509", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:17:44.813", "Id": "35509", "Score": "4", "Tags": [ "c#", "optimization", "recursion", "pathfinding" ], "Title": "Optimizing this maze-solver" }
35509
<p>I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some incite as to how I can do this more efficiently i.e. fewer lines of code.</p> <p>I love to make my code elegant, but I don't see how to do it any better.</p> <pre><code> String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ","); int w = 0, a = 0, y = -1; for(int i = 0; i &lt; x.length(); i++) { if(x.charAt(i) == ',') { w++; } } Double[] z = new Double[w]; for(int i = 0; i &lt; x.length(); i++) { if(x.charAt(i) == ',') { z[a] = Double.parseDouble(x.substring((y + 1), i)); y = i; a++; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:00:30.903", "Id": "57579", "Score": "0", "body": "Fewer lines of code does not mean that your program is more efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:03:15.833", "Id": "57580", "Score": "0", "body": "@Pazis: Whats the distinction?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:12:29.253", "Id": "57581", "Score": "0", "body": "@lukeb28 Calling a function like `orderEveryDogInTheWorld();` will take more time than calling `int x = 0;` and `x = x + 1;`, even though the second example is two lines." } ]
[ { "body": "<p>I suggest next way:</p>\n\n<pre><code> String x = (JOptionPane.showInputDialog(\". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)\") + \",\");\n String[] split = x.split(\",\");\n Double[] z = new Double[split.length];\n int i = 0;\n for (String s : split) {\n if(s.trim().isEmpty()){\n continue;\n }\n try {\n z[i++] = Double.valueOf(s.trim());\n } catch (NumberFormatException e) {\n e.printStackTrace();\n }\n }\n</code></pre>\n\n<p>1)<code>split()</code> instead of loop for <em>','</em></p>\n\n<p>2)validate spaces</p>\n\n<p>read more about <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html\" rel=\"nofollow\">String</a> class and it's functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:06:06.690", "Id": "57582", "Score": "0", "body": "I've never seen split, s.trim, or .isEmpty. Would you mind running through how these functions work? I prefer comprehension to memorization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:11:34.110", "Id": "57583", "Score": "0", "body": "@lukeb28 It will sink in more (requiring less memorization) if you hunt for them in the docs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:01:47.673", "Id": "35511", "ParentId": "35510", "Score": "2" } } ]
{ "AcceptedAnswerId": "35511", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:53:12.320", "Id": "35510", "Score": "1", "Tags": [ "java" ], "Title": "Parsing an array of comma-numbers obtained from an input dialog" }
35510
<p>I've just finished reading <em>Learn You a Haskell</em> and I've started to experiment on my own. I just wanted to create a very simple game system where player A can attack player B.</p> <p>Now I have 2 questions:</p> <ol> <li><p>My <code>autoAttack</code> function was very daunting to write. How could I improve it?</p></li> <li><p>How would I format my <code>autoAttack</code> function correctly? I don't find it very pleasing to read.</p></li> </ol> <p></p> <pre><code>main = print $ createActor `autoAttack` createActor type Vector2= (Float,Float) type Vector3 = (Float,Float,Float) data StatsSystem = StatsSystem {physicalDamage :: Float, spellPower :: Float, health :: Float, mana :: Float, attackRange :: Float, castRange :: Float, attackSpeed :: Float } deriving(Show) data MovementSystem = MovementSystem {direction :: Vector2, speed :: Float, position :: Vector3 } deriving(Show) data Actor = Actor {stats :: StatsSystem, ms :: MovementSystem } deriving(Show) createActor :: Actor createActor = Actor {stats = StatsSystem {physicalDamage = 1.0, spellPower = 1.0, health = 10.0, mana = 1.0, attackRange = 1.0, castRange = 1.0, attackSpeed = 1.0 }, ms = MovementSystem{direction = (1.0,1.0), speed = 50.0, position = (0,0,0) } } autoAttack :: Actor -&gt; Actor -&gt; Actor autoAttack Actor {stats = StatsSystem {physicalDamage = p, spellPower = _, health = _, mana = _, attackRange = _, castRange = _, attackSpeed = _ }, ms = m } Actor {stats = s2, ms = m2 } = Actor {stats = StatsSystem {physicalDamage = physicalDamage s2, spellPower = spellPower s2, health = health s2 - p, mana = mana s2, attackRange = attackRange s2, castRange = castRange s2, attackSpeed = attackSpeed s2 }, ms = m2 } </code></pre>
[]
[ { "body": "<p>First, when you are not using fields in a record, you don't have to use _ to mark that they should be ignored; you only need to include the fields in the pattern that you are actually using.</p>\n\n<p>Second, it is possible to update a couple of fields in a record without respecifying the whole thing from scratch. If <code>x</code> is the name of the old record and you want to set the field <code>a</code> to 42 and <code>b</code> to 24, then the expression <code>x { a = 42, b = 24 }</code> is equal to the record <code>x</code> with <code>a</code> set to 42 and <code>b</code> set to 24.</p>\n\n<p>Putting these ideas together, <code>autoAttack</code> could be rewritten like so:</p>\n\n<pre><code>autoAttack :: Actor -&gt; Actor -&gt; Actor\nautoAttack actor@(Actor {stats = stats@(StatsSystem {physicalDamage = p, health = h}})) =\n actor {stats = stats { health = h - p } }\n</code></pre>\n\n<p>Where we have used the syntax <code>actor@(Actor ..)</code> to bind the <code>Actor</code> to the name <code>actor</code>, which is a useful pattern for when you want to both pattern match on an argument and also have access to its value.</p>\n\n<hr>\n\n<p>Just to be clear, it is worth mentioning that, because data is immutable, changing a couple of fields involves making a full copy of the data structure. (Thanks to Daniel Wagner for bringing this up).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T04:11:27.367", "Id": "57586", "Score": "1", "body": "To be precise: it is in fact _not_ possible (in GHC) to update a couple of fields in a record without rebuilding the whole thing from scratch; however, there is a bit of syntax sugar (which you described well) that makes describing how to rebuild it more palatable than listing the new value of every single field." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T04:49:49.917", "Id": "57587", "Score": "0", "body": "You are right, I can see how my wording might be confusing. I changed \"rebuilding\" to \"respecifying\" and added an end note." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T03:00:24.653", "Id": "35513", "ParentId": "35512", "Score": "7" } }, { "body": "<p>Two things that can help clean a lot of stuff up are the <code>lens</code> library and the <code>RecordWildCards</code> language extension.</p>\n\n<p><code>RecordWildCards</code> allows you to set record fields in a very declarative fashion. See the changes to <code>createActor</code> to get an idea of how that can help.</p>\n\n<p>The various functions in <code>lens</code> help a lot when manipulating nested records. <code>autoAttack</code> becomes much shorter and easier to read (once you've gotten used to the various <code>lens</code> combinators).</p>\n\n<pre><code>{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Lens\n\ndata StatsSystem = StatsSystem {\n _physicalDamage :: Float\n , _spellPower :: Float\n , _health :: Float\n , _mana :: Float\n , _attackRange :: Float\n , _castRange :: Float\n , _attackSpeed :: Float\n } deriving Show\n\ndata MovementSystem = MovementSystem {\n _direction :: (Float, Float)\n , _speed :: Float\n , _position :: (Float, Float, Float)\n } deriving Show\n\ndata Actor = Actor {\n _stats :: StatsSystem\n , _ms :: MovementSystem\n } deriving Show \n\nmakeLenses ''Actor\nmakeLenses ''StatsSystem\nmakeLenses ''MovementSystem\n\ncreateActor :: Actor\ncreateActor = Actor StatsSystem {..} MovementSystem {..} where\n _physicalDamage = 1.0\n _spellPower = 1.0\n _health = 10.0\n _mana = 1.0\n _attackRange = 1.0\n _castRange = 1.0\n _attackSpeed = 1.0\n _direction = (1.0, 1.0)\n _speed = 50.0\n _position = (0.0, 0.0, 0.0)\n\nautoAttack :: Actor -&gt; Actor -&gt; Actor\nautoAttack a0 a1 = a1&amp;stats.health -~ a0^.stats.physicalDamage\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T03:20:20.797", "Id": "35514", "ParentId": "35512", "Score": "5" } }, { "body": "<p>Maybe I'm being a bit primitive here, but what's wrong with a couple of helper functions?</p>\n\n<pre><code>punchStrength a = physicalDamage $ stats a\n-- or...\n-- punchStrength = physicalDamage.stats\n\n\nhurtActor a amt = a { stats = (stats a) { health = old_health - amt } }\n where old_health = health $ stats a\n\nautoAttack a0 a1 = hurtActor a1 (punchStrength a0)\n</code></pre>\n\n<p>I'll grant you that the record syntax in hurtActor is a bit ugly, but the lens stuff isn't a huge improvement what with its 9 million line-noise operators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T20:24:28.647", "Id": "57588", "Score": "0", "body": "They grow on you. ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T10:45:19.547", "Id": "35515", "ParentId": "35512", "Score": "1" } } ]
{ "AcceptedAnswerId": "35513", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T02:15:26.193", "Id": "35512", "Score": "4", "Tags": [ "haskell" ], "Title": "How to simplify the record syntax with pattern matching?" }
35512
PEG.js is a parser generator written in JavaScript for Node.js or the browser. Its parsing expression grammar syntax is more powerful than traditional LL(k) and LR(k) parsers and accommodates expressive error messages and inline JavaScript.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T10:40:23.657", "Id": "35528", "Score": "0", "Tags": null, "Title": null }
35528
<p>I was implementing a rolling median solution and was not sure why my Python implementation was around 40 times slower than my C++ implementation.</p> <p>Here are the complete implementations:</p> <p><strong>C++</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string.h&gt; using namespace std; int tree[17][65536]; void insert(int x) { for (int i=0; i&lt;17; i++) { tree[i][x]++; x/=2; } } void erase(int x) { for (int i=0; i&lt;17; i++) { tree[i][x]--; x/=2; } } int kThElement(int k) { int a=0, b=16; while (b--) { a*=2; if (tree[b][a]&lt;k) k-=tree[b][a++]; } return a; } long long sumOfMedians(int seed, int mul, int add, int N, int K) { long long result = 0; memset(tree, 0, sizeof(tree)); vector&lt;long long&gt; temperatures; temperatures.push_back( seed ); for (int i=1; i&lt;N; i++) temperatures.push_back( ( temperatures.back()*mul+add ) % 65536 ); for (int i=0; i&lt;N; i++) { insert(temperatures[i]); if (i&gt;=K) erase(temperatures[i-K]); if (i&gt;=K-1) result += kThElement( (K+1)/2 ); } return result; } // default input // 47 5621 1 125000 1700 // output // 4040137193 int main() { int seed,mul,add,N,K; cin &gt;&gt; seed &gt;&gt; mul &gt;&gt; add &gt;&gt; N &gt;&gt; K; cout &lt;&lt; sumOfMedians(seed,mul,add,N,K) &lt;&lt; endl; return 0; } </code></pre> <p><strong>Python</strong></p> <pre><code>def insert(tree,levels,n): for i in xrange(levels): tree[i][n] += 1 n /= 2 def delete(tree,levels,n): for i in xrange(levels): tree[i][n] -= 1 n /= 2 def kthElem(tree,levels,k): a = 0 for b in reversed(xrange(levels)): a *= 2 if tree[b][a] &lt; k: k -= tree[b][a] a += 1 return a def main(): seed,mul,add,N,K = map(int,raw_input().split()) levels = 17 tree = [[0] * 65536 for _ in xrange(levels)] temps = [0] * N temps[0] = seed for i in xrange(1,N): temps[i] = (temps[i-1]*mul + add) % 65536 result = 0 for i in xrange(N): insert(tree,levels,temps[i]) if (i &gt;= K): delete(tree,levels,temps[i-K]) if (i &gt;= K-1): result += kthElem(tree,levels,((K+1)/2)) print result # default input # 47 5621 1 125000 1700 # output # 4040137193 main() </code></pre> <p>On the above mentioned input (in the comments of the code), the C++ code took around 0.06 seconds while Python took around 2.3 seconds.</p> <p>Can some one suggest the possible problems with my Python code and how to improve to less than 10x performance hit?</p> <p>I don't expect it to be anywhere near C++ implementation but to the order of 5-10x. I know I can optimize this by using libraries like NumPy (and/or SciPy). I am asking this question from the point of view of using Python for solving programming challenges. These libraries are usually not allowed in these challenges. I am just asking if it is even possible to beat the time limit for this algorithm in Python.</p> <p>In case somebody is interested, the C++ code is borrowed from floating median problem <a href="http://community.topcoder.com/tc?module=Static&amp;d1=match_editorials&amp;d2=srm310" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T11:51:47.873", "Id": "57634", "Score": "1", "body": "No can do, Python lists are rather slow when you iterate a lot. You could try using the `array` module from the standard library instead. It provide an efficient array class for numeric values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:21:07.880", "Id": "57637", "Score": "1", "body": "Using array is also not helpful as it further degrades the performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T13:05:32.837", "Id": "57641", "Score": "0", "body": "Loops are the main bottlenecks. Using numpy doesn't help here, on the contrary it further degrades the performance." } ]
[ { "body": "<p>Integer math in tight loops is an area where C++ will definitely run circles around Python. I think your expectations are too high. However, I'd like to point out a couple of things for you, even if they are not enough to reach your goal.</p>\n\n<p>Avoid indexing when you can use direct iteration instead. For example, <code>insert</code> can be written like this and Python won't have to deal with <code>i</code>:</p>\n\n<pre><code>def insert(tree,n):\n for level in tree:\n level[n] += 1\n n /= 2\n</code></pre>\n\n<p>Python does not optimize constant subexpressions out of loops, so you'll want to compute <code>(K+1)/2</code> before the main loop and store it in a variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:29:08.677", "Id": "35636", "ParentId": "35530", "Score": "6" } }, { "body": "<p>A 40x speed difference between C++ and Python for this sort of work is not uncommon. Implementing the optimizations by @JanneKarilla helps. Additionally you can ommit both <code>if</code> statements by looping in two segments, first from 0 to K, then from K to N, which shaves off a fair amount of time.</p>\n\n<p>The fastest that I can come up with uses the \"maintain a sorted array\" approach and is about 4.5 x faster than your original code for the input given:</p>\n\n<pre><code>from collections import deque\nfrom bisect import bisect_left, insort\n\ndef rolling_median(iterable, K):\n # taking iterator so it works on sequences and generators\n it = iter(iterable)\n\n # a deque has optimized access from its endpoints\n # we consume and store the first K values\n deq = deque(next(it) for _ in xrange(K))\n\n # initialize the sorted array\n sor = sorted(deq)\n\n # index of median in sorted list\n i = (K+1)//2 -1\n\n yield sor[i]\n for r in it:\n # `deq` keeps track of chrological order\n out = deq.popleft()\n deq.append(r)\n # `sor` keeps track of sortedness\n sor.pop(bisect_left(sor, out))\n insort(sor, r)\n yield sor[i]\n\ndef RNG(seed, mul, add, N):\n tk = seed\n for _ in xrange(N):\n yield tk\n tk = (tk * mul + add) % 65536\n\ndef main(seed=47, mul=5621, add=1, N=125000, K=1700):\n rand = RNG(seed, mul, add, N)\n return sum(rolling_median(rand, K))\n</code></pre>\n\n<p>It's possible to shave off some more milisec I'm sure, but I wanted to write a nice and general rolling median function <code>:)</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T00:54:48.940", "Id": "35651", "ParentId": "35530", "Score": "3" } } ]
{ "AcceptedAnswerId": "35636", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T11:38:39.950", "Id": "35530", "Score": "10", "Tags": [ "python", "c++", "performance" ], "Title": "Rolling median solution" }
35530
<p>i'm wondering is there <strong>any way to optimize this code</strong>? It must be able to work with big files, <strong>for example, formatting raw 140kb .txt file (12.5k words) takes 2 seconds (measured with Stopwatch class)</strong>. Text example <a href="http://pastebin.com/2p88v8EN" rel="nofollow">http://pastebin.com/2p88v8EN</a> Maybe i used here some bad techniques or there is some part to simplify? Maybe multithreading? I'm not familiar with this yet. Would be grateful for help!</p> <p>Code below:</p> <pre><code>class TextManipulations { public string[] wordsDist; // main array, contains words in alphabetic order and output lines public void TextFormat(string sourcePath) // creating method that will format our source text according to task { string textInput = System.IO.File.ReadAllText(sourcePath).ToLower(); // reading text from file, lowercased at start for precise search MatchCollection m = Regex.Matches(textInput, @"\b[\w']+\b"); // exact search of all alphanumeric "words" including words with apostrophe List&lt;string&gt; words = new List&lt;string&gt;(); // creating List&lt;T&gt; for containing unknown amount of words foreach (Match match in m) // assigning all matches to List&lt;string&gt; { words.Add(match.ToString()); } words.Sort(); // sorting words in alphabetic order wordsDist = words.Distinct().ToArray(); // assigning words to main array without duplicates System.IO.File.WriteAllLines(@"D:\output.txt", wordsDist); // writing words into txt file to edit in setLineNumbers method } public void setLineNumbers(string sourcePath) // creating method for adding line numbers { string[] linesOutput = new string[wordsDist.Count()]; // creating array that will contain line numbers string[] lines = System.IO.File.ReadAllLines(sourcePath); // assigning source text by lines for (int j = 0; j &lt; wordsDist.Count(); j++) // main cycle checking each word for presence in each line { for (int i = 0; i &lt; lines.Count(); i++) { if (Regex.IsMatch(lines[i].ToLower(), "\\b" + wordsDist[j] + "\\b")) // using ToLower() here, because we can't use it in line 33 { linesOutput[j] += (i + 1).ToString() + ", "; // adding line numbers according to word } } } for (int i = 0; i &lt; wordsDist.Count(); i++) // connection of two relative arrays { wordsDist[i] += "_______________________________" + linesOutput[i]; wordsDist[i] = wordsDist[i].Remove(wordsDist[i].Length - 2); // removing last ',' char } System.IO.File.WriteAllLines(@"D:\output.txt", wordsDist); // writing final output result into txt file } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:38:03.683", "Id": "57638", "Score": "1", "body": "Have you tried profiling the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:46:04.127", "Id": "57639", "Score": "0", "body": "Also, could you post a link to an example of the txt file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:55:28.820", "Id": "57640", "Score": "0", "body": "Hey, here is the text example http://pastebin.com/2p88v8EN I didn't profiled code before, i will try now, thanks!" } ]
[ { "body": "<p>Rewritten code:</p>\n\n<pre><code>class TextManipulations\n{\nprivate const string AlphanumericWords = @\"\\b[\\w']+\\b\";\npublic string[] WordsDist;\n\npublic void TextFormat(string sourcePath, string output)\n{\n var textInput = File.ReadAllText(sourcePath).ToLower();\n var m = Regex.Matches(textInput, AlphanumericWords);\n var words = new SortedSet&lt;string&gt;();\n\n foreach (Match match in m)\n {\n words.Add(match.ToString());\n }\n\n WordsDist = words.ToArray();\n\n File.WriteAllLines(output, WordsDist);\n}\n\npublic void SetLineNumbers(string sourcePath, string output)\n{\n var lines = File.ReadAllLines(sourcePath).AsParallel().Select(x =&gt; x.ToLowerInvariant()).ToArray();\n\n var regExs = WordsDist.Select(word =&gt; new Regex(\"\\\\b\" + word + \"\\\\b\")).ToArray();\n\n var wordsOut = new string[regExs.Length];\n\n Parallel.For(0, regExs.Length, j =&gt;\n {\n var sb = new List&lt;int&gt;(15);\n var regEx = regExs[j];\n for (var i = 0; i &lt; lines.Length; i++)\n {\n if (regEx.IsMatch(lines[i]))\n {\n sb.Add(i + 1);\n }\n }\n\n wordsOut[j] = WordsDist[j] + \"_______________________________\" + string.Join(\", \", sb);\n });\n\n File.WriteAllLines(output, wordsOut);\n}\n\n}\n</code></pre>\n\n<h2>TextFormat</h2>\n\n<p>Using a SortedSet is better becouse we don't need additional Sort() or Distinct() calls becouse it will handle all these stuff by it's self.</p>\n\n<h2>SetLineNumbers</h2>\n\n<p>The main problem was is that the testing Regex was always created inside the second for loop instead of creating once and then using it in all the iterations. The parallel stuff isn't necessary but we can speed up the code a little bit with that.</p>\n\n<h2>Results</h2>\n\n<p>Your code was executed on my machine a little bit above 2 secs and my code is finishing around 0.25 secs.</p>\n\n<h2>Other things</h2>\n\n<p>Do not ever write comments at the line endings becouse they are really useless and annoying.\nI've added an additional parameter to each method which can be used to specify the output file. (But the code still isn't really reuseable or testable.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:33:22.730", "Id": "57643", "Score": "0", "body": "This is awesome. Never tried sortedSet or AsParallel(), thanks! I will dig into your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:46:11.440", "Id": "57644", "Score": "0", "body": "Why do you have `wordsOut[j] += …`? `wordsOut[j] = …` would be much clearer. Also, why are initializing the list to 15? Why exactly that number?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:47:01.630", "Id": "57645", "Score": "0", "body": "One more thing: `ToList()` tends to be faster than `ToArray()` (because it can make one less copy)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T16:31:12.570", "Id": "57655", "Score": "0", "body": "@svick: the += is a typo. I'm using 15 becouse in the result set most of the time the matching count is below 10 but there are significant number of result count more then 10 with a few match. Yes ToList() can be more effective but it doesn't matter in this case much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:32:52.273", "Id": "57992", "Score": "0", "body": "This would be more efficient if you [compile your regex](http://msdn.microsoft.com/en-us/library/gg578045(v=vs.110).aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:32:29.053", "Id": "58007", "Score": "0", "body": "In this case compiling the regular expressions are incrasing startup time so grately that it would not worth doing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T12:32:13.577", "Id": "58096", "Score": "0", "body": "@PeterKiss don't you see anything wrong with making a new instance of a regex for each and every distinct word? What about the startup time of that? \nYou can use a single `new Regex(AlphanumericWords, RegexOptions.Compiled);` instead (see my answer) and then you only run a single regex command over each line once rather once for each unique word." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T12:54:01.137", "Id": "58099", "Score": "0", "body": "Your solution will fail if your dictionary doesn't contains the key from the line. This is becouse the OP base solution is incorrect: the methods can be called separately but the second one is based on the first result (distinct words)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:02:02.997", "Id": "35533", "ParentId": "35532", "Score": "5" } }, { "body": "<p>I posted the basis of this answer to your question when you first asked it on StackOverflow.</p>\n\n<p>The best answer is to remove both the <code>Distinct()</code> and the <code>Regex</code> and process everything by character.</p>\n\n<pre><code>class TextManipulations\n{\n public string[] WordsDist;\n\n public void TextFormat(string sourcePath)\n {\n HashSet&lt;string&gt; Words = new HashSet&lt;string&gt;();\n foreach (string line in File.ReadLines(sourcePath))\n {\n int wordStart = 0;\n for (int i = 0; i &lt; line.Length; i++)\n {\n char c = line[i];\n if (c == ' ')\n {\n string word = line.Substring(wordStart, i - wordStart).Trim().ToLower();\n Words.Add(word);\n wordStart = i + 1;\n }\n }\n if (wordStart &lt; line.Length)\n {\n string word = line.Substring(wordStart, line.Length - wordStart).Trim().ToLower();\n Words.Add(word);\n }\n }\n WordsDist = Words.OrderBy(word =&gt; word).ToArray();\n File.WriteAllLines(\"output.txt\", WordsDist);\n }\n\n public void SetLineNumbers(string sourcePath)\n {\n Dictionary&lt;string, List&lt;int&gt;&gt; wordLineNumbers = WordsDist.ToDictionary(word =&gt; word, word =&gt; new List&lt;int&gt;());\n int lineNo = 0;\n foreach (string line in File.ReadLines(sourcePath))\n {\n lineNo++;\n int wordStart = 0;\n for (int i = 0; i &lt; line.Length; i++)\n {\n char c = line[i];\n if (c == ' ')\n {\n string word = line.Substring(wordStart, i - wordStart).Trim().ToLower();\n wordLineNumbers[word].Add(lineNo);\n\n wordStart = i + 1;\n }\n }\n if (wordStart &lt; line.Length)\n {\n string word = line.Substring(wordStart, line.Length - wordStart).Trim().ToLower();\n wordLineNumbers[word].Add(lineNo);\n }\n }\n File.WriteAllLines(\"output.txt\", wordLineNumbers.Select(kvp =&gt; string.Format(\"{0}, {1}\", kvp.Key, string.Join(\", \", kvp.Value))));\n }\n}\n</code></pre>\n\n<p>However this changes the functionality slightly as it doesn't strip out punctuation and the like (and only splits on white spaces), but if you want to keep the exact same output then this will do the job:</p>\n\n<pre><code>class TextManipulations : ITextManipulations\n{\n private const string AlphanumericWords = @\"\\b[\\w']+\\b\";\n private static readonly Regex wordRegex = new Regex(AlphanumericWords, RegexOptions.Compiled);\n public string[] WordsDist;\n\n public void TextFormat(string sourcePath)\n {\n HashSet&lt;string&gt; Words = new HashSet&lt;string&gt;();\n\n foreach (string line in File.ReadLines(sourcePath))\n {\n foreach (Match wordMatch in wordRegex.Matches(line))\n {\n Words.Add(wordMatch.Value.Trim().ToLower());\n }\n }\n WordsDist = Words.OrderBy(word =&gt; word).ToArray();\n File.WriteAllLines(\"output.txt\", WordsDist);\n }\n\n public void SetLineNumbers(string sourcePath)\n {\n Dictionary&lt;string, List&lt;int&gt;&gt; wordLineNumbers = WordsDist.ToDictionary(word =&gt; word, word =&gt; new List&lt;int&gt;());\n int lineNo = 0;\n foreach (string line in File.ReadLines(sourcePath))\n {\n lineNo++;\n foreach (string word in wordRegex.Matches(line).OfType&lt;Match&gt;().Select(wordMatch =&gt; wordMatch.Value.Trim().ToLower()).Distinct())\n {\n wordLineNumbers[word].Add(lineNo);\n }\n }\n File.WriteAllLines(\"output.txt\", wordLineNumbers.Select(kvp =&gt; string.Format(\"{0}_______________________________{1}\", kvp.Key, string.Join(\", \", kvp.Value))));\n }\n}\n</code></pre>\n\n<p>Some tests...While your Pastebin link is no longer available I created a suitable 172KB file with 4.2k unique words.</p>\n\n<p>Performance of calling <code>TextFormat</code> followed by <code>SetLineNumbers</code></p>\n\n<pre><code>Your code total runtime: 8689ms\nCode by Peter Kiss total runtime: 440ms\nMy split only on white space code: 61ms\nMy code using a single Compiled Regex: 87ms\n</code></pre>\n\n<p>Additionally my code reads the file line-by-line and reuses the same memory rather than loading the entire file into memory. This means that for very large files (say 100 MB+) my code will continue to scale better due to not copying around of additional arrays all over the place.</p>\n\n<p>Testing with much larger files this pattern continues, eg: 1446kb input file with 12100 unique words.</p>\n\n<pre><code>Your code total runtime: test not run (would take too long)\nCode by Peter Kiss total runtime: 9079ms\nMy split only on white space code: 279ms\nMy code using a single Compiled Regex: 651ms\n</code></pre>\n\n<p>So with a larger file my 2nd set of code performs 13 times faster compared to 5 times faster with a 172KB file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:24:41.127", "Id": "35681", "ParentId": "35532", "Score": "2" } } ]
{ "AcceptedAnswerId": "35681", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T12:21:24.253", "Id": "35532", "Score": "5", "Tags": [ "c#", "optimization", "console" ], "Title": "How to optimize C# console application" }
35532
<p>I've got a page on a website that shows a table, and upon clicking on a row in the table, it can dynamically load in more results. I am new to jQuery though.</p> <p><strong>index.php page:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Knife kills&lt;/title&gt; &lt;script src="jquery-2.0.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#list tr").bind("click", function(event) { //Get clicked row var clickedRow = $("#list tr#" + this.id); //Increase clicks if (!$(clickedRow).data("clicks")) { $(clickedRow).data("clicks", 0); } $(clickedRow).data("clicks", $(clickedRow).data("clicks") + 1); //Check if detailed information has been retrieved if ($(clickedRow).data("detailed")) { if ($(clickedRow).data("clicks") % 2 == 0) { //Hide $("#list tr#" + this.id + "row").remove(); } else { //Show $($(clickedRow).data("detailed")).insertAfter($(clickedRow)); } } else { var loading = $("&lt;tr&gt;&lt;td colspan=3&gt;Loading...&lt;/td&gt;&lt;/tr&gt;"); loading.insertAfter($(clickedRow)); $.ajax({ url: "ajax_detailed.php", data: { id: this.id }, success: function(html) { if (html) { //Success $(loading).remove(); $(html).insertAfter($(clickedRow)); $(clickedRow).data("detailed", html); } else { //Error $(loading).remove(); } } }); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="list"&gt; &lt;tr&gt;&lt;th&gt;#&lt;/th&gt;&lt;th&gt;Player&lt;/th&gt;&lt;th&gt;Kills&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt; &lt;?php $con = mysql_connect("localhost", "bf4", "bf4") or die(mysql_error()); mysql_select_db("bf4") or die(mysql_error()); $query = mysql_query("SELECT p.playerId AS pid, p.playerName AS name, COUNT(`playerkills`.`id`) AS amount FROM `playerkills` JOIN players p ON playerkills.playerId = p.playerId WHERE weaponId = 9 GROUP BY playerkills.playerId ORDER BY amount DESC;") or die(mysql_error()); $i = 0; $lastamount = -1; $offset = 0; while ($result = mysql_fetch_object($query)) { if ($lastamount != $result-&gt;amount) { $i += 1 + $offset; $offset = 0; } else { $offset++; } echo "\t\t\t&lt;tr id='{$result-&gt;pid}' style='cursor: pointer;'&gt;&lt;td&gt;".$i."&lt;/td&gt;&lt;td&gt;".$result-&gt;name."&lt;/td&gt;&lt;td&gt;".$result-&gt;amount."&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n"; $lastamount = $result-&gt;amount; } mysql_close($con) or die(mysql_error()); ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p><strong>ajax_detailed.php page:</strong></p> <pre><code>&lt;?php $con = mysql_connect("localhost", "bf4", "bf4") or die(mysql_error()); mysql_select_db("bf4") or die(mysql_error()); $id = mysql_real_escape_string($_GET['id']); echo "&lt;tr id='{$id}row'&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Target&lt;/th&gt;&lt;th&gt;Kills&lt;/th&gt;&lt;/tr&gt;"; $query = mysql_query("SELECT p.playerName AS name, COUNT(`playerkills`.`id`) AS amount FROM `playerkills` JOIN players p ON playerkills.targetId = p.playerId WHERE weaponId = 9 AND playerkills.playerId = '{$id}' GROUP BY playerkills.targetId ORDER BY amount DESC;"); while ($result = mysql_fetch_object($query)) { echo "&lt;tr id='{$id}row'&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;".$result-&gt;name."&lt;/td&gt;&lt;td&gt;".$result-&gt;amount."&lt;/td&gt;&lt;/tr&gt;"; } mysql_close($con) or die(mysql_error()); ?&gt; </code></pre> <p>I have the feeling that my jQuery is way too complicated. I hope others can shed light on it.</p>
[]
[ { "body": "<p>Some basic things (looking only the at the JS)</p>\n\n<ul>\n<li>Don't keep repeating <code>$(clickedRow)</code> - <code>clickedRow</code> is already a jQuery object. There's no need to use <code>$()</code> again.</li>\n<li>Avoid manually tracking a number to figure out whether to hide or show the details. Easier to check if the details are present or not and proceed accordingly.</li>\n</ul>\n\n<p>Functionality-wise, there are <em>a lot</em> of ways to do what you need. I'd suggest breaking things out into functions, and a lot of other stuff.</p>\n\n<p>But I don't want to go too far from your current code, so here's a simple, \"light\" refactoring (and <a href=\"http://jsfiddle.net/9YYWj/\" rel=\"nofollow\">here's a demo</a>)</p>\n\n<pre><code>$(function() { // same as $(document).ready()\n $(\"#list tr\").on(\"click\", function (event) { // use .on() instead of .bind() (since jQuery 1.7)\n // Get relevant rows, the simpler way\n var xhr,\n id = this.id,\n clickedRow = $(this),\n loadingRow = clickedRow.next(\".loading\"),\n detailsRow = clickedRow.next(\"#\" + id + \"row\");\n\n if(loadingRow.length &gt; 0) {\n return; // stop here if we're currently loading\n }\n\n // Hide details and stop, if the details are shown\n if(detailsRow.length &gt; 0) {\n detailsRow.remove();\n return;\n }\n\n // insert cached details and stop, if possible\n if(clickedRow.data(\"details\")) {\n clickedRow.data(\"details\").insertAfter(clickedRow);\n return;\n }\n\n // if we get this far, we'll need to load the details, so:\n\n // show the loading message\n loadingRow = $('&lt;tr class=\"loading\"&gt;&lt;td colspan=\"3\"&gt;Loading...&lt;/td&gt;&lt;/tr&gt;').insertAfter(clickedRow);\n\n // fetch details (using the deferred/promise API)\n xhr = $.ajax({\n url: \"ajax_detailed.php\",\n data: { id: id },\n cache: true\n });\n\n // add details when they've loaded\n xhr.done(function (html) {\n // I'm skipping the if(html) check, since the server should\n // return an error code if there's an error. And if so, this\n // done-handler will never be called anyway\n detailsRow = $(html).insertAfter(clickedRow);\n clickedRow.data(\"details\", detailsRow);\n });\n\n // remove the loading row regardless of how the ajax request went\n xhr.always(function (html) {\n loadingRow.remove();\n });\n });\n});\n</code></pre>\n\n<p>The PHP also looks iffy to me, but it's been a long time since I had to work with PHP, so I won't comment. </p>\n\n<p><strike>I will say though, that you're extremely vulnerable to SQL injection attacks. For instance, if I send an id value of <code>0'; DROP DATABASE bf4; DROP USER bf4;</code> to your ajax_detailed.php script, it'll permanently delete your entire database and remove the database user. You <em>may</em> want to look into that...</strike></p>\n\n<p>Ignore the above - I had overlooked the call to <code>mysql_real_escape_string</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T09:08:11.403", "Id": "57755", "Score": "0", "body": "Okay I'll definitely need to refactor my code more into functions, thanks for the comments. As for SQL injection, the `mysql_real_escape_string` will cover that. However the code is definitely not 100% secure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:03:28.477", "Id": "57775", "Score": "0", "body": "@skiwi ah, I actually overlooked the call to `mysql_real_escape_string` - sorry (but note that that function has been deprecated)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:22:28.220", "Id": "57779", "Score": "1", "body": "If `$_GET['id']` is numeric, better cast it to an `int` instead of using `mysql_real_escape_string`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T04:37:13.307", "Id": "35568", "ParentId": "35536", "Score": "2" } } ]
{ "AcceptedAnswerId": "35568", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T15:10:58.733", "Id": "35536", "Score": "3", "Tags": [ "javascript", "php", "jquery", "beginner", "mysql" ], "Title": "Dynamically-loading interactive table" }
35536
<p>I was given the task of batch process a single-level control break program to produce a lecturer information report by lecturer from a university course file.</p> <p>I have attempted to create a solution using a OO design in Java. I have run into some problems as I don't think the the modules are cohesive as they are not very independent enough which makes it difficult to maintain. Also if the input file had additional lecturer's the code would have to be changed in many places to accommodate this.</p> <p>I would very much appreciate it if someone would look through my design solution and offer alternatives to address the problems I've highlighted above. Also maybe suggest an alternative solution!! I'm first year student so new to programming.</p> <p>Question details:</p> <blockquote> <p>Each record on the Teaching-module file contains details of a lecture’s teaching load; that is, a record number, the school code, the Lecturers department number, the lecturer’s identity number, the lecture’s name, the module number of the module being taught, the credit hours for that module, and class size. There may be more than one record for each lecturer, depending on the number of modules he or she teaches. The Teaching-module file must be sorted into ascending sequence of lecturer number within department, within school. Tip treat as a concatenated single field.</p> <p>The program is to read the sorted teaching-module file sequentially, calculate the lecture’s contact hours <code>((class size/50)* credit hours)</code>, and produce the lecturer information report.</p> <p>Report example:</p> <p><img src="https://i.stack.imgur.com/dnK2E.png" alt="enter image description here"></p> </blockquote> <p>Below is my solution so far:</p> <pre><code> public class DSAPDAssignmentB2 { /** * @param args the command line arguments */ public static void main(String[] args) { String teachMod = ("1,CSM,501,SM0156,Simon Thorne,BCO200,24,30,"+ "2,CSM,500,AC1157,Nigel Jones,BCO104,24,60,"+ "3,CSM,500,SM0156,Simon Thorne,BCO113,12,60,"+ "4,CSM,500,AC1157,Nigel Jones,BCO104,24,30,"+ "5,CSM,500,AC1156,Richard Adlam,BCO113,12,60,"+ "6,CSM,500,AC1157,Nigel Jones,BCO109,12,90,"+ "7,CSM,503,SM0156,Simon Thorne,CIS414,12,30,"+ "8,CSM,501,AC1156,Richard Adlam,BCO222,12,40,"+ "9,CSM,500,AC1156,Richard Adlam,BCO114,12,60,"+ "10,CSM,501,AC1157,Nigel Jones,BCO200,60,40,"+ "11,CSM,500,AC1156,Richard Adlam,BCO106,24,60,"+ "12,CSM,501,SM0156,Simon Thorne,BCO207,12,30,"+ "13,CSM,500,AC1157,Nigel Jones,BCO112,24,30,"); //LecturerDetails simonThorne = new LecturerDetails("Simon Thorne", "SM0156"); ArrayList&lt;String&gt; aList = fileToRecords(teachMod, 8); aList = trimOffRecNo(aList); aList = sortRecords(aList,4,7); updateLecturerFile(aList); createReport(); //System.out.println("Simon Thorne details are: "); //simonThorne.toString(); //System.out.println("Nigel Jones details are: "); //nigelJones.toString(); //System.out.println("Richard Adlam details are: "); //richardAdlam.toString(); //System.out.println("*************************************1"); //for(String string : aList){ // System.out.println(string); //} System.out.println("End"); }//End main public static LecturerDetails simonThorne = new LecturerDetails("Simon Thorne", "SM0156"); public static LecturerDetails nigelJones = new LecturerDetails("Nigel Jones", "AC1157"); public static LecturerDetails richardAdlam = new LecturerDetails("Richard Adlam", "AC1156"); //Takes a String and splits it into chunks, each chunk is stored in an ArrayList. //Here we specify how much of the String we chunk into our list. //Each chunk in the ArrayList represents a lecturer record taken from the teaching module public static ArrayList fileToRecords(String s, int chunk){ ArrayList&lt;String&gt; chunks = new ArrayList&lt;&gt;(); //Create our ArrayList StringBuffer sb = new StringBuffer(); //We use a StringBuffer to append each character char[] c = s.toCharArray(); //Convert our String into a char array int j = 0; for(int i = 0; i &lt; s.length(); i++){ //Loop through each char in our String sb.append(c[i]); //Append each char as we take a stroll if(c[i]==','){ //Check if the char is a delimiter j++; //If so then keep a count as we walk past if(j==chunk){ //Check if we have reached the end marker for our chunk chunks.add(sb.toString()); //If so then add the chunk to our ArrayList j=0; //reset delimiter count sb = new StringBuffer(); //Empty our StringBuffer } } } return chunks; //return array } //Here we trim off the record numbers as this is useless information //The record number is followed by a delimiter so we eject both public static ArrayList trimOffRecNo(ArrayList&lt;String&gt; list){ ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;(); //Create our ArrayList for(int i=0;i&lt;list.size();i++){ //Loop through each element in list for(int j=0; j&lt;list.get(i).length();j++){ //Loop through each char if(list.get(i).charAt(j) == ','){ //Check for first delimiter... //...then whip out the rest of the String aList.add(list.get(i).substring(j+1, list.get(i).length())); break; //Let's have no exceptions here } } } return aList; //Return array } public static void updateLecturerFile(ArrayList&lt;String&gt; list){ ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;(); aList = sortRecords(list, 9,14); String temp = null; for(int i = 0; i &lt; list.size();i++){ temp = aList.get(i).substring(8,14); switch(temp){ case "AC1156": richardAdlam.updateMe(aList.get(i).toString()); System.out.println(aList.get(i).toString()); break; case "AC1157": nigelJones.updateMe(aList.get(i).toString()); break; case "SM0156": simonThorne.updateMe(aList.get(i).toString()); //System.out.println(aList.get(i).toString()); break; } } } public static void createReport(){ String temp = null; System.out.println("\nSCHOOL\tDEPARTMENT\tLECTURER\tLECTURER\tMODULE\tCREDIT\tCLASS\tCONTACT"); System.out.println("ID\tNO\t\tID\t\tNAME\t\tCODE\tHOURS\tSIZE\tHOURS"); ArrayList&lt;TeachingLoad&gt; simon = simonThorne.getTeachingLoad(); ArrayList&lt;TeachingLoad&gt; nigel = nigelJones.getTeachingLoad(); ArrayList&lt;TeachingLoad&gt; richard = richardAdlam.getTeachingLoad(); String dept = "500"; int deptHours = 0; int schoolHours = 0; for(int i = 0; i&lt;3;i++){ if(i==1) dept = "501"; else if(i==2) dept = "503"; int hours = 0; int totalHours = 0; for(TeachingLoad tl : simon){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ simonThorne.getID()+"\t\t"+simonThorne.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); hours = 0; totalHours = 0; for(TeachingLoad tl : nigel){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ nigelJones.getID()+"\t\t"+nigelJones.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); hours = 0; totalHours = 0; for(TeachingLoad tl : richard){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ richardAdlam.getID()+"\t\t"+richardAdlam.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; schoolHours = schoolHours +deptHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); System.out.println("\tCONTACT HOURS FOR DEPARTMENT "+deptHours); deptHours = 0; } System.out.println("CONTACT HOURS FOR SCHOOL "+schoolHours); } //Sorts the ArrayList records naturally. User can specify start &amp; end of chunk in String to sort. //Could be useful if we wanted to sort by module number or name! public static ArrayList sortRecords(ArrayList&lt;String&gt; list, int start, int end){ String s1, s2, temp; //Some local variables for(int i = 0 ; i &lt; list.size(); i++){ //Loop throuth each element in list for(int j = list.size()-1; j&gt;i ;j--){ //Loop through each char s1 = list.get(j-1).substring(start,end); //Exreact 1st substring System.out.println(s1); s2 = list.get(j).substring(start,end); //Extract 2nd substring if(i+1&lt;list.size()&amp;&amp;s1.compareTo(s2)&gt;-1){ //Compare them lexicographically temp = list.get(j-1); //If s1 follows s2 then switch both list.set(j-1, list.get(j)); list.set(j, temp); } } } for(String s : list){ System.out.println(s); } return list; //Retrun sorted list }//End sortRecords }//End class public class LecturerDetails { private String ID; private String name; ArrayList&lt;TeachingLoad&gt; list; public LecturerDetails() { } public LecturerDetails(String name, String ID) { this.name = name; this.ID = ID; list = new ArrayList&lt;&gt;(20); } public void updateMe(String file){ String school=null, deptNo=null, moduleNo=null, creditHours=null, classSize=null; String temp; int delimitCount = 0; int lastCount = 0; for(int i = 0; i &lt; file.length(); i++){ if(file. charAt(i) == ','){ temp = file.substring(lastCount, i); lastCount = i+1; delimitCount++; switch(delimitCount){ case 1: school = temp; break; case 2: deptNo = temp; break; case 5: moduleNo = temp; break; case 6: creditHours = temp; break; case 7: classSize = temp; break; } } } list.add(new TeachingLoad(school, deptNo, moduleNo, creditHours, classSize)); } public String getID() { return ID; } public String getName() { return name; } public void setID(String ID) { this.ID = ID; } public void setName(String name) { this.name = name; } public ArrayList&lt;TeachingLoad&gt; getTeachingLoad() { return list; } @Override public String toString() { //for(TeachingLoad tl : list){ // System.out.println(tl); //} return ("LecturerDetails");// + "ID=" + ID + ", name=" + name); } } public class TeachingLoad { private String schoolCode; private String departmentNumber; private String moduleNo; private String creditHours; private String classSize; public TeachingLoad() { } public TeachingLoad(String schoolCode, String departmentNumber, String moduleNo, String creditHours, String classSize) { this.schoolCode = schoolCode; this.departmentNumber = departmentNumber; this.moduleNo = moduleNo; this.creditHours = creditHours; this.classSize = classSize; } public String getSchoolCode() { return schoolCode; } public String getDepartmentNumber(){ return departmentNumber; } public String getModuleNo() { return moduleNo; } public String getCreditHours() { return creditHours; } public String getClassSize() { return classSize; } public void setSchoolCode(String schoolCode) { this.schoolCode = schoolCode; } public void setDepartmentNumber(String departmentNumber){ this.departmentNumber = departmentNumber; } public void setModuleNo(String moduleNo) { this.moduleNo = moduleNo; } public void setCreditHours(String creditHours) { this.creditHours = creditHours; } public void setClassSize(String classSize) { this.classSize = classSize; } @Override public String toString() { return "Entry{" + "schoolCode=" + schoolCode + " moduleNo=" + moduleNo + " creditHours=" + creditHours + " classSize=" + classSize + '}'; } } </code></pre> <p>Below is a printout:</p> <p><img src="https://i.stack.imgur.com/PE5Nu.png" alt="enter image description here"></p> <p>I suppose it's a bit of an ask...I've changed the main line (see below) Here I've now created a Map which contains details of lecturers. The call to create lecturerObject() searches for the new lecturer unique ID's and creates new objects if they don't already exist. So now in updateLecturerFile() I have been able to remove the switch statement and the use of "Magic Numbers" - Thanks to UnholySampler for pointing that out to me! I suppose this way the program can handle reports of different numbers of lecturers now (great I've made some progress here). The lecturer unique ID's are "SM0156" &amp; "AC1157" etc etc. I will have to amend the createReport() function to accommodate these changes. Within the createReport() function it still relies on hard coding to process the 3 lecturer details within the input string. Now I want it to be able to handle any number of lecturers so I will have to remove the three Collection loops there now that I have the lecturer details stores in a Map this should be doable.??? Still though I feel the program could be better as I mentioned above. The updated main line is below: (I'll post the updated createReport() when I know what I got to do with it!)</p> <pre><code>public class DSAPDAssignmentB2 { /** * @param args the command line arguments */ public static void main(String[] args) { String teachMod = ("1,CSM,501,SM0156,Simon Thorne,BCO200,24,30,"+ "2,CSM,500,AC1157,Nigel Jones,BCO104,24,60,"+ "3,CSM,500,SM0156,Simon Thorne,BCO113,12,60,"+ "4,CSM,500,AC1157,Nigel Jones,BCO104,24,30,"+ "5,CSM,500,AC1156,Richard Adlam,BCO113,12,60,"+ "6,CSM,500,AC1157,Nigel Jones,BCO109,12,90,"+ "7,CSM,503,SM0156,Simon Thorne,CIS414,12,30,"+ "8,CSM,501,AC1156,Richard Adlam,BCO222,12,40,"+ "9,CSM,500,AC1156,Richard Adlam,BCO114,12,60,"+ "10,CSM,501,AC1157,Nigel Jones,BCO200,60,40,"+ "11,CSM,500,AC1156,Richard Adlam,BCO106,24,60,"+ "12,CSM,501,SM0156,Simon Thorne,BCO207,12,30,"+ "13,CSM,500,AC1157,Nigel Jones,BCO112,24,30,"); ArrayList&lt;String&gt; aList = fileToRecords(teachMod, 8); createLecturerObject(aList); //Create a collection of LecturerDetails in a Map aList = trimOffRecNo(aList); //aList = sortRecords(aList,4,7); updateLecturerFile(aList); //createReport(); }//End main public static HashMap&lt;String, LecturerDetails&gt; lecturerList = new HashMap(); //Takes a String and splits it into chunks, each chunk is stored in an ArrayList. //Here we specify how much of the String we chunk into our list. //Each chunk in the ArrayList represents a lecturer record taken from the teaching module public static ArrayList fileToRecords(String s, int chunk){ ArrayList&lt;String&gt; chunks = new ArrayList&lt;&gt;(); //Create our ArrayList StringBuffer sb = new StringBuffer(); //We use a StringBuffer to append each character char[] c = s.toCharArray(); //Convert our String into a char array int j = 0; for(int i = 0; i &lt; s.length(); i++){ //Loop through each char in our String sb.append(c[i]); //Append each char as we take a stroll if(c[i]==','){ //Check if the char is a delimiter j++; //If so then keep a count as we walk past if(j==chunk){ //Check if we have reached the end marker for our chunk chunks.add(sb.toString()); //If so then add the chunk to our ArrayList j=0; //reset delimiter count sb = new StringBuffer(); //Empty our StringBuffer } } } return chunks; //return array } public static void createLecturerObject(ArrayList&lt;String&gt; al){ String thisLec = null; int delimitCount = 0; for(int i = 0; i&lt;al.size();i++){ for(int j = 0;j&lt;al.get(i).length();j++){ if(al.get(i).charAt(j) == ','){ delimitCount++; if(delimitCount == 3){ thisLec = al.get(i).substring(j+1, j+7); if(!lecturerList.containsKey(thisLec)){ lecturerList.put(thisLec, new LecturerDetails()); lecturerList.get(thisLec).setID(thisLec); } delimitCount = 0; break; } } } } } //Here we trim off the record numbers as this is useless information //The record number is followed by a delimiter so we eject both public static ArrayList trimOffRecNo(ArrayList&lt;String&gt; list){ ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;(); //Create our ArrayList for(int i=0;i&lt;list.size();i++){ //Loop through each element in list for(int j=0; j&lt;list.get(i).length();j++){ //Loop through each char if(list.get(i).charAt(j) == ','){ //Check for first delimiter... //...then whip out the rest of the String aList.add(list.get(i).substring(j+1, list.get(i).length())); break; //Let's have no exceptions here } } } return aList; //Return array } public static void updateLecturerFile(ArrayList&lt;String&gt; list){ ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;(); //aList = sortRecords(list, 9,14); aList = list; String temp = null; for(int i = 0; i &lt; aList.size();i++){ temp = aList.get(i).substring(8,14); for(String key : lecturerList.keySet()){ if(key.equals(temp)){ lecturerList.get(temp).updateMe(aList.get(i)); System.out.println("In update lecturer"); } } } } /** public static void createReport(){ String temp = null; System.out.println("\nSCHOOL\tDEPARTMENT\tLECTURER\tLECTURER\tMODULE\tCREDIT\tCLASS\tCONTACT"); System.out.println("ID\tNO\t\tID\t\tNAME\t\tCODE\tHOURS\tSIZE\tHOURS"); ArrayList&lt;TeachingLoad&gt; simon = simonThorne.getTeachingLoad(); ArrayList&lt;TeachingLoad&gt; nigel = nigelJones.getTeachingLoad(); ArrayList&lt;TeachingLoad&gt; richard = richardAdlam.getTeachingLoad(); String dept = "500"; int deptHours = 0; int schoolHours = 0; for(int i = 0; i&lt;3;i++){ if(i==1) dept = "501"; else if(i==2) dept = "503"; int hours = 0; int totalHours = 0; for(TeachingLoad tl : simon){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ simonThorne.getID()+"\t\t"+simonThorne.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); hours = 0; totalHours = 0; for(TeachingLoad tl : nigel){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ nigelJones.getID()+"\t\t"+nigelJones.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); hours = 0; totalHours = 0; for(TeachingLoad tl : richard){ if(tl.getDepartmentNumber().equals(dept)){ hours = (int) (hours + (double)Integer.parseInt(tl.getClassSize())/50*Integer.parseInt(tl.getCreditHours())); System.out.println(tl.getSchoolCode()+"\t"+tl.getDepartmentNumber()+"\t\t"+ richardAdlam.getID()+"\t\t"+richardAdlam.getName()+"\t"+ tl.getModuleNo()+"\t"+tl.getCreditHours()+"\t"+tl.getClassSize()+"\t"+hours); totalHours = totalHours + hours; } } deptHours = deptHours + totalHours; schoolHours = schoolHours +deptHours; System.out.println("\t\t\tCONTACT HOURS FOR LECTURER \t\t\t\t"+totalHours); System.out.println("\tCONTACT HOURS FOR DEPARTMENT "+deptHours); deptHours = 0; } System.out.println("CONTACT HOURS FOR SCHOOL "+schoolHours); }*/ //Sorts the ArrayList records naturally. User can specify start &amp; end of chunk in String to sort. //Could be useful if we wanted to sort by module number or name! public static ArrayList sortRecords(ArrayList&lt;String&gt; list, int start, int end){ String s1, s2, temp; //Some local variables for(int i = 0 ; i &lt; list.size(); i++){ //Loop throuth each element in list for(int j = list.size()-1; j&gt;i ;j--){ //Loop through each char s1 = list.get(j-1).substring(start,end); //Exreact 1st substring //System.out.println(s1); s2 = list.get(j).substring(start,end); //Extract 2nd substring if(i+1&lt;list.size()&amp;&amp;s1.compareTo(s2)&gt;-1){ //Compare them lexicographically temp = list.get(j-1); //If s1 follows s2 then switch both list.set(j-1, list.get(j)); list.set(j, temp); } } } return list; //Retrun sorted list }//End sortRecords }//End clasS </code></pre>
[]
[ { "body": "<p>Variable Names: The name should describe the data that is being stored there. <code>list</code> and <code>aList</code> don't give you any context for what they are being used for. Try to avoid single letter names or abbreviations that might not be clear to other people reading the code.</p>\n\n<p>Additionally, when I saw</p>\n\n<pre><code>for(TeachingLoad tl : simon){\n</code></pre>\n\n<p>I was confused because I expected <code>simon</code> to be an object that represented a person, not a list of things that are associated with the person. In this case, you only use these lists to iterate over, so you could change it to </p>\n\n<pre><code>for(TeachingLoad tl : simon.getTeachingLoad()){\n</code></pre>\n\n<p>and now there is one less variable to worry about.</p>\n\n<hr>\n\n<p>For <code>trimOffRecNo()</code>, you only ever use <code>i</code> to get the current element from <code>list</code> (which you do repeatedly). You can just change that to be a foreach loop. This will make the code more readable.</p>\n\n<pre><code>public static ArrayList trimOffRecNo(ArrayList&lt;String&gt; list){\n ArrayList&lt;String&gt; aList = new ArrayList&lt;&gt;(); //Create our ArrayList\n for(String rec : list){ //Loop through each element in list\n for(int j=0; j&lt;rec.length();j++){ //Loop through each char\n if(rec.charAt(j) == ','){ //Check for first delimiter...\n //...then whip out the rest of the String\n aList.add(rec.substring(j+1, rec.length()));\n break; //Let's have no exceptions here\n }\n }\n }\n return aList; //Return array \n}\n</code></pre>\n\n<p>Additionally, you can write this code without the inner loop.</p>\n\n<pre><code>public static List&lt;String&gt; trimOffRecNo(List&lt;String&gt; list){\n List&lt;String&gt; result = new ArrayList&lt;&gt;();\n for(String rec : list){\n int index = rec.indexOf(',');\n if (index == -1) {\n //TODO: decide what to do when there is no comma\n } else {\n result.add(rec.substring(index+1, rec.length());\n }\n }\n return result;\n}\n</code></pre>\n\n<p>I would change the function name. The current name seems to imply that you are changing the content you are passing in. Instead, what <strong>is</strong> happening is that you are extracting values.</p>\n\n<hr>\n\n<p>Repeated code: The best example of this is <code>createReport()</code>. This could be rewritten along these lines:</p>\n\n<pre><code>public static int printLoad(LecturerDetails details, String dept) {\n int totalHours = 0;\n\n for (TeachingLoad tl : details.getTeachingLoad()) {\n //calculate hours, add to totalHours, and print content\n }\n return totalHours;\n}\n\npublic static void createReport() {\n //setup stuff\n\n int deptHours = 0;\n\n for (LecturerDetails details : list of professors) {\n deptHours += printLoad(details, getDept(details));\n // between detail stuff\n }\n // end stuff\n}\n</code></pre>\n\n<hr>\n\n<p>When you are adding up hours, I suspect there might be a bug.</p>\n\n<pre><code>for each item {\n hours = hours + mathForThisItem();\n // other things\n totalHours = totalHours + hours;\n}\n</code></pre>\n\n<p><code>hours</code> is accumulating with each item in addition to <code>totalHours</code>. I don't know the business logic behind this math, but I suspect that <code>hours</code> is intended to be the hours for just one item.</p>\n\n<hr>\n\n<p>You can split a String with <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29\" rel=\"nofollow noreferrer\"><code>split()</code></a> instead of having to iterate over a string's characters to match on a specific. Since you weren't using <code>indexOf()</code> in another point, it might make sense to look over the other methods that are available in the built in classes that come with Java.</p>\n\n<hr>\n\n<p><code>updateLecturerFile()</code> has a number of cases where you have <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a> or values. The link gives a simple example of what I'm talking about and describing why this is not a great idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T16:58:45.383", "Id": "57799", "Score": "0", "body": "Thanks, I've just added a workaround to the 'Magic Number' issue. See updated main line above..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T16:48:05.430", "Id": "35606", "ParentId": "35538", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T16:22:34.110", "Id": "35538", "Score": "5", "Tags": [ "java", "object-oriented", "beginner" ], "Title": "Batch process as an OO design solution" }
35538
<p>I am very new to <code>python</code> (probably too new to consider efficiency etc.). But I am bit confused about which method to use while reading a file for <code>post-processing</code>. Here I am reading it line-by-line. There is other methods also for reading the file(e.g <code>infile.read()</code>), one of them is to load the complete file in memory. Can someone kindly discuss this?</p> <p>My code in current condition is:</p> <pre><code>#!/usr/bin/python import sys,math,re try: inf=sys.argv[1] except: print "usage:", sys.argv[0], "argument"; sys.exit(1) infile=sys.argv[1]; oufile=sys.argv[2] ifile=open(infile, 'r'); ofile=open(oufile, 'w') pattern=r'species,subl,cmp=\s{4}(.*)\s{4}(.*)\s{4}(.*)\s{3}s1,torque=(.{12})(.{12})' ssc1=[];ssc2=[];ssc3=[]; s1=[]; t=[] for line in ifile: match = re.search(pattern, line) if match: ssc1. append(int(match.group(1))) s1. append(float(match.group(4))) t. append(float(match.group(5))) for i in range(len(t)): print('%g %12.5e %12.5e' % (ssc1[i], s1[i], t[i])) ifile.close(); ofile.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:00:23.290", "Id": "57664", "Score": "0", "body": "Why would you not use proper coding style and conventions. Code looks too ugly. Also,while handling the IO operations with files, do have check on file size when you loading the complete file in memory." } ]
[ { "body": "<p>First, Where are you writing in <code>ofile</code>?</p>\n\n<p>Second, ;) you can use <code>with</code> statement to opening and closing files like below:</p>\n\n<pre><code>pattern=r'species,subl,cmp=\\s{4}(.*)\\s{4}(.*)\\s{4}(.*)\\s{3}s1,torque=(.{12})(.{12})'\ninfile=sys.argv[1]; outfile=sys.argv[2]\nwith open(infile, \"r\") as ifile, open(outfile, \"w\") as ofile:\n for line in ifile:\n match = re.match(pattern, line)\n if match:\n ofile.write('%g %12.5e %12.5e' % (int(match.group(1)), float(match.group(4)), float(match.group(5))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:43:07.783", "Id": "57666", "Score": "0", "body": "I don't like encouraging such wide source lines (`ofile.write`), and this certainly makes some assumptions about the intent of the code, but agreed with both intended points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:51:54.913", "Id": "57670", "Score": "0", "body": "as I have said, I am very new to python. So, but is there any particular benefit of `with` statement to open file? \nI have not gone far enough to find this opening method in my book (python in a nutshell)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T07:26:22.683", "Id": "57739", "Score": "1", "body": "@BaRud The `with` statement guarantees the closing of the file when execution leaves the `with` block, no matter how." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:35:37.927", "Id": "35546", "ParentId": "35540", "Score": "3" } }, { "body": "<p>With regards to reading the file, I would say that reading it line by line is a great way to go. That way only part of it will be in memory at a time and you can thus handle a much larger file. If you know file sizes are small, and performance matters, and profiling shows another approach to be better, then you can consider an alternative. In the meantime, <code>for line in somefile</code> is quite idiomatic, and isn't likely to be the bottleneck.</p>\n\n<p>That said, you discard some of the memory benefit when you store all the values in several lists, only to iterate over them, printing them one at a time. With no further context, I would tend to suggest you rewrite your loop like this:</p>\n\n<pre><code>for line in ifile:\n match = re.search(pattern, line)\n if match:\n ssc1 = int(match.group(1))\n s1 = float(match.group(4))\n t = float(match.group(5))\n print(\"%g %12.5e %12.5e\" % (ssc1, s1, t))\n</code></pre>\n\n<p>But obviously if in your real context you need to load all the values before you can process them, or if you care about certain differences in behavior here, like whether one invalid matched group causing <code>int</code> or <code>float</code> to raise an exception should prevent all output, then you should keep your current approach.</p>\n\n<p>I would also suggest some small changes:</p>\n\n<ul>\n<li>Remove unused variables (<code>inf</code>, <code>ssc2</code>, <code>ssc3</code>, <code>ofile</code>, <code>oufile</code>).</li>\n<li>Use more descriptive variable names.</li>\n<li>Avoid bare except. At the very least, catch <code>BaseException</code>; alternately consider the LBYL of checking the number of values in <code>sys.argv</code>.</li>\n<li>Avoid doing multiple things on a single line (replace <code>;</code> with newlines).</li>\n<li>Consider <a href=\"http://docs.python.org/dev/library/re.html?highlight=re.compile#re.compile\" rel=\"nofollow\">compiling the regular expression</a>, and possibly using named groups instead of group indices; the latter makes it easier to update the regex's captures.</li>\n<li>Consider refactoring most of this into a function whose name describes what it's doing, and handle passing relevant arguments from <code>sys.argv</code> to it in an <code>if __name__ == '__main__'</code> block. This would allow it to be usable as a module in addition to as a script.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:16:12.377", "Id": "57673", "Score": "0", "body": "I'd prefer using `str.format` over the `%` style string formatting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:11:34.267", "Id": "57681", "Score": "0", "body": "thanks for your detailed explanation. But as I am new, and yet to learn every thing, can you kindly refer me the some source on compiling regex and named group (i.e. 5th point)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:19:55.003", "Id": "57778", "Score": "0", "body": "See the docs for [re](http://docs.python.org/dev/library/re.html?highlight=re.compile#re.compile) `rx = re.compile(pattern); match = rx.search(line)`; as for named groups, see the same page for `(?P<name>...)`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:38:59.627", "Id": "35547", "ParentId": "35540", "Score": "3" } } ]
{ "AcceptedAnswerId": "35547", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T16:56:43.657", "Id": "35540", "Score": "2", "Tags": [ "python" ], "Title": "the better method of I/O from file" }
35540
<p>I am designing a basic in-memory cache storage with a thin CRUD (actually CRD) interface. The design is inspired by backend solutions such as <a href="https://parse.com/" rel="nofollow">Parse</a> and <a href="https://www.stackmob.com/" rel="nofollow">StackMob</a>.</p> <p>Main characteristics:</p> <ul> <li><p>Cache consists of tables(schemas) storing hashes.</p></li> <li><p>The keys(fields) in a table are fixed(enforced).</p></li> <li><p>Maximum memory efficiency for storing large data.</p></li> </ul> <p>Here is the design I came up with, which is tested and fully functional.</p> <p>There are too many Exceptions for my taste, but somehow I need to enforce things that "should not happen". Another thought was to log errors silently and then ignore them. However, that means my code using this API will have to account for those errors, increasing the complexity.</p> <p>The basic methods are <code>create</code>, <code>readOne</code>, <code>read</code>, and <code>delete</code>. CRUD usually includes <code>update</code> but I find it useless as it can be accessed by combining 'read', 'delete', 'create' and requires additional decision how to handle concurrency.</p> <p>I'm curious to get feedback and thankful for any critiques or remarks regarding what can be improved.</p> <pre><code>/** Local In-Memory Cache: Tables referred by their string names * Storing hashes: * all hashes must have 'id' as key * all hashes must have keys other than 'id' * and hashes in the same table must have the same key structure (enforced) * Basic CRUD interface + 'readOne' for the first entry + 'realDelete' * optimized to save memory: arrays packed into |-separated strings and gz(de/in)flated */ class LocStore { // ass. array 'table' =&gt; string of keys private $_keys = array(); // assoc. array of strings indexed by table and id private $_values = array(); /** create entry, enforce the same keys and new id * @param string $table * @param ass. array $hash, must have 'id' not null */ public function create ($table, array $hash) { $id = $hash['id']; if (! $id) throw new Exception('Id is null'); unset($hash['id']); if (! $hash) throw new Exception('Empty hash beside id'); // sort by keys alphabetically ksort($hash); $keyString = $this-&gt;_toString(array_keys($hash)); if ( empty($this-&gt;_keys[$table]) ) { $this-&gt;_keys[$table] = $keyString; } elseif ($this-&gt;_keys[$table] != $keyString) { throw new Exception('Array keys mismatch'); } if ( isset($this-&gt;_values[$table]) &amp;&amp; ! empty($this-&gt;_values[$table][$id]) ) { throw new Exception("Id '$id' already exists"); } $this-&gt;_values[$table][$id] = $this-&gt;_toString(array_values($hash)); // for chaining return $this; } // read one entry, empty array if nothing is there public function readOne ($table) { if ( empty($this-&gt;_values[$table]) ) return array(); reset($this-&gt;_values[$table]); $id = key($this-&gt;_values[$table]); return $this-&gt;read($table, $id); } // read by id, empty array if not found public function read ($table, $id) { if ( empty($this-&gt;_values[$table]) || empty($this-&gt;_values[$table][$id]) ) return array(); $keys = $this-&gt;_toArray($this-&gt;_keys[$table]); $values = $this-&gt;_toArray($this-&gt;_values[$table][$id]); $result = array_combine($keys, $values); $result['id'] = $id; return $result; } // delete by id, exception if not found public function delete ($table, $id) { if ( empty($this-&gt;_values[$table]) || empty($this-&gt;_values[$table][$id]) ) { throw new Exception('Deleting non-existant entry'); } unset($this-&gt;_values[$table][$id]); return $this; } public function readDelete($table, $id) { $hash = $this-&gt;read($table, $id); if ($hash) $this-&gt;delete($table, $id); return $hash; } private function _toString (array $array) { $json = json_encode($array); return gzdeflate($json); } private function _toArray ($string) { $string = gzinflate($string); return json_decode($string); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:03:06.497", "Id": "59475", "Score": "0", "body": "Out of interest why not just use memcached?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T14:22:28.300", "Id": "59661", "Score": "0", "body": "I've considered memcached or other in-memory databases. I actually could not see the reason to use any of them. I understand there is no compression out of the box, API is not suitable for tables, the code is long and hidden inside thousands of other files in Zend. I'd still need to rewrite and adapt, and I can do just that with much shorter code and full control of what it does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T14:29:08.023", "Id": "59662", "Score": "0", "body": "@Dave Is there anything I miss or overlook that way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:06:15.350", "Id": "59669", "Score": "0", "body": "The whole point of memcached is to cache sql query results so that instead of having to hit the mysqld every time you simply pull the result set from memcached instead saving disk IO and load on the mysqld doing it in php like this means that your php script memory usage will skyrocket you'll probably find you have to edit your php.ini to allow larger memory usage by script 64mb is default i think also on pages with large datasets then you'll be increasing load time massively due to your gzip part as it has to zip/unzip massive datasets AND page your mysqld." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:07:35.010", "Id": "59670", "Score": "0", "body": "not to mention you have to handle persistance of your cache object across page loads which is either storing it in a session or some how committing it to a text file or db anyway. While there's nothing massively wrong with your code (that I can see at least) there's also no benefit to your application by doing what you're doing only detractors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:26:27.717", "Id": "59683", "Score": "0", "body": "@Dave I see, then it must be different memcached I was looking at: [http://docs.libmemcached.org/]. The purpose of my code here is in-memory store with basic API. I rather not mix it with actual database storage as it would break the SRP. I've tried to make it general purpose so I can re-use it with or without a database. Yes, there is no persistence, which is intended, it would be other module's responsibility if needed. Only storage as single responsibility. This is what I learned from Uncle Bob's great Clean Code book. I wouldn't see how I could do it easier with memcached." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:51:17.927", "Id": "59685", "Score": "0", "body": "read up on memcached http://net.tutsplus.com/tutorials/php/faster-php-mysql-websites-in-minutes/ http://stackoverflow.com/questions/815041/memcached-vs-apc-which-one-should-i-choose http://php.net/manual/en/book.memcached.php as for your in memory store with basic API you're still just making hard work without any benefits if you're doing it in PHP the only time you'll see benefit is if you off shore it outside of the runtime onto a separate daemon otherwise its just overhead php isn't very good at what you want to do as its non state aware and non persistent storage between page loads" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:27:59.780", "Id": "59697", "Score": "0", "body": "@Dave Thanks, it is actually exactly for a separate data maintenance and transfer cron daemon. There are no pages, no user interaction. So what you say confirms my understanding that using memcached or likes wouldn't be beneficial. A user request would go independently via javascript directly to BaaS, with no PHP involved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:20:25.697", "Id": "59731", "Score": "0", "body": "doesn't matter if there's user interaction or not if you're pulling large datasets from a DB regularly and the data is mostly similar there's still massive benefits to memcached over a home rolled especially one based around php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:48:05.567", "Id": "59754", "Score": "0", "body": "@Dave As I don't use mysql, don't do sessions, need memory control, worry less about speed, need a short simple code easy to put on any server without worrying about installations, I am not sure what are the benefits. I'd be happy to learn if there are any but could think of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:28:32.140", "Id": "59770", "Score": "0", "body": "Without knowing the full extent of your application, what you hope to achieve and an idea of its function and architecture I can't fully advise on any alternatives just typically if you're looking at writing a data storage system in pure php it typically means you've made some wrong design decisions somewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T15:24:22.110", "Id": "61760", "Score": "0", "body": "@Dave Point taken, thanks - here is [a new version with explanation](http://codereview.stackexchange.com/questions/37349/in-memory-data-cache-architecture-for-data-transfer)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T17:01:38.663", "Id": "35541", "Score": "2", "Tags": [ "php", "object-oriented", "database", "cache" ], "Title": "In-memory data cache architecture" }
35541
<p>My goal is to provide a function with the following functionality:</p> <pre><code>// Will throw iff a != 42. check(a == 42) &lt;&lt; a &lt;&lt; " is not equal to 42!"; </code></pre> <p>I have the following:</p> <pre><code>class check { public: check(bool everything_OK = false) : should_throw{!everything_OK} { } check(const check&amp;) = delete; ~check() noexcept(false) { if (should_throw &amp;&amp; !uncaught_exception()) { throw runtime_error(stream.str()); } } template&lt;typename T&gt; check&amp; operator &lt;&lt; (T&amp;&amp; t) { if (!should_throw) { return *this; } stream &lt;&lt; std::forward&lt;T&gt;(t); return *this; } private: const bool should_throw; stringstream stream; }; </code></pre> <p>The thing is, all guidelines I have read forbid throwing in the destructor. I have also read experts saying they do not know of a good use of std:uncaught_exception. Can I still achieve what I want? </p> <p>ADDITION: Loki’s point below can be fixed by defining a macro:</p> <pre><code>#define my_check(expr) (expr) ? ((void)0) : check(false) </code></pre> <p>But once we allow ourselves to use macros, there are other solutions provided below. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T10:25:28.287", "Id": "57762", "Score": "0", "body": "Added noexcept(false)" } ]
[ { "body": "<p>For what you appear to be trying to accomplish, the risk of a call to <code>std::terminate</code> doesn't seem like as horrible a problem as the usual case, for three reasons:</p>\n\n<ul>\n<li>Someone is unlikely to hold on to an instance of <code>CheckStream</code>, so there's a smaller window</li>\n<li>In its nameless-temporary usage, the stream of <code>operator&lt;&lt;</code> calls are also relatively unlikely to throw, and</li>\n<li>I'm guessing this used in unit tests rather than main code lines, so a <code>std::terminate</code> isn't as likely to be catastrophic (though still annoying if it blocks subsequent tests).</li>\n</ul>\n\n<p>That said, it's still a risk, and this use of <code>std::uncaught_exception</code> is a <a href=\"http://www.gotw.ca/gotw/047.htm\" rel=\"nofollow\">bad idea</a>.</p>\n\n<p>Ignoring the use of <code>std::uncaught_exception</code> (i.e. pretending it always fails) there are two operations to worry about: the <code>operator&lt;&lt;</code> call and the preparation of its arguments; an exception in either would crash and burn. It may be helpful cut down on the potential for the former by adding a try/catch around <code>stream &lt;&lt; std::forward&lt;T&gt;(t);</code>, but that doesn't help the latter case of preparing <code>t</code>.</p>\n\n<p>One way to resolve this would be to move the exception from the destructor. Perhaps standardize on always requiring checks to end with <code>&lt;&lt; std::endl</code>. Then <code>CheckStream</code> could decide whether to throw inside <code>operator&lt;&lt;</code> instead of its destructor. But how do you enforce the trailing <code>endl</code>? All I can think of is throwing an exception in the destructor if you didn't see it. That's back to square one, but at least the omission is a calling programmer's misuse, so could be fair grounds for <code>std::terminate</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T10:08:06.683", "Id": "57759", "Score": "0", "body": "What do you mean is the problem if operator << throws? \n\nThat would give a normal std::bad_alloc (or similar) exception, wouldn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:23:08.860", "Id": "57781", "Score": "0", "body": "Sure, std::bad_alloc is likely, but as operator<< can be provided by other people, it can do arbitrary amounts of work. So the window of worry from (`check(cond)`, through `<< a` and `<< b`, to its destruction) is potentially wider than it looks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:03:10.233", "Id": "57802", "Score": "0", "body": "But why should I worry about that? The exception will be correctly propagated, won’t it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:11:04.107", "Id": "57806", "Score": "0", "body": "I'll need more time to fully wrap my head around http://www.gotw.ca/gotw/047.htm, but there the subtle problems with using `std::uncaught_exception` are covered. The simplest problem: you can't know whether the current exception will be caught closer to the destructor than the `runtime_error` would be. If all you want to know is the problem with throwing from a destructor, then codereview may be the wrong place for this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:13:34.683", "Id": "57807", "Score": "0", "body": "I have read that article and I don’t think the “subtle problems” there applies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:09:14.600", "Id": "57821", "Score": "0", "body": "OK, I have now made up a (quite contrived) example where it actually matters. It is probably best to use a function instead." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:10:06.857", "Id": "35550", "ParentId": "35543", "Score": "1" } }, { "body": "<p>Ignoring the throwing out of the destructor (which is a bad idea).</p>\n\n<p>My main problem is with usage:</p>\n\n<pre><code>check(a == 42) &lt;&lt; a &lt;&lt; \" is not equal to 42!\"; \n</code></pre>\n\n<p>Here you present a trivial case. But not all error checking is trivial. I think a more realistic case (that will happen more often than you think);</p>\n\n<pre><code>Universe a;\n// .... STUFF\ncheck(a.theMeaningLTUAE(42)) &lt;&lt; a &lt;&lt; \" The truth not reached \" &lt;&lt; a.checkInvariants();\n</code></pre>\n\n<p>Here we have calls to functions that will need to be evaluated even if they are never used (specifically <code>checkInvariants()</code> may be expensive (or even the streaming of <code>a</code>)). If the check passes you are still obliged to call it here but its value are simply discarded. I would prefer that the function is never called if no error message is going to be produced. </p>\n\n<p>What you really want is a short cut operator that prevents subsequent operations from happening. Note overloading <code>&amp;&amp;</code> and <code>||</code> on a class does not yield short-cut operators.</p>\n\n<p>Or alternatively any functions should be passed as callbacks to <code>operator&lt;&lt;</code> and only evaluated if there output is required. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:40:08.287", "Id": "57793", "Score": "0", "body": "Very good point about how the work preparing an argument for `operator<<` is not elided by the early return therein." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:47:07.127", "Id": "57794", "Score": "0", "body": "@MichaelUrman: The language guarantees that all parameters are fully evaluated before a function is called. `operator<<` is simply a function call, thus all parameters must be fully evaluated before the call is made. Thus you can not elide the call to any functions. The reason for this is that functions can have side affects, the compiler can not make assumptions that it is not required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T16:47:04.057", "Id": "57798", "Score": "0", "body": "That's what I tried to agree with, but used too few words to do so with clarity. To take your example, the call to `a.checkInvariants()` is not elided by the early return in `check::operator<<`. Usage like `altcheck(a.theMeaningLTUAE(42), [&](ostream& o) { o << a << \" The truth not reached \" << a.checkInvariants(); })` should address this. The implementation would be much lighter, but the lambda syntax is heavy here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:01:56.240", "Id": "57801", "Score": "0", "body": "You raise a good point, thanks. My main reason for opening this question, however, is the “throwing from the destructor” issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:05:20.323", "Id": "57804", "Score": "0", "body": "To expand a bit: basically your objection can be fixed by defining a macro making use of the ?: operator. Then no << operator will even be evaluated." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:23:40.630", "Id": "35602", "ParentId": "35543", "Score": "2" } }, { "body": "<p>Another way to sidestep the use of <code>std::uncaught_exception</code>, as well as address the very good point Loki Astari made about the throwaway work done preparing for calls to <code>check::operator&lt;&lt;</code> is to use an alternate approach. The calling code would look like this:</p>\n\n<pre><code>// Will throw iff a != 42.\ncheck(a == 42, [&amp;](ostream&amp; err) { err &lt;&lt; a &lt;&lt; \" is not equal to 42!\"; });\n</code></pre>\n\n<p>That lambda feels a bit heavy for something you want to be easy to use. With macros it could even look like this (but is the cure worse than the disease?):</p>\n\n<pre><code>CHECK(a == 42, err &lt;&lt; a &lt;&lt; \" is not equal to 42!\");\n</code></pre>\n\n<p>To implement this, <code>check</code> becomes a simple function, so all concerns about throwing in a destructor vanish:</p>\n\n<pre><code>template &lt;typename Describe&gt;\nvoid check(bool success, Describe describe_failure)\n{\n if (!success)\n {\n stringstream message;\n describe_failure(message);\n throw runtime_error(message.str());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:17:41.707", "Id": "57808", "Score": "0", "body": "I agree that there are alternative solutions if macros are allowed. Perhaps the magic word “err” should be omitted as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:07:38.253", "Id": "57859", "Score": "0", "body": "@Ben I was torn on that as well, but making it either `CHECK(a == 42, a << \" is not equal to 42!\")` or `CHECK(a == 42, << a << \" is not equal to 42!\")` seemed even worse." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:11:09.450", "Id": "35608", "ParentId": "35543", "Score": "2" } }, { "body": "<p>Not throwing in destructor is possible if changing &lt;&lt; to a comma is acceptable:</p>\n\n<pre><code>check(a == 42, a, \" is not equal to 42.\");\n</code></pre>\n\n<p>But this is not as readable. The definition:</p>\n\n<pre><code>template&lt;typename... Args&gt;\nvoid check(bool everything_OK, Args&amp;&amp;... args)\n{\n // Code which throws\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:59:12.847", "Id": "35612", "ParentId": "35543", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T17:32:36.627", "Id": "35543", "Score": "2", "Tags": [ "c++", "c++11" ], "Title": "”check” function – OK to throw in destructor?" }
35543
<p>I've created a simple NAT library, with four essential functions: </p> <ol> <li>Find the UNPN device (the router in my case).</li> <li>Get the external IP address. </li> <li>Add a port forwarding entry.</li> <li>Delete a port forwarding entry.</li> </ol> <p>Currently, updating an entry in the NAT table will change only the internal client ip address or the internal port, so to update an external port you have to delete it first then insert a new one. </p> <p>TODO:</p> <ol> <li>Add other functionality (listing mapping entries, number of entries ...).</li> <li>Add support for other platforms.</li> <li>more testing if possible.</li> </ol> <p>An example is included; just un-comment the part that you want to test. The library compiled and tested against Visual Studio 2008.</p> <p>Any suggestions: optimization, coding style, bugs.</p> <p><strong>main.c</strong>:</p> <pre><code>#pragma comment(lib, "ws2_32.lib") #include &lt;winsock2.h&gt; #include &lt;ws2tcpip.h&gt; #include &lt;windows.h&gt; #include &lt;stdio.h&gt; #if (_MSC_VER &gt;= 1500) #include &lt;Strsafe.h&gt; #endif #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) #define TCP_PROTOCOL 0 #define UDP_PROTOCOL 1 #define INVALID_ARGS 402 #define ACTION_FAILED 501 #define ENTRY_MAPPING_NOTEXIST 714 #define INVALID_REMOTEHOST_IP 715 #define INVALID_REMOTEHOST_PORT 716 #define ENTRY_CONFLICT 718 #define SAME_PORT_REQUIRED 724 #define ONLY_PERMANENT_LEASE 725 #define OWILDCARD_IP_REQUIRED 726 #define OWILDCARD_PORT_REQUIRED 727 int boradcastDiscovery(char *upnpDeviceIp); int getExternalpAddress(char *upnpDeviceIp, char *localIp, char *externalIpAddress); int addPortForwardEntry(char *upnpDeviceIp, char *localIp, int externalPort, int internalPort, int protocol, char *internalp, char *entryDescription); int deletePortForwardEntry(char *upnpDeviceIp, char *localIp, int externalPort, int protocol); int main() { char buf[512], ipAddress[16]; int errorCode = 0; /*ZeroMemory(ipAddress, 16); boradcastDiscovery(ipAddress); printf("UPNP device IP: %s\n", ipAddress);*/ /*ZeroMemory(ipAddress, 16); errorCode = getExternalpAddress("192.168.1.1", "192.168.1.4", ipAddress); switch(errorCode) { case INVALID_ARGS: printf("Invalid query arg's.\n"); break; case ACTION_FAILED: printf("Query failed to get external IP.\n"); break; default: printf("External IP address: %s\n", ipAddress); break; }*/ /*ZeroMemory(ipAddress, 16); errorCode = addPortForwardEntry("192.168.1.1", "192.168.1.4", 9000, 4000, TCP_PROTOCOL, "192.168.1.7", "TEST FROM LIBRARY"); switch(errorCode) { case INVALID_ARGS: printf("Invalid query arg's.\n"); break; case ACTION_FAILED: printf("Query failed to add entry mapping.\n"); break; case INVALID_REMOTEHOST_IP: printf("Invalid IP address.\n"); break; case INVALID_REMOTEHOST_PORT: printf("Invalid Port number.\n"); break; case ENTRY_CONFLICT: printf("Such entry already exist.\n"); break; case SAME_PORT_REQUIRED: printf("External and internal port must be the same.\n"); break; case ONLY_PERMANENT_LEASE: printf("External and internal port must be the same.\n"); break; case OWILDCARD_IP_REQUIRED: printf("External and internal port must be the same.\n"); break; case OWILDCARD_PORT_REQUIRED: printf("External and internal port must be the same.\n"); break; default: printf("Port mapping entry added sussccefully.\n"); break; }*/ /*ZeroMemory(ipAddress, 16); errorCode = deletePortForwardEntry("192.168.1.1", "192.168.1.2", 5000, TCP_PROTOCOL); switch(errorCode) { case INVALID_ARGS: printf("Invalid query arg's.\n"); break; case ACTION_FAILED: printf("Query failed to add entry mapping.\n"); break; case ENTRY_MAPPING_NOTEXIST: printf("Entry mapping doesn't exist.\n"); break; default: printf("Port mapping entry deleted sussccefully.\n"); break; }*/ while(1) ; return 0; } </code></pre> <p><strong>UpNp discover:</strong></p> <pre><code>int boradcastDiscovery(char *upnpDeviceIp) { char *searchIGDevice = "M-SEARCH * HTTP/1.1\r\nHost:239.255.255.250:1900\r\nST:urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\nMan:\"ssdp:discover\"\r\nMX:3\r\n\r\n", buf[512]; int result = -1; WSADATA wsaData; struct sockaddr_in upnpControl, broadcast_addr; result = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if(result != 0) return WSAGetLastError(); SOCKET sock = INVALID_SOCKET; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) return WSAGetLastError(); if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, searchIGDevice, sizeof(searchIGDevice)) == SOCKET_ERROR) return WSAGetLastError(); upnpControl.sin_family = AF_INET; upnpControl.sin_port = htons(0); upnpControl.sin_addr.s_addr = INADDR_ANY; if (bind(sock, (sockaddr*)&amp;upnpControl, sizeof(upnpControl)) == SOCKET_ERROR) return WSAGetLastError(); broadcast_addr.sin_family = AF_INET; broadcast_addr.sin_port = htons(1900); broadcast_addr.sin_addr.s_addr = inet_addr("239.255.255.250"); if(sendto(sock, searchIGDevice, lstrlen(searchIGDevice)+1, 0, (sockaddr *)&amp;broadcast_addr, sizeof(broadcast_addr)) == SOCKET_ERROR) return WSAGetLastError(); int bcLen = sizeof(broadcast_addr); ZeroMemory(buf, 512); if(recvfrom(sock, buf, 512, 0, (sockaddr *)&amp;broadcast_addr, &amp;bcLen) &lt; 0) return WSAGetLastError(); else { closesocket(sock); WSACleanup(); if(strstr(buf, "device:InternetGatewayDevice")) { int i = 0; char *deviceIp = strstr(buf, "http://") + 7; while(*deviceIp != ':') { upnpDeviceIp[i] = *deviceIp; *deviceIp++; ++i; } return 0; } else return -1; } } </code></pre> <p><strong>Get external IP address:</strong></p> <pre><code>int getExternalpAddress(char *upnpDeviceIp, char *localIp, char *externalIpAddress) { WSADATA wsaData; struct sockaddr_in upnpControl, upnpDevice; int i = 0, j = 0, result = -1, bodyLen = 0; char c, *tmp = NULL, *pLen = NULL, *bodyResponse = NULL, // a pointer to HTTP body response pBodyLen[5], responseHeader[512], getExternalIpRequest[622]; int reuseAddress = 1; // A SOAP request to get external IP address ZeroMemory(getExternalIpRequest, 622); StringCbPrintf(getExternalIpRequest, 622, "POST /UD/?3 HTTP/1.1\r\n" "Content-Type: text/xml; charset=\"utf-8\"\r\n" "SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress\"\r\n" "User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n" "Host: %s\r\n" "Content-Length: 303\r\n" "Connection: Close\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n\r\n" "&lt;?xml version=\"1.0\"?&gt;" "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;" "&lt;SOAP-ENV:Body&gt;" "&lt;m:GetExternalIPAddress xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"/&gt;" "&lt;/SOAP-ENV:Body&gt;" "&lt;/SOAP-ENV:Envelope&gt;\r\n\r\n", upnpDeviceIp); result = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if(result != 0) return WSAGetLastError(); SOCKET sock = INVALID_SOCKET; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) return WSAGetLastError(); if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&amp;reuseAddress, sizeof(reuseAddress)) == SOCKET_ERROR) return WSAGetLastError(); ZeroMemory(&amp;upnpControl, sizeof(upnpControl)); upnpControl.sin_family = AF_INET; if(localIp == NULL) upnpControl.sin_addr.s_addr = INADDR_ANY; else upnpControl.sin_addr.s_addr = inet_addr(localIp); ZeroMemory(&amp;upnpDevice, sizeof(upnpDevice)); upnpDevice.sin_family = AF_INET; upnpDevice.sin_port = htons(80); upnpDevice.sin_addr.s_addr = inet_addr(upnpDeviceIp); if(connect(sock, (struct sockaddr *)&amp;upnpDevice, sizeof(struct sockaddr)) == SOCKET_ERROR) return WSAGetLastError(); if(send(sock, getExternalIpRequest, lstrlen(getExternalIpRequest), 0) == SOCKET_ERROR) return WSAGetLastError(); ZeroMemory(responseHeader, 512); while(recv(sock, &amp;c, 1, 0) &gt; 0) { responseHeader[i] = c; // We got the http header, extract the body length from it if(strstr(responseHeader, "\r\n\r\n")) { // Move the pointer to the first digit pLen = strstr(responseHeader, "Content-Length: ") + 16; ZeroMemory(pBodyLen, 5); // Get the body length while(*pLen != '\r') { pBodyLen[j] = *pLen; *pLen++; ++j; } bodyLen = atoi(pBodyLen); j = 0; bodyResponse = (char *)MALLOC(bodyLen); while(recv(sock, &amp;c, 1, 0) &gt; 0) { bodyResponse[j] = c; ++j; if(j == bodyLen) { // We got the HTTP body closesocket(sock); } } } ++i; } i = 0; tmp = strstr(bodyResponse, "&lt;NewExternalIPAddress&gt;") + 22; ZeroMemory(externalIpAddress, 16); while(*tmp != '&lt;') { externalIpAddress[i] = *tmp; *tmp++; ++i; } FREE(bodyResponse); WSACleanup(); return 0; } </code></pre> <p><strong>Add port forward entry:</strong></p> <pre><code>int addPortForwardEntry(char *upnpDeviceIp, char *localIp, int externalPort, int internalPort, int protocol, char *internalp, char *entryDescription) { WSADATA wsaData; struct sockaddr_in upnpControl, upnpDevice; int i = 0, j = 0, result = -1, bodyLen = 0, numErrorCode = 0; char c, *pLen = NULL, *proto = NULL, *bodyResponse = NULL, pBodyLen[5], responseHeader[2000], addForwardEntryRequest[1200], addForwardEntryRequestHeader[1500]; proto = (char *)MALLOC(4); ZeroMemory(proto, 4); if(protocol == TCP_PROTOCOL) StringCbPrintf(proto, 4, "TCP"); else StringCbPrintf(proto, 4, "UDP"); // A SOAP request to insert a port forwarding entry ZeroMemory(addForwardEntryRequest, 1200); ZeroMemory(addForwardEntryRequestHeader, 1500); StringCbPrintf(addForwardEntryRequest, 1200, "&lt;?xml version=\"1.0\"?&gt;" "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;" "&lt;SOAP-ENV:Body&gt;" "&lt;m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"&gt;" "&lt;NewRemoteHost&gt;" "" "&lt;/NewRemoteHost&gt;" "&lt;NewExternalPort&gt;" "%d" "&lt;/NewExternalPort&gt;" "&lt;NewProtocol&gt;" "%s" "&lt;/NewProtocol&gt;" "&lt;NewInternalPort&gt;" "%d" "&lt;/NewInternalPort&gt;" "&lt;NewInternalClient&gt;" "%s" "&lt;/NewInternalClient&gt;" "&lt;NewEnabled&gt;" "1" "&lt;/NewEnabled&gt;" "&lt;NewPortMappingDescription&gt;" "%s" "&lt;/NewPortMappingDescription&gt;" "&lt;NewLeaseDuration&gt;" "0" "&lt;/NewLeaseDuration&gt;" "&lt;/m:AddPortMapping&gt;" "&lt;/SOAP-ENV:Body&gt;" "&lt;/SOAP-ENV:Envelope&gt;\r\n\r\n", externalPort, proto, internalPort, internalp, entryDescription); StringCbPrintf(addForwardEntryRequestHeader, 1500, "POST /UD/?3 HTTP/1.1\r\n" "Content-Type: text/xml; charset=\"utf-8\"\r\n" "SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping\"\r\n" "User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n" "Host: %s\r\n" "Content-Length: %d\r\n" "Connection: Close\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n\r\n", upnpDeviceIp, lstrlen(addForwardEntryRequest)); StringCchCat(addForwardEntryRequestHeader, 1500, addForwardEntryRequest); result = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if(result != 0) return WSAGetLastError(); SOCKET sock = INVALID_SOCKET; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) return WSAGetLastError(); ZeroMemory(&amp;upnpControl, sizeof(upnpControl)); upnpControl.sin_family = AF_INET; if(localIp == NULL) upnpControl.sin_addr.s_addr = INADDR_ANY; else upnpControl.sin_addr.s_addr = inet_addr(localIp); upnpControl.sin_port = 0; ZeroMemory(&amp;upnpDevice, sizeof(upnpDevice)); upnpDevice.sin_family = AF_INET; upnpDevice.sin_port = htons(80); upnpDevice.sin_addr.s_addr = inet_addr(upnpDeviceIp); if(connect(sock, (struct sockaddr *)&amp;upnpDevice, sizeof(upnpDevice)) == SOCKET_ERROR) return WSAGetLastError(); if(send(sock, addForwardEntryRequestHeader, lstrlen(addForwardEntryRequestHeader), 0) == SOCKET_ERROR) return WSAGetLastError(); ZeroMemory(responseHeader, 2000); while(recv(sock, &amp;c, 1, 0) &gt; 0) { responseHeader[i] = c; if(strstr(responseHeader, "\r\n\r\n")) { // Move the pointer to the first digit pLen = strstr(responseHeader, "Content-Length: ") + 16; ZeroMemory(pBodyLen, 5); // Get the body length while(*pLen != '\n') { pBodyLen[j] = *pLen; *pLen++; ++j; } bodyLen = atoi(pBodyLen); // body length j = 0; bodyResponse = (char *)MALLOC(bodyLen); ZeroMemory(bodyResponse, bodyLen); while(recv(sock, &amp;c, 1, 0) &gt; 0) { bodyResponse[j] = c; ++j; if(j == bodyLen) { closesocket(sock); } } } ++i; } // Check if uPnp reject our entry i = 0; if(strstr(bodyResponse, "&lt;errorCode&gt;")) { char errorCode[3], *tmp = strstr(bodyResponse, "&lt;errorCode&gt;") + 11; while(*tmp != '&lt;') { errorCode[i] = *tmp; *tmp++; ++i; } FREE(bodyResponse); numErrorCode = atoi(errorCode); return numErrorCode; } // Check the entry that we insert if is exist in the mapping table ZeroMemory(addForwardEntryRequest, 1200); ZeroMemory(addForwardEntryRequestHeader, 1500); StringCbPrintf(addForwardEntryRequest, 1200, "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;\r\n" "&lt;SOAP-ENV:Body&gt;\r\n" "&lt;m:GetSpecificPortMappingEntry xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"&gt;\r\n" "&lt;NewRemoteHost/&gt;\r\n" "&lt;NewExternalPort&gt;%d&lt;/NewExternalPort&gt;\r\n" "&lt;NewProtocol&gt;%s&lt;/NewProtocol&gt;\r\n" "&lt;/m:GetSpecificPortMappingEntry&gt;\r\n" "&lt;/SOAP-ENV:Body&gt;\r\n" "&lt;/SOAP-ENV:Envelope&gt;\r\n\r\n", externalPort, proto); StringCbPrintf(addForwardEntryRequestHeader, 1500, "POST /UD/?3 HTTP/1.1\r\n" "Content-Type: text/xml; charset=\"utf-8\"\r\n" "SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetSpecificPortMappingEntry\"\r\n" "User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n" "Host: %s\r\n" "Content-Length: %d\r\n" "Connection: Close\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n\r\n", upnpDeviceIp, lstrlen(addForwardEntryRequest)); StringCchCat(addForwardEntryRequestHeader, 1500, addForwardEntryRequest); sock = INVALID_SOCKET; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) return WSAGetLastError(); if(connect(sock, (struct sockaddr *)&amp;upnpDevice, sizeof(upnpDevice)) == SOCKET_ERROR) return WSAGetLastError(); if(send(sock, addForwardEntryRequestHeader, lstrlen(addForwardEntryRequestHeader), 0) == SOCKET_ERROR) return WSAGetLastError(); i = 0; ZeroMemory(responseHeader, 2000); while(recv(sock, &amp;c, 1, 0) &gt; 0) { responseHeader[i] = c; if(strstr(responseHeader, "\r\n\r\n")) { // Move the pointer to the first digit j = 0; pLen = strstr(responseHeader, "Content-Length: ") + 16; ZeroMemory(pBodyLen, 5); // Get the body length while(*pLen != '\n') { pBodyLen[j] = *pLen; *pLen++; ++j; } bodyLen = atoi(pBodyLen); j = 0; bodyResponse = (char *)MALLOC(bodyLen); ZeroMemory(bodyResponse, bodyLen); while(recv(sock, &amp;c, 1, 0) &gt; 0) { bodyResponse[j] = c; ++j; if(j == bodyLen) { closesocket(sock); WSACleanup(); } } } ++i; } // Check if the request rejected i = 0; if(strstr(bodyResponse, "&lt;errorCode&gt;")) { char errorCode[3], *tmp = strstr(bodyResponse, "&lt;errorCode&gt;") + 11; while(*tmp != '&lt;') { errorCode[i] = *tmp; *tmp++; ++i; } FREE(bodyResponse); numErrorCode = atoi(errorCode); return numErrorCode; } return 0; } </code></pre> <p><strong>Delete port forward entry:</strong></p> <pre><code>int deletePortForwardEntry(char *upnpDeviceIp, char *localIp, int externalPort, int protocol) { WSADATA wsaData; struct sockaddr_in upnpControl, upnpDevice; int i = 0, j = 0, result = -1, bodyLen = 0, numErrorCode = 0; char c, *pLen = NULL, *proto = NULL, *bodyResponse = NULL, pBodyLen[5], responseHeader[700], deleteForwardEntryRequest[700], deleteForwardEntryRequestHeader[1000]; proto = (char *)MALLOC(4); ZeroMemory(proto, 4); if(protocol == TCP_PROTOCOL) StringCbPrintf(proto, 4, "TCP"); else StringCbPrintf(proto, 4, "UDP"); // A SOAP request to delete a mapping entry ZeroMemory(deleteForwardEntryRequest, 700); ZeroMemory(deleteForwardEntryRequestHeader, 1000); StringCbPrintf(deleteForwardEntryRequest, 1200, "&lt;?xml version=\"1.0\"?&gt;" "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;" "&lt;SOAP-ENV:Body&gt;" "&lt;m:DeletePortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"&gt;" "&lt;NewRemoteHost&gt;" "" "&lt;/NewRemoteHost&gt;" "&lt;NewExternalPort&gt;" "%d" "&lt;/NewExternalPort&gt;" "&lt;NewProtocol&gt;" "%s" "&lt;/NewProtocol&gt;" "&lt;/m:DeletePortMapping&gt;" "&lt;/SOAP-ENV:Body&gt;" "&lt;/SOAP-ENV:Envelope&gt;\r\n\r\n", externalPort, proto); StringCbPrintf(deleteForwardEntryRequestHeader, 1500, "POST /UD/?3 HTTP/1.1\r\n" "Content-Type: text/xml; charset=\"utf-8\"\r\n" "SOAPAction: \"urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping\"\r\n" "User-Agent: Mozilla/4.0 (compatible; UPnP/1.0; Windows 9x)\r\n" "Host: %s\r\n" "Content-Length: %d\r\n" "Connection: Keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n\r\n", upnpDeviceIp, lstrlen(deleteForwardEntryRequest)); StringCchCat(deleteForwardEntryRequestHeader, 1500, deleteForwardEntryRequest); result = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if(result != 0) return WSAGetLastError(); SOCKET sock = INVALID_SOCKET; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) return WSAGetLastError(); ZeroMemory(&amp;upnpControl, sizeof(upnpControl)); upnpControl.sin_family = AF_INET; if(localIp == NULL) upnpControl.sin_addr.s_addr = INADDR_ANY; else upnpControl.sin_addr.s_addr = inet_addr(localIp); upnpControl.sin_port = 0; ZeroMemory(&amp;upnpDevice, sizeof(upnpDevice)); upnpDevice.sin_family = AF_INET; upnpDevice.sin_port = htons(80); upnpDevice.sin_addr.s_addr = inet_addr(upnpDeviceIp); if(connect(sock, (struct sockaddr *)&amp;upnpDevice, sizeof(upnpDevice)) == SOCKET_ERROR) return WSAGetLastError(); if(send(sock, deleteForwardEntryRequestHeader, lstrlen(deleteForwardEntryRequestHeader), 0) == SOCKET_ERROR) return WSAGetLastError(); ZeroMemory(responseHeader, 700); while(recv(sock, &amp;c, 1, 0) &gt; 0) { responseHeader[i] = c; if(strstr(responseHeader, "\r\n\r\n")) { // Move the pointer to the first digit j = 0; pLen = strstr(responseHeader, "Content-Length: ") + 16; ZeroMemory(pBodyLen, 5); // Get the body length while(*pLen != '\n') { pBodyLen[j] = *pLen; *pLen++; ++j; } bodyLen = atoi(pBodyLen); j = 0; bodyResponse = (char *)MALLOC(bodyLen); ZeroMemory(bodyResponse, bodyLen); while(recv(sock, &amp;c, 1, 0) &gt; 0) { bodyResponse[j] = c; ++j; if(j == bodyLen) { closesocket(sock); WSACleanup(); } } } ++i; } // Check f our request rejected i = 0; if(strstr(bodyResponse, "&lt;errorCode&gt;")) { char errorCode[3], *tmp = strstr(bodyResponse, "&lt;errorCode&gt;") + 11; while(*tmp != '&lt;') { errorCode[i] = *tmp; *tmp++; ++i; } FREE(bodyResponse); numErrorCode = atoi(errorCode); return numErrorCode; } else return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:49:30.000", "Id": "57669", "Score": "0", "body": "I'd recommend splitting this code into separate blocks, or only include what's most necessary for review. Excessively-long code could discourage reviewing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:55:09.410", "Id": "57678", "Score": "0", "body": "@Jamal Do you mean splitting code by inserting each function in its own code tag?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:56:44.350", "Id": "57679", "Score": "0", "body": "Only if this would work as separate questions. Otherwise, you could just have more than one block in this question, each with a short description of what's included." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T01:06:34.290", "Id": "57699", "Score": "1", "body": "What's the point of `main` - it is just a `while(1)` loop with everything else commented out." } ]
[ { "body": "<p>My main comment is that you need to concentrate on avoiding duplication of\ncode and on writing smaller functions. 50 lines or so is the sort of max length I use. You also use long names that are often\ntoo long giving the code a very dense appearance and making it difficult ot\nread. Smaller functions, reduced variable scope and hence shorter name sizes\nwill help here.</p>\n\n<p>In function <code>boradcastDiscovery</code>, the name could be better as the current\n(misspelt) name doesn't say what the function does. <code>getGateway()</code> perhaps?</p>\n\n<p>In this function we have:</p>\n\n<pre><code>struct sockaddr_in upnpControl,\n broadcast_addr;\n\nSOCKET sock = INVALID_SOCKET;\nsock = socket(AF_INET, SOCK_DGRAM, 0);\nif (sock == INVALID_SOCKET)\n return WSAGetLastError();\n\nif(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, searchIGDevice, sizeof(searchIGDevice)) == SOCKET_ERROR)\n return WSAGetLastError();\n\nstruct sockaddr_in upnpControl;\nupnpControl.sin_family = AF_INET;\nupnpControl.sin_port = htons(0);\nupnpControl.sin_addr.s_addr = INADDR_ANY;\nif (bind(sock, (sockaddr*)&amp;upnpControl, sizeof(upnpControl)) == SOCKET_ERROR)\n return WSAGetLastError();\n</code></pre>\n\n<p>This could easily be extracted to a function:</p>\n\n<pre><code>static int\ngetBroadcastSocket(char *device, size_t size)\n{\n SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);\n if (sock == INVALID_SOCKET) {\n return -1;\n }\n int status = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, device, size);\n if (status != SOCKET_ERROR) {\n struct sockaddr_in s;\n s.sin_family = AF_INET;\n s.sin_port = htons(0);\n s.sin_addr.s_addr = INADDR_ANY;\n status = bind(sock, (sockaddr*)&amp;s, sizeof s);\n }\n if (status == SOCKET_ERROR) {\n close(sock);\n return -1;\n }\n return sock;\n}\n</code></pre>\n\n<p>Notice that <code>sock</code> is closed on error.</p>\n\n<p>Another example is in code such as this which extracts a field from a string\nand is repeated numerous times thoughout the whole code:</p>\n\n<pre><code>if(strstr(responseHeader, \"\\r\\n\\r\\n\")) {\n // Move the pointer to the first digit\n pLen = strstr(responseHeader, \"Content-Length: \") + 16;\n ZeroMemory(pBodyLen, 5);\n // Get the body length\n while(*pLen != '\\r') {\n pBodyLen[j] = *pLen;\n *pLen++;\n ++j;\n }\n</code></pre>\n\n<p>This should be extracted into a suitable function. Also of note in this code\nare:</p>\n\n<ul>\n<li>the use of explicit lengths (16 and 5 here), which is bad practice;</li>\n<li>the lack of checks for target buffer overflow (often difficult);</li>\n<li>the use of variable <code>j</code> which was initialize far away at the start of the\nfunction;</li>\n<li>inappropriate loop type - a <code>for</code> would be better.</li>\n</ul>\n\n<p><hr>\nA few other comments:</p>\n\n<ul>\n<li><p>The address \"239.255.255.250\" would be better if extracted to a #define at the top\nperhaps.</p></li>\n<li><p>The code</p>\n\n<pre><code>char *proto = NULL,\n...\nproto = (char *)MALLOC(4);\nZeroMemory(proto, 4);\nif(protocol == TCP_PROTOCOL)\n StringCbPrintf(proto, 4, \"TCP\");\nelse\n StringCbPrintf(proto, 4, \"UDP\");\n</code></pre></li>\n</ul>\n\n<p>would be better as</p>\n\n<pre><code> const char *proto = (protocol == TCP_PROTOCOL) ? \"TCP\" : \"UDP\";\n</code></pre>\n\n<ul>\n<li><p>Some of your calls to <code>ZeroMemory</code> often look redundant. The sizes in these\ncalls and in calls to <code>StringCbPrintf</code> are often explicit numbers rather than\nusing <code>sizeof</code>, which would be better.</p></li>\n<li><p>The huge xml strings are distracting and would, I think, be better extracted\ninto suitably named functions, passing in the target buffer and the parameters\nthat need to be printed into the strings.</p></li>\n<li><p>Variables should be defined close to their first point of use and initialised\non use if possible. For example there is no benefit in writing:</p>\n\n<pre><code>SOCKET sock = INVALID_SOCKET;\nsock = socket(AF_INET, SOCK_STREAM, 0);\n</code></pre>\n\n<p>when you could write</p>\n\n<pre><code>SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);\n</code></pre></li>\n<li><p>you are using TCP so you don't have to create a complete string before\nsending it. For example instead of writing</p>\n\n<pre><code>createHeader(header, ...);\ncreateRequest(request, ...);\nconcatenate(combined, header, request);\nsend(combined);\n</code></pre>\n\n<p>you can instead do:</p>\n\n<pre><code>createHeader(header, ...);\nsend(header);\ncreateRequest(request, ...);\nsend(request);\n</code></pre></li>\n</ul>\n\n<p>Hopefully you will find something above that is of use :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T16:18:31.210", "Id": "35604", "ParentId": "35549", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:46:57.210", "Id": "35549", "Score": "5", "Tags": [ "c", "library", "networking", "windows" ], "Title": "A simple NAT library" }
35549
<p>I've learned PHP following only tutorials on the web and I'm quite sure my style is not at top.</p> <p>I'd like to understand how this code could be written in a more elegant way:</p> <pre><code>&lt;? $posts = // array with informations about posts fetched with PHP PDO from DB $html = "&lt;ul&gt;"; foreach($posts as $post) { $html .= "&lt;li&gt;&lt;h2&gt;".$post["title"]."&lt;/h2&gt;&lt;span&gt;".$post["text"]."&lt;/span&gt;&lt;/li&gt;"; } $html .= "&lt;/ul&gt;"; echo $html; </code></pre> <p>I'm not sure if this is already a good piece of code or not. I hope you guys can help me out.</p>
[]
[ { "body": "<p>There is nothing overtly incorrect with your code. </p>\n\n<p>However, one thing that makes PHP nice to work with for web development is it's ability to interpolate variables. When you use double quotes around a string, PHP will interpolate (replace variables with their value). When you do not want that behavior, then you should use single quotes. You should also use single quotes to delimit keys in arrays, rather than double quotes, which will also interpolate variables, should they be found.</p>\n\n<p>Here's what I'd do in your case, inside the foreach.</p>\n\n<pre><code>$html .= \"&lt;li&gt;&lt;h2&gt;{$post['title']}&lt;/h2&gt;&lt;span&gt;{$post['text']}&lt;/span&gt;&lt;/li&gt;\";\n</code></pre>\n\n<p>This looks more like html, and doesn't require dropping in and out of the string output or concatenating all over the place.</p>\n\n<p>You might wonder why you need the blocks around the $post array variables. This is so that you can include the single quotes around the array key without confusing the php parser. If you were to try this:</p>\n\n<pre><code>$html .= \"&lt;li&gt;&lt;h2&gt;$post['title']&lt;/h2&gt;&lt;span&gt;$post['text']&lt;/span&gt;&lt;/li&gt;\";\n</code></pre>\n\n<p>You'll find you get a parse error. The block tells php to parse that code and insure it works fine. You can actually omit the single quotes and the code will parse, but it's better stylistically to always include them when dealing with array keys. This works without the block.</p>\n\n<pre><code>$html .= \"&lt;li&gt;&lt;h2&gt;$post[title]&lt;/h2&gt;&lt;span&gt;$post[text]&lt;/span&gt;&lt;/li&gt;\";\n</code></pre>\n\n<p>Whilst this might be a micro-optimization, when you omit the single quotes, php has to determine whether or not 'title' or 'text' are actually constants you've defined. It's also just in general, good practice to always reference variables in the same manner, for consistency and readability.</p>\n\n<p>If you want your html markup to look a bit cleaner, it's also easy enough to add newlines using \"\\n\".</p>\n\n<pre><code>$html = \"&lt;ul&gt;\\n\";\nforeach($posts as $post) {\n $html .= \"&lt;li&gt;&lt;h2&gt;{$post['title']}&lt;/h2&gt;&lt;span&gt;{$post['text']}&lt;/span&gt;&lt;/li&gt;\\n\";\n\n}\n$html .= \"&lt;/ul&gt;\\n\";\n</code></pre>\n\n<p>One final note, since this is a code review -- what this code does, is intermix markup and data in a way that they can not be separated. There is a school of thought in the design pattern world, that data (models) should be pure, and that \"views\" should be responsible for output. For example, let's say that you want to provide this same data in json format for an ajax call you're doing someplace else in your code. This routine is not going to work, because you baked in the html markup. </p>\n\n<p>One of the hallmarks of a spaghetti/php application is rampant intermixing of logic and HTML code, and views are a great way to avoid that from the get-go. </p>\n\n<p>Your code will work, but it inherently has the weakness of intermixing your logic and data with your markup. </p>\n\n<p>Template systems like smarty or twig to name a few (although most all of the PHP frameworks that provide MVC have a template system) encourage you to put your presentation (view) code into separate files. When it comes time to output your code, you inject the data into the view, and your view code can then create your output. You can do this in a lot of different ways, including using pure old PHP scripts, and alternative PHP syntax. I'd encourage you to look at some examples in the manuals of these template/view libraries. </p>\n\n<p>As a simple example, here's how you could have your code in a php \"view\" file that you could require or include.</p>\n\n<pre><code>/* You might name this file postView.php */\n/* You'll start in HTML mode */\n&lt;ul&gt;\n&lt;? foreach($posts as $post): ?&gt;\n &lt;li&gt;&lt;h2&gt;&lt;?=$post['title']?&gt;&lt;/h2&gt;&lt;span&gt;&lt;?=$post['text']?&gt;&lt;/span&gt;&lt;/li&gt;\n&lt;? endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Now your logic looks like:</p>\n\n<pre><code>&lt;?php\n// Fill your $post from the $_POST super glob.\n// Do whatever other logic you need\n\n// Time for output\nrequire_once(postView.php);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:13:48.040", "Id": "35559", "ParentId": "35551", "Score": "4" } }, { "body": "<p>Your code, while not <em>wrong</em> in a strict sense, is not as efficient as it can be. Think about what you're doing here:</p>\n\n<pre><code>$html = '&lt;ul&gt;';\n</code></pre>\n\n<p>This assigns a string constant to a variable <code>$html</code>. All well and good, but then, in your loop looks like this:</p>\n\n<pre><code>foreach($posts as $post)\n{\n $html .= \"&lt;li&gt;&lt;h2&gt;\".$post['title'].\"&lt;/h2&gt;&lt;span&gt;\".$post['text'].\"&lt;/span&gt;&lt;/li&gt;\";\n}\n$html .= \"&lt;/ul&gt;\";\necho $html;\n</code></pre>\n\n<p>Now what you should understand is that <em>true</em> concatenation isn't as easy as the syntax might have you believe it is. You're actually having to create a new string, and reassign the <code>$html</code> variable on each iteration of your string. You could think about your code as being a shorter version of writing:</p>\n\n<pre><code>$html = \"&lt;ul&gt;\".\"&lt;li&gt;&lt;h2&gt;\".$posts[0]['title'].\"&lt;/h2&gt;&lt;span&gt;\".$posts[0]['test'].\"&lt;/span&gt;&lt;/li&gt;\".\"&lt;li&gt;&lt;h2&gt;\".$posts[1]['title'].\"&lt;/h2&gt;&lt;span&gt;\".$posts[1]['text'].\"&lt;/span&gt;&lt;/li&gt;\".\"&lt;/ul&gt;\";\n</code></pre>\n\n<p>Now this is, I think you'll agree, packed with pointless concatenation. Especially since you're then just passing the string to the <code>echo</code> language construct... Why not drop the variable all together?</p>\n\n<pre><code>echo '&lt;ul&gt;';\nforeach($posts as $post)\n{\n echo '&lt;li&gt;&lt;h2&gt;',$post['title'], '&lt;/h2&gt;&lt;span&gt;', $post['text'], '&lt;/span&gt;&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n</code></pre>\n\n<p>And yes, those are <strong>comma's</strong>, not dots. By using comma's the values (string constants and variables) are passed to the <code>echo</code> language construct left to right. No strings are concatenated. Just like, if you've looked at the <em>hello world</em> expamples of C++ <code>std::COUT &lt;&lt; \"Hello \" &lt;&lt; \"world\";</code> does.</p>\n\n<p>Of course, echoing markup depends on the context in which it is used, but in a template/viewscript, one would more commonly write:</p>\n\n<pre><code>&lt;ul&gt;\n&lt;?php foreach ($posts as $post) { ?&gt;\n &lt;li&gt;&lt;h2&gt;&lt;?= $post['title'] ?&gt;&lt;/h2&gt;&lt;span&gt;&lt;?=$post['text'] ?&gt;&lt;/span&gt;&lt;/li&gt;\n&lt;?php } ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>where <code>&lt;?=</code> is equivalent to <code>&lt;?php echo</code>. As opposed to the PHP short tag (<code>&lt;?</code>) is always available, and doesn't require an ini-setting change.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T07:45:46.977", "Id": "35582", "ParentId": "35551", "Score": "2" } }, { "body": "<p>A small extra suggestion: be aware that the above method will not send any content to the client until after you have constructed that (potentially huge string) in memory.\nIt is better to directly echo the contents in this case. This will start sending your result HTML right away, which could help performance. This is especially the case if it takes a while to construct a full post, e.g.</p>\n\n<pre><code>&lt;?\n$posts = // array with minimal info\n\n$html = \"&lt;ul&gt;\";\nforeach($posts as $post) {\n if($post[\"display\"]) {\n $fullPost = $postDao-&gt;fetch($post); // takes 30ms to fetch full post\n $html .= \"&lt;li&gt;&lt;h2&gt;\".$fullPost[\"title\"].\"&lt;/h2&gt;&lt;span&gt;\".$fullPost[\"text\"].\"&lt;/span&gt;&lt;/li&gt;\";\n }\n}\n$html .= \"&lt;/ul&gt;\";\necho $html;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T09:06:34.970", "Id": "35590", "ParentId": "35551", "Score": "2" } } ]
{ "AcceptedAnswerId": "35559", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:52:48.157", "Id": "35551", "Score": "4", "Tags": [ "php" ], "Title": "Is this a good way to print output?" }
35551
<p>The whole question is <a href="https://codereview.stackexchange.com/questions/10776/better-implementation-of-a-simplified-regular-expression-engine">Simplified regular expression engine</a>. I have solved the question, and in turn felt the need to get it reviewed. Any suggestions for clean up and optimization would help. Also please verify my complexity: Complexity: O (n), where n is the length of the longer or regex or string.</p> <pre><code>public final class Regex { private static final char STAR = '*'; private static final char DOT = '.'; private Regex() {}; /** * The index of first non-star character following first occurence of star * eg: if regex is a**b, then index is startIndex is 1 and return value is 3 (index of b) * * @param regex : the regex string. * @param starIndex : index of the first occurene of * after a non *, eg: a**b, then starIndex would be 1 * @return : the index of first non-star character following first occurence of star */ private static int getNonStarIndex(String regex, int starIndex) { assert regex != null; assert starIndex &gt;= 0 &amp;&amp; starIndex &lt; regex.length(); for (int k = starIndex + 1; k &lt; regex.length(); k++) { if (regex.charAt(k) != '*') { return k; } } return regex.length(); } /** * A * means 0 or more number of any char matches * A . means just a single any char match. * * @param regex : The regex to match the string again * @param str : The string to be matched. * @return : true / false */ public static boolean match(String regex, String str) { if (regex == null) throw new NullPointerException("The regex cannot be null"); if (str == null) throw new NullPointerException("The str cannot be null"); int i = 0; int j = 0; while ((i &lt; regex.length() &amp;&amp; j &lt; str.length())) { if (regex.charAt(i) == str.charAt(j) || regex.charAt(i) == DOT) { i++; j++; } else if (regex.charAt(i) == STAR) { int nextNonStarIndex = getNonStarIndex(regex, i); /* * For a case where regex and string, both have not yet reached the last char but regex is all *'s till end. * Eg: Regext abc*** &amp;&amp; String is abcxyz */ if (nextNonStarIndex == regex.length()) return true; /* * regex: a*.*c, abc */ if (regex.charAt(nextNonStarIndex) == DOT) {i = nextNonStarIndex + 1; j++; continue;} boolean match = false; for (int k = j; k &lt; str.length(); k++) { if (regex.charAt(nextNonStarIndex) == str.charAt(k)) { // now move to the next char, after a match succeeds with first char after adjacent stars. i = nextNonStarIndex + 1; j = k + 1; match = true; break; } } if (!match) { return false; } } else { return false; } } /* * String has reached the end but not the regex. * regx = "abc**" and str = "abc"; */ if (i != regex.length()) { for (int x = i; x &lt; regex.length() ; x++) { if (regex.charAt(x) != STAR) return false; } } if (j != str.length()) { return false; } return true; } public static void main(String[] args) { String[] regexList = { "abc****", "abc", "a*b*c", "****abc", "**a**b**c****", "abc*"}; String str1 = "abc"; for (String regex : regexList) { System.out.println(Regex.match(regex, str1)); } String regex = "abc****"; String[] strList1 = {"abcxyz", "abcx", "abc"}; for (String str : strList1) { System.out.println(Regex.match(regex, str)); } regex = "***abc"; String[] strList2 = {"xyzabc", "xabc", "abc"}; for (String str : strList2) { System.out.println(Regex.match(regex, str)); } System.out.println(Regex.match("a.c", "abc")); System.out.println(Regex.match("a*.*c", "abc")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:13:45.023", "Id": "57672", "Score": "5", "body": "I think this warrants a [tag:reinventing-the-wheel] tag :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:44:36.270", "Id": "57676", "Score": "0", "body": "It would be useful if you included your test-harness as well (confirming it works, and allowing me to step through your code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:49:00.107", "Id": "57677", "Score": "0", "body": "added test harness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:10:16.750", "Id": "57680", "Score": "0", "body": "Your solution fails `System.out.println(Regex.match(\"\", \"\"));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:11:54.617", "Id": "57682", "Score": "0", "body": "Always include negative test cases in your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T00:49:45.233", "Id": "57698", "Score": "0", "body": "System.out.println(Regex.match(\"\", \"\")); returns true. should it not ? if not why not ? Appreciate your suggesions though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:50:10.853", "Id": "57710", "Score": "0", "body": "@retailcoder thanks... learnt this new tag today :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:18:05.303", "Id": "57713", "Score": "0", "body": "@JavaDev you should leave the original code here and post the updated code as a follow-up question if you want that code reviewed, otherwise it makes readers have to go to revision history to see the code that rolfl's answer is reviewing :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:48:47.090", "Id": "57715", "Score": "0", "body": "@retailcoder sure, but how to post something as follow-up ?" } ]
[ { "body": "<h1>Style</h1>\n\n<ul>\n<li>Use 'final' keyword where you can. It enables the JIT compiler to make better choices when optimizing, and it also ensures that bugs don't creep in to your code. For example, <code>private static int getNonStarIndex(String regex, int starIndex) {...}</code> should be <code>private static final int getNonStarIndex(final String regex, final int starIndex) {...}</code> and <code>public static boolean match(String regex, String str) {...}</code> should be <code>public static final boolean match(final String regex, final String str) {...}</code></li>\n<li>Use better names for non-for-loop variables. <code>i</code> is OK for <code>for (int i = 0; i &lt; ...; i++)</code> because this is a clear 'standard', but using <code>i</code> and <code>j</code> are poor choices for variables that are manipulated inside the loops. <code>rexpos</code> and <code>strpos</code> are examples of names I would use.</li>\n<li>I always put '1-line-blocks' on their own line, but I accept that <code>if (regex == null) throw new NullPointerException(\"The regex cannot be null\");</code> type lines are OK. But, the following 1-liner is never OK: <code>if (regex.charAt(nextNonStarIndex) == DOT) {i = nextNonStarIndex + 1; j++; continue;}</code></li>\n</ul>\n\n<h1>Functional</h1>\n\n<p>More detailed assessment.... I added the following tests to your code:</p>\n\n<pre><code> System.out.println(\"Should be false from here\");\n\n System.out.println(Regex.match(\"abc\", \"abcd\"));\n System.out.println(Regex.match(\"*a\", \"abcd\"));\n System.out.println(Regex.match(\"a\", \"\"));\n System.out.println(Regex.match(\".a*c\", \"abc\"));\n System.out.println(Regex.match(\"a.*b\", \"abc\"));\n System.out.println(Regex.match(\"..\", \"abc\"));\n System.out.println(Regex.match(\"\", \"\"));\n System.out.println(Regex.match(\"\", \"abc\"));\n</code></pre>\n\n<p>and discovered that your code fails for <code>Regex.match(\"\", \"\")</code>. This is just bad form. The 'assignment' gave a whole bunch of positive and negative test cases, but you only chose to test the positive ones. That counts as 'half-a-job' when testing is concerned. It took me a few minutes to copy/paste the tests in and found what should be a 'fail-the-assignment' condition.</p>\n\n<p>Then I looked at your algorithm and figured it was 'failing' early tests too early... let me try to explain.... consider the following:</p>\n\n<pre><code>Regex.match(\"a*.b.*c\", \"axxbxxbxxc\");\n</code></pre>\n\n<p>The above is not one of the official test cases, but, it <strong>should</strong> return <code>true</code>, but your code returns <code>false</code>.</p>\n\n<p>This is because you look for only the most 'obvious' match... </p>\n\n<h1>Recommendations</h1>\n\n<p>The algorithm you have chosen is too simplistic, having only 1 loop inside the 'STAR' handling loop.</p>\n\n<p>I re-worked your code to use recursion instead, and it handles things much better. Without giving the whole algorithm away, consider a recursive function (copy/paste of your code, renamed <code>match</code> to be <code>matchRecursive</code>):</p>\n\n<pre><code>public static boolean matchRecursive(final String regex, int regexpos,\n final String str, int strpos) {\n while ((regexpos &lt; regex.length() &amp;&amp; strpos &lt; str.length())) {\n if (regex.charAt(regexpos) == str.charAt(strpos) || regex.charAt(regexpos) == DOT) {\n regexpos++;\n strpos++;\n } else if (regex.charAt(regexpos) == STAR) {\n regexpos++;\n // see if there's anything remaining in the regex.\n // if not, return true (star matches rest of str).\n // otherwise, recursively check if the rest of the regex\n // matches anywhere in the rest of the str....\n while (strpos &lt; str.length()) {\n if (matchRecursive(regex, regexpos, str, strpos) {\n return true;\n }\n strpos++;\n }\n } else {\n return false;\n }\n }\n\n // tidy up odd use-cases like:\n // regexes ending in * when there's nothing left in str.\n // empty regex\n // etc.\n return ....;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:04:39.327", "Id": "57712", "Score": "0", "body": "Firstly a huge thanks, improved code and re-posted. Secondly \"\".matches(\"\"); returns true in java, so keeping implementation aligned with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T07:42:48.230", "Id": "57741", "Score": "0", "body": "This is a great answer except for the first suggestion. The `final` modifier has three distinct roles: On classes, it makes them uninheritable, on methods, it makes them non-overridable, and on variables, it makes them assign-once. Disallowing a subclass to override a method is more often than not a stupid idea (compare Open-Closed Principle), whereas single-assignment is a useful technique to reduce bugs. Note that there are few cases where a `final` modifier on a variable would actually affect performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T14:45:11.720", "Id": "57785", "Score": "1", "body": "I think you underestimate the power of `final`. Apart from the logic-constraints you describe above, it has proven to be a defensive bug-trapping tool, performance enhancing, and intent-revealing mechanism. This is in my experience at least. `final` is like a door. It is better to close your doors even when you live in a safe area because an open door is an invitation to come in. Regardless, this is an opinion thing, and will never be resolved. By the way, I prefer vi over emacs, eclipse over intellij, and linux over windows or mac... . ;-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T01:07:27.920", "Id": "35561", "ParentId": "35552", "Score": "8" } } ]
{ "AcceptedAnswerId": "35561", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:57:24.903", "Id": "35552", "Score": "5", "Tags": [ "java", "optimization", "parsing", "regex", "reinventing-the-wheel" ], "Title": "Regex parser - request for review and optimization" }
35552
<p>I am writing an API which gets results from a DynamoDB table and puts the JSON back into the browser.</p> <p>The code below works and returns the desired results. However, after reading about async and callbacks, it's becoming important for me to know if I should be writing this in another way. Does the following scale well with hundreds of concurrent API callers?</p> <p>This code does not seem to be using callbacks. Is it asynchronous?</p> <pre><code>var restify = require('restify'); var AWS = require('aws-sdk'); AWS.config.update({region: 'us-east-1'}); var db = new AWS.DynamoDB(); function myFunction(req, res, next) { var params = { TableName : 'myTable', KeyConditions : { "number" : { "AttributeValueList" : [ { "S" : req.params.simethingid } ], "ComparisonOperator" : "EQ" } } } db.query(params, function(err, data) { if (err) { console.log(err); } else { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain; charset=UTF-8'); res.send(JSON.stringify(data, undefined, 2)); console.log(JSON.stringify(data, undefined, 2)) res.end(); } }); return next(); } server.get('/searchme/:somethingid', myFunction); </code></pre>
[]
[ { "body": "<p>Can't speak to how it'll scale, but for your 2nd question: Yes, the code above is asynchronous.</p>\n\n<p>When you call <code>db.query()</code> or <code>server.get()</code> you pass a callback as the 2nd argument. That's the asynchronous stuff, as you don't know when that callback will be invoked.</p>\n\n<p>You basically just say \"call me when it's done\" and continue about your business (i.e. in the case of <code>db.query()</code> the evaluation will proceed to <code>return next();</code> without \"waiting\" for the query to finish).</p>\n\n<p>If it were <em>synchronous</em>, it'd be something like <code>result = db.query(params);</code> where everything would wait for the query to return something to assign to <code>result</code>.</p>\n\n<p>By the way (so this is actually a <em>review</em> and not just an explanation)</p>\n\n<ul>\n<li>fix your indentation</li>\n<li>in JS it's better to <strong>not</strong> use the brace-on-new-line style</li>\n<li>you're missing some semi-colons</li>\n<li>you don't need to quote all those property names in the params object</li>\n<li>beware of using <code>undefined</code>, since that isn't actually a keyword. Some runtimes let you say <code>undefined = 23</code> in which case <code>undefined</code> is then just another (defined) variable. Use <code>null</code> instead</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:09:08.187", "Id": "35557", "ParentId": "35554", "Score": "2" } } ]
{ "AcceptedAnswerId": "35557", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:18:02.777", "Id": "35554", "Score": "1", "Tags": [ "javascript", "json", "api", "asynchronous", "callback" ], "Title": "Node.js DynamoDB callback" }
35554
<p>I've made this simple function for reading <strong>N</strong> bits from an <code>unsigned char*</code> (with a possible offset) and I'm willing to share it here, get a review, suggestions for improving it, etc...</p> <pre><code>typedef struct bits_t { unsigned char *data; unsigned int len; } bits_t; bits_t *read_bits(unsigned char *src, int bits_offset, int nbits){ unsigned int curr_bit, curr_byte, remaining_to_read, bit_position_in_byte; curr_bit = curr_byte = 0; remaining_to_read = nbits; bits_t *bits = malloc(sizeof(bits_t)); bits-&gt;len = nbits; bits-&gt;data = calloc(1, bits-&gt;len); for(curr_bit = 1; curr_bit &lt;= nbits; curr_bit++){ if(curr_bit &gt;= bits_offset &amp;&amp; remaining_to_read){ curr_byte = (curr_bit - 1) / 8; bit_position_in_byte = (curr_bit - 1) - (curr_byte * 8); bits-&gt;data[remaining_to_read - 1] = read_bit(src[curr_byte], bit_position_in_byte); remaining_to_read--; } } return bits; } </code></pre> <p>Main:</p> <pre><code>unsigned char *x = "oo"; bits_t *bits = read_bits(x, 0, 16); for(i = 0; i &lt; bits-&gt;len; i++){ printf("%d", bits-&gt;data[i]); } </code></pre> <p>Result: <code>0110111101101111</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T23:55:00.343", "Id": "57687", "Score": "0", "body": "1. Your function is never called. 2. Have a look at [this other question](http://stackoverflow.com/questions/7863499/conversion-of-char-to-binary-in-c) (or other similar questions) and note that your code could be made much shorter and faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T00:00:45.827", "Id": "57688", "Score": "0", "body": "1. I'm just showing how I'm calling my function. Obviously, I'm doing that inside main... 2. Err... Do you even know what my function is doing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T00:09:08.237", "Id": "57691", "Score": "0", "body": "1. A full working example would be appreciated. Show main. Your code shows x is assigned, never used, and then a result is printed. 2. There are library functions to produce binary representations of char/int. Why wouldn't you use them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T00:14:50.747", "Id": "57692", "Score": "0", "body": "1. Done, sorry for the confusion. 2. Because I'm not reading entire bytes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T00:44:06.363", "Id": "57697", "Score": "1", "body": "Thanks. I think it would be more efficient if you determined the input chars to iterate over and then placed the appropriate values (mostly one input byte at a time) into your struct. This should reduce the index calculations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T06:00:43.660", "Id": "57724", "Score": "0", "body": "I would much rather pass in a `bit_t *` than allocate one inside the function and pray the caller will remember to free it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:32:24.480", "Id": "57747", "Score": "1", "body": "Your `read_bit` implementation seems to be missing. Is it a macro or an actual function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:49:23.120", "Id": "60240", "Score": "1", "body": "Use `size_t` rather than `unsigned int` for `len` and `nbits`. Maybe also `bits_offset`." } ]
[ { "body": "<ol>\n<li>Consider checking <code>src[currentByte]</code> for <code>'\\0'</code> and abort when it's true (apparently the passed in string wasn't long enough). Depends on your usage though.</li>\n<li>Alternatively to the previous point you could add a <code>source_length</code> parameter to let the caller supply the information of how long the sequence really is.</li>\n<li><p>I would consider changing the interface slightly. Have some methods which manage the object for you:</p>\n\n<pre><code>bits_t *new_bits_t(int nbits)\n{\n bits_t *res = malloc(sizeof(bits_t));\n res-&gt;data = calloc(nbits);\n res-&gt;len = nbits;\n return res;\n}\n\n// frees the memory allocated for the structure and sets the reference to NULL\nvoid delete_bits_t(bits_t **bits)\n{\n if (bits == NULL || *bits == NULL) return;\n free((*bits)-&gt;data);\n free(*bits);\n *bits = NULL;\n}\n</code></pre>\n\n<p>Then your <code>read_bits</code> function could fill in the structure passed in and also return error code in case the reading failed (i.e. source is too short):</p>\n\n<pre><code>int read_bits(unsigned char *src, bits_t *bits, int bits_offset)\n{\n ...\n}\n</code></pre></li>\n<li><p><code>bit_position_in_byte = (curr_bit - 1) - (curr_byte * 8);</code> should be equivalent to <code>bit_position_in_byte = (curr_bit - 1) % 8;</code></p></li>\n<li>Your loop is one based for some reason but inside the loop you have to subtract 1 from <code>current_bit</code> everywhere. You should just make your loop 0 based which would de-clutter the loop a bit.</li>\n<li>I would find <code>bit_in_byte</code> just as descriptive a name as <code>bit_position_in_byte</code>.</li>\n<li><p>You could get rid of the <code>remaining_to_read</code> by calculating the position:</p>\n\n<pre><code>for (curr_bit = 0; curr_bit &lt; nbits; ++curr_bit) {\n input_bit = curr_bit + bits_offset - 1;\n input_byte = input_bit / 8;\n bit_in_byte = input_bit % 8;\n bits-&gt;data[nbits - curr_bit - 1] = read_bit(src[input_byte], bit_in_byte);\n}\n</code></pre></li>\n<li>The loop apparently fills <code>data</code> from the end which seems little bit unexpected to me (kind of string reversal).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T10:00:28.310", "Id": "57758", "Score": "0", "body": "Let me get home and apply those changes :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:41:31.887", "Id": "35587", "ParentId": "35555", "Score": "3" } }, { "body": "<p>Using <code>_t</code> as a suffix is <a href=\"https://stackoverflow.com/a/3225396/1157100\">reserved by POSIX</a>. Also the structure is\nunnecessary. The <code>len</code> field is essentially unused - the caller knows the\nlength already. So just allocate and return an array. Note that you need to\ncheck that the allocation succeeded.</p>\n\n<p>Parameter <code>src</code> should be <code>const</code></p>\n\n<p>Why is everything unsigned except <code>nbits</code>? I would make all apart from the chars signed -\nmaking things unsigned adds nothing here and so is just 'noise'. </p>\n\n<p>Variables should generally be defined one per line and initialised immediately\n- although it is better to define them at the point of first use.</p>\n\n<p>It is normal to start indexing at 0 rather than 1. And your loop should start\nat <code>bits_offset</code>, rather than starting at 1 and indexing through.</p>\n\n<p>Here is a revised version. Note the use of <code>%</code> to get the bit offset.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nstatic unsigned char* read_bits(const unsigned char *src, int offset, int nbits)\n{\n unsigned char *s = malloc((size_t) nbits);\n if (s) {\n --nbits;\n for (int bit = offset; nbits &gt;= 0; ++bit, --nbits){\n int byte = bit / 8;\n int bit_position = bit % 8;\n s[nbits] = (src[byte] &gt;&gt; bit_position) &amp; 1;\n }\n }\n return s;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T20:28:04.257", "Id": "57857", "Score": "0", "body": "Good, but I think you've misinterpreted the function's intent, which is to interpret arbitrary data as numeric bits. I think `unsigned char *bits_big_endian(const char *src, int bit_offset, unsigned int nbits)` would be a more appropriate signature. Data, being non-numeric, are most naturally `char[]`, not `unsigned char[]`. @alexandernst wants the output as `0` and `1`, not `'0'` and `'1'`. A numeric bit would be `unsigned char`, and a numeric bit string should not be terminated with `'\\0'`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:06:20.407", "Id": "57886", "Score": "0", "body": "@200_success thanks, you are quite right. I modified it to fit the spec." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:25:04.057", "Id": "57963", "Score": "0", "body": "Sorry for not replying yesterday, I was busy. I tried your code but it won't return anything actually. Have a look here: http://ideone.com/v1BJCV" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:29:51.530", "Id": "58006", "Score": "0", "body": "Alex, the code you tried was the edited version above but with my original `main` (which assumed a string was returned). I removed `main` from the code above because your original `main` works with this code. My original code, which output a string can be seen if you click on the \"edited 21 hours ago\" link below the code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:49:04.850", "Id": "35630", "ParentId": "35555", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:45:29.110", "Id": "35555", "Score": "3", "Tags": [ "c", "bitwise" ], "Title": "Function for reading bits" }
35555
<p>I've just finished a program for a 2-way carousel. Meaning, if I click left or right, you are able to go up and down, depending on where you are. This is suppose to work for iPad or tablet only.</p> <p>I would like to know how to make the code better or if there are any suggestions. I would appreciate it. I am new at this, so I've done my best.</p> <pre><code>$(document).ready(function() { // Find matches var mql = window.matchMedia("(orientation: portrait)"); var all = document.getElementById("slider-view"); var winWidth = 0; var winHeight = 0; winWidth = window.innerHeight; winHeight = window.innerWidth; // If there are matches, we're in portrait if(mql.matches) { // Portrait orientation $(all).addClass('portrait-transform'); $(all).css('height', window.innerWidth); $(all).css('width', window.innerHeight); $(all).css('top', (window.innerHeight - window.innerWidth) / 2); $(all).css('left', (window.innerWidth - window.innerHeight) / 2); winWidth = window.innerHeight; winHeight = window.innerWidth; console.log('height '+ $(all).css('height')+' width '+$(all).css('width')+' top '+$(all).css('top')+' left '+$(all).css('left')); } else { // Landscape orientation $('#slider-view').removeClass('portrait-transform'); all.style.height = window.innerHeight + "px"; all.style.width = window.innerWidth + "px"; winWidth = window.innerWidth; winHeight = window.innerHeight; console.log('height '+ $(all).css('height')+' width '+$(all).css('width')+' top '+$(all).css('top')+' left '+$(all).css('left')); } // Add a media query change listener mql.addListener(function(m) { if(m.matches) { // Changed to portrait $(all).addClass('portrait-transform'); $(all).css('height', window.innerWidth); $(all).css('width', window.innerHeight); $(all).css('top', (window.innerHeight - window.innerWidth) / 2); $(all).css('left', (window.innerwidth - window.innerheight) / 2); console.log('height '+ $(all).css('height')+' width '+$(all).css('width')+' top '+$(all).css('top')+' left '+$(all).css('left')); } else { // Changed to landscape $(all).removeClass('portrait-transform'); $(all).css('height', window.innerWidth); $(all).css('width', window.innerHeight); $(all).css('top', 0); $(all).css('left', 0); var winWidth = window.innerWidth; var winHeight = window.innerHeight; console.log('height '+ $(all).css('height')+' width '+$(all).css('width')+' top '+$(all).css('top')+' left '+$(all).css('left')); } }); var sliderWidth = window.innerWidth; var sliderHeight = window.innerHeight; // Assigns the container that has all the sectios that will be scrolled horizontally var sliderH = $('.nav-h'); var sliderVMiddle = $('.nav-v-middle'); var sliderVLast = $('.nav-v-last'); // Gets the number of slides of the horizontal slider var sliderCountH = $('.nav-h').children().size(); var sliderCountVMiddle = $('.nav-v-middle').children().size(); var sliderCountVLast = $('.nav-v-last').children().size(); // assign width and height to the main scrollers $('.nav-h &gt; div').css('width', winWidth); // Asigns the width to the view $('.nav-h &gt; div').css('height', winHeight); // Asigns the height to the view $('.nav-v-middle &gt; div').css('width', winWidth); // Asigns the width to the view $('.nav-v-middle &gt; div').css('height', winHeight); // Asigns the height to the view $('.nav-v-last &gt; div').css('width', winWidth); // Asigns the width to the view $('.nav-v-last &gt; div').css('height', winHeight); // Asigns the height to the view var viewWidth = sliderCountH * winWidth; var heightVMiddle = sliderCountVMiddle * winHeight; var heightVLast = sliderCountVLast * winHeight; $('.nav-h').css('width', viewWidth); // assigns the width $('.nav-v-middle').css('height', heightVMiddle); // assigns the width $('.nav-v-last').css('height', heightVLast); // assigns the width var viewSliderH = $('#slider-view').css('width', winWidth); // Asigns the width to the view var viewSliderV = $('#slider-view').css('height', winHeight); // Asigns the height to the view var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; if ( isMobile.any() ) { $('a#prevh').toggle(); $('a#nexth').toggle(); $('a#prevv').toggle(); $('a#nextv').toggle(); var horizontalIndex = 0; var verticalIndexMiddle = 0; var verticalIndexLast = 0; // actions for the swiperight $(sliderH).hammer({prevent_default:true}).on('swiperight', function() { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + (sliderHeight*verticalIndexMiddle) }, 400); verticalIndexMiddle = 0; } if(verticalIndexLast!==0) { $('&gt; div', sliderVLast).animate({ top: '+=' + (sliderHeight*verticalIndexLast) }, 400); verticalIndexLast = 0; } if(horizontalIndex!==0){ $('&gt; div', sliderH).animate({ left: '+=' + sliderWidth }, 400); horizontalIndex-=1; } }); // Actions for the swipeLeft $(sliderH).hammer({prevent_default:true}).on('swipeleft', function() { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + (sliderHeight*verticalIndexMiddle) }, 400); verticalIndexMiddle = 0; } if(verticalIndexLast!==0) { $('&gt; div', sliderVLast).animate({ top: '+=' + (sliderHeight*verticalIndexLast) }, 400); verticalIndexLast = 0; } if(horizontalIndex!==sliderCountH-1){ $('&gt; div', sliderH).animate({ left: '-=' + sliderWidth }, 400); horizontalIndex+=1; } }); // Actions for the swipeUp $(sliderH).hammer({prevent_default:true}).on('swipedown', function() { if(horizontalIndex==1) { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ 'top': '+=' + sliderHeight }, 400); verticalIndexMiddle-=1; } } else if (horizontalIndex==2) { if(verticalIndexLast!==sliderCountVLast-1) { $('&gt; div', sliderVMiddle).animate({ 'top': '+=' + sliderHeight }, 400); verticalIndexLast-=1; } } }); // Actions for the swipeDown $(sliderH).hammer({prevent_default:true}).on('swipeup', function() { if(horizontalIndex==1) { if(verticalIndexMiddle!==sliderCountVMiddle-1) { $('&gt; div', sliderVMiddle).animate({ top: '-=' + sliderHeight }, 600); verticalIndexMiddle+=1; } } else if (horizontalIndex==2) { if(verticalIndexLast!==sliderCountVLast-1) { $('&gt; div', sliderVLast).animate({ top: '-=' + sliderHeight }, 600); verticalIndexLast+=1; } } }); } else { var horizontalIndex = 0; var verticalIndexMiddle = 0; var verticalIndexLast = 0; $('a#prevh').on('click', function(event) { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + (sliderHeight*verticalIndexMiddle) }, 600); verticalIndexMiddle = 0; } if(verticalIndexLast!==0) { $('&gt; div', sliderVLast).animate({ top: '+=' + (sliderHeight*verticalIndexLast) }, 600); verticalIndexLast = 0; } if(horizontalIndex!==0) { $('&gt; div', sliderH).animate({ left: '+=' + sliderWidth }, 600); horizontalIndex-=1; } console.log('horizontal '+horizontalIndex+' vertical1 '+verticalIndexMiddle+' vertical2 '+verticalIndexLast); }); $('a#nexth').on('click', function(event) { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + (sliderHeight*verticalIndexMiddle) }, 600); verticalIndexMiddle = 0; } if(verticalIndexLast!==0) { $('&gt; div', sliderVLast).animate({ top: '+=' + (sliderHeight*verticalIndexLast) }, 600); verticalIndexLast = 0; } if(horizontalIndex!==sliderCountH-1) { $('&gt; div', sliderH).animate({ left: '-=' + sliderWidth }, 600); horizontalIndex+=1; } console.log('horizontal '+horizontalIndex+' vertical1 '+verticalIndexMiddle+' vertical2 '+verticalIndexLast); }); $('a#prevv').on('click', function(event) { if(horizontalIndex==1) { if(verticalIndexMiddle!==0) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + sliderHeight }, 600); verticalIndexMiddle-=1; } } else if (horizontalIndex==2) { if(verticalIndexLast!==sliderCountVLast-1) { $('&gt; div', sliderVMiddle).animate({ top: '+=' + sliderHeight }, 600); verticalIndexLast-=1; } } console.log('horizontal '+horizontalIndex+' vertical1 '+verticalIndexMiddle+' vertical2 '+verticalIndexLast); }); $('a#nextv').on('click', function(event) { if(horizontalIndex==1) { if(verticalIndexMiddle!==sliderCountVMiddle-1) { $('&gt; div', sliderVMiddle).animate({ top: '-=' + sliderHeight }, 600); verticalIndexMiddle+=1; } } else if (horizontalIndex==2) { if(verticalIndexLast!==sliderCountVLast-1) { $('&gt; div', sliderVLast).animate({ top: '-=' + sliderHeight }, 600); verticalIndexLast+=1; } } console.log('horizontal '+horizontalIndex+' vertical1 '+verticalIndexMiddle+' vertical2 '+verticalIndexLast); }); } }); </code></pre>
[]
[ { "body": "<p>There's <em>a lot</em> of code there, so allow me to generalize a bit rather than go line by line.</p>\n\n<p>I see some overall issues with your code:</p>\n\n<ol>\n<li>There's a lot of repetition, redundancy, and hard-coded values</li>\n<li>You're mixing jQuery and raw DOM pretty randomly instead of sticking to one or the other</li>\n<li>You're not using jQuery very efficiently (many lines can be combined)</li>\n<li>I get the feeling you're not using stylesheets efficiently either, considering all the styling you're doing in JavaScript</li>\n</ol>\n\n<p>That last bit is difficult to judge without seeing everything in action, but call it a gut feeling.</p>\n\n<p>For the rest, here are some examples:</p>\n\n<h3>jQuery or native DOM?</h3>\n\n<p>You start out by getting the <code>slider-view</code> element using <code>document.getElementById()</code> instead of just using jQuery's <code>$()</code>.\nFor the rest of the code, you then call <code>$(all)</code> to wrap that element again and again.</p>\n\n<p>Instead you can just say <code>var all = $('#slider-view')</code>, and you won't have to use <code>$(all)</code> anywhere; <code>all</code> will already be a jQuery object.</p>\n\n<h3>More efficient jQuery</h3>\n\n<p>You should combine more of your expressions, rather than doing just one thing per line. For instance (assuming <code>all = $('#slider-view')</code>), the first <code>if</code>-block can be written as:</p>\n\n<pre><code>all.addClass('portrait-transform').css({\n height: window.innerWidth,\n width: window.innerHeight,\n top: (window.innerHeight - window.innerWidth) / 2,\n left: (window.innerWidth - window.innerHeight) / 2\n});\n</code></pre>\n\n<p>and similarly for the <code>else</code> block, and many other places in the code.</p>\n\n<p>I should add that jQuery also supports relative animation values, which could be beneficial here. For instance, to move something 50 pixels right, you can use <code>.animate({left: \"+=50\"})</code> instead of calculating an absolute value.<br>\nI'm not saying you <em>must</em> use that feature of jQuery, but it's just to mention that it's there.</p>\n\n<h3>DRY - Don't repeat yourself</h3>\n\n<p>With regard to repetition and redundancy, you're repeating <em>a lot</em> of code for mobile/non-mobile.<br>\nAs far as I can tell, you want your slides to move up, down, left or right. The code for doing that is identical regardless of how the move was triggered. Hence, you should abstract that into functions.</p>\n\n<p>For instance, make <code>slideUp()</code>, <code>slideDown()</code>, <code>slideLeft()</code> and <code>slideRight()</code> functions and let them figure out how much to move things for mobile/non-mobile. That way, the non-mobile event handlers could look like this:</p>\n\n<pre><code>$('a#prevh').on('click', slideRight);\n</code></pre>\n\n<p>for non-mobile, and like this:</p>\n\n<pre><code>sliderH.hammer({prevent_default:true}).on('swiperight', slideRight);\n</code></pre>\n\n<p>for mobile.</p>\n\n<p>All your code for sliding things around would be in one place and easier to maintain. And while you're at it, you might want to move the 600/400 pixel values into variables, so you only have to write (or calculate) those in one place.</p>\n\n<p>Of course moving a slide up is basically the same as moving it down (as is left vs right); the same calculations, just multiplied by -1 or +1. So that can no doubt be generalized and refactored further. Be sure to have a look around this site; there have been plenty of code reviews of slideshow/carousel code, and they might give you some ideas.</p>\n\n<hr>\n\n<p>There's more, but the above are the most pressing concerns in terms of structure. Fixing the big stuff will make it easier to focus on the details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:03:46.137", "Id": "57702", "Score": "0", "body": "Thanks a lot! I will make these changes and later I will publish again to keep polishing my code!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:18:08.197", "Id": "57714", "Score": "0", "body": "@Monica No problem. However, be sure to post new code as a new question. If you just update a question, existing answers will lose their context. So be sure to mark this current question as answered by clicking a checkmark somewhere, and create a new one if you have new code you want reviewed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:06:15.823", "Id": "57901", "Score": "0", "body": "Thank you as soon as make the corrections, I'll do that. I am pretty sure more stuff will come up." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T01:41:15.510", "Id": "35562", "ParentId": "35556", "Score": "2" } }, { "body": "<p>By order of importance :<br>\n- You can do quite a lot of code factorization.<br>\n- You should comment more<br>\n- You might choose here and there more clear names.</p>\n\n<p>Rq : The code below does <em>not</em> handle the 600 vs 400 issue(you must defines those figures in some var, then you'll figure out the changes)</p>\n\n<p>But this code should be more easy to maintain once you added some comments to it, since it holds in 160 lines vs your 310 lines, and does things only once.</p>\n\n<p>The idea - that you can really push further than i did - is to have functional blocks easy to understand, written from higher importance to lower (utilities are at the end).</p>\n\n<pre><code>$(document).ready(function () {\n\nvar all = $(\"#slider-view\");\n\nvar winWidth = window.innerHeight;\nvar winHeight = window.innerWidth;\n\nhandlePortraitOrLandscape();\n\n// ---------------------------------- \n// general element size setup\n\nvar sliderWidth = winWidth; // why renaming ?\nvar sliderHeight = winHeight; // why renaming ?\n\n// Assigns the container that has all the sectios that will be scrolled horizontally \nvar sliderH = $('.nav-h');\nvar sliderVMiddle = $('.nav-v-middle');\nvar sliderVLast = $('.nav-v-last');\n\n// Gets the number of slides of the horizontal slider\nvar sliderCountH = sliderH.children().size();\nvar sliderCountVMiddle = sliderVMiddle.children().size();\nvar sliderCountVLast = sliderVLast.children().size();\n\n// assign width and height to the main scrollers\nsetCssRect(sliderH, sliderCountH * winWidth, winHeight);\nsetCssRect(sliderVMiddle, sliderCountVMiddle * winHeight, winHeight);\nsetCssRect(sliderVLast, winWidth, sliderCountVLast * winHeight);\n\n// var viewSliderH, viewSliderV are not used, and width / height allready set in HandlePortraitOrLandscape() \n\nvar horizontalIndex = 0;\nvar verticalIndexMiddle = 0;\nvar verticalIndexLast = 0;\n\n// -----------------------------\n// event handlers hooking\n\nif (isMobile()) {\n // *** do those four changes at once with a class \n $('a#prevh').toggle();\n $('a#nexth').toggle();\n $('a#prevv').toggle();\n $('a#nextv').toggle();\n\n var hammer = $(sliderH).hammer({ prevent_default: true });\n\n // Comment here\n hammer.on('swiperight', swipeRight);\n hammer.on('swipeleft', swipeLeft);\n hammer.on('swipedown', swipeDown);\n hammer.on('swipeup', swipeUp);\n} else {\n // Comment here\n $('a#prevh').on('click', swipeRight);\n $('a#nexth').on('click', swipeLeft);\n $('a#prevv').on('click', swipeDown);\n $('a#nextv').on('click', swipeUp);\n}\n\n // -----------------------------\n // event handlers\n\nfunction swipeRight() {\n findMeAGoodHorizontalName(sliderCountH - 1, -1);\n}\n\nfunction swipeLeft() {\n findMeAGoodHorizontalName(0, 1);\n}\n\nfunction swipeDown() {\n findMeAGoodVerticalName(0, sliderCountVLast - 1, sliderVMiddle, sliderVMiddle, -1);\n}\n\nfunction swipeUp() {\n findMeAGoodVerticalName(sliderCountVMiddle - 1, sliderCountVLast - 1, sliderVMiddle, sliderVLast, +1);\n}\n\n// -----------------------------\n// slider animation functions\n\nfunction findMeAGoodHorizontalName(hLimit, hShift) {\n if (verticalIndexMiddle !== 0) {\n animateDivTop(sliderVMiddle, sliderHeight * verticalIndexMiddle);\n verticalIndexMiddle = 0;\n }\n if (verticalIndexLast !== 0) {\n animateDivTop(sliderVLast, sliderHeight * verticalIndexLast);\n verticalIndexLast = 0; \n }\n if (horizontalIndex != hLimit) {\n animateDivLeft(sliderH, sliderWidth * hShift);\n horizontalIndex += hShift;\n }\n}\n\nfunction findMeAGoodVerticalName(verticalLimit1, verticalLimit2, animatedSlider1, animatedSlider2, vShift) {\n if (horizontalIndex == 1) {\n if (verticalIndexMiddle !== verticalLimit1) {\n animateDivTop(animatedSlider1, vShift * sliderHeight);\n verticalIndexMiddle += vShift;\n }\n } else if (horizontalIndex == 2) {\n if (verticalIndexLast !== verticalLimit2) {\n animateDivTop(animatedSlider2, vShift * sliderHeight);\n verticalIndexLast += vShift;\n }\n }\n}\n\n// -----------------------------\n// css helpers \n\nfunction animateDivTop(elt, increase) {\n $('&gt; div', elt).animate({\n top: '+=' + increase\n }, 400);\n}\n\nfunction animateDivLeft(elt, increase) {\n $('&gt; div', elt).animate({\n left: '+=' + increase\n }, 400);\n}\n\n// sets css size properties on the jQuery element.\n// works with width, height OR width, height, top, left.\nfunction setCssRect(elt, width, height, top, left) {\n elt.css('width', width);\n elt.css('height', height);\n if (arguments.length &gt; 2) {\n elt.css('top', top);\n elt.css('left', left);\n }\n}\n\n// some comment here\nfunction handlePortraitOrLandscape() {\n // Find matches // rewrite comment.\n var mql = window.matchMedia(\"(orientation: portrait)\");\n\n // If there are matches, we're in portrait\n setupPortaitOrLandscape(mql.matches);\n\n // Add a media query change listener\n mql.addListener(function (m) {\n setupPortaitOrLandscape(m.matches);\n });\n\n function setupPortaitOrLandscape(isPortrait) {\n if (isPortrait) setupPortraitMode();\n else setupLandscapeMode();\n }\n\n function setupPortraitMode() {\n all.addClass('portrait-transform');\n setCssRect(all, winHeight, winWidth, (winHeight - winWidth) / 2, (winWidth - winHeight) / 2);\n }\n\n function setupLandscapeMode() {\n all.removeClass('portrait-transform');\n setCssRect(all, winWidth, winHeight, 0, 0);\n }\n}\n\n// -----------------------------\n// UTILITY \n\nvar mobileTests = { //easier to update\n Android: /Android/i,\n BlackBerry: /BlackBerry/i,\n iOS: /iPhone|iPad|iPod/i,\n Opera: /Opera Mini/i,\n Windows: /IEMobile/i,\n};\n\n// Detect if browser is a mobile browser.\nfunction isMobile() {\n for (var tst in mobileTests) {\n if (navigator.userAgent.match(tst)) return true;\n }\n return false;\n};\n\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:17:06.157", "Id": "57705", "Score": "0", "body": "Oh WOW this is great! I will totally make these changes. Thank you very much, just by looking at this I am learning so much about the mistakes I am making" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:24:07.070", "Id": "57745", "Score": "0", "body": "You're welcome ! i had forgotten to reset verticalIndexLast in 'findMeAGoodHorizontalName', it's corrected. I think you should always wonder, when copy pasting some code of yours, if you shouldn't rather build a function (or a class) that does that task. Less work, less bugs !" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:08:03.380", "Id": "35563", "ParentId": "35556", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T22:59:10.227", "Id": "35556", "Score": "2", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "2-way carousel for iPad and tablet" }
35556
<p>As mentioned in @rolfl comment. What this program does is that it "resequences the cards using a fixed system and count the number of times the resequencing happens before the output is the same as the input."</p> <p>I was wondering how I could make this program faster or perhaps use less memory. I thought about using <code>dictionaries</code> instead of <code>lists</code> as they have faster look ups. I'm not sure how to decrease the memory size of this program.</p> <pre><code>num_cards = input("Please enter the number of cards in the deck: ") def num_of_round(num_cards): rounds = 0 orig_order = range(1,num_cards + 1) card_list = list(orig_order) table_list = [] while 1: while len(card_list) &gt; 0: table_list.append(card_list[0]) # STEP 1: add top card to table card_list.remove(card_list[0]) # remove top card from deck if len(card_list) == 0: break card_list.append(card_list[0]) # STEP 2: after removal of card, put top card on bottom of deck card_list.remove(card_list[0]) # update ordering of deck rounds += 1 # a round has passed table_list.reverse() card_list, table_list = table_list, card_list if card_list == orig_order: break print rounds num_of_round(num_cards) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:22:21.383", "Id": "57706", "Score": "0", "body": "Is this 'shuffle' code? It appears to resequence the cards using a fixed system and count the number of times the resequencing happens before the output is the same as the input.... right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:23:12.427", "Id": "57707", "Score": "0", "body": "@rolfl yes it is" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:27:32.010", "Id": "57708", "Score": "1", "body": "Sounds like if you wanted to, you could reduce this to essentially no memory, and no time, by working out what the function is that describes the problem, and then just do the math rather than doing the actual work" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:31:11.763", "Id": "57709", "Score": "0", "body": "@rolfl that is something I also considered. I thought it would be too hard to come up with a formula to compute this." } ]
[ { "body": "<p>Here is a good opportunity to break out a couple of tools from the standard library.</p>\n\n<p><code>collections.deque</code> offers fast appends and pops on both ends and is thus perfect to represent your deck of cards, when you take cards from the top and put some back to the bottom.</p>\n\n<p><code>itertools.cycle</code> can be used to switch between the two destinations of the cards: the top of the pile (<code>table_list.appendleft</code>) and the bottom of the deck (<code>card_list.append</code>). Using <code>appendleft</code> there avoids the need to reverse the pile each round.</p>\n\n<p>Also, a <code>while True</code> loop with a <code>round += 1</code> inside could be a <code>for round ...</code> loop instead.</p>\n\n<pre><code>from collections import deque\nfrom itertools import cycle, count\n\ndef num_of_round(num_cards):\n orig_order = deque(xrange(num_cards))\n card_list = deque(orig_order)\n table_list = deque()\n\n for rounds in count(1):\n appendfunc = cycle((table_list.appendleft, card_list.append))\n while card_list:\n append = next(appendfunc)\n append(card_list.popleft())\n card_list, table_list = table_list, card_list \n if card_list == orig_order:\n return rounds\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:43:41.317", "Id": "35726", "ParentId": "35564", "Score": "3" } } ]
{ "AcceptedAnswerId": "35726", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T02:16:21.660", "Id": "35564", "Score": "1", "Tags": [ "python", "optimization", "combinatorics", "performance", "shuffle" ], "Title": "Increase efficiency of card-ordering program" }
35564
<p>The first function, <code>sqlPull()</code>, connects to a local MySQL database and pulls the last 20 rows from the database every 5 seconds. The data coming in is a list of tuples, where <code>MAC</code>, <code>RSSI</code> and <code>TimeStamp</code> are the 3 elements in each tuple. The data is entering the database at a variable rate, where sometimes I'll have tons of entries in a minute and sometimes I will have very few. The data that is coming in consists of a MAC address, an <code>RSSI</code> and a <code>TimeStamp</code> for every time a user's device pings our hardware. So, we will have unique MAC addresses that will have changing <code>RSSIs</code> and <code>TimeStamps</code> over a period of time. </p> <p>Since I never know how many database entries will be added within the 5 seconds that the first function runs on, the second function, <code>dupCatch()</code> is used to detect and eliminate duplicates.</p> <p>The third function, <code>post()</code>, just sends a POST request to Google Analytics with the data stripped of duplicates.</p> <p>Here is how I would like to optimize my code:</p> <p>My next step in this process is to calculate the length of time between a users first and last entries in the database. We can assume that the max time between a user's entry and exit is 2 hours (in this time, the users would probably have 10-15 pings with different <code>RSSI</code>s and timestamps). I have been trying to think of the best way to do this with the current code, but everything I am thinking of seems so unwieldy. In my mind, <code>sqlPull()</code> and/or <code>dupCatch()</code> could be rewritten/optimized to better serve my purposes for a function to calculate length of time between entry and exit.</p> <p>How would you pull data that is coming in at a variable and unpredictable rate?</p> <pre><code>import mysql.connector import datetime import requests import time run = True def sqlPull(): connection = mysql.connector.connect(user='XXXXX', password='XXXXX', host='XXXXX', database='XXXXX') cursor = connection.cursor() cursor.execute("SELECT TimeStamp, MAC, RSSI FROM wifiscan ORDER BY TimeStamp DESC LIMIT 20;") data = cursor.fetchall() connection.close() time.sleep(5) return data seen = set() def dupCatch(): data = sqlPull() new_data = [] for (TimeStamp, MAC, RSSI) in data: if (TimeStamp, MAC, RSSI) not in seen: seen.add((TimeStamp, MAC, RSSI)) new_data.append((TimeStamp, MAC, RSSI)) print new_data return new_data def post(): new_data = dupCatch() for ((TimeStamp, MAC, RSSI)) in new_data: payload = {'v':'1','tid':'XXXXXX','cid': '1','t':'event', 'ec': MAC, 'ea': 'InStore', 'el': RSSI} requests.post("http://www.google-analytics.com/collect", data = payload) while run is True: post() </code></pre>
[]
[ { "body": "<p>You need rate-limit the amount of records you receive. You'll have to determine what the best rate is by yourself, as that is specific to your scenario.</p>\n\n<h2>High Priority:</h2>\n\n<ul>\n<li><p>Keep the list of \"synced\" entries in the database. Something like an <code>IsSentToAnalytics</code> column.</p></li>\n<li><p>After you process a batch, update the database records you just selected with the synced set to yes, or 1, or true. The simplest way to do this would be to update each entry one by one, but there are more efficient solutions to that out there.</p></li>\n<li><p>Your database query should only select from items that are not yet synced. This will be lighter on the database. (i.e. add the predicate <code>and where IsSentToAnalytics &lt;&gt; 1</code>)</p></li>\n<li><p>Your <code>dupCheck</code> is catering for the above flag, essentially you're pulling unused data every time if it's a quiet period hence why you need the <code>dupCheck</code>. And also, MISSING data if it's a busy period. That can happen if you got more than 20 entries added to your database since your last run. This may be fine for hobby projects, but shoddy for production deployments.</p></li>\n<li><p>Please, please add a surrogate primary key to your database. If anything, it keeps you from having to generate a hash every time you want to do a <code>dupCheck</code>.</p></li>\n<li><p>The above entry kind of depends on how you generate the data. But since you have timestamp in there, I'm assuming every single record is unique anyways, so you might as well use the surrogate key as suggested. By the way, the surrogate key will be a sequence used as a primary key. Every entry inserted gets a unique value.</p></li>\n<li><p>Edit. From your feedback below, you say you sometimes have duplicate values for the same timestamp. If that's the case, then you need to filter them out before inserting into the database initially. Whatever job/service that creates those entries needs to filter out the duplicates. You can try insert, and catch the DBException because it will fail the column constraint. Or, you could first do a select, and if no result is returned, insert, otherwise discard. You'll need to edit your question with more info for us to give you more detail on that.</p></li>\n</ul>\n\n<h2>Low Priority:</h2>\n\n<ul>\n<li><p>Move your sleep method into your while loop, not in your SQL pull, please. There is no need to sleep before returning data. Put the sleep where it belongs. Either that or change your function to be called <code>PullDataAndSleep</code>. If you think that function name is fine, then don't change the code inside it, just rename. Otherwise, put the sleep elsewhere.</p></li>\n<li><p>Reuse your connection. You are disconnecting and reconnecting to the database every 5 seconds, it's pointless unless you expect your database connection to drop.</p></li>\n<li><p>Change your while loop to just be \"while Run\", that's like saying <code>while var == True</code>. You're basically saying if <code>True == True</code>, then run. It's redundant.</p></li>\n<li><p>Pull from the database at constant intervals(you are using 5s, play around with it).</p></li>\n<li><p>Enforce an upper-bound amount of returned entries (you have 20)</p></li>\n<li><p>The last two entries above will help you rate-limit how many requests you send off to Google. If you spam them too quickly, they might block/ban your IP.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:22:11.143", "Id": "57863", "Score": "0", "body": "That point-form list could use some formatting & prioritization :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:28:06.780", "Id": "57864", "Score": "0", "body": "@retailcoder Added some formatting and separated into two priorities. Can't help that I think in lists :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:29:21.710", "Id": "57865", "Score": "0", "body": "No problem - thanks for [contributing](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission?cb=1)!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T01:51:53.770", "Id": "57899", "Score": "0", "body": "@ZoranPavlovic Hi thanks you for your detailed response. I have one question before I dive into this (90% of which i do not understand). You say \" But since you have timestamp in there, I'm assuming every single record is unique anyways.\" This is actually not true - Every once in a while i get multiple entries with the same timestamp. Knowing this, would you change anything about your post? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T15:51:23.787", "Id": "57954", "Score": "0", "body": "@user1887261 Not really... Since you have the dupCheck on the consuming side it means that you don't need those duplicates. So you can just throw them away. I'll add how as another point in the high-priority list just now." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T20:46:26.340", "Id": "35632", "ParentId": "35566", "Score": "2" } }, { "body": "<h2>Optimal Querying</h2>\n\n<p>I would try to arrange things such that you don't have to don't have to worry about duplicate records.</p>\n\n<p>In your query you can pull only records that have a time stamp at least one second prior to the current database time. You will similarly only pull records that are greater than or equal to the server time during the last pull.</p>\n\n<p>You will need a way to track that last/next query time in the event the system stops running and you have to restart it. Be sure your solution will never query the same data twice or exclude any particular second.</p>\n\n<h2>Exit Detection</h2>\n\n<p>It sounds like you'll want the exit detection to provide a different type of response. I doubt you'll be able to reuse the pull code. </p>\n\n<p>For efficiency you can have the database query all records within the last couple of hours, group by MAC, giving maximum time found, minimum time found and perhaps the number of records involved for each MAC.</p>\n\n<p>Maybe go with something like pullRecent and pullSessions.</p>\n\n<h2>Notes</h2>\n\n<p>I agree with Zoran, there is no point in putting a delay in the query function. That logic should probably reside in your while loop.</p>\n\n<p>For recovery purposes you could use a single row table that tracks the highest last or the next second to query from.</p>\n\n<p>If you wanted to make your polling responsive to changing usage levels then consider having a counter in the tracking table (or a separate memory based table) that is updated during addition of wifiscan records. Perform a poll run whenever N records are added or M minutes passes. Rest the counter during each poll event.</p>\n\n<p>Session calculation efforts could also be managed with the help of a tracking table. However, I suspect you will need a way to \"extend\" sessions that continue to be active after you've already found an earlier start and end time. If you need to find a continuous period of non-use to find session boundaries than the two hour grouped query I suggested won't suffice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T00:17:57.523", "Id": "96291", "ParentId": "35566", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T03:24:47.420", "Id": "35566", "Score": "4", "Tags": [ "python", "mysql" ], "Title": "Data-pulling fuctions" }
35566
<p><em>I originally asked this <a href="https://stackoverflow.com/questions/20039172/seeking-the-right-ways-to-convert-these-two-python-functions-to-go">question</a> on StackOverflow. Reproduced here by recommendation.</em></p> <p>I've got a number of Python scripts that I'm considering converting to Go. I'm seeking confirmation that I'm using Go in essentially the way it was meant to be used. Full code is available here: <a href="https://gist.github.com/anonymous/7521526" rel="nofollow noreferrer">https://gist.github.com/anonymous/7521526</a></p> <p><strong>So the primary question is: Am I writing what is considered "good Go" ?</strong></p> <p><strong>Python function #1</strong>: Look at the files in a folder and extract the latest encoded date in the filenames.</p> <pre><code>def retrieveLatestDateSuffix(target): return max(map("".join, filter(lambda x: x, map(lambda x: re.findall(r"_([0-9]{8})\.txt$", x), os.listdir(target))))) </code></pre> <p>My translation for #1:</p> <pre><code>var rldsPat = regexp.MustCompile(`_([0-9]{8})\.txt$`) func retrieveLatestDateSuffix(target string) (string, error) { if fis, e := ioutil.ReadDir(target); e == nil { t := "" for _, fi := range fis { if m := rldsPat.FindStringSubmatch(fi.Name()); m != nil { if m[1] &gt; t { t = m[1] } } } return t, nil } else { return "", e } } </code></pre> <p><strong>Python function #2</strong>: Add a date suffix to each filename inside a folder that doesn't already have a suffix added. Printing the from/to for now instead of doing the rename.</p> <pre><code>def addDateSuffix(target, suffix): for fn in filter(lambda x: re.search(r"(?&lt;!_[0-9]{8})\.txt$", x), os.listdir(target)): pref, ext = os.path.splitext(fn) gn = "{0}_{1}{2}".format(pref, suffix, ext) print(fn, " -&gt; ", gn) </code></pre> <p>My translation for #2:</p> <pre><code>var adsPat1 = regexp.MustCompile(`\.txt$`) var adsPat2 = regexp.MustCompile(`_[0-9]{8}\.txt$`) func addDateSuffix(target string, suffix string) error { if fis, e := ioutil.ReadDir(target); e == nil { for _, fi := range fis { if m1 := adsPat1.FindStringSubmatch(fi.Name()); m1 != nil { if m2 := adsPat2.FindStringSubmatch(fi.Name()); m2 == nil { ext := filepath.Ext(fi.Name()) gn := fmt.Sprintf("%s_%s%s", strings.TrimSuffix(fi.Name(), ext), suffix, ext) fmt.Println(fi.Name(), "-&gt;", gn) } } } return nil } else { return e } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:07:39.937", "Id": "57744", "Score": "3", "body": "`rldsPat, `adsPat1`, `adsPat2` - `wtfPat`? Plse dnt try to sve lttrs n vribl nms :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:55:31.543", "Id": "58072", "Score": "1", "body": "Just saw another post of this and your comment on it. To your bigger question of whether you should be using Go here, agree with your \"maybe not\". I can't tell if this is part of an app or standalone, but at least the task of adding and reading date suffixes on filenames is a great fit for Python/Perl; much as I like Go, I don't see much advantage to using Go for this task. (On the other hand, an app that needed or wanted lower-level bit-slinging, more direct OS access, concurrency, etc. might fit with Go's strengths.)" } ]
[ { "body": "<p>Early return is better than nesting. For example:</p>\n\n<pre><code>var adsPat1 = regexp.MustCompile(`\\.txt$`)\nvar adsPat2 = regexp.MustCompile(`_[0-9]{8}\\.txt$`)\nfunc addDateSuffix(target string, suffix string) error {\n fis, e := ioutil.ReadDir(target)\n if e != nil {\n return e\n }\n for _, fi := range fis {\n if m1 := adsPat1.FindStringSubmatch(fi.Name()); m1 == nil {\n continue\n }\n if m2 := adsPat2.FindStringSubmatch(fi.Name()); m2 != nil {\n continue\n }\n ext := filepath.Ext(fi.Name())\n gn := fmt.Sprintf(\"%s_%s%s\", strings.TrimSuffix(fi.Name(), ext), suffix, ext)\n fmt.Println(fi.Name(), \"-&gt;\", gn)\n }\n return nil\n}\n</code></pre>\n\n<p>Also see this post for more idiomatic go discussion: <a href=\"https://stackoverflow.com/questions/20028579/what-is-the-idiomatic-version-of-this-function\">https://stackoverflow.com/questions/20028579/what-is-the-idiomatic-version-of-this-function</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T05:47:26.903", "Id": "35573", "ParentId": "35567", "Score": "5" } }, { "body": "<p>Here's a script with both functions. Changes I made:</p>\n\n<ul>\n<li><code>strings.HasSuffix</code> will do to test for <code>/\\.txt$/</code>.</li>\n<li><code>os.Open</code>ing the dir and calling <code>Readdirnames</code> is shorter.</li>\n<li><code>dateSuffixPat.MatchString</code> is all <code>addDateSuffix</code> needs.</li>\n<li>I used named return values like Jared did.</li>\n<li><code>dateSuffixPat</code> is a more descriptive name. </li>\n<li>I used a string slice to cut off <code>.txt</code>; unsure if I think it's better, but it's shorter.</li>\n</ul>\n\n<p>You could make further changes, like changing the APIs of these funcs to make a directory that's already been <code>os.Open</code>'d, or even just have them accept the list of names from <code>Readdirnames</code>; then you avoid repeating the <code>os</code> calls and error checks.</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"os\"\n \"regexp\"\n \"strings\"\n)\n\nvar dateSuffixPat = regexp.MustCompile(`_([0-9]{8})\\.txt$`)\n\nconst ext = \".txt\"\n\nfunc addDateSuffix(dirname string, suffix string) (err error) {\n dir, err := os.Open(dirname)\n if err != nil {\n return\n }\n fns, err := dir.Readdirnames(0)\n if err != nil {\n return\n }\n for _, fn := range fns {\n if !strings.HasSuffix(fn, ext) || dateSuffixPat.MatchString(fn) {\n continue\n }\n datedFn := fmt.Sprintf(\"%s_%s%s\", fn[:len(fn)-len(ext)], suffix, ext)\n fmt.Println(fn, \"-&gt;\", datedFn)\n }\n return\n}\n\nfunc retrieveLatestDateSuffix(dirname string) (latest string, err error) {\n dir, err := os.Open(dirname)\n if err != nil {\n return\n }\n fns, err := dir.Readdirnames(0)\n if err != nil {\n return\n }\n for _, fn := range fns {\n if m := dateSuffixPat.FindStringSubmatch(fn); m != nil {\n if m[1] &gt; latest {\n latest = m[1]\n }\n }\n }\n return\n}\n\nconst dir = \".\"\n\nfunc main() {\n err := addDateSuffix(dir, \"19920101\")\n if err != nil {\n // you would rarely panic in real life, but toy script, fine\n panic(err)\n }\n latest, err := retrieveLatestDateSuffix(dir)\n if err != nil {\n panic(err)\n }\n fmt.Println(latest)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:16:18.873", "Id": "58066", "Score": "0", "body": "Unfortunately, Go is just going to be longer than python for a lot of stuff. You can do some cool stuff with it, though. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:17:04.597", "Id": "58067", "Score": "0", "body": "And, not to bug, but there are a [couple](http://stackoverflow.com/questions/20028579/what-is-the-idiomatic-version-of-this-function) related [questions](http://stackoverflow.com/questions/20026320/go-how-to-tell-if-folder-is-writable) over on SO with answers with upvotes that you haven't accepted. Might be worth accepting or clarifying why you don't think the question's been answered, depending on what you think. (Conflict-of-interest disclosure--I answered one of them.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:11:36.280", "Id": "35742", "ParentId": "35567", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T04:29:46.137", "Id": "35567", "Score": "3", "Tags": [ "python", "go" ], "Title": "Am I writing good Go here? Python functions converted to Go" }
35567
<p>I put the readable version into the gist file -> <a href="https://gist.github.com/poc7667/7523230" rel="nofollow">link</a></p> <p>Please ignore the <code>print</code> and <code>comment</code> in the following code.</p> <p>I often have to write this sort of logic: init the conditions, and deep into loop condition, get the variables in each iteration and break when the condition meets.</p> <p>As you can see, I get the first line in a region and then loop until the region ends.</p> <p>The exit condition is <code>while True and (beginning_spaces - start_beginning_spaces)</code>.</p> <p>Are there any better practices in my case?</p> <pre><code> def get_exception_region(self, except_region, max_lines_in_exception=100): ''' # get current line number row, _ = self.view.rowcol(except_region.a) # get next line's starting point next_row_starting = self.view.text_point(row + 1, 0) # get the whole next line next_row_region = self.view.full_line(next_row_starting) print(self.view.substr(next_row_region)) ''' # Init first setting try: row, _ = self.view.rowcol(except_region.a) next_line_text, next_line_region = self.get_next_line__text_and_region(row) prev_line_text, prev_line_region = next_line_text, next_line_region beginning_spaces = self.count_the_beginning_spaces(next_line_text) start_row, start_beginning_spaces = row, beginning_spaces print "=================Start=================" print row, beginning_spaces, next_line_text.strip() while True and (beginning_spaces - start_beginning_spaces) &lt; max_lines_in_exception : row = row + 1 next_line_text , next_line_region = self.get_next_line__text_and_region(row) beginning_spaces = self.count_the_beginning_spaces(next_line_text) print row, beginning_spaces, next_line_text.strip() if beginning_spaces &gt; 1 and beginning_spaces != start_beginning_spaces: print "=================Exit=================" break prev_line_text, prev_line_region = next_line_text, next_line_region return row, prev_line_text, prev_line_region pass except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("[Error]\n", exc_type, fname, exc_tb.tb_lineno) raise e sys.exit(e) #EndOfExcept </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:02:06.190", "Id": "57742", "Score": "2", "body": "Isn't `while True and somecondition` same as `while somecondition`? Am I missing something obvious here?" } ]
[ { "body": "<p>I'm having trouble figuring out exactly what your code is doing. It's called <code>get_exception_region</code> but it appears to do a lot of printing. Is that just for debugging purposes? I'm going to assume that's the case, and thus that <code>get_exception_region</code> returns the row (line number?), text, and region of the line following the exception. Here are my suggestions, given that assumption:</p>\n\n<ul>\n<li>Change the docstring to reflect what <code>get_exception_region</code> does, not how it does it. From another angle, describe why someone would choose to call <code>get_exception_region</code>, not what code they would have to write in its place. If there's any code in the docstring, it should show how to call the function, not reminders on functions it may call to implement itself. If you need the latter, comments are more appropriate for that.</li>\n<li>If you have control over it, the name <code>except_region.a</code> doesn't convey much. Consider using a more descriptive name than <code>a</code>.</li>\n<li>As mentioned by @ChrisWue, drop the <code>True and</code> from your <code>while</code> condition. At best it does nothing; at worst it distracts readers and slows the program.</li>\n<li>Consider if rewriting your while loop as a for loop (<code>for row in range(start_row, start_row + max_lines_in_exception): ...</code>) would add or diminish clarity. This would avoid code with a slight <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> (<code>row = row + 1</code>), but in this case I'm uncertain whether the replacement would be better.</li>\n<li>Avoid catching <code>Exception</code>; if you must suppress most exceptions, it's typically better to catch <code>BaseException</code> (at least in python 3). That said, since this code quickly re-raises the exception, this advice is less crucial than usual.</li>\n<li>Avoid accessing attributes like <code>tb_frame</code>, <code>f_code</code>, and <code>co_filename</code> in a function not specifically geared towards this. Instead for the usage in your exception handler, prefer using tools from <a href=\"http://docs.python.org/dev/library/traceback.html\" rel=\"nofollow\"><code>traceback</code></a> such as <code>print_exc</code>; in other cases <a href=\"http://docs.python.org/dev/library/inspect.html\" rel=\"nofollow\"><code>inspect</code></a> can be similarly useful.</li>\n<li>Remove dead code. Having <code>raise e</code> followed by <code>sys.exit(e)</code> is misleading, since the <code>raise</code> will unconditionally prevent the <code>exit</code> from executing. Similarly the <code>pass</code> after <code>return</code> will never be reached.</li>\n<li>If all you are really doing in this handler is printing out a partial trace, consider omitting the try/except handler entirely, and letting the caller be fully responsible.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:29:27.507", "Id": "35603", "ParentId": "35574", "Score": "3" } }, { "body": "<p>Some code is duplicated between before and inside the <code>while</code> loop. You could place that code in a generator:</p>\n\n<pre><code>from itertools import count\n\ndef exception_lines(self, except_region):\n startrow, _ = self.view.rowcol(except_region.a)\n for row in count(startrow):\n text, region = self.get_next_line__text_and_region(row)\n beginning_spaces = self.count_the_beginning_spaces(text)\n #print row, beginning_spaces, text.strip()\n yield row, text, region, beginning_spaces\n</code></pre>\n\n<p>Using the generator, your main loop is simplified:</p>\n\n<pre><code>#print \"=================Start=================\"\nlines = self.exception_lines(except_region)\nstart_row, prev_line_text, prev_line_region, start_beginning_spaces = next(lines)\n\nfor row, next_line_text, next_line_region, beginning_spaces in lines:\n if beginning_spaces &gt; 1 and beginning_spaces != start_beginning_spaces:\n #print \"=================Exit=================\"\n return row, prev_line_text, prev_line_region\n prev_line_text, prev_line_region = next_line_text, next_line_region\n</code></pre>\n\n<p>I have retained to show where they would go in this approach, but commented them out, seconding Michael's remark.</p>\n\n<p>Note that I took the <code>(beginning_spaces - start_beginning_spaces) &lt; max_lines_in_exception</code> condition out. Unless my reasoning is in error, the condition is always true because your <code>break</code> condition triggers first. I am assuming here that <code>max_lines_in_exception &gt; 1</code> always, and <code>start_beginning_spaces &gt;= 0</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:20:11.440", "Id": "35624", "ParentId": "35574", "Score": "1" } } ]
{ "AcceptedAnswerId": "35624", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T06:06:51.983", "Id": "35574", "Score": "1", "Tags": [ "python" ], "Title": "How to refract a while loop with a necessary initial setting?" }
35574
<p>I had an half an hour interview with Microsoft for an intern position. I was asked to generate a list of alternatively positioned odd and even number out of an array of unsorted integers. I guess it was below the interviewer expectations since I did not get the offer. Can any one give me some hints on improving my code?</p> <pre><code>import java.util.ArrayList; public class EvenOddArray { private int min(int n, int m) { int min; if (n &gt; m){ min = m; } else { min = n; } return min; } public ArrayList&lt;Integer&gt; generateEvenOddArray(int[] list) { ArrayList&lt;Integer&gt; oddList = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; evenList = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; resultList = new ArrayList&lt;Integer&gt;(); for (int number : list) { if (number%2 == 0){ evenList.add(number); } else { oddList.add(number); } } int numberOfEvenNumbers = evenList.size(); int numberOfOddNumbers = oddList.size(); int minOfOddAndEven = min(numberOfEvenNumbers,numberOfOddNumbers); ArrayList&lt;Integer&gt; longestList = getLongestList(evenList,oddList); int i ; for (i = 0; i &lt; minOfOddAndEven; i++) { resultList.add(2*i,oddList.get(i) ); resultList.add(2*i+1,evenList.get(i)); } if(longestList != null ){ for (int j = i; j &lt; longestList.size(); j++) { resultList.add(longestList.get(j)); } } return resultList; } private ArrayList&lt;Integer&gt; getLongestList(ArrayList&lt;Integer&gt; listone, ArrayList&lt;Integer&gt; listTwo) { if (listone.size()&lt;listTwo.size()){ return listTwo; } else if (listone.size()&gt;listTwo.size()){ return listone; } return null; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:26:58.353", "Id": "57746", "Score": "0", "body": "in your min(int, int) method, what if n = m? Then neither is the min." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:06:29.527", "Id": "57776", "Score": "0", "body": "@user1021726 If `n == m` then **both** are the min, and therefor it does not matter which one gets returned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:08:34.867", "Id": "57860", "Score": "1", "body": "@Andre, right now, I believe 0 would be returned instead of m or n." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T03:43:08.140", "Id": "57969", "Score": "1", "body": "- Does the given array contain duplicate elements or only unique values? - Resultant array would be sorted or unsorted ?" } ]
[ { "body": "<ol>\n<li><p>You probably should have used <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html\" rel=\"nofollow\"><code>Math.min()</code></a>. Even if it was requested by the interviewer to not use anything else besides <code>ArrayList</code>, <code>min</code> can be written much more concise as</p>\n\n<pre><code>return n &lt;= m ? n : m\n</code></pre>\n\n<p>(1 line of code vs. 8)</p></li>\n<li><p>This loop is little bit ugly:</p>\n\n<blockquote>\n<pre><code> for (i = 0; i &lt; minOfOddAndEven; i++) {\n resultList.add(2*i,oddList.get(i) );\n resultList.add(2*i+1,evenList.get(i)); \n}\n</code></pre>\n</blockquote>\n\n<p>While I think it should work (don't have a Java compiler handy to try) it's a bit confusing to add the numbers at specified indices. I think it is legal to call <code>add(index, item)</code> where <code>index == size()</code> which should add an element to the end of the list. So your code happens to work but you need to look twice to make sure. It's totally unnecessary to do this. You could have simply done:</p>\n\n<pre><code>for (i = 0; i &lt; minOfOddAndEven; i++) {\n resultList.add(oddList.get(i));\n resultList.add(evenList.get(i)); \n}\n</code></pre>\n\n<p>Same result but cleaner.</p></li>\n<li><p>Copying the remainder of the list could have been done with <code>subList</code>:</p>\n\n<pre><code>if (longestList != null)\n{\n resultList.addAll(longestList.subList(minOfOddAndEven, longestList.size());\n}\n</code></pre></li>\n<li><p>Overall I think the interviewer might have wanted to see the use of iterators. You could have greatly simplified your code with this:</p>\n\n<pre><code>Iterator&lt;Integer&gt; odds = oddList.iterator();\nIterator&lt;Integer&gt; evens = evenList.iterator();\n\nwhile (odds.hasNext() || evens.hasNext())\n{\n if (odds.hasNext())\n {\n resultList.Add(odds.next());\n }\n if (evens.hasNext())\n {\n resultList.Add(evens.next());\n }\n}\n</code></pre>\n\n<p>This way you iterate over both lists at once and don't have to implement the \"which list is longer and then copy the remainder part\"</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T07:58:59.893", "Id": "35583", "ParentId": "35576", "Score": "10" } }, { "body": "<p><code>&lt;!Joke&gt;</code> You didn't get the job because you were using Java in Microsoft <code>:P</code> <code>&lt;/Joke&gt;</code></p>\n\n<p>Now the serious part...</p>\n\n<ul>\n<li><p>First thing to keep in mind when you are writing a production code or any code that would be reviewed by someone else, keep it precise and well documented. I mean, on seeing the below code someone have to make a stack in his head how it is working</p>\n\n<pre><code>int i ;\nfor (i = 0; i &lt; minOfOddAndEven; i++) {\n resultList.add(2*i,oddList.get(i) ); // why 2*i ?\n resultList.add(2*i+1,evenList.get(i)); // why 2*i+1 ? \n}\nif(longestList != null ){\n for (int j = i; j &lt; longestList.size(); j++) { // why starting form i ?\n resultList.add(longestList.get(j));\n }\n}\n</code></pre>\n\n<p>See what was I talking about. Throw some comment why are you doing this. Also a good Javadoc will fulfil the cause.</p></li>\n<li><p><code>getLongestList</code> can be shorten as</p>\n\n<pre><code>return listone.size() &gt; listTwo.size() ? listone : listTwo;\n</code></pre>\n\n<p>though I prefer <code>firstList</code> instead of <code>listone</code> and <code>secondList</code> instead of <code>listTwo</code>. I don't know why are you returning <code>null</code>, if two lists are same <code>listTwo</code> will be returned and that won't hamper the logic.</p></li>\n<li><p>You should know <a href=\"https://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n\">polymorphism is a vital part of OOP</a> language so instead of </p>\n\n<pre><code>ArrayList&lt;Integer&gt; oddList = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<p>use</p>\n\n<pre><code>List&lt;Integer&gt; oddList = new ArrayList&lt;Integer&gt;();\n</code></pre></li>\n<li><p>Creating the <code>evenList</code> and <code>oddList</code> should be done in a helper method.</p></li>\n<li><p>I don't know why I feel like you should provide a constructor to the class. A constructor with parameter as the array.</p></li>\n<li><p>Lots of redundant newline makes the code bigger than the original. Get rid of those.</p></li>\n</ul>\n\n<hr>\n\n<h2>Algorithm wise optimization</h2>\n\n<p>With your algorithm </p>\n\n<p><strong>Space Complexity</strong> </p>\n\n<p>O(n) [ for the array []list ]</p>\n\n<p>+</p>\n\n<p>O(n/2) [ for <code>oddList</code> in average case ]</p>\n\n<p>+</p>\n\n<p>O(n/2) [ for <code>evenList</code> in average case ]</p>\n\n<p>+</p>\n\n<p>O(n) [ for <code>resultList</code> ]</p>\n\n<p>+</p>\n\n<p>O(n/2) [ for <code>longestList</code> in average case ]</p>\n\n<p><strong>Time Complexity</strong></p>\n\n<p>O(n) [ for generating <code>oddList</code> and <code>evenList</code> ]</p>\n\n<p>+</p>\n\n<p>O(n) [ for generating <code>resultList</code> ]</p>\n\n<p>Now you can optimize it with <a href=\"https://stackoverflow.com/questions/14441483/move-all-even-numbers-on-the-first-half-and-odd-numbers-to-the-second-half-in-an\">partitioning algorithm</a>. Then create the <code>resultList</code> with alternate indexing odd and even numbers. <em>\"A picture is worth a thousand words\"</em>...</p>\n\n<p><img src=\"https://i.stack.imgur.com/g8TWi.png\" alt=\"enter image description here\"></p>\n\n<p>With optimized algorithm</p>\n\n<p><strong>Space complexity</strong></p>\n\n<p>O(n) [ for the array <code>list</code> ]</p>\n\n<p>+</p>\n\n<p>O(1) [ for swapping ]</p>\n\n<p>+</p>\n\n<p>O(n) [ for <code>resultList</code> ]</p>\n\n<p><strong>Time Complexity</strong></p>\n\n<p>O(n) [ partitioning ]</p>\n\n<p>+</p>\n\n<p>O(n) [ generating <code>resultList</code> ]</p>\n\n<hr>\n\n<p>As a last note. I think you should contact your interviewer and ask why didn't he like your code <em>politely</em>. If he is a good interviewer he will definitely contact you back, if he doesn't don't worry at least you tried.</p>\n\n<p>Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T10:41:38.747", "Id": "35971", "ParentId": "35576", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T06:42:41.170", "Id": "35576", "Score": "8", "Tags": [ "java", "array", "interview-questions" ], "Title": "Generating a list of alternatively positioned odd and even number out of an array of unsorted integers" }
35576
<p>I have a bit of code that I use to update my blog. Basically, I send an email to a particular address, and every x minutes the daemon fetches the emails, creates the files, executes middleman and then synchronizes it all to S3.</p> <p>The thing is that I'm using lots of different apps to do it all, be it system commands, Python scripts (s3cmd), Ruby apps with node server (middleman), etc.</p> <p>The code works (well, most of the time) but is an eye-sore, and I have a hard time living with myself when I know this code exists. I've posted it below, and <a href="https://gist.github.com/jvzr/7473113" rel="nofollow">it's also available as a commented gist</a>, as it is too long to put here. I've tried to comment on all the quirks and requirements I had in mind when writing this.</p> <p>I'm not experienced in Ruby (as you can probably tell). Can someone with a little spare time help me refactor this code to a saner level?</p> <pre><code>#!/usr/local/bin/ruby # -*- encoding: utf-8 -*- require "rubygems" require "mail" require "fileutils" require "daemons" # I know I probably shouldn't use constants like that… DEBUG = true DELETE = true # And most definitely not global variables $log = "/Users/johndoe/log.txt" $path = "/Users/johndoe/source/data" $needs_sync = "/Users/johndoe/sync" $needs_generate = "/Users/johndoe/generate" FileUtils.touch($log) # I don't see anything wrong with the following lines. file_size = (File.size($log).to_f / 2**20) if file_size &gt; 0.1 File.write(log, "") end Mail.defaults do retriever_method :imap, :address =&gt; "imap.mail.com", :port =&gt; 993, :user_name =&gt; "johndoe@mail.com", :password =&gt; "ph4tpassword", :enable_ssl =&gt; true end # OK, here it starts to get hairy. First, global variables, again… # Also, no class, no sane logic, just plain "shell scripting" thinking translated into insanely coded Ruby def set_dates date = Time.now.utc datetmz = Time.now $year = date.strftime("%Y").to_s $month = date.strftime("%02m").to_s $day = date.strftime("%02d").to_s $time = date.strftime("%02T").to_s timetmz = datetmz.strftime("%02T").to_s $now = "#{$year}/#{$month}/#{$day} #{timetmz}" end # This seems about right def slugalize(text, separator = "-") re_separator = Regexp.escape(separator) result = text.to_s result.gsub!(/[^\x00-\x7F]+/, "") result.gsub!(/[^a-z0-9\-_\+]+/i, separator) result.gsub!(/\./, "") result.gsub!(/#{re_separator}{2,}/, separator) result.gsub!(/^#{re_separator}|#{re_separator}$/, "") result.downcase! return result end # This doesn't seem good. My requirement is to reverse fill the log (latest on top) def log(alert) if DEBUG set_dates FileUtils.touch($log) File.open($log, "r") do |orig| File.unlink($log) File.open($log, "w") do |new| new.write "#{$now[5..-1]} - #{alert}\n" new.write(orig.read()) end end end end # OK. I had lots of trouble with these two. Middleman is a long process, # and without doing some kind of process fork or multithreading, the whole # daemon randomly crashes when it arrives here. I'm not sure it is good though. def generate pid = Process.fork do File.delete($needs_generate) log("Generating…") middleman = Process.spawn("middleman build --clean", :chdir =&gt; "/Users/johndoe") Process.wait log("Generated.") FileUtils.touch($needs_sync) end Process.detach(pid) end # Here too. s3cmd sync can take a very long time (4 minutes for instance). def sync pid = Process.fork do File.delete($needs_sync) log("Synchronizing…") Dir.chdir("/Users/johndoe") do Dir::mkdir("gzip") unless File.exists?("gzip") FileUtils.rm_rf Dir.glob("gzip/*") FileUtils.cp_r(Dir["build/*"], "gzip") end Dir.chdir("/Users/johndoe/gzip") do `find . -iname "*.*" -type f -exec sh -c "gzip -n -c -9 "{}" &gt; tmp &amp;&amp; cat tmp &gt; "{}"" ";"` File.delete("tmp") `find . -name ".DS_Store" -delete` s3cmd = "/usr/local/bin/s3cmd" opts = "-P --rr --delete-removed --guess-mime-type --no-check-md5 --no-preserve -H --add-header=Content-Encoding:gzip" bucket = "s3://www.mybucket.com/" in5minutes = "--add-header=Cache-control:max-age=300,must-revalidate" in15minutes = "--add-header=Cache-control:max-age=900,must-revalidate" in1day = "--add-header=Cache-control:max-age=86400,must-revalidate" in8days = "--add-header=Cache-control:max-age=691200,must-revalidate" sync = `#{s3cmd} sync #{opts} #{in8days} . #{bucket}` sitemap = `#{s3cmd} put #{opts} #{in1day} sitemap.xml #{bucket}sitemap.xml` feed = `#{s3cmd} put #{opts} #{in15minutes} feed.xml #{bucket}feed.xml` archives = `#{s3cmd} put #{opts} --recursive #{in15minutes} archives #{bucket}` index = `#{s3cmd} put #{opts} #{in5minutes} index.html #{bucket}index.html` end log("Synchronized.") end Process.detach(pid) end # This whole function seems right though. def check_mail emails = Mail.find_and_delete(mailbox: "INBOX", what: :first, count: 10, order: :asc) if (emails.length == 0 ) log("No email found.") else emails.each do |email, imap, uid| if email.subject.empty? email.skip_deletion next end subject = email.subject slug = slugalize(subject.dup) if email.body.decoded.empty? email.skip_deletion next end body = email.body.decoded kind = "post" link = body.lines.first.split(/\s+/).find_all { |u| u =~ /^https?:/ }.join if link.match(/^http/) kind = "link" body = body.lines.to_a[1..-1].join end log("#{subject} (#{kind})") path = $path.dup if kind == "link" path &lt;&lt; "/links" else path &lt;&lt; "/posts" end path &lt;&lt; "/%s-%s-%s-%s.markdown" % [$year, $month, $day, slug] open(path, "w") do |str| str &lt;&lt; "---\n" str &lt;&lt; %Q|title: "#{subject}"\n| if kind == "link" str &lt;&lt; "link: #{link}\n" end str &lt;&lt; "date: %s-%s-%sT%s\n" % [$year, $month, $day, $time] str &lt;&lt; "---\n" str &lt;&lt; body.chomp! end url = "http://www.mybucket.com/" url &lt;&lt; "linked/" if kind == "link" url &lt;&lt; "#{year}/#{month}/#{slug}/" twtsubj = truncate(subject, 115) twtsubj.insert(0, "★ ") if kind == "post" #Twitter.update("#{twtsubj} #{url}") email.skip_deletion if !DELETE end FileUtils.touch($needs_generate) end end ############################ log("Daemon started.") # OK, finally, let me explain the whole "files" thing. As it crashed randomly, # the only way to get the script to actually generate the site and sync it # when the daemon starts again. # If the whole thing doesn't crash, I don't think I'd need it then. loop do check_mail if File.exists?($needs_generate) generate end if File.exists?($needs_sync) sync end sleep 300 end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:42:17.420", "Id": "57725", "Score": "0", "body": "Thanks for the tip. I should have looked better. I see no way to move my own question though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T21:22:31.510", "Id": "57726", "Score": "0", "body": "I asked the moderator to move it for you. But, because you don't have the code in your question, expect it to be closed there too. As is, you're asking people to chase down the link, which wastes people's time, plus, if/when the link breaks your question will be worthless to anyone else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T21:35:49.030", "Id": "57727", "Score": "0", "body": "Thanks @theTinMan. I've added the code in that case. I've yet to familiarize myself with the very peculiar way SO works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T21:39:52.340", "Id": "57728", "Score": "1", "body": "SO isn't peculiar, it's very common-sense oriented. Consider how it works: There are people asking questions, and volunteers answer them. The volunteers do this on their own time and, to help them help you, they need you to supply the information needed in the question. If you were asked your question, along with a bunch of others, wouldn't you want to have the necessary data right there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T21:41:30.257", "Id": "57729", "Score": "0", "body": "And, BTW, that *isn't* a lot of code. You should see when someone inserts a big Java stack trace." } ]
[ { "body": "<p>Well, I tend to agree on at least one count - this one is an eye-sore! Here are my 2 cents on what you need to do:</p>\n\n<p>Break your code into following files:</p>\n\n<ul>\n<li><strong>config.rb</strong>: If you spend some time looking at open-source projects out there, you'd notice that almost all applications separation configuration from logic. This is a good thing to do and will reduce the eyesore instantaneously. Create a module named <code>Configuration</code>.</li>\n<li><strong>logger.rb</strong>: Your requirement to reverse fill a log is absurd. Why do you want that? If you want to see latest logs, just <code>tail -f</code> your file if you are on a Unix system. In your best interests, you should just use a Logging gem out there which can rotate logs for you. At any rate, create a module <code>Logger</code> with the log method here.</li>\n<li><strong>email_checker.rb</strong>: Move the <code>check_mail</code> functionality there into a <code>EmailChecker</code> module.</li>\n<li><strong>generator.rb</strong>: Move the <code>generate</code> method there as part of the <code>Generator</code> module.</li>\n<li><strong>syncer.rb</strong>: Move the <code>sync</code> method there as part of the <code>Syncer</code> module.</li>\n<li><strong>myproc.rb</strong>: Write your loop here using all the modules defined previously.</li>\n<li><strong>myproc_control.rb</strong>: Use the <a href=\"http://daemons.rubyforge.org/\" rel=\"nofollow\">Daemon gem</a>.</li>\n</ul>\n\n<p>Once you've done this, you can ask a question with each individual file and get a much better response. Here are some of my other quick observations:</p>\n\n<ol>\n<li>Isn't set_date equivalent to Time.now.strftime(\"%Y/%m/%d/ %T\")? And if you can live with hyphens in place of slashes, you can use Time.now.strftime(\"%F %T\").</li>\n<li>The check_email method needs refactoring. For example, \n<ol>\n<li>Combine the conditions when you'll skip the iteration cycle together like <code>if email.subject.empty? or email.body.decoded.empty?</code>.</li>\n<li>Extract out the code needed to send out a Twitter update.</li>\n</ol></li>\n<li>In the sync method, you don't need to create individual variables for each interval. Use a method which will return the appropriate option with the correct amount of seconds corresponding to the given time interval.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T11:11:40.880", "Id": "35827", "ParentId": "35577", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:28:49.480", "Id": "35577", "Score": "1", "Tags": [ "ruby", "beginner" ], "Title": "Daemon code for updating blog" }
35577
<p>I write the following version of an if-statement very often. And every time, I hate the way that I make it, but I don't know how to improve it.</p> <p>For example, I have two <code>ArrayList</code>'s. If one of them is not empty, then I convert it to a <code>StringBuilder</code> and send it per mail. The problem is, first I check if one of them is not empty to know if I should send a mail, and then I check it again to know which of them is not empty. Example code:</p> <pre><code>if(!array1.isEmpty() || !array2.isEmpty()){ // I need to distinguish the StringBuilder StringBuilder array1string = new StringBuilder(); StringBuilder array2string = new StringBuilder(); // so one of them is not empty. but which? now I must double check it if(!array1.isEmpty()){ for(String string : array1){ array1string.append(string); } } if(!array2.isEmpty()){ for(String string : array2){ array2string.append(string); } } mail.sendMail("Array1: " + array1string == null?"-":array1string.toString() + ", Array2: " + array2string == null?"-":array2string.toString()); } </code></pre> <p>So is there a way to prevent this double check?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:21:25.723", "Id": "57791", "Score": "3", "body": "`array1string` and `array2string` will never be equal to `null`; you're giving them each a value near the start of the code segment. They might result in empty strings, but they're not `null`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T11:34:19.260", "Id": "58093", "Score": "0", "body": "@dTDesign: Do you know that the mail that is sent might still indicate that both arrays are empty?" } ]
[ { "body": "<p>Your code can be shortened to:</p>\n\n<pre><code>if(!array1.isEmpty() || !array2.isEmpty()) {\n mail.sendMail(\"Array1: \" + getContent(array1) + \", Array2: \" + getContent(array2));\n}\n</code></pre>\n\n<p>When you have:</p>\n\n<pre><code>String getContent(ArrayList&lt;String&gt; list) {\n if(!list.isEmpty()) {\n StringBuilder sb = new StringBuilder();\n for(String string : list) {\n sb.append(string);\n }\n return sb.toString();\n }\n return \"-\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:44:31.433", "Id": "57749", "Score": "0", "body": "You mean `if (!array.isEmpty())`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T09:02:50.647", "Id": "57754", "Score": "0", "body": "This is why I love this site. very elegant way. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T10:58:57.637", "Id": "57763", "Score": "0", "body": "I think the whole code block inside `getArrayContent` method can be substituted with `return array.isEmpty() ? \"-\" : Arrays.toString(array);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T11:18:46.580", "Id": "57764", "Score": "1", "body": "@tintinmj `Arrays.toString()` adds `,`, `[` and `]` to the output, something that OP does not want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:33:24.630", "Id": "57773", "Score": "2", "body": "The OP said they were `ArrayLists`, not *arrays*. `String[]` should be `List<String>`, and the method can actually be built with generics to support any kind of list. I'll add an answer to show how." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:29:03.437", "Id": "35585", "ParentId": "35584", "Score": "13" } }, { "body": "<p>Adam's answer is good, but I just couldn't resist modifying his method a bit:</p>\n\n<pre><code>&lt;E&gt; String getArrayContent(Collection&lt;E&gt; list) {\n if(list.isEmpty())\n return \"-\";\n\n StringBuilder sb = new StringBuilder();\n for(E value : list) {\n sb.append(value);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>This method has the following modifications compared to Adam's:</p>\n\n<ul>\n<li>It uses <code>Collection</code> because you stated that you were using <code>ArrayList</code> in the question. (And this method works with any type of collection, not only <code>List</code> or <code>ArrayList</code>). <code>Collection</code> is the superinterface which declares both <code>isEmpty()</code> and extends <code>Iterable</code></li>\n<li>It uses generics so it can be used for any kind of collection, not only <code>Collection&lt;String&gt;</code></li>\n<li>I prefer to return early to simplify readability and not have to indent code more than necessary</li>\n</ul>\n\n<p>If you also want a method for regular arrays, that method could call the method for collections by converting the array to a list:</p>\n\n<pre><code>&lt;E&gt; String getArrayContent(E[] array) {\n return getArrayContent(Arrays.asList(array));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:39:52.310", "Id": "35595", "ParentId": "35584", "Score": "11" } } ]
{ "AcceptedAnswerId": "35585", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:22:50.947", "Id": "35584", "Score": "11", "Tags": [ "java" ], "Title": "Improve my if-statement to prevent double checks" }
35584
<p>I am developing a bean class which has multi face properties (name has first name, last name and middle name). The object is going to be used to create an xml file. Please compare my two methods to incorporate the same in my application.</p> <p>Method 1:</p> <pre><code>public class SampleVO { String firstName; String middleName; String lastName; // getters and setters } </code></pre> <p>Method 2:</p> <pre><code>//Main object public class SampleVO1 { NameVO name = new NameVO(); // getters and setters } //Name object public class NameVO { String firstName; String middleName; String lastName; // getters and setters } </code></pre> <p>Note: Above is just a sample. The requirement is to group a set of properties. In Which way of the above performance/code standards will be good?</p>
[]
[ { "body": "<p>From a performance perspective both approaches are comparable. Yes, method 2 will use some additional memory and require a few more instructions for instantiating your <code>NameVO</code>, but unless you're dealing with millions of objects, I would not worry too much about that. </p>\n\n<p>From a coding standards perspective, method 2 is superior over method 1. In general, composite values (such as names) deserve their own object. </p>\n\n<p>First of all, it allows you to add additional methods in your <code>NameVO</code>, such as the likely <code>String getFullName()</code>, which handles the possibility of having <code>null</code> as a middleName. This also gives you the flexibility to change the contents of a <code>NameVO</code> later on, for example by adding initials, salutations, etc. </p>\n\n<p>Secondly, it gives you the option to reuse <code>NameVO</code> in other contexts. For example, you could have a <code>Customer</code> object with a <code>name</code> field, and a <code>Supplier</code> with a <code>name</code> field, etc.</p>\n\n<p>Thirdly, if your code uses validation, you can decouple the validation of the contents of a name from the validation of the existence of a name. </p>\n\n<p>Furthermore, by adding an <code>equals</code> and <code>hashCode</code>, you also gain the possibility to store your objects in a <code>Map</code>, indexed by <code>NameVO</code>. </p>\n\n<p>As an aside, I would even go so far as to suggest a slightly modified version of your method 2:</p>\n\n<pre><code>public class SampleVO {\n NameVO name;\n // getters and setters\n}\n\n//Name object\npublic class NameVO {\n final String firstName;\n final String middleName;\n final String lastName;\n\n public NameVO(String firstName, String middleName, String lastName) {\n // assignments\n }\n\n // getters \n}\n</code></pre>\n\n<p>This effectively makes your <code>NameVO</code> immutable, making it more suitable for use as a key in a <code>Map</code>. It also makes it safer to pass <code>NameVO</code> objects around without having to fear side effects. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:22:31.390", "Id": "57780", "Score": "0", "body": "Ah, I might have misunderstood the question. I thought `SampleVO` also was an independent name object. In that case I have to perfectly agree with you. You are completely right about immutability and using as key in a `Map`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:04:14.600", "Id": "57803", "Score": "0", "body": "As for the key-in-the map, it may not be obvious that it also needs an override to the `hashCode` and `equals` method." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:11:23.157", "Id": "35597", "ParentId": "35591", "Score": "6" } } ]
{ "AcceptedAnswerId": "35597", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T10:21:47.197", "Id": "35591", "Score": "3", "Tags": [ "java" ], "Title": "Java beans performance with object inside object" }
35591
<p>I have this basic JavaScript that, using a constructor, validates the form where the login fields can't be empty. All this WITHOUT using any JS libraries.</p> <pre><code>function Validator(txtbox) { this.txtbox = txtbox; } var validator = new Validator([ "username", "password"]); Validator.prototype.validate = function(form) { for(var i = 0, l=this.txtbox.length; i &lt; l; i++) { var status = document.getElementById("status-msg"); if (form[this.txtbox[i]].value == 0) { status.innerHTML="The " + form[this.txtbox[i]].name + " is empty"; status.style.display = "inline-block" status.className = "error"; return false; } else { status.innerHTML="Login successful"; status.style.display = "inline-block" status.className = "success"; } } } function runValidate(form) { validator.validate(form); } </code></pre> <p>I'm wondering how I can make it more efficient or better.</p>
[]
[ { "body": "<p>Your Validator(txtbox) function needs to change it's parameter name. It reads like it takes a single element, but in your case you are sending an array of elements. </p>\n\n<p>All your validation does is just making sure there is something in the textbox, but i could still send a whitespace string into it, and if it was asking for my phone number there's no validating if it's a valid number, or not. Or maybe it's asking for my credit card and I send in my name. There's no validation for that.</p>\n\n<p>I would also set it up so that the validation function takes the actual target element as parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:05:38.477", "Id": "57770", "Score": "0", "body": "Many thanks for your answer. So a good name would be something like txtBoxArr maybe? Should I then check if the textbox is null?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:20:45.100", "Id": "57772", "Score": "0", "body": "Sure, or if you decide to pass an array of elements I'd go with \"elements\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:35:47.983", "Id": "57774", "Score": "0", "body": "Ok, thanks again. When you say \" actual target element as parameter\" - how would I go about doing that?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T11:56:06.340", "Id": "35594", "ParentId": "35592", "Score": "0" } }, { "body": "<p>Why not add some <a href=\"http://usejsdoc.org/\" rel=\"nofollow\">JSDoc</a> to your code:</p>\n\n<pre><code>/**\n*@constructor\n*@param {Array} txtbox - An array of whatever\n*@returns {Validator}\n*/\nfunction Validator(txtbox) {\n /**\n *@private\n */\n this.txtbox = txtbox;\n}\n\nvar validator = new Validator([ \"username\", \"password\"]);\n\n/**\n*@public\n*@memberOf Validator.prototype\n*@param {Form} form - The form holding the login information\n*/\nValidator.prototype.validate = function(form) {\n for(var i = 0, l=this.txtbox.length; i &lt; l; i++) {\n var status = document.getElementById(\"status-msg\");\n if (form[this.txtbox[i]].value == 0) {\n status.innerHTML=\"The \" + form[this.txtbox[i]].name + \" is empty\";\n status.style.display = \"inline-block\"\n status.className = \"error\";\n return false;\n }\n else {\n status.innerHTML=\"Login successful\";\n status.style.display = \"inline-block\"\n status.className = \"success\";\n }\n }\n}\n\nfunction runValidate(form) {\n validator.validate(form);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T14:07:08.967", "Id": "35599", "ParentId": "35592", "Score": "1" } } ]
{ "AcceptedAnswerId": "35599", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T11:19:50.827", "Id": "35592", "Score": "3", "Tags": [ "javascript", "constructor" ], "Title": "Login field validator" }
35592
<p>I was searching for a way to put a <code>Tuple&lt;List&gt;</code> into a <code>Tuple&lt;IEnumerable&gt;</code>, and I found that Tuple has no covariance.</p> <ol> <li><a href="https://stackoverflow.com/questions/2872867/is-c-sharp-4-0-tuple-covariant">Is C# 4.0 Tuple covariant</a></li> <li><a href="https://stackoverflow.com/questions/6437845/co-contravariance-tuplestring-ienumerablestring-not-satisfied-with-listst">Co/Contravariance? Tuple> not satisfied with List</a></li> </ol> <p>I decide to make my own implementation of an interface which subclass a tuple with a support for Covariance:</p> <pre><code>/// &lt;summary&gt; /// A wrapper around Tuple for gaining covariance /// &lt;/summary&gt; public static class ITuple { private class _ITuple&lt;T1&gt; : Tuple&lt;T1&gt;, ITuple&lt;T1&gt; { public _ITuple(T1 item1) : base(item1) { } } public static ITuple&lt;T1&gt; Create&lt;T1&gt;(T1 item1) { return new _ITuple&lt;T1&gt;(item1); } private class _ITuple&lt;T1, T2&gt; : Tuple&lt;T1, T2&gt;, ITuple&lt;T1, T2&gt; { public _ITuple(T1 item1, T2 item2) : base(item1, item2) { } } public static ITuple&lt;T1, T2&gt; Create&lt;T1, T2&gt;(T1 item1, T2 item2) { return new _ITuple&lt;T1, T2&gt;(item1, item2); } private class _ITuple&lt;T1, T2, T3&gt; : Tuple&lt;T1, T2, T3&gt;, ITuple&lt;T1, T2, T3&gt; { public _ITuple(T1 item1, T2 item2, T3 item3) : base(item1, item2, item3) { } } public static ITuple&lt;T1, T2, T3&gt; Create&lt;T1, T2, T3&gt;(T1 item1, T2 item2, T3 item3) { return new _ITuple&lt;T1, T2, T3&gt;(item1, item2, item3); } } public interface ITuple&lt;out T1&gt; { T1 Item1 { get; } } public interface ITuple&lt;out T1, out T2&gt; { T1 Item1 { get; } T2 Item2 { get; } } public interface ITuple&lt;out T1, out T2, out T3&gt; { T1 Item1 { get; } T2 Item2 { get; } T3 Item3 { get; } } </code></pre> <p>Some tests and usage:</p> <pre><code>[TestMethod] public void TestCompile() { // no assertion, just test that the compilation work ITuple&lt;Exception&gt; item = ITuple.Create&lt;NullReferenceException&gt;(null); ITuple&lt;IEnumerable&lt;int&gt;&gt; item2 = ITuple.Create&lt;List&lt;int&gt;&gt;(null); } [TestMethod] public void TestEqual() { Assert.AreEqual(ITuple.Create(1, Tuple.Create("a")), ITuple.Create(1, Tuple.Create("a"))); Assert.AreNotEqual(ITuple.Create(1, Tuple.Create("a")), ITuple.Create(1, Tuple.Create("b"))); } </code></pre> <p>I choose to hide the implementation of the concrete class <code>_ITuple</code> inside the static class, so you have access only to the public and static builder <code>ITuple.Create</code>.</p> <p>Problems:</p> <ol> <li><p><strong>Subclass and equality support</strong></p> <p>Subclassing the tuple is easy and there is nothing to do, and this is my concern. Is there something am I missing? I see no reason why equalities and hashcode souldn't work as expected with classic Tuple, but maybe you will find a problem somewhere which I didn't think of.</p></li> <li><p><strong>Naming convention</strong></p> <ul> <li>Like the static class <code>Tuple</code> contains all the <code>Create</code> static methods, <code>ITuple</code>, which is not an interface, has the static builder. At what point is this weird to name a non interface with an <code>I</code> prefix?</li> <li>At first, I called the <code>ITuple</code> interface <code>ICovariantTuple</code>, but found it too long, and there is no <code>ITuple</code> in the framework. Is this evident that <code>ITuple</code> is covariant?</li> </ul></li> </ol>
[]
[ { "body": "<ol>\n<li><p>I think that non-interface types shouldn't be called <code>ISomething</code>. You could just call the static class <code>Tuple</code> and differentiate it from <code>System.Tuple</code> by using a different namespace. Or you could call the class something like <code>TupleEx</code>, though that's not very descriptive.</p>\n<p>But the best option is if you could figure out a good name for the type that differentiates it from <code>System.Tuple</code>. I agree that <code>CovariantTuple</code> is quite long, though I don't have any better ideas.</p>\n</li>\n<li><p>I also don't like the name <code>_ITuple</code>, even if it's not publicly visible. I would call it something like <code>TupleImpl</code>. (Again, if you figure out a good name, you could use that here too.)</p>\n</li>\n<li><p>Regarding equality: your <code>ITuple</code>s will show as equal to normal <code>Tuple</code>s with the same contents. This most likely is what you want, but you should be aware of it.</p>\n<p>I don't think there are any other problems with equality or hash codes.</p>\n</li>\n<li><p>Consider not writing everything on a single line. I think it will make the code clearer.</p>\n</li>\n<li><p>It might make sense to add some way to convert <code>System.Tuple</code> to <code>ITuple</code> and back.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:01:21.957", "Id": "57800", "Score": "1", "body": "+1, points 1 and 5 possibly lead us to a `TupleFactory` with methods like `Create()` and `CreateCovariant()`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T16:41:08.070", "Id": "35605", "ParentId": "35601", "Score": "7" } } ]
{ "AcceptedAnswerId": "35605", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:01:06.363", "Id": "35601", "Score": "10", "Tags": [ "c#", ".net", "covariance" ], "Title": "A Covariant Tuple" }
35601
<p>I would like some comments on my code and implementation for this simple piece of jQuery. </p> <p>Basically it is 2 div boxes #side1 and #side2, in a container div called #frontimage, where #side2 can be swung out by dragging from right to left along #frontimage. </p> <p>My jQuery code below continuously updates the CSS transform rotateY parameters for #side2 based on a mousemove event. </p> <p>Here is a working example: </p> <p><a href="http://jsfiddle.net/Sr4zw/embedded/result/" rel="nofollow">http://jsfiddle.net/Sr4zw/embedded/result/</a></p> <p>And here is the complete code including HTML and CSS:</p> <p><a href="http://jsfiddle.net/Sr4zw/" rel="nofollow">http://jsfiddle.net/Sr4zw/</a></p> <pre><code>$(document).ready(function() { var yDegrees = 0, slidingLength = 372, maxRotation = -45; $("#frontimage").on('mousedown', function( event ) { var originX = event.pageX; $("#frontimage").on("mousemove", function( event ) { yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation); if (yDegrees &lt; maxRotation) { yDegrees = maxRotation; }; if (yDegrees &gt; 0) { yDegrees = 0; }; originX = event.pageX; $("#side2").css({ '-webkit-transform': 'rotateY(' + yDegrees + 'deg)', '-moz-transform': 'rotateY(' + yDegrees + 'deg)', '-ms-transform': 'rotateY(' + yDegrees + 'deg)', '-o-transform': 'rotateY(' + yDegrees + 'deg)', 'transform': 'rotateY(' + yDegrees + 'deg)' }); }); }); $('html').on('mouseup', function() { $("#frontimage").off('mousemove'); }); }); </code></pre> <p>Some comments on my implementation: </p> <p><code>yDegrees</code> stores the current rotation degree. <code>slidingLength</code> is the length (in pixels) of the mouse drag that changes <code>yDegrees</code>. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:39:51.473", "Id": "57813", "Score": "1", "body": "As per the FAQ, please embed the code you'd like reviewed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:44:50.900", "Id": "57814", "Score": "1", "body": "Right, I've done that now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:53:12.167", "Id": "57815", "Score": "0", "body": "@Malachi: Any ideas on a better title?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:54:49.577", "Id": "57816", "Score": "0", "body": "@Jamal, working on it. not sure what the thing does yet. but I do see some code that looks wrong. I am no good at figuring out Titles.....lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:05:42.603", "Id": "57818", "Score": "0", "body": "The code manipulates the CSS transform properties of a div by dragging left and right on the div. I'm updating the title." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:14:19.110", "Id": "57823", "Score": "0", "body": "cool. I am new to Javascript/jQuery so it took me a couple of minutes to follow what was going on in the code. and I am being distracted by work...ugh. seems like your code works well, the two if statements in the middle of the code make me a little nervous about edge cases but I imagine there is logic behind that, that I am not catching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:19:02.437", "Id": "57824", "Score": "0", "body": "To my knowledge the code works as it should across all recent browsers. But since it is my first foray into JavaScript and jQuery, I would like some comments on my implementation and code in general, which I am sure is not the most elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:06:44.530", "Id": "57844", "Score": "0", "body": "there is a lot of activity using the Javascript Tag so I am going to add it to your question, I am just starting to dive into Javascript and I know there are more people that can better help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-08T17:34:36.193", "Id": "233548", "Score": "0", "body": "Commenting on user experience, it doesn't support touch events so I can't drag it on my phone." } ]
[ { "body": "<p><strong>Edit:</strong>\nSomething else that I now noticed while I was reviewing this answer, your if statements could be written differently, it looks like it should be an if/else statement rather than two separate if statements. </p>\n\n<p>We know that if <code>yDegrees</code> is less than <code>maxRotation</code> that it is not equal to zero, nor will it be equal to zero after <code>yDegrees</code> is set to <code>-45</code>(<code>maxRotation</code>).</p>\n\n<p>Here is your code</p>\n\n<blockquote>\n<pre><code> if (yDegrees &lt; maxRotation) {\n yDegrees = maxRotation;\n };\n if (yDegrees &gt; 0) {\n yDegrees = 0;\n };\n</code></pre>\n</blockquote>\n\n<p>and here is what I am proposing</p>\n\n<pre><code>if (yDegrees &lt; maxRotation) {\n yDegrees = maxRotation;\n} else if (yDegrees &gt; 0) {\n yDegrees = 0;\n}\n</code></pre>\n\n<p>If you wanted to, you could make this a one line piece of code in your JavaScript by writing a ternary inside of a ternary like this:</p>\n\n<pre><code>yDegrees = yDegrees &lt; maxRotation ? maxRotation : (yDegrees &gt; 0 ? 0 : yDegrees);\n</code></pre>\n\n<p>I also noticed that you set <code>originX</code> again after these if statements, but don't actually change it's value anywhere since the last time that you set it, and you don't use it again after this second setting of the variable, I assume that it is dead code, you should just get rid of that extra variable set.</p>\n\n<hr>\n\n<p>From one Beginner to another,</p>\n\n<p>the code looks good to me, </p>\n\n<ol>\n<li>The formatting is clean</li>\n<li>The code flows well and it isn't extremely hard to follow the code.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:09:04.040", "Id": "35621", "ParentId": "35609", "Score": "3" } }, { "body": "<p>The semicolons after the closing braces are really unnecessary, and the indentation is a bit off here:</p>\n\n<blockquote>\n<pre><code> if (yDegrees &lt; maxRotation) {\n yDegrees = maxRotation;\n };\n if (yDegrees &gt; 0) {\n yDegrees = 0;\n };\n</code></pre>\n</blockquote>\n\n<p>It would be better this way:</p>\n\n<pre><code> if (yDegrees &lt; maxRotation) {\n yDegrees = maxRotation;\n }\n if (yDegrees &gt; 0) {\n yDegrees = 0;\n }\n</code></pre>\n\n<p>This could be written more compactly:</p>\n\n<blockquote>\n<pre><code>yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);\n</code></pre>\n</blockquote>\n\n<p>Like this:</p>\n\n<pre><code>yDegrees += (originX - event.pageX) / slidingLength * maxRotation;\n</code></pre>\n\n<p>That is, using <code>+=</code> and removing unnecessary parentheses.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-12T22:32:03.703", "Id": "73519", "ParentId": "35609", "Score": "6" } } ]
{ "AcceptedAnswerId": "35621", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:39:06.923", "Id": "35609", "Score": "5", "Tags": [ "javascript", "jquery", "css", "beginner", "jquery-ui" ], "Title": "Simple jQuery drag event" }
35609
<p>This is a template for one of our data injection tokens. </p> <p>When I first looked at the template, it was worse than it is now. I would like some input on this because I think that it can be cleaned up even better.</p> <p><em>Side note: this is code that we've received from a vendor to use in conjunction with their application for inserting data into an XML file so that a VBScript can retrieve the data.</em></p> <p>Here comes all the fun.</p> <pre><code>public class CustomFormLoad : ICustomFormLoad { #region ICustomFormLoad Members string MachineName = System.Environment.MachineName; string conSource; public string GetCustomXml(string siteId, int userId, string keyId, string keyXml, string dataXml) { // connect to the production DB to get the connection source for the machine the token is called from. string ConnectSource = "Data Source" ; //removed for security reasons SqlConnection connect = new SqlConnection(ConnectSource); string SelectStatement = "select ReportServer from TokenServers Where ActiveServerMachine = '" + MachineName + "'"; SqlCommand myCommand = new SqlCommand(SelectStatement, connect); SqlDataReader reader; ArrayList myArray = new ArrayList(); try { connect.Open(); reader = myCommand.ExecuteReader(); while (reader.Read()) { myArray.Add(reader.GetString(0)); } reader.Close(); } catch (Exception e) { return "&lt;Error desc='Could not determine report server'/&gt;"; } finally { connect.Close(); } string[] array = myArray.ToArray(typeof(string)) as string[]; conSource = array[0]; conSource = conSource.Replace("\\\\", "\\"); // get case ID from xml document XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(dataXml); XPathNavigator XpathNav; XpathNav = xmlDoc.CreateNavigator(); XPathExpression expr = XpathNav.Compile("//Record/NoticeData/Case/@CaseID"); XPathNodeIterator nodes = XpathNav.Select(expr); if (nodes.Count == 0) { return null; } else { int CaseID = 0; try { nodes.MoveNext(); { CaseID = int.Parse(nodes.Current.Value); } } catch { return "&lt;Error desc='CaseID could not be determined'/&gt;"; } // Create a connection object // TODO: FILL IN THE CONNECTION STRING string Connection = "Generic Place Holder" SqlConnection con = new SqlConnection(Connection); con.Open(); // INSERT THE SINGLE/MULTIPLE DATA SCRIPT HERE //Create a DataAdapter, and then provide the name of the stored procedure. // TODO: FILL IN THE STORED PROCEDURE NAME string spName = "spPhoneNums"; //*** IMPORTANT – Add stored procedure name here! string xmlElementName = "PhoneNumber"; //*** IMPORTANT – Your data will be injected into an XML file, the name used here will be the name of the node that encapsilates your data! string spColName = ""; //*** IMPORTANT – the name of the column the data is located in the stored procedure is listed here for the above xmlElementName! string AttName = "PartyType"; string spAttName = "Code"; string AttName1 = "phoneHome"; //*** IMPORTANT - the name of the data to be stored as an attribute, should be similar to the name used in the column data is located in stored procedure! string spAttName1 = "phoneHome"; //*** IMPORTANT - the name of the column the data is located in the stored procdure the data is listed here for the above attribute! string AttName2 = "phoneWork"; string spAttName2 = "phoneWork"; string AttName3 = "phoneCell"; string spAttName3 = "phoneCell"; //*** For multiple data columns repeat the above AttName and spAttName (e.g. string AttName1 = “AttributeName2”, string spAttName1 = “?” …) SqlDataAdapter MyDataAdapter = new SqlDataAdapter(spName, con); MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; // Create a DataSet DataSet oDS = new DataSet(); // Add Parameters for the Stored Procedure // TODO: FILL IN THE STORED PROCEDURE PARAMETERS MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@CaseID", SqlDbType.Int)); //*** IMPORTANT - The stored procedure used should have a single Parameter named @CaseID! MyDataAdapter.SelectCommand.Parameters[0].Value = CaseID; // Fill the DataSet with data // TODO: FILL IN THE STORED PROCEDURE NAME //MyDataAdapter.Fill(oDS.Tables["tblFileDate"], "dbo.spCaseManagerFileDate"); MyDataAdapter.Fill(oDS, spName); xmlDoc = new XmlDocument(); XmlNode MainNode = xmlDoc.CreateElement(xmlElementName + "s"); xmlDoc.AppendChild(MainNode); XmlNode Elem; foreach (DataRow row in oDS.Tables[0].Rows) //*** loop through each row of returned data and put in xml form { Elem = xmlDoc.CreateElement(xmlElementName); XmlAttribute productAttribute = xmlDoc.CreateAttribute(AttName); productAttribute.Value = (string)row[spAttName]; Elem.Attributes.Append(productAttribute); if (!row.IsNull(spAttName1)) { productAttribute = xmlDoc.CreateAttribute(AttName1); productAttribute.Value = (string)row[spAttName1]; Elem.Attributes.Append(productAttribute); } //*** For multiple data columns repeat the below as necessary: if (!row.IsNull(spAttName2)) { productAttribute = xmlDoc.CreateAttribute(AttName2); productAttribute.Value = (string)row[spAttName2]; Elem.Attributes.Append(productAttribute); } if (!row.IsNull(spAttName3)) { productAttribute = xmlDoc.CreateAttribute(AttName3); productAttribute.Value = (string)row[spAttName3]; Elem.Attributes.Append(productAttribute); } //string XrefNum = (string)row[spColName]; //Elem.AppendChild(xmlDoc.CreateTextNode(XrefNum.ToString())); MainNode.AppendChild(Elem); } // Dispose of SQL objects VERY IMPORTANT!! MyDataAdapter.Dispose(); con.Close(); return xmlDoc.InnerXml; } } #endregion } </code></pre> <p>When I first saw this, there were no <code>Using</code> blocks. They had the connections being closed in the wrong order at the bottom, so there was some stuff that wasn't being closed. </p> <p>I've added quite a bit of code in here.</p> <p><strong>Edit/Update</strong></p> <p>It looks like this isn't one of the dll's that I've updated with the <code>Using</code> blocks.</p> <p>I am, however, working on this specific token, so I am in the position to change the code to use the <code>Using</code> blocks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:28:39.180", "Id": "57875", "Score": "0", "body": "http://programmers.stackexchange.com/questions/27798/what-should-be-the-maximum-length-of-function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:59:50.267", "Id": "57883", "Score": "0", "body": "For clarification, that linked question is not about the **contents** of your code so much as its **length**. It is simply a general principle as to the length that a function should not need to exceed. Dan Lyon's answer goes over how to actually determine splitting the function. MORE CLARIFICATION: Even if every line of code was well-written, that function is just too long to be easily understood. Split it down to smaller functions that max out at 60 lines, if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:05:18.047", "Id": "57885", "Score": "0", "body": "EXAMPLE: For instance, in this specific case, you could have `readDataSource`, `createXMLDoc`, and `buildXMLFromSource`. Or something like that." } ]
[ { "body": "<pre><code>string MachineName = System.Environment.MachineName;\n</code></pre>\n\n<p>Why do you have this in a field? When you need to know the machine name, just access the <code>Environment.MachineName</code> property.</p>\n\n<pre><code>string conSource;\n</code></pre>\n\n<p>I don't see any reason why this is a field. Actually, I don't see any reason why this exists, it's written, but never read.</p>\n\n<pre><code>string ConnectSource\n</code></pre>\n\n<p>Local variables should be in <code>camelCase</code>, that means <code>connectSource</code> in this case. This applies to other local variables named this way too.</p>\n\n<p>Also, having different variables called <code>conSource</code> and <code>ConnectSource</code> is very confusing. Try to give better names to your variables and don't shorten their names, it will make your code more readable.</p>\n\n<pre><code>string SelectStatement = \"select ReportServer from TokenServers Where ActiveServerMachine = '\" + Environment.MachineName + \"'\";\n</code></pre>\n\n<p>Get into the habit of not forming SQL queries like this. Instead, use parametrized queries. It's cleaner and safer (no chance of SQL injections).</p>\n\n<pre><code>ArrayList myArray = new ArrayList();\n</code></pre>\n\n<p>Don't ever use <code>ArrayList</code>, it's there just for backwards compatibility with .Net 1.0. Instead use <code>List&lt;T&gt;</code>, in this case, <code>List&lt;string&gt;</code>.</p>\n\n<p>Also, <code>myArray</code> is a very bad name for a variable. Use a descriptive name like <code>servers</code>, or something like that.</p>\n\n<p>One more thing, it looks to me like the contents of this array are never actually used anywhere. Why is all this code even there?</p>\n\n<pre><code>catch (Exception e)\n{\n return \"&lt;Error desc='Could not determine report server'/&gt;\";\n}\n</code></pre>\n\n<p>This is a very bad way to deal with exceptions.</p>\n\n<ol>\n<li><p>You should catch only specific exceptions that you know about. Quite often, application crash caused by an unhandled exception is <em>the right way</em> to deal with unexpected exceptions, because it means no data is corrupted and you learn quickly about it.</p></li>\n<li><p>You're throwing away all information about the exception that happened. This will make debugging problems that arise much harder.</p></li>\n<li><p>I think it should not be the responsibility of this method to format the error response. Instead, it should be centralized in the code that calls this method.</p></li>\n</ol>\n\n<p>An example of reasonable error handling could look like this:</p>\n\n<pre><code>catch (SqlException e)\n{\n throw new FormLoadException(\"Could not determine report server.\", e);\n}\n</code></pre>\n\n<hr>\n\n<p>I think I'll stop there. On just a few lines, there were quite a lot significant issues. I think that you should first try to improve the code yourself and then you should come back and ask another question about the issues that you missed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:33:14.677", "Id": "57853", "Score": "0", "body": "that exception that is caught, tells us that the table where this information is coming from is wrong. the string that is being returned is inserted into the xml, so when we have an issue with the token it will show in the xml, it is one of the debugging steps. the 3rd party application is a little over complex in what it all does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:38:09.013", "Id": "57854", "Score": "0", "body": "sorry, `conSource` is used in my connection string, which I replaced with `Generic place holder` to protect my connection string. all the input that goes into this comes from a SQL record, and that information is created by the application, so I don't really have to worry about SQL Injection." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:16:13.107", "Id": "35623", "ParentId": "35610", "Score": "5" } }, { "body": "<p>There is a lot here to go over:</p>\n\n<h2>Single Responsibility Principle</h2>\n\n<p>There are too many things going on in this method. It performs multiple database queries, and it parses/traverses XML. This should be split out into several, narrowly-focused methods.</p>\n\n<h2>Database</h2>\n\n<p>I would suggest using an ORM of some sort for your database access. There are plenty of solutions out there, some more well-known examples being <a href=\"http://nhforge.org/Default.aspx\">nHibernate</a> and Microsoft's own <a href=\"http://msdn.microsoft.com/en-us/data/ef.aspx\">Entity Framework</a>. My team has also played around with <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/hh361033.aspx\">F# Type Providers</a>.</p>\n\n<p>For the sake of my answer, though, I will assume making a change like that is probably outside the scope of what you are doing. With that in mind, I would suggest using an IDataReader rather than a SqlDataAdapter, since you appear to know the exact structure of the return data. Reading with IDataReader will involve less overhead, and more importantly, it will be easier to read.</p>\n\n<h2>XML Building</h2>\n\n<p>The older System.Xml objects still have their uses from time to time, but I have found the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq%28v=vs.110%29.aspx\">System.Xml.Linq</a> objects to be <em>far</em> cleaner and easier to work with for most tasks.</p>\n\n<p>A quick example:</p>\n\n<pre><code> var homeNumbers = new List&lt;string&gt;{\"867-5309\", \"648-8888\"};\n var workNumbers = new List&lt;string&gt;{\"867-5309\", \"648-8888\"};\n var numbers = new XElement(\"PhoneNumbers\");\n var doc = new XDocument(numbers);\n for(int i = 0; i &lt; homeNumbers.Count; i++)\n {\n var number = new XElement(\"PhoneNumber\");\n numbers.Add(number);\n number.Add(new XAttribute(\"phoneHome\", homeNumbers[i]));\n number.Add(new XAttribute(\"phoneWork\", workNumbers[i]));\n }\n</code></pre>\n\n<p>Even better would be a way to map data objects from the database code to XML. Normally, this is where I might suggest System.Runtime.Serialization.DataContractSerializer, but it does not support attributes :(</p>\n\n<h2>Unused Code</h2>\n\n<p>I ran across a number of variables which are not used or assigned and then never read. Some examples include <code>conSource</code> and <code>spColName</code>. I cannot ascertain whether they should be removed or if the code meant to use them has yet to be added.</p>\n\n<h2>Constants</h2>\n\n<p>Most of the string literals in the code appear to be good candidates for constant values rather than local string variables.</p>\n\n<h2>Boxing</h2>\n\n<p>There are a few places where unnecessary boxing occurs. Specifically, the ArrayList used to store report servers and the DataSet used to store the second query result will both box values. The former can be easily replaced with a List, which also eliminates the need to perform the ToArray call. The latter is taken care of by changing the database code to use something other than a SqlDataAdapter (see above).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:47:34.577", "Id": "57855", "Score": "0", "body": "this code actually takes an XML Document in and adds elements to the document and then returns the document (which is needed by the parent application) so I am not sure that I want to go that way with the Linq, I haven't used it before. so you and @svick have both given me two things that I am going to look into that I haven't used before, both which I think I should already know to begin with List<T> and Linq I have heard a lot about them but have been avoiding having to learn them for lots of reasons. but I want to!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T20:22:27.137", "Id": "57856", "Score": "0", "body": "BTW, storing `string`s in an `ArrayList` is not boxing, because `string` is already a reference type. Though that doesn't mean it's a good idea to do it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:39:26.710", "Id": "35629", "ParentId": "35610", "Score": "8" } }, { "body": "<p>I have realized that this code doesn't make use of any <code>using</code> statements...</p>\n\n<p>In one spot I have</p>\n\n<blockquote>\n<pre><code> string ConnectSource = \"Data Source\" ; //removed for security reasons\n\n SqlConnection connect = new SqlConnection(ConnectSource);\n string SelectStatement = \"select ReportServer from TokenServers Where ActiveServerMachine = '\" + MachineName + \"'\";\n SqlCommand myCommand = new SqlCommand(SelectStatement, connect);\n SqlDataReader reader;\n ArrayList myArray = new ArrayList();\n try\n {\n connect.Open();\n reader = myCommand.ExecuteReader();\n while (reader.Read())\n {\n myArray.Add(reader.GetString(0));\n }\n reader.Close();\n }\n catch (Exception e)\n {\n return \"&lt;Error desc='Could not determine report server'/&gt;\";\n\n }\n finally\n {\n connect.Close();\n }\n</code></pre>\n</blockquote>\n\n<p>When I should have something like this:</p>\n\n<pre><code>string SelectStatement = \"select ReportServer from TokenServers Where ActiveServerMachine = '\" + MachineName + \"'\"; \nusing (SqlConnection connect = new SqlConnection(ConnectSource))\nusing (SqlCommand myCommand = new SqlCommand(SelectStatement, connect))\n{\n ArrayList myArray = new ArrayList();\n SqlDataReader reader;\n\n try\n {\n connect.Open();\n using (reader = myCommand.ExecuteReader())\n {\n while (reader.Read())\n {\n myArray.Add(reader.GetString(0));\n }\n }\n }\n catch (Exception e)\n {\n return \"&lt;Error desc='Could not determine report server'/&gt;\";\n }\n}\n</code></pre>\n\n<p>This makes it much cleaner, the only reason that the try/catch is still there is to let the user know that the server couldn't be determined. </p>\n\n<hr>\n\n<p>There are plenty of opportunities to use <code>using</code> statements/blocks in this code and they should be utilized for safety's sake.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-17T15:41:32.320", "Id": "73953", "ParentId": "35610", "Score": "3" } } ]
{ "AcceptedAnswerId": "35629", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T17:41:23.353", "Id": "35610", "Score": "4", "Tags": [ "c#", "sql", "sql-server" ], "Title": "Injecting data into XML using a dll" }
35610
<p>I've just completed the WordWrap Kata in the Ruby Kata gem and I'd love some feedback. Thanks!</p> <p>Here's the Kata:</p> <pre><code>$kata take word_wrap.rb WordWrap Kata Create a "WordWrap" class that is initialized with an integer parameter - detail: The parameter is the wrap column - example: WordWrap.new 4 - detail: Non-integer parameters raise an exception - example: WordWrap.new raises an exception - example: WordWrap.new "foo" raises an exception completed (Y|n): "wrap" method Create a wrap method that takes a string parameter - example: WordWrap.new(5).wrap "this is text" - detail: The method should raise an exception for non-string parameters - example: WordWrap.new(4).wrap([1,2,3]) raises an exception completed (Y|n): It should wrap the empty string to an empty string - example: WordWrap.new(4).wrap("") returns "" completed (Y|n): It should return one short word as-is - example: WordWrap.new(6).wrap("word") returns "word" completed (Y|n): It should wrap text at the last space before the wrap length - example: WordWrap.new(5).wrap("word word") returns "word\nword" - example: WordWrap.new(5).wrap("word word word") returns "word\nword\nword" - example: WordWrap.new(10).wrap("word word word") returns "word word\nword" completed (Y|n): Long words without spaces should be broken at the wrap length - example: WordWrap.new(4).wrap("wordword") returns "word\nword" completed (Y|n): Strings with long words and spaces should mix breaking words and at spaces - example: WordWrap.new(3).wrap("word word word") returns "wor\nd\nwor\nd\nwor\d" completed (Y|n): ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓ ┃ Requirement ┃ Time ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Create a "WordWrap" class that is initialized with an integer parameter ┃ 00:09:37 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Create a wrap method that takes a string parameter ┃ 00:06:59 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ It should wrap the empty string to an empty string ┃ 00:03:55 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ It should return one short word as-is ┃ 00:01:53 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ It should wrap text at the last space before the wrap length ┃ 00:34:53 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Long words without spaces should be broken at the wrap length ┃ 00:06:16 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Strings with long words and spaces should mix breaking words and at spaces ┃ 00:05:04 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━┛ </code></pre> <p>My specs:</p> <pre><code>require 'spec_helper' require 'wordwrap' describe WordWrap do describe "#initialize" do let(:wrap_column) { 1 } it "instantiates" do expect { WordWrap.new }.to raise_exception end it "accepts an integer parameter" do expect { WordWrap.new(wrap_column) }.to_not raise_exception end it "rejects non integer parameters" do expect { WordWrap.new("foo") }.to raise_exception end end describe ".wrap" do let(:wrap_column) { 5 } subject(:word_wrap) { WordWrap.new(wrap_column) } specify { expect { word_wrap.wrap("this is text") }.to_not raise_exception } specify { expect { word_wrap.wrap([1,2,3]) }.to raise_exception } it "wraps the empty string to the empty string" do word_wrap.wrap("").should eq("") end it "returns short words (i.e. char count &lt; wrap_column) without modifying them" do word_wrap.wrap("word").should eq("word") end it "wraps text at the last space before the wrap_column" do WordWrap.new(5).wrap("word word").should eq("word\nword") end it { WordWrap.new(5).wrap("word word word").should eq("word\nword\nword") } it { WordWrap.new(10).wrap("word word word").should eq("word word\nword") } it { WordWrap.new(4).wrap("wordword").should eq("word\nword") } it "mixes breaks at words and spaces" do WordWrap.new(3).wrap("word word word").should eq("wor\nd\nwor\nd\nwor\nd") end end end </code></pre> <p>And, finally, the WordWrap Class:</p> <pre><code>class WordWrap def initialize(wrap_column) if (!wrap_column.integer?) raise(ArgumentError, "expected Integer got #{wrap_column.class}") end @wrap_column = wrap_column end def wrap(words) if (!words.is_a?(String)) raise(ArgumentError, "expected String and got #{words.class}") end wrapped_words = "" wrap_count = 0 word_array = words.scan(/\w+/) word_array.each_with_index do |current_word, index| next_word = word_array[index + 1] puts "current_word: #{current_word}" puts "next_word: #{next_word}" if (current_word.length &gt; @wrap_column) wrapped_words &lt;&lt; current_word[0..@wrap_column - 1] &lt;&lt; "\n" wrapped_words &lt;&lt; current_word[@wrap_column..-1] if !next_word.nil? wrapped_words &lt;&lt; "\n" end elsif next_word.nil? wrapped_words &lt;&lt; current_word else if (current_word.length + next_word.length + wrap_count) &gt; @wrap_column wrapped_words &lt;&lt; current_word &lt;&lt; "\n" wrap_count = 0 else wrapped_words &lt;&lt; current_word &lt;&lt; " " wrap_count += current_word.length + next_word.length end end end wrapped_words end end </code></pre> <p>As you can see, <code>wrap()</code> is a pretty ugly function with lots of branching. Any ideas for streamlining it would be greatly appreciated.</p> <h2>Edit:</h2> <p>Thanks to the suggestions below, I've refactored <code>wrap</code> into something more readable:</p> <pre><code>def wrap text if (text.class != String) raise Exception "expected String but paramater has class #{text.class}" end if text.empty? return "" end letter_array = text.split("") last_space = false offset = 0 current_length = 0 letter_array.each_with_index do |letter, index| if (letter =~ /\s/) last_space = index end if (current_length == @wrap_length &amp;&amp; last_space) letter_array[last_space] = "\n" current_length = index - last_space last_space = false elsif (current_length == @wrap_length) letter_array.insert(index, "\n") current_length = 0 else current_length += 1 end end if (letter_array.last == "\n") letter_array.delete_at(-1) end letter_array.inject(:+) end </code></pre>
[]
[ { "body": "<p>Here are some things you can improve:</p>\n\n<ol>\n<li>Ruby has a method <a href=\"http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-each_cons\" rel=\"nofollow\"><code>each_cons(n)</code></a>. In your code, you can write <code>word_array.each_cons(2) do |current_word, next_word|</code>.</li>\n<li>There is a bug in the code where you write <code>wrapped_words &lt;&lt; current_word[@wrap_column..-1]</code>. This assumes that a word can be broken only once. For example, <code>WordWrap.new(3).wrap(\"wordword\")</code> will return \"wor\\ndword\".</li>\n<li>Extending the above logic, the next block adding a new line in the case <code>next_word</code> is not nil is also a bug. Consider the input \"word w\" when you have to wrap on 3 columns. Your output will be \"wor\\nd\\nw\" whereas the correct output should be \"wor\\nd w\".</li>\n</ol>\n\n<p>I'll not be adding any more code comments since you seem to have some pretty serious bugs in your code owing to all those conditions. What I do recommend is to revise your strategy. Try thinking along these lines for a pretty solution:</p>\n\n<ol>\n<li>Scan the input string one character at a time.</li>\n<li>Remember the current length of scan.</li>\n<li>Remember the position of the last space seen every time you encounter a space.</li>\n<li>If the current length of the scan is equal to the <code>wrap</code> value, it's time to take action based on the position of the last space seen:\n<ol>\n<li>If it's not nil, you have to copy everything up to that position into the result string plus a new line. Reset the current_length based on how much was copied.</li>\n<li>If it's nil, copy everything up to the current index and then add a new line.</li>\n</ol></li>\n<li>Reset the position of the last space seen to nil.</li>\n<li>If it's the end of string and your result string has a new line at the end, chomp it off.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T18:49:57.397", "Id": "64915", "Score": "0", "body": "Thanks Chandranshu. I've redone the exercise using your suggestions of examining every character and I like that solution much better. Very clean and readable. I'm always amazed at how changing a single assumption can so drastically effect the result." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:10:19.897", "Id": "35817", "ParentId": "35614", "Score": "1" } } ]
{ "AcceptedAnswerId": "35817", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:12:14.273", "Id": "35614", "Score": "1", "Tags": [ "ruby", "rspec" ], "Title": "Ruby Kata Gem: WordWrap" }
35614
<p>I am creating a <a href="http://en.wikipedia.org/wiki/Frogger" rel="nofollow">Frogger game</a> in Flash AS3 and just wanted to see if anyone can help me improve it without breaking the game.</p> <p>The reason I ask for it because I don't have any errors, but I do get over 50 of these:</p> <blockquote> <p>Warning: 3596: Duplicate variable definition.</p> </blockquote> <pre><code>package { import flash.display.*; import flash.events.*; import flash.ui.*; public class Frogger extends MovieClip { private var life, timeElapsed, totalTimer:Number; private var p1speedX, p1speedY:Number; private var gotoWin, gotoLose, standingOnLog:Boolean; private var logs, Trucks, homes, logsYPos, TrucksYPos:Array; public function startMenu() { btnStartGame.addEventListener(MouseEvent.CLICK, gotoStartGame); stop(); } public function startWin() { btnBack.addEventListener(MouseEvent.CLICK, gotoMenu); } public function startLose() { btnBack.addEventListener(MouseEvent.CLICK, gotoMenu); } public function startGame() { timeElapsed = 0; totalTimer = 60; life = 3; p1speedX = 0; p1speedY = 0; gotoWin = false; gotoLose = false; standingOnLog = false; Trucks = new Array(); logs = new Array(); homes = new Array(); logsYPos = new Array(115,165,215,265); TrucksYPos = new Array(365,415,465,515); setupGame(); addEventListener(Event.ENTER_FRAME,update); stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler); stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler); stage.focus = this; for (var i=1; i&lt;=3; i++) { var newTruck = new Truck(); newTruck.x = -300 * i; newTruck.y = TrucksYPos[0]; newTruck.speedX = 5; Trucks.push(newTruck); addChild(newTruck); } for (var i=1; i&lt;=1; i++) { var newTruck = new Truck(); newTruck.x = (170 * i) + 500; newTruck.y = TrucksYPos[1]; newTruck.speedX = -25; Trucks.push(newTruck); addChild(newTruck); } for (var i=1; i&lt;=4; i++) { var newTruck = new Truck(); newTruck.x = (-220 * i) + 100; newTruck.y = TrucksYPos[2]; newTruck.speedX = 8; Trucks.push(newTruck); addChild(newTruck); } for (var i=1; i&lt;=2; i++) { var newTruck = new Truck(); newTruck.x = (200 * i) + 350; newTruck.y = TrucksYPos[3]; newTruck.speedX = -5; Trucks.push(newTruck); addChild(newTruck); } for (var i=1; i&lt;=4; i++) { var newLog = new LogWood(); newLog.x = -300 * i; newLog.y = logsYPos[0]; newLog.speedX = 5; logs.push(newLog); addChild(newLog); swapChildren(mcP1,newLog); } for (var i=1; i&lt;=2; i++) { var newLog = new LogWood(); newLog.x = (170 * i) + 500; newLog.y = logsYPos[1]; newLog.speedX = -5; logs.push(newLog); addChild(newLog); swapChildren(mcP1,newLog); } for (var i=1; i&lt;=2; i++) { var newLog = new LogWood(); newLog.x = (-220 * i) + 100; newLog.y = logsYPos[2]; newLog.speedX = 14; logs.push(newLog); addChild(newLog); swapChildren(mcP1,newLog); } for (var i=1; i&lt;=3; i++) { var newLog = new LogWood(); newLog.x = (250 * i) + 400; newLog.y = logsYPos[3]; newLog.speedX = -5; logs.push(newLog); addChild(newLog); swapChildren(mcP1,newLog); } } private function setupGame() { for (var i=0; i&lt; MovieClip(root).numChildren; i++) { var object = MovieClip(root).getChildAt(i); if (object is Home) { homes.push(object); }}} private function gotoStartGame(evt:MouseEvent) { btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame); gotoAndStop("game"); } private function gotoMenu(evt:MouseEvent) { btnBack.removeEventListener(MouseEvent.CLICK, gotoMenu); gotoAndStop("menu"); } private function keyDownHandler(evt:KeyboardEvent) { if (evt.keyCode == Keyboard.LEFT) { p1speedX = -1; } else if (evt.keyCode == Keyboard.RIGHT) { p1speedX = 1; } if (evt.keyCode == Keyboard.UP) { p1speedY = -1; } else if (evt.keyCode == Keyboard.DOWN) { p1speedY = 1; } } private function keyUpHandler(evt:KeyboardEvent) { if ((evt.keyCode == Keyboard.LEFT) || (evt.keyCode == Keyboard.RIGHT)) { p1speedX = 0; } if ((evt.keyCode == Keyboard.UP) || (evt.keyCode == Keyboard.DOWN)) { p1speedY = 0; } } public function update(evt:Event) { handleUserInput(); handleGameLogic(); handleDraw(); if (gotoWin) triggerGoToWin(); else if (gotoLose) triggerGoToLose(); } private function handleUserInput() { if (p1speedX &gt; 0) { if (mcP1.x + 50 &lt; 800) mcP1.x += 50; p1speedX = 0; mcP1.rotation = 90; mcP1.play(); } else if (p1speedX &lt; 0) { if (mcP1.x - 50 &gt; 0) mcP1.x -= 50; p1speedX = 0; mcP1.rotation = -90; mcP1.play(); } if (p1speedY &lt; 0) { mcP1.y -= 50; p1speedY = 0; mcP1.rotation = 0; mcP1.play(); } else if (p1speedY &gt; 0) { if (mcP1.y + 50 &lt; 600) mcP1.y += 50; p1speedY = 0; mcP1.rotation = -180; mcP1.play(); } } private function handleGameLogic() { timeElapsed++; for (var i=Trucks.length-1; i&gt;= 0; i--) { Trucks[i].x += Trucks[i].speedX; if (Trucks[i].hitTestPoint(mcP1.x,mcP1.y)) { life--; resetGame(); } if (Trucks[i].speedX &lt; 0 &amp;&amp; Trucks[i].x &lt;= -50) { Trucks[i].x = 850; } else if (Trucks[i].speedX &gt; 0 &amp;&amp; Trucks[i].x &gt;= 850) { Trucks[i].x = -50; } } var standingOnLog = false; for (var i=logs.length-1; i&gt;= 0; i--) { logs[i].x += logs[i].speedX; if (logs[i].hitTestPoint(mcP1.x,mcP1.y)) { standingOnLog = true; mcP1.x += logs[i].speedX; } if (logs[i].speedX &lt; 0 &amp;&amp; logs[i].x &lt;= -50) { logs[i].x = 850; } else if (logs[i].speedX &gt; 0 &amp;&amp; logs[i].x &gt;= 850) { logs[i].x = -50; } } for (var i in homes) { if (homes[i].hitTestObject(mcP1)) { homes[i].gotoAndStop("occupied"); mcP1.x = 400; mcP1.y = 565; } } if (mcP1.y &lt; 290) { if (!standingOnLog) { life--; resetGame(); } } if ((totalTimer - Math.floor(timeElapsed/30) &lt;= 0) || (life &lt;= 0)) gotoLose = true; var allOccupied = true; for (var i in homes) { if (homes[i].currentLabel == "empty") allOccupied = false; } if (allOccupied) gotoWin = true; } private function handleDraw() { txtTime.text = String(totalTimer - Math.floor(timeElapsed/30)); txtLife.text = String(life); } private function clearGame() { for (var i=Trucks.length-1; i&gt;= 0; i--) { removeChild(Trucks[i]); Trucks.splice(i,1); } for (var i=logs.length-1; i&gt;= 0; i--) { removeChild(logs[i]); logs.splice(i,1); } } private function triggerGoToWin() { clearGame(); removeEventListener(Event.ENTER_FRAME, update); gotoAndStop("win"); } private function triggerGoToLose() { clearGame(); removeEventListener(Event.ENTER_FRAME, update); gotoAndStop("lose"); } private function resetGame() { mcP1.x = 400; mcP1.y = 565; } } } </code></pre>
[]
[ { "body": "<p>It is just a warning. The source of the warnings is that you redeclare the same variable <code>newTruck:Truck</code> numerous times in your startGame function as well as <code>newLog:LogWood</code>.</p>\n\n<p>It's just a warning, because it is ok to do so. The reason it warns you is that it might not be your intention to do so, therefore helping you out.</p>\n\n<p>If you want to get rid of those, you can declare the variables once in startGame before the loops like this:</p>\n\n<pre><code>var newTruck:Truck;\n</code></pre>\n\n<p>and then just reuse them in your loops, for example:</p>\n\n<pre><code>newTruck = new Truck();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:00:17.923", "Id": "35633", "ParentId": "35622", "Score": "4" } }, { "body": "<p><strong>To be consistent</strong> with your variable names, I would rename <code>Trucks</code> to lowercase <code>trucks</code>.</p>\n\n<p><strong>You have several for-loops</strong> that are very similar, for creating Trucks and LogWoods. Consider creating a function <code>createTruck(x, y, speed);</code> the implementation could also take care of adding the truck to the corresponding <code>Array</code> and adding the child to the MovieClip. That way, you could rewrite a for-loop like this:</p>\n\n<pre><code> for (var i=1; i&lt;=2; i++)\n {\n createTruck(200 * i) + 350, trucksYPos[3], -5);\n }\n</code></pre>\n\n<p>And by doing this you also don't need the <code>newTruck</code> variable, as that will only exist within the <code>createTruck</code> function.</p>\n\n<p><strong>Instead of using</strong> the type Array, I suggest you use the <code>Vector</code> class which has the advantage of being typed so it only allows adding objects of a specific type. This has a significant compile-time advantage since it allows for better type-checking but it has a <a href=\"https://stackoverflow.com/questions/8551527/as3-vector-of-arrays/8551727#8551727\">run-time disadvantage</a>. (Although I don't think you need to be worried about the run-time disadvantage)</p>\n\n<p><strong>I am curious</strong> about how you use your <code>startWin</code> and <code>startLose</code> methods. I assume they're being called from a timeline somewhere. All they do is to add an event listener for the click of a button. Of course this is important, but should it have it's own method? Especially considering they do the exact same thing it feels strange. As soon as your btnBack exists (is not null), add the event listener, and do it only once. I don't see the need for two separate methods.</p>\n\n<p><strong>Using a switch-statement</strong> in your <code>keyDownHandler</code> method would reduce your line count and improve the readability of your code.</p>\n\n<pre><code> switch (evt.keyCode) {\n case Keyboard.LEFT:\n p1speedX = -1;\n break;\n case Keyboard.RIGHT:\n p1speedX = 1;\n break;\n case Keyboard.UP:\n p1speedY = -1;\n break;\n case Keyboard.DOWN:\n p1speedY = 1;\n break;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:30:31.670", "Id": "57877", "Score": "1", "body": "Although commonly thought otherwise, the real performance benefits in using Vectors is with int, uint, and Number. See this link for details on that aspect - http://stackoverflow.com/questions/8551527/as3-vector-of-arrays/8551727#8551727 When dealing with non-primitive number types such as in this code, you aren't going to get the advantage most would suspect. The stronger typing is a compile time benefit, not run-time performance in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:35:38.780", "Id": "57878", "Score": "0", "body": "@prototypical I didn't say it was a run-time performance benefit. I mostly prefer `Vector` just because of the compile time benefit. (This is actually one of the reasons I prefer the Java language, there are so many errors that are caught in compile-time rather than run-time, but that's a different topic)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:38:37.523", "Id": "57880", "Score": "0", "body": "Yeah, I agree, was mostly trying to give more clarity to the benefits of Vector vs Array. I do agree the compile-time advantages are worthy of note. I wasn't trying to say you were wrong, but rather just point to more on the topic of differences." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:41:49.930", "Id": "57881", "Score": "0", "body": "\"so it only allows adding objects of a specific type.\" might leave one to wonder what that limitation buys them or if that is something they desire given their specific situation. So, Im glad you expounded on that in the comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:46:54.597", "Id": "57882", "Score": "2", "body": "@prototypical And I'm glad you gave me the information about the run-time performance difference. I actually did not know that. I will update my answer with some of the information in these comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:02:25.923", "Id": "57884", "Score": "1", "body": "I think the run-time disadvantage is rather negligible myself. I tend to use Vectors mostly. However, there are some situations where I want to store multiple types, and in that case I choose an Array. When I discovered the performance aspect, my Vectors for game entities suddenly felt slower, haha :) Whereas before I felt like I was heavily optimizing by switching!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:08:44.890", "Id": "57887", "Score": "0", "body": "@prototypical \"What we see depends mainly on what we look for\" perhaps ;) I try to use Vectors as much as possible. Although I remember when I had to convert about around 2000 lines of code, which made heavily use of Arrays, to using Vectors instead. I wish I knew about vectors right from the start :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:27:03.987", "Id": "35635", "ParentId": "35622", "Score": "3" } }, { "body": "<p>Those errors come if you declare the same variable more then once within the same scope, your loops are declaring <code>i</code> as a new variable each time, you should put those different loops into different functions to perform the action required or use some kind of loop variable if you must do it this way...</p>\n\n<pre><code>private var loopVar:int = 0;\n\nfor(loopVar = 0; loopVar &lt; 3; loopVar++)\nfor(loopVar = 0; loopVar &lt;= secondLoopValue; loopVar++)\n</code></pre>\n\n<p>Not the best option but this will remove those errors because <code>i</code> wont be declared over and over, also quicker to reuse a variable rather then declare a new one (I think).</p>\n\n<p>Just don't have more then one loop in any function or get use to those errors, the second option works for me sometimes ;) reminds me I still have work to do at the end of the project.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-08T17:24:09.160", "Id": "90187", "ParentId": "35622", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:11:35.400", "Id": "35622", "Score": "5", "Tags": [ "game", "actionscript-3", "actionscript" ], "Title": "Frogger game in Actionscript 3" }
35622
<p>I had to write my own iterator implementation for my structure which has <code>ArrayList&lt;Vector&gt;</code> field. An iterator is supposed to iterate over mentioned <code>List</code>. Any suggestions on improving it, or anything else?</p> <pre><code>public class ExamplesIterator implements Iterator&lt;Vector&gt; { private List&lt;Vector&gt; examples; //ArrayList&lt;Vector&gt; will be set here private int index; public ExamplesIterator(List&lt;Vector&gt; examples) { this.examples = examples; index = 0; } @Override public Vector next() { if(hasNext()) { return examples.get(index++); } else { throw new NoSuchElementException("There are no elements size = " + examples.size()); } } @Override public boolean hasNext() { return !(examples.size() == index); } @Override public void remove() { if(index &lt;= 0) { throw new IllegalStateException("You can't delete element before first next() method call"); } examples.remove(--index); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:32:41.833", "Id": "57852", "Score": "3", "body": "In Java it is illegal to call `remove()` twice in a row, or without calling `next()` first. See this code I have written here for some ideas: https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/ContentList.java#L655" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:15:19.423", "Id": "58002", "Score": "0", "body": "@rolfl I will take this into account. Thanks. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-01T21:00:28.523", "Id": "160395", "Score": "0", "body": "this article may help you: http://www.yegor256.com/2015/04/30/iterating-adapter.html" } ]
[ { "body": "<p>I think your implementation is overall very good, two small comments:</p>\n\n<ul>\n<li>Improving readability for return statement in <code>hasNext</code> to <code>return examples.size() != index;</code></li>\n<li>Making the <code>examples</code> field <strong>final</strong>: <code>private final List&lt;Vector&gt; examples;</code></li>\n</ul>\n\n<p>However, if the <code>Vector</code> class here is <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html\">java.util.Vector</a> you should know that it is considered deprecated in favor of the <code>ArrayList</code> class.</p>\n\n<p>Also, since you create your iterator from a <code>List&lt;Vector&gt;</code> you could get an <code>Iterator&lt;Vector&gt;</code> by calling <code>list.iterator();</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:13:31.367", "Id": "58000", "Score": "0", "body": "Well... I completely forgot about that I can call `list.iterator();` :P. Thank you !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:35:06.990", "Id": "35627", "ParentId": "35626", "Score": "8" } } ]
{ "AcceptedAnswerId": "35627", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:25:15.557", "Id": "35626", "Score": "7", "Tags": [ "java", "iterator" ], "Title": "Iterator Implementation" }
35626
<p>I made a simple app that fetches the favourite programming language of a Github user, by simply inserting their username. The full code is uploaded on Github, please feel free to fork it from <a href="https://github.com/elmargasimov/lovelanguage" rel="nofollow">https://github.com/elmargasimov/lovelanguage.</a></p> <p>The stack: </p> <ul> <li>Yo Backbone generator from Yeoman</li> <li>Require.js</li> <li>Underscore</li> <li>Sass</li> </ul> <p>Background to the code:</p> <ol> <li>I have declared top level controllers that I initialise from my App router.</li> <li>Inside my controllers I initialise the views and models.</li> <li>I have two models, one which is the User model and the other one is a sub model of the users starred collection.</li> <li>I also have two views, one top level view that fetches the user info and that acts as the glue between the User view and model.</li> </ol> <p><strong>Router (app.js)</strong></p> <pre><code>var AppRouter = Backbone.Router.extend({ routes: { '/*' : 'index', '*about' : 'about' }, initialize: function() { // Declare top level app controllers this.controllers = {}; }, index: function() { // Create new fetchUserController instance this.controllers.fetchUserController = new FetchUserController(); }, about: function() { this.controllers.aboutController = new AboutController(); }, start: function () { Backbone.history.start(); console.log("Launch App"); } }); </code></pre> <p><strong>UserModel (user.js)</strong></p> <pre><code>var UserModel = Backbone.Model.extend({ defaults: { "avatar_url": "", "login": "", "name": "", "id": null, "html_url": "", "favourite_language": "", }, fetchStarred: function () { var _this = this; // Create new starred model instance this.starred = new StarredModel(); // Set the root url to {this.urlRoot}/starred this.starred.urlRoot = this.urlRoot + "/starred"; // Fetch model attributes this.starred.fetch({ success: function (model, response, options) { // Create a new langueages array to store all the languages of the starred repo's var languages = []; // Loop over the response _.each(response, function (index) { // Only grab the language key from the list of attributes var language = index.language // For each language retrieved push to 'languages' array languages.push(language); }); // Set the languages attribute of the starred model to the languages array _this.starred.set('languages', languages); // Compute the mode language of the user _this.starred.mode(languages); // Make a reference to the mode language var modeLanguage = _this.starred.attributes.modeLanguage; // Set the user's favourite language to the mode language _this.set('favourite_language', modeLanguage); } }); } }); </code></pre> <p><strong>StarredModel (starred.js)</strong></p> <pre><code>var StarredModel = Backbone.Model.extend({ defaults: { languages: [], modeLanguage: "", languageMap: {} }, mode: function(array) { var _this = this; // If the languages array is empty, return false if(array.length === 0) { console.log("Cannot compute mode: Empty array"); return false; } var languageMap = {}, modeLanguage, maxCount = 1; _.each(array, function(index) { // Start at the index and loop for each language var language = index; // If language does not yet exist in the languageMap if(typeof languageMap[language] === "undefined") { // Set language key and value equal to 1 languageMap[language] = 1; } else { // Else add 1 to the count languageMap[language] += 1; } // If language value is greater than 1 if(languageMap[language] &gt; maxCount) { // Set modeLanguage equal to the key of the current language modeLanguage = language; // Set new highest count to value of the current language maxCount = languageMap[language]; } // Save the languageMap and modeLanguage as an attribute of this model _this.set("languageMap", languageMap); _this.set("modeLanguage", modeLanguage); }); // Return the mode language return modeLanguage; } }); </code></pre> <p><strong>FetchUserModel (fetchuser.js)</strong></p> <pre><code>var FetchuserView = Backbone.View.extend({ el: $('form.ll-fetch-user-form'), events: { submit: 'fetch' }, template: JST['app/scripts/templates/fetchuser.ejs'], fetch: function (e) { e.preventDefault(); var _this = this; // Hook up to username input field and remove all empty white space var usernameInput = this.$el.find('#ll-github-username-input').val().replace(/\s/g, ''); // Set urlRoot this.model.urlRoot = "https://api.github.com/users/" + usernameInput; // Fetch model attributes this.model.fetch({ success: function (model, response, options) { _this.userInfo(); } }); }, userInfo: function () { // Create new user view and pass in this model instance var userInfo = new UserView({model: this.model}); // Render the view and insert top level element into '.ll-content' $('section.ll-content').html(userInfo.render().el); // Unbind this view, so we don't end up with zombie views this.unbind(); // Remove this view altogeter this.remove(); } }); </code></pre> <p><strong>UserView (userview.js)</strong></p> <pre><code>var UserView = Backbone.View.extend({ tagName: 'section', className: 'll-user-info', template: JST['app/scripts/templates/user.ejs'], initialize: function () { this.listenTo(this.model, 'change', this.render); this.model.fetchStarred(); }, render: function () { this.$el.html(this.template(this.model.toJSON())); return this; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:44:51.487", "Id": "57978", "Score": "0", "body": "Wouldn't `this.$el` be undefined? Shouldn't it be `this.el`?" } ]
[ { "body": "<p>Can't say much about the javascript in general as I don't use it but:</p>\n\n<p>Please do not comment every line of code. This means you write your program twice: once in the comments and once in code. They are bound to drift apart and get out of sync and all of a sudden you have code which does the opposite of what the comment says and then you are in trouble. Bad comments are worse than no comments.</p>\n\n<p>As Jeff Atwood pointed out quite nicely: <a href=\"http://www.codinghorror.com/blog/2006/12/code-tells-you-how-comments-tell-you-why.html\" rel=\"nofollow\">Code tells you how and comments tell you why</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T10:31:13.910", "Id": "57924", "Score": "0", "body": "Hi @ChrisWue, I have a different view. While of course it is bad practice to comment on every line of code. As you pointed out so well, we should still make sure the reader knows WHY we wrote what we wrote. I have worked in places where due to the absence of comments, we had to throw away large chunks of code, since we didn't understand what it did or how it was related to its current application. My rule of thumb is, if it is simple and generically done, then don't comment. But if it is new and unique, then comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:40:23.183", "Id": "57976", "Score": "1", "body": "@Elmar If the code makes sense, then it doesn't need a comment. When we are first learning a language or methodology what we think is new and unique is usually either 1. simple and generic or 2. poorly executed. In either case, the comments are not useful. For option 1 they are redundant. For option 2 they are probably incorrect. Your rule of thumb should be to write code that can be understood by anyone _qualified_ to maintain that code. If looking up a command immediately makes it clear what it does, then you don't need a comment. Adding comments is like adding noise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T07:46:39.327", "Id": "58078", "Score": "1", "body": "@Elmar: First your comments don't comment why you wrote what you wrote. It just reiterates what each line of code is doing which you can see by looking at the code. And second, if you need to comment every line of code with the reason why you wrote it you have a problem anyway. I'm all in favor of good comments but they should be used appropriately." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T09:25:54.127", "Id": "35683", "ParentId": "35628", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T19:37:11.977", "Id": "35628", "Score": "2", "Tags": [ "javascript", "jquery", "backbone.js", "underscore.js" ], "Title": "Need review and best practice tips for a Backbone project" }
35628
<p>The code below is used to download a JSON data from the web and use the data to fill a spinner. I would like to know if there is better way. Is it wise to move everything from <code>onGetPriceType</code> to the <code>AsyncTask</code>?</p> <p><strong>Interface</strong></p> <pre><code>public interface GetBuildTypeInterface { public void onGetBuildType(HashMap&lt;String,String&gt; result); } </code></pre> <p><strong>AsyncTask</strong></p> <pre><code>public class GetBuildType extends AsyncTask&lt;Void, Void, JSONArray&gt; { private GetBuildTypeInterface callback; public GetBuildType(GetBuildTypeInterface callback) { this.callback = callback; } @Override protected JSONArray doInBackground(Void... params) { UserFunctions u = new UserFunctions(); return u.getBt(); } @Override protected void onPostExecute(JSONArray result) { super.onPostExecute(result); HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); if (result != null) { map = result.parse(); callback.onGetBuildType(map); } else { callback.onGetBuildType(null); } } } </code></pre> <p><strong>Activity</strong></p> <pre><code>public class AddFillActivityApp extends ErrorActivity implements GetBuildTypeInterface { ArrayAdapter&lt;String&gt; adapterBuild; Spinner spinBuildType; @Override public void onGetPriceType(final HashMap&lt;String, String&gt; result) { if (result != null) { List&lt;String&gt; fields = new ArrayList&lt;String&gt;(); fields.addAll(result.keySet()); adapterPrice = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, fields); adapterPrice .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinPriceType.setAdapter(adapterPrice); spinPriceType .setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { if (position &gt; -1) { String selection = spinPriceType .getSelectedItem().toString(); a.setNot_priceFor(result.get(selection)); } } @Override public void onNothingSelected(AdapterView&lt;?&gt; arg0) { } }); }else error(); } } </code></pre>
[]
[ { "body": "<p>I see a very big advantage of your current approach rather than moving the implementation of <code>onGetPriceType</code> to the <code>GetBuildType</code> class <em>(May I suggest changing the name to <code>GetBuildTypeTask</code>?)</em></p>\n\n<ul>\n<li><strong><a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29\" rel=\"nofollow\">Decoupling code</a></strong>. Your <code>GetBuildType</code> class is 100% independent of your activity. That is a good sign. If needed, you could at any time re-use the <code>GetBuildType</code> class and provide it with another <code>GetBuildTypeInterface</code>.</li>\n</ul>\n\n<p><em>A side suggestion:</em> I assume that <code>result.parse()</code> doesn't need to be run on the UI-thread, so you can change your class to extend <code>AsyncTask&lt;Void, Void, Map&lt;String, String&gt;&gt;</code> and make the conversion to map in <code>doInBackground</code> (or return null if <code>u.getBt()</code> returns null). Also, you don't need to create a new empty HashMap before parsing the JsonArray, simply <code>Map&lt;String, String&gt; map = jsonArray.parse();</code> will do.</p>\n\n<p>The only disadvantage I see with your current implementation is that you get an extra interface. But I really don't think that's so bad compared to having decoupled code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:01:50.897", "Id": "35642", "ParentId": "35639", "Score": "2" } } ]
{ "AcceptedAnswerId": "35642", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:16:28.890", "Id": "35639", "Score": "2", "Tags": [ "java", "android" ], "Title": "Filling a spinner from JSON web data" }
35639
<p>This is a trade script for an online virtual currency exchange I have been developing. We have a team of 3, and we all work in our own trees. Since we're all young and not very experienced, we would like some feedback and advice prior to hiring penetration testing.</p> <pre><code>if (isUserLoggedIn()) { //get balances } function GetMoney($user, $currency) { $user2 = $user; $sql = @mysql_query("SELECT * FROM balances WHERE `User_ID`='$user2' AND `Coin`='$currency'") $id = @mysql_result($sql, 0, "id"); if ($id &lt; 1) { $old = mysql_result($sql, 0, "Amount"); return $old; } else { $old = mysql_result($sql, 0, "Amount"); return $old; } } $id = mysql_real_escape_string($_GET["market"]); $result = mysql_query("SELECT * FROM Wallets WHERE `Id`='$id'"); $name = mysql_real_escape_string(mysql_result($result, 0, "Acronymn")); $fullname = mysql_real_escape_string(mysql_result($result, 0, "Name")); if($id == 1) { header( 'Location: index.php?page=account' ) ; die(); } if($name == NULL) { header( 'Location: index.php?page=invalid_market' ) ; die(); } $market_id = mysql_result($result, 0, "Market_Id"); $SQL2 = mysql_query("SELECT * FROM Wallets WHERE `Id`='$market_id'"); $Currency_1a = mysql_result($SQL2, 0, "Acronymn"); $Currency_1 = mysql_result($SQL2, 0, "Id"); //-------------------------------------- if(isset($_POST["price2"])) { if ($_POST["price2"] &gt; 0 &amp;&amp; $_POST["Amount2"] &gt; 0) { $PricePer = mysql_real_escape_string($_POST["price2"]); $Amount = mysql_real_escape_string($_POST["Amount2"]); $X = $PricePer * $Amount; $Total = file_get_contents("/system/calculatefees.php?P=" . $X); $Fees = file_get_contents("/system/calculatefees2.php?P=" . $X); $user_id = $loggedInUser-&gt;user_id; if(TakeMoney($Total,$user_id,$Currency_1) == true) { AddMoney($Fees,101,$Currency_1); mysql_query("INSERT INTO trades (`To`,`From`,`Amount`,`Value`,`User_ID`,`Type`,`Fee`,`Total`)VALUES ('$name','$Currency_1a','$Amount','$PricePer','$user_id','$name','$Fees','$Total');"); } else { echo "&lt;p class='notify-red' id='notify'&gt;You cannot afford that!&lt;/p&gt;"; } } else { echo "&lt;p class='notify-red' id='notify'&gt;Please fill in all the forms!!&lt;/p&gt;"; } } //-------------------------------------- if (isset($_GET["cancel"])) { $ids = mysql_real_escape_string($_GET["cancel"]); $tradesql = @mysql_query("SELECT * FROM trades WHERE `Id`='$ids'"); $from = @mysql_result($tradesql, 0, "From"); $owner = @mysql_result($tradesql, 0, "User_ID"); $Fee = @mysql_result($tradesql,0,"Fee"); $Total = @mysql_result($tradesql,0,"Total"); $sql = mysql_query("SELECT * FROM Wallets WHERE `Acronymn`='$from'"); $from_id = mysql_result($sql,0,"Id"); if(TakeMoney($Fee,101,$from_id,true) == true) { AddMoney($Total,$owner,$from_id); } else { echo "&lt;p class='notify-red' id='notify'&gt;You cannot afford that!&lt;/p&gt;"; } mysql_query("DELETE FROM trades WHERE `Id`='$ids'"); } //-------------------------------------- if(isset($_POST["Amount"])) { if ($_POST["price1"] &gt; 0 &amp;&amp; $_POST["Amount"] &gt; 0) { $PricePer = mysql_real_escape_string($_POST["price1"]); $Amount = mysql_real_escape_string($_POST["Amount"]); $Fees = file_get_contents("/system/calculatefees2.php?P=" . $Amount); $Total = $Fees + $Amount; echo $Total; $user_id = $loggedInUser-&gt;user_id; if(TakeMoney($Total,$user_id,$id) == true) { AddMoney($Fees,101,$id); mysql_query("INSERT INTO trades (`To`,`From`,`Amount`,`Value`,`User_ID`,`Type`,`Fee`,`Total`)VALUES ('$Currency_1a','$name','$Amount','$PricePer','$user_id','$name','$Fees','$Total');"); } else { echo "&lt;p class='notify-red' id='notify'&gt;You cannot afford that!&lt;/p&gt;"; } } else { echo "&lt;p class='notify-red' id='notify'&gt;Please fill in all the forms!!&lt;/p&gt;"; } } ?&gt; &lt;link rel="stylesheet" type="text/css" href="../assets/css/trade.css" /&gt; &lt;link href="assets/css/tables.css" type="text/css" rel="stylesheet" /&gt; &lt;center&gt;&lt;h3&gt;Trade &lt;?php echo $fullname; ?&gt;&lt;/h3&gt;&lt;/center&gt; &lt;div id="chart"&gt; &lt;script src="../assets/charts/effects.js"&gt;&lt;/script&gt; &lt;script src="../assets/charts/Chart.js"&gt;&lt;/script&gt; &lt;script src="../assets/charts/excanvas.js"&gt;&lt;/script&gt; &lt;meta name = "viewport" content = "initial-scale = 1, user-scalable = no"&gt; &lt;canvas id="canvas" height="400" width="700" style="background: #333; margin: 0 auto;" &gt;&lt;/canvas&gt; &lt;script&gt; var lineChartData = { labels : ["1 Week","24 Hour","8 Hour","4 Hour","2 Hour","1 Hour","Last Trade"], datasets : [ { //Coin A strokeColor : "#fff", pointColor : "#000", pointStrokeColor : "#fff", data : [&lt;?php echo $trade_data; ?&gt;] } ] } var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData); &lt;/script&gt; &lt;/body&gt; &lt;/div&gt; &lt;div id="boxB"&gt; &lt;div id="boxA"&gt; &lt;div id="col1"&gt; &lt;!-- Sell Form--&gt; &lt;?php if (isUserLoggedIn()) { ?&gt; &lt;div id="sellform" &gt; &lt;center&gt;&lt;h2&gt;Sell &lt;?php echo $name; ?&gt;&lt;/h2&gt;&lt;/center&gt; &lt;form action="index.php?page=trade&amp;market=&lt;?php echo $id; ?&gt;" method="POST" autocomplete="off" history="off"&gt; &lt;label&gt;Amount:&lt;/label&gt;&lt;input type="text" style="width:100px;" name="Amount" onKeyUp="calculateFees1(this)" id="Amount"/&gt; &lt;label&gt;Price:&lt;/label&gt;&lt;input type="text" style="width:100px;" name="price1" onKeyUp="calculateFees1(this)" id="price1" /&gt; &lt;label&gt;Receive:&lt;/label&gt;&lt;input type="text" style="width:100px;" id="earn1"/&gt; &lt;label&gt;Total:&lt;/label&gt;&lt;input type="text" style="width:100px;" id="fee1"/&gt; &lt;label&gt;Execute:&lt;/label&gt;&lt;input type="submit" name="Sell" value="Sell"/&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;!--Sell Order Book--&gt; &lt;div id="sellorders"&gt; &lt;?php include("open_orders_from.php"); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="col2"&gt; &lt;!--Buy Form--&gt; &lt;?php if (isUserLoggedIn()) { ?&gt; &lt;div id="buyform"&gt; &lt;center&gt;&lt;h2&gt;Buy &lt;?php echo $name; ?&gt;&lt;/h2&gt;&lt;/center&gt; &lt;form action="index.php?page=trade&amp;market=&lt;?php echo $id; ?&gt;" method="POST" autocomplete="off" history="off"&gt; &lt;label&gt;Amount:&lt;/label&gt;&lt;input type="text" style="width:100px;" onKeyUp="calculateFees2()" name="Amount2" id="Amount2"/&gt; &lt;label&gt;Price:&lt;/label&gt;&lt;input type="text" style="width:100px;" id="price2" onKeyUp="calculateFees2()" onKeyUp="calculateFees2()" name="price2"/&gt; &lt;label&gt;Total:&lt;/label&gt;&lt;input type="text" style="width:100px;" id="fee2"/&gt; &lt;label&gt;Execute:&lt;/label&gt;&lt;input type="submit" name="Buy" id="Buy" value="Buy"/&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;!--Buy Order Book--&gt; &lt;div id="buyorders"&gt; &lt;?php include("open_orders_to.php"); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php if (isUserLoggedIn()) { ?&gt; &lt;div id="user-orders"&gt; &lt;?php include("open_orders.php"); ?&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p><strong>Generation of Market list/Last price in index.php</strong></p> <pre><code>&lt;ul id="market-list"&gt; &lt;?php $sql = mysql_query("SELECT * FROM Wallets ORDER BY `Acronymn` ASC"); while ($row = mysql_fetch_assoc($sql)) { if($row["Market_Id"] == 0) { } else { $sql_2 = mysql_query("SELECT * FROM Trade_History WHERE `Market_Id`='". $row["Id"] . "' ORDER BY Timestamp DESC"); $last_trade = mysql_result($sql_2,0,"Price"); ?&gt; &lt;li&gt;&lt;a href='index.php?page=trade&amp;market=&lt;?php echo $row["Id"]; ?&gt;'&gt;&lt;?php echo $row["Acronymn"]; ?&gt; &amp;rarr; BTC &lt;?php echo "&lt;font class='price'&gt;".sprintf("%2.8f",$last_trade)."&lt;/font&gt;"; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } } ?&gt; &lt;/ul&gt; </code></pre> <p><strong>Chat</strong> from index.php</p> <p> </p> <pre><code>&lt;div id="messages"&gt;&lt;/div&gt; &lt;?php //check if user is banned. //check if user is logged in then display forms. if (isUserLoggedIn()){ $username = $loggedInUser-&gt;display_username; //define color of usernames. if(!isUserAdmin($id)) { $color = "#999999"; }else{ $color = "#FF9900"; } echo' &lt;form id="ajaxPOST" history="off" autocomplete="off"&gt; &lt;input type="hidden" value="'.$color.'" name="color" /&gt; &lt;input type="hidden" value="'.$username.'" name="username" /&gt; &lt;input type="text" id="message" maxlength="255" name="message" /&gt; &lt;input type="submit" id="chat-submit" value="Post Message" /&gt; &lt;/form&gt;'; } else { echo' &lt;div id="LoggedOut"&gt;&lt;/br&gt;&lt;b&gt;&lt;center&gt;You must be logged in to chat&lt;/center&gt;&lt;/b&gt;&lt;/div&gt;'; } ?&gt; &lt;/div&gt; </code></pre> <p><strong>jQuery code (index.php)</strong></p> <pre><code>$(document).ready(function() { //load messages $('#messages').load('chat/ajaxLOAD.php'); $('#ajaxPOST').submit(function() { $.post('chat/ajaxPOST.php', $('#ajaxPOST').serialize(), function(data){ //clear the message field $('#message').val(''); //reload messages $('#messages').delay(1000).load('chat/ajaxLOAD.php').delay(1000).scrollTop($("#messages")[0].scrollHeight); }); return false; }); }); </code></pre> <p><strong>ajaxPOST.php</strong></p> <pre><code>include 'chat.config.php'; $color = $_POST['color']; $username = $_POST['username']; $message = $_POST['message']; if ($_POST['message'] == null) { }else{ $db-&gt;Query("INSERT INTO messages (color, username, message) VALUES ('".$color."','".$username."','".$message."')"); } </code></pre> <p><strong>ajaxLOAD.php</strong></p> <pre><code> include 'chat.config.php'; $db-&gt;query('SELECT * FROM messages ORDER BY (id) ASC'); $data = $db-&gt;GET(); foreach($data as $key =&gt; $value) { echo "&lt;li id='msg_row'&gt;&lt;b style='color: ".$value['color'].";'&gt;".$value['username']."&lt;/b&gt; : &lt;i&gt;".$value['message']."&lt;/i&gt;&lt;/li&gt;"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T02:01:13.017", "Id": "58235", "Score": "4", "body": "[**Don't use `mysql_*` functions in new code!**](http://stackoverflow.com/q/12859942/1667018)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T02:09:32.210", "Id": "58237", "Score": "0", "body": "why? pdo seems scary to me, and would require us to rewrite the entire application. is what we're doing not safe enough already to prevent injections?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T02:54:09.690", "Id": "58240", "Score": "2", "body": "Let me quote from the link I have provided in my first comment: ***Officially [deprecated](https://wiki.php.net/rfc/mysql_deprecation)** (as of PHP 5.5. It's likely to be removed in the next major release.)* There is much more, so please check the accepted answer where this points to. Why would a professional programmer be afraid of PDO? OOP's been around for 4 or 5 decades (depending on what you pick as the beginning)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T03:49:20.630", "Id": "58249", "Score": "0", "body": "I did read the link you provided, as well as one that was posted in a similar topic about switching to PDO, and i will gradually migrate toward using it as i learn and grow as a programmer. However, my question was not on the deprecation of mysql functions or about PDO. i asked for any vulnerabilities i might have missed in the code, or any i do not know about. For the record, i haven't even started college yet, so maybe that will help you understand where i'm coming from. I don't have any formal education in programming at this time, just self taught/trial and error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:49:51.010", "Id": "58340", "Score": "0", "body": "Can we see the full query in `GetMoney`? - it appears to have been abbreviated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:44:04.830", "Id": "58406", "Score": "0", "body": "yeah, i'll add it real quick. fighting with some jquery atm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:47:29.883", "Id": "58408", "Score": "0", "body": "What happens when `$currency = \"'\"`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:09:38.367", "Id": "58416", "Score": "0", "body": "this function selects the users balance from the balances table. the logic below adds or subtracts from the value in the balance of whatever coin = (id). its kind of hard to explain, but so far trading works as its supposed to. for a live demo see [https://openex.pw](https://openex.pw) username `testing123` password `12345678`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T00:25:02.737", "Id": "58494", "Score": "2", "body": "Using PDO instead of mysql_* _is_ a security improvement! You should *always* construct queries with [placeholders for parameters](http://www.php.net/manual/en/pdostatement.execute.php), and *never* using string interpolation or concatenation. If you blindly incorporate data strings into your SQL without escaping, the data could be interpreted as code, a.k.a an SQL injection vulnerability. See http://bobby-tables.com" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T07:18:15.903", "Id": "58531", "Score": "0", "body": "in accordance with the suggestions of Verdran and others, i have moved away from mysql to mysqli in my latest code. i will update the post for peer review/advice. thanks for being helpful guys. i gotta admit using OOP mysqli is a dream compared to mysql." } ]
[ { "body": "<p>There's quite a few things you can fix here. If it is not already in version control, do that <em>first</em>, and then do a commit for every improvement; that way, if anything goes wrong, you can roll back easily. Git is good, but use whatever you know.</p>\n\n<p>Firstly, the business logic and the page layout need to be separated. Many a tutorial on the web mixes the two up, perhaps because many years ago programmers were just too thrilled with the web's possibilities to remember the benefits of modularisation. So, at the very least, move the first half of the code to a separate file, and then <code>require</code> it in your first line.</p>\n\n<p>That becomes your 'logic' file. Whilst you appear to have a few functions in your logic file, the bulk of this is not split into functions at all, and ought to be. There are too many variables sitting in \"global space\" that need to be local to a function; this will destroy them when each function ends, which is what we want. That said, a few will need to persist in order to be displayed in your HTML layout; potentially they could be the results of functions, although there are several ways to do it.</p>\n\n<p>One step better would be to use a templating engine of some kind, so that your business logic is wrapped up nicely in objects. However, that might be a case of trying to learn too many things at once, so perhaps leave this one for the time being.</p>\n\n<p>In terms of the logic itself, try to avoid the <code>@</code> error suppression operator, since it will hide problems from you during development. It is better to test intermediate database operations (from connection, then from the query, then from reading results) and just output an error gracefully.</p>\n\n<p>I noticed also that the <code>if</code> clause in <code>GetMoney</code> has two paths that do exactly the same thing. You may wish to check this.</p>\n\n<p>Where you do a financial transaction, this must be in a database transaction to avoid something being being debited without a corresponding credit - you want this so either everything completes or nothing does.</p>\n\n<p>The <code>file_get_contents</code> refers to an absolute pathname rather than something in the current project. It is better to obtain this path from a configuration file, rather than \"hardwiring\" it into code. Also, this appears to be a PHP file - note that this PHP will <em>not</em> be run to generate data - <code>file_get_contents</code> will treat it just like a text file.</p>\n\n<hr>\n\n<p>For the template part (essentially the second half of your code) you may find using the colon form of statements easier to read. As you've discovered, braces do work here, but <code>&lt;?php if (isUserLoggedIn()): ?&gt;</code> and <code>&lt;?php endif ?&gt;</code> is much clearer.</p>\n\n<p>I notice from your live demo that you do not have a DOCTYPE, which means your document will not be treated as standards-based. Just add <code>&lt;!DOCTYPE html&gt;</code> to the first line (assuming you are targetting HTML5) and this will be fixed.</p>\n\n<p>The tag <code>&lt;/br&gt;</code> is not valid markup - I think you meant the self-closing tag <code>&lt;br /&gt;</code>.</p>\n\n<p>The link tag <code>&lt;a href='index.php?page=trade&amp;market=6'&gt;</code> is not valid; you need to encode the special characters. Thus, it should be <code>&lt;a href='index.php?page=trade&amp;amp;market=6'&gt;</code>. See the \"View Source\" in Firefox - items it does not understand are shaded in red.</p>\n\n<p>Avoid the <code>&lt;font&gt;</code> tag completely; use <code>&lt;span&gt;</code> with a style class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T07:10:22.247", "Id": "58530", "Score": "0", "body": "wow, thats a lengthy list. question, on the link tags. why does it even matter? and secondly this is dynamic content generated from a database query. i've added that portion of index.php to my original post. are you suggesting i add the html entity code for \"&\" like `&amp;` . won't that break my url/code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T09:26:56.837", "Id": "58543", "Score": "0", "body": "In your template code, it looks like you could just write the entity explicitly. If you have a URL in a string, then in your template file you can also do `<?php echo htmlspecialchars($url) ?>` and that will do the trick as well. It won't break your URL, no; the ampersand entity is understood as being a single character, the ampersand. If it is supplied \"bare\" then the browser will assume it is the start of an entity, but that it was unfinished. Whilst in most cases the browser will work out what you mean, it is much better to be clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T09:30:17.507", "Id": "58544", "Score": "0", "body": "Btw, you can check the above by running your document through the W3C validator - it will pick up this error, the DOCTYPE thing, plus any others I missed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:03:51.333", "Id": "58552", "Score": "0", "body": "template code? what do you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:50:29.347", "Id": "58558", "Score": "0", "body": "Heh, I saw the earlier version of that comment `;)`, but you misunderstood it. The \"template\" is a common name given to the browser output part of your code, in the same context as \"[template engine](https://en.wikipedia.org/wiki/Template_processor)\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T13:17:46.117", "Id": "58580", "Score": "0", "body": "forgive me lol, i don't speak the \"lingo\" yet. i just call html = html, js = js, php = php. no need for confusion. guess i'm pretty alone in that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T13:26:33.407", "Id": "58581", "Score": "0", "body": "No problem. A template _contains_ HTML markup, but it's not the same thing. Read the Wikipedia article I linked to for more info. Incidentally, I wrote a [very simple template system](https://github.com/halfer/TemplateSystem), which I use for an MVC-like approach to organising code. It's not a replacement for a fully-featured system like Smarty or Twig, but it may be helpful in terms of understanding what a template engine does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T14:36:51.080", "Id": "58587", "Score": "0", "body": "oh, i just now got what you were saying. yeah, i use userCake 1.4 template system. i guess i should just be separating functions and moving them into the models folder, but for now we are building. we can worry about cleanliness when we cross that bridge lol. i do appreciate your advice though." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T23:13:06.587", "Id": "35889", "ParentId": "35645", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:47:58.713", "Id": "35645", "Score": "1", "Tags": [ "php", "mysql", "security", "finance" ], "Title": "Online virtual currency exchange" }
35645
<p>This code section is from the main method of my Annual Fuel Use class. The program projects my annual fuel usage based on at least three fill ups of my car. Here, I am calculating the max and min for distance (which is miles traveled), MPG, and price per gallon. I'd like a general review.</p> <pre><code>//initialization of array of objects AnnualFuelUse[] fillUps = {new AnnualFuelUse (1, 1, 6500, 6800, 9.70, 3.11), new AnnualFuelUse (2, 10, 6800, 7052, 8.10, 3.08), new AnnualFuelUse (3, 20, 7052, 7349, 9.20, 3.15)}; //calculate Min and Max for distance, MPG, and price per gallon double minDist = 0, maxDist = 0; double minMPG = 0.0, maxMPG = 0.0, minPrice = 0.0, maxPrice = 0.0; Double dMin = Double.MAX_VALUE; Double dMax = Double.MIN_VALUE; Double mpgMin = Double.MAX_VALUE; Double mpgMax = Double.MIN_VALUE; Double priceMin = Double.MAX_VALUE; Double priceMax = Double.MIN_VALUE; for (int i = 0; i &lt; fillUps.length; i++) { if (fillUps[i].getDist() &lt; dMin){ dMin = fillUps[i].getDist(); minDist = dMin; } if (fillUps[i].getDist() &gt; dMax) { dMax = fillUps[i].getDist(); maxDist = dMax; } if (fillUps[i].getMilesPerGallon() &lt; mpgMin) { mpgMin = fillUps[i].getMilesPerGallon(); minMPG = mpgMin; } if (fillUps[i].getMilesPerGallon() &gt; mpgMax) { mpgMax = fillUps[i].getMilesPerGallon(); maxMPG = mpgMax; } if (fillUps[i].getPrice() &lt; priceMin) { priceMin = fillUps[i].getPrice(); minPrice = priceMin; } if (fillUps[i].getPrice() &gt; priceMax) { priceMax = fillUps[i].getPrice(); maxPrice = priceMax; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T01:11:21.047", "Id": "57894", "Score": "0", "body": "You forgot to change some of your `>` to `<`. As per [your StackOverflow question](http://stackoverflow.com/questions/20060321/java-erromax-and-min-of-array-object-data/20060373#20060373)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T01:21:38.387", "Id": "57895", "Score": "0", "body": "I take your suggestion, forgot to change it when I pasted... haha thanks!" } ]
[ { "body": "<p>The code violates <a href=\"http://pragprog.com/articles/tell-dont-ask\" rel=\"nofollow\">Tell, Don't Ask</a>:</p>\n\n<blockquote>\n <p>Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.\n ~Alec Sharp</p>\n</blockquote>\n\n<p>Before we get to that, consider:</p>\n\n<pre><code>fillUps[i].getDist() &gt; dMin\n</code></pre>\n\n<p>Can be written:</p>\n\n<pre><code>fillUps[i].canTravel( dMin )\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>fillUps[i].getPrice() &gt; priceMax\n</code></pre>\n\n<p>Can be written:</p>\n\n<pre><code>fillUps[i].priceExceeds( priceMax );\n</code></pre>\n\n<p>The important question remains unanswered: <em>why</em> does the code check against distance and price? If all you want to do is determine how much it will cost on a given tank of gas, then write:</p>\n\n<pre><code>float maxDistance = fillUps[i].calculateDistance();\n</code></pre>\n\n<p>If you want to know the price to fill the remainder of the tank, write:</p>\n\n<pre><code>float price = fillUps[i].calculateFillPrice();\n</code></pre>\n\n<p>Move the code that uses the variables into the class that has the variables.</p>\n\n<p>You can also compare objects, rather than the internal variables. For example:</p>\n\n<pre><code>AnnualFuelUse fillUps[] // ...\nAnnualFuelUse minPriceFillUp;\n\nfor (int i = 0; i &lt; fillUps.length; i++) {\n if( fillUps[i].exceedsPrice( fillUps[i-1] ) ) {\n maxPriceFillUp = fillUps[i];\n }\n\n if( fillUps[i].exceedsDistance( fillUps[i-1] ) ) {\n maxDistanceFillUp = fillUps[i];\n }\n\n // ...\n}\n</code></pre>\n\n<p>At the end of the loop you'll have <em>objects</em> that contain the desired information. With those objects you can then ask them to perform specific tasks. Then make the get accessor methods <code>private</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T04:48:18.800", "Id": "58674", "Score": "0", "body": "+1. \"Ask, don't Tell\" is a fundamental perspective for writing Object Oriented code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T00:44:54.787", "Id": "35650", "ParentId": "35647", "Score": "4" } }, { "body": "<p>Each and every one of your if-statements can be simplified.</p>\n\n<pre><code>if (fillUps[i].getDist() &gt; dMin){\n dMin = fillUps[i].getDist();\n minDist = dMin;\n}\n</code></pre>\n\n<p>First of all, since you modify two variables at the same time, you can write it on the same line.</p>\n\n<pre><code>if (fillUps[i].getDist() &gt; dMin){\n minDist = dMin = fillUps[i].getDist();\n}\n</code></pre>\n\n<p>However, this is a sign that you might have too many variables, since <code>minDist</code> is the same as <code>dMin</code>. I would keep the variables of primitive type <code>double</code> and get rid of the not-primitive variables. Since <code>Double.MAX_VALUE</code> and <code>Double.MIN_VALUE</code> is a regular <code>double</code>, I don't see the need for the <code>Double</code> type. Just be sure to initialize your min/max variables properly (<code>Double.MIN_VALUE</code> or <code>Double.MAX_VALUE</code>).</p>\n\n<p>And then, what you are doing is to always get the minimum of two values, so this can be simplified by using the <code>Math.min</code> method.</p>\n\n<pre><code>minDist = Math.min(fillUps[i].getDist(), minDist);\n</code></pre>\n\n<p>So each of your four-line if-statement segments can each become one line!</p>\n\n<pre><code>for (int i = 0; i &lt; fillUps.length; i++) {\n minDist = Math.min(fillUps[i].getDist(), minDist);\n maxDist = Math.max(fillUps[i].getDist(), maxDist);\n minMPG = Math.min(fillUps[i].getMilesPerGallon(), minMPG);\n maxMPG = Math.max(fillUps[i].getMilesPerGallon(), maxMPG);\n minPrice = Math.min(fillUps[i].getPrice(), minPrice);\n maxPrice = Math.max(fillUps[i].getPrice(), maxPrice);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T01:12:19.863", "Id": "35652", "ParentId": "35647", "Score": "4" } } ]
{ "AcceptedAnswerId": "35652", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T00:13:28.310", "Id": "35647", "Score": "7", "Tags": [ "java", "object-oriented" ], "Title": "Calculating min and max with if-statements within a for-loop" }
35647
<p>My homework is to make a program that calculates the total value of products sold. It works, but I use the <code>if</code> statement because it was asking for the quantity on the output before ending the loop. And for the same reason, I couldn't make the program ask the user again to enter a number from 1 to 5.</p> <pre><code>import java.util.Scanner; public class Sales { public static void main(String[] args) { Scanner input = new Scanner(System.in); double sum = 0; int n = -1 ; while(n !=0 ) { System.out.println("Enter product number 1-5 (Enter to stop)"); n = input.nextInt(); if (n==0) break; System.out.println("Enter quantity of product"); int q = input.nextInt(); switch (n) { case 1: sum += 2.98*q; break; case 2: sum += 4.50*q; break; case 3: sum += 9.98*q; break; case 4: sum += 4.49*q; break; case 5: sum += 6.87*q; break; default: sum += 0; break; } } System.out.printf("Total cost is $%.2f",sum); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Prefer not to use single characters as variable names (except for simple loop counters). Saving a few keystrokes is not worth it if your readers cannot understand your code.</p>\n\n<p>Based on the context, it looks like <code>n</code> and <code>q</code> should respectively be named <code>productNumber</code> and <code>productQuantity</code>.</p></li>\n<li><p>The <code>sum += 0</code> in the <code>default</code> looks unnecessary. Just remove it if so, even if it's only there to have the <code>default</code> do something. Keep things simple.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:33:51.997", "Id": "57902", "Score": "3", "body": "`Saving a few keystrokes is not worth it if your readers cannot understand the code` - well said!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:00:54.773", "Id": "35654", "ParentId": "35649", "Score": "4" } }, { "body": "<p>A slighty longer answer:</p>\n\n<pre><code>import java.util.InputMismatchException;\nimport java.util.Scanner;\n\n/**\n * Calculates the sum of given products.\n */\npublic class ProductSumCalculator {\n\n /**\n * Represents a product with a price.\n */\n protected enum Product {\n APPLE(1, \"Apple\", 2.98d),\n BANANA(2, \"Banana\", 4.50d),\n MANGO(3, \"Mango\", 9.98d),\n PINEAPPLE(4, \"Pineapple\", 4.49),\n CHERRY(5, \"Cherry\", 6.87);\n\n protected double price;\n\n protected int productNumber;\n\n protected String productTitle;\n\n private Product(int productNumber, String productTitle, double price) {\n this.price = price;\n this.productNumber = productNumber;\n this.productTitle = productTitle;\n }\n\n public static Product getByNumber(int number) {\n for (Product product : values()) {\n if (product.productNumber == number) {\n return product;\n }\n }\n return null;\n }\n\n @Override\n public String toString() {\n return productNumber + \" - \" + productTitle + \" - \" + String.format(\"$%.2f\", price);\n }\n }\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n try {\n double sum = 0.0d;\n\n int input = -1;\n\n while (input != 0) {\n System.out.println(\"Please make your choice: \");\n for (Product product : Product.values()) {\n System.out.println(product);\n }\n System.out.println(\"0 - Quit and show sum\");\n\n input = readNumberInput(scanner);\n\n if (input == 0) {\n break;\n }\n\n if (input != -1) {\n Product product = Product.getByNumber(input);\n\n if (product == null) {\n System.out.println(\"The entered product number was not correct. Please try again.\");\n } else {\n System.out.println(\"Enter quantity of product [\" + product.productTitle + \"]:\");\n\n input = readNumberInput(scanner);\n\n if (input &gt; 0) {\n sum += product.price * input;\n }\n }\n }\n }\n\n System.out.println(\"Total sum of all the chosen products is: \" + String.format(\"$%.2f\", sum));\n } finally {\n scanner.close();\n }\n }\n\n /**\n * Reads a number from a scanner instance and catches erroneous input.\n * \n * @param scanner\n * @return\n */\n private static int readNumberInput(Scanner scanner) {\n try {\n return scanner.nextInt();\n } catch (InputMismatchException ex) {\n String inputString = scanner.next();\n System.out.println(\"Input [\" + inputString + \"] was not correct. Please choose a number.\");\n return -1;\n }\n }\n}\n</code></pre>\n\n<p>Let's run over this code, shall we:</p>\n\n<ul>\n<li>I created an enum of 'Product' so that you can easily add/remove products and change their number, title or price and so that your main code doesn't have to change when adding/removing products</li>\n<li>Overridden the toString method of a Product so you can print them out in the program</li>\n<li>Validate the input from the user (ALWAYS validate input from the user)</li>\n<li>Closed the scanner instance (ALWAYS close your resources when possible)</li>\n<li>Added more clear instructions for the user with better guidance through the 'program'</li>\n</ul>\n\n<p>I know it's a stupid little program, but it's an easy example of how your code will be able to change more easily later on, by adding/removing products, validating user input, etc... The one thing I could have added is more documentation, but in this case it's very trivial :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:14:09.457", "Id": "35698", "ParentId": "35649", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T00:43:28.103", "Id": "35649", "Score": "2", "Tags": [ "java", "homework" ], "Title": "Calculating a total price by using switch statement and sentinel controlled loop" }
35649
<p>Below is my implementation for an interview question of printing a binary tree level by level. I've also included some methods for creating a binary tree from a vector in my solution. Please review my solution.</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;type_traits&gt; template &lt;typename T&gt; struct Node { T data; Node&lt;T&gt;* left; Node&lt;T&gt;* right; Node (T d, Node&lt;T&gt;* l = nullptr, Node&lt;T&gt;* r = nullptr) : data(d), left(l), right(r) {} }; template&lt;typename T&gt; void deleteTree ( Node&lt;T&gt;* n) { if ( !n ) return; deleteTree(n-&gt;left); deleteTree(n-&gt;right); delete n; } template &lt;typename T&gt; void printBinaryTree (Node&lt;T&gt;* n ) { std::unordered_map&lt;int, std::vector&lt;Node&lt;T&gt;*&gt; &gt; m; printBinaryTree (n, m, 0); for ( auto&amp; i : m ) { std::cout &lt;&lt; " Level " &lt;&lt; i.first &lt;&lt; ": "; for ( auto&amp; j : i.second ) std::cout &lt;&lt; j-&gt;data &lt;&lt; " "; } std::cout &lt;&lt; std::endl; } // print a binary tree level by level template &lt;typename T&gt; void printBinaryTree (Node&lt;T&gt;* n, std::unordered_map&lt;int, std::vector&lt;Node&lt;T&gt;*&gt; &gt;&amp; m, int level ) { if (n) { ++level; printBinaryTree ( n-&gt;left ,m,level); printBinaryTree ( n-&gt;right,m,level); m[level].push_back(n); } } template &lt;typename ItType&gt; auto buildBinaryTree (ItType start, ItType end) -&gt; Node&lt;typename std::iterator_traits&lt;ItType&gt;::value_type&gt;* { using T =typename std::iterator_traits&lt;ItType&gt;::value_type; auto first = start; auto last = std::prev(end); if ( first &gt; last ) // error case return nullptr; else if ( first &lt; last ) { auto mid = first + ( last - first ) / 2; // avoid overflow Node&lt;T&gt;* n = new Node&lt;T&gt;(*mid); n-&gt;left = buildBinaryTree ( first, mid); n-&gt;right = buildBinaryTree ( mid+1, end); return n; } // equal return new Node&lt;T&gt;(*first); } template &lt;typename T&gt; Node&lt;T&gt;* buildBinaryTree (std::vector&lt;T&gt;&amp; v) { if ( v.empty() ) return nullptr; std::sort(v.begin(), v.end()); return buildBinaryTree (v.begin(), v.end()); } int main() { std::vector&lt;int&gt; v { 1,2,3,4,5,6,7,8,9,10 }; Node&lt;int&gt;* root = buildBinaryTree ( v ); printBinaryTree (root); deleteTree(root); } </code></pre>
[]
[ { "body": "<ol>\n<li><p>You should only use single letter variable names for loop variables. Parameters and other local variables should have more descriptive names. For example when I first quickly glanced over the code I saw this <code>printBinaryTree (n, m, 0);</code> and thought <em>&quot;Strange, why is he passing in two nodes?&quot;</em> associating that <code>m</code> has a similar meaning to <code>n</code>. I had to look again before I realized that <code>m</code> is actually a map. Using names like <code>node</code> or <code>map</code> would result in easier readability.</p>\n</li>\n<li><p><code>void printBinaryTree (Node&lt;T&gt;* n, std::unordered_map&lt;int, std::vector&lt;Node&lt;T&gt;*&gt; &gt;&amp; m, int level)</code> does not print the tree and should therefor not be named such. It collects all nodes on the same level. Better name might have been <code>buildLevelMap</code></p>\n</li>\n<li><p><code>buildBinaryTree</code> apparently expects that the elements to be inserted are in order. You swallow the error case by simply returning a <code>nullptr</code>. You should throw an exception instead to make it clear to the caller that this is invalid input.</p>\n</li>\n<li><p>You represent a binary tree by a reference to a node which happens to be the root. However if the caller accidentally replaces it with a reference to a different node memory leaks because some part of the tree is now lost.</p>\n<p>You should encapsulate the tree in a class like <code>BinaryTree</code> which handles the construction of the tree in the constructor or through a factory method and handles the deletion of the nodes in it's destructor. This way the user can pass around an instance of the tree and not even care about how you store the data internally which facilitates encapsulation (although in a templated class this becomes somewhat a moot point). It would also result in more idiomatic C++ by creating an object through a constructor and destroying an object via a destructor rather than calling a delete function.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:50:48.720", "Id": "57996", "Score": "0", "body": "Thanks for the comments, this is helpful. Regarding #3, I call a sort to make sure the items are in order. I could throw an exception or have clients handle the null case. In #4, it is fine if they pass an arbitrary node to represent root, it will be treated as root in that case. Definitely could have encapsulated the binary tree and had the destructor handle clean up and was thinking this when creating the deleteMethod. Agree on the naming an variables, good call. +1 upvote for helpful comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:49:19.293", "Id": "35682", "ParentId": "35656", "Score": "4" } }, { "body": "<p>I got the following output:</p>\n\n<blockquote>\n<pre><code>Level 1: 5 Level 2: 2 8 Level 4: 4 7 10 Level 3: 1 3 6 9\n</code></pre>\n</blockquote>\n\n<p>Printing the <strong>layers in a non-deterministic order</strong> is probably undesirable behaviour. You used an <code>unordered_map</code>, which guarantees the order of neither its keys nor its values. To impose order on the values (the nodes of each level), you store a <code>vector</code> in the map, which complicates the data structure.</p>\n\n<p>The traditional way to do a <strong>breadth-first traversal</strong> of a tree is to use a <strong>queue</strong>, and to work iteratively on elements of the queue rather than recursively on elements of the tree. Not only is this a less complex data structure than an unordered map of ints to vectors of nodes, it also stores nodes from no more than two levels of the tree at a time, rather than all nodes of the tree at once.</p>\n\n<pre><code>#include &lt;queue&gt;\n#include &lt;utility&gt; // for std::pair\n\ntemplate &lt;typename T&gt;\nvoid printBinaryTree(const Node&lt;T&gt; *n) {\n if (nullptr == n) {\n return;\n }\n int level = 0;\n\n // Use a queue for breadth-first traversal of the tree. The pair is\n // to keep track of the depth of each node. (Depth of root node is 1.)\n typedef std::pair&lt;const Node&lt;T&gt;*,int&gt; node_level;\n std::queue&lt;node_level&gt; q;\n q.push(node_level(n, 1));\n\n while (!q.empty()) {\n node_level nl = q.front();\n q.pop();\n if (nullptr != (n = nl.first)) {\n if (level != nl.second) {\n std::cout &lt;&lt; \" Level \" &lt;&lt; nl.second &lt;&lt; \": \";\n level = nl.second;\n }\n std::cout &lt;&lt; n-&gt;data &lt;&lt; ' ';\n q.push(node_level(n-&gt;left, 1 + level));\n q.push(node_level(n-&gt;right, 1 + level));\n }\n }\n std::cout &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>As a final touch, pay attention to the <strong>const-correctness</strong> of the function's parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:14:37.843", "Id": "58001", "Score": "0", "body": "I thought about the map v. unordered_map after posting, good call on that. Also, I like your solution a lot as it simplifies things and uses a standard traversal method. Thanks for sharing this with me. +1 and solution check." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T10:33:26.203", "Id": "35685", "ParentId": "35656", "Score": "8" } }, { "body": "<p>i have a easier code.......... consider a tree made of nodes of structure</p>\n\n<pre><code> struct treeNode{\n treeNode *lc;\n element data;\n short int bf;\n treeNode *rc;\n};\n</code></pre>\n\n<p>Tree's depth can be found out using</p>\n\n<pre><code>int depth(treeNode *p){\n if(p==NULL) return 0;\n int l=depth(p-&gt;lc);\n int r=depth(p-&gt;rc);\n if(l&gt;=r)\n return l+1;\n else\n return r+1;\n}\n</code></pre>\n\n<p>below gotoxy function moves your cursor to the desired position</p>\n\n<pre><code>void gotoxy(int x,int y)\n{\nprintf(\"%c[%d;%df\",0x1B,y,x);\n}\n</code></pre>\n\n<p>Then Printing a Tree can be done as:</p>\n\n<pre><code>void displayTreeUpDown(treeNode * root,int x,int y,int px=0){\nif(root==NULL) return;\ngotoxy(x,y);\nint a=abs(px-x)/2;\ncout&lt;&lt;root-&gt;data.key;\ndisplayTreeUpDown(root-&gt;lc,x-a,y+1,x);\ndisplayTreeUpDown(root-&gt;rc,x+a,y+1,x);\n}\n</code></pre>\n\n<p>which can be called using:</p>\n\n<pre><code>display(t,pow(2,depth(t)),1,1);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-29T02:26:04.323", "Id": "159217", "ParentId": "35656", "Score": "1" } } ]
{ "AcceptedAnswerId": "35685", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:09:59.637", "Id": "35656", "Score": "7", "Tags": [ "c++", "c++11", "interview-questions", "tree" ], "Title": "Printing out a binary tree level by level" }
35656
<p>I've written a program all by myself, but I just want to make sure I did it right and if anybody has any suggestions on improving it in any way.</p> <ol> <li><p>Define and implement the <code>Die</code> class depicted by the following UML diagram to create an ADT for one die (singular of dice) with faces showing values between 1 and the <code>numberOfFaces</code> on the die. Define a two-parameter constructor with defaults of 6 faces and 1 for face value. Define and implement a <code>roll()</code> method to simulate the rolling of the die by generating a random number between 1 and <code>numberOfFaces</code> and storing that number in <code>faceValue</code>. Provide an accessor to return the die’s face value and a <code>print()</code> method to print the die’s face value.</p></li> <li><p>Use composition to design a <code>PairOfDice</code> class, composed of two six-sided <code>Die</code> objects. Create a driver program with a <code>main()</code> function to rolls a <code>PairDice</code> object 1000 times, counting then displaying the number of snake eyes (i.e. two ones) and box cars (i.e. two sixes) that occur.</p></li> </ol> <p><strong>die.h</strong></p> <pre><code>#ifndef DIE_H #define DIE_H class die { private: int numberOfFaces; int faceValue; public: die(); die(int, int); int roll(); void print(); }; #endif </code></pre> <p><strong>die.cpp</strong></p> <pre><code>#include "die.h" #include&lt;iostream&gt; #include&lt;ctime&gt; #include&lt;random&gt; using namespace std; die::die() { numberOfFaces=6; faceValue=1; } die::die(int numOfFaces, int faceVal) { numberOfFaces=numOfFaces; faceValue=faceVal; } int die::roll() { faceValue=rand()%numberOfFaces; return faceValue; } void die::print() { cout &lt;&lt; faceValue &lt;&lt; endl; } </code></pre> <p><strong>pairOfDice.h</strong></p> <pre><code>#include "die.h" #ifndef PAIROFDICE_H #define PAIROFDICE_H class pairOfDice : public die { private: die die1; die die2; int value1; int value2; int total; public: pairOfDice(); int roll(); }; #endif </code></pre> <p><strong>pairOfDice.cpp</strong></p> <pre><code>#include "pairOfDice.h" pairOfDice::pairOfDice() :die(6,1) { value1=1; value2=1; total=value1+value2; } int pairOfDice::roll() { value1=die::roll(); value2=die::roll(); total=value1+value2; return total; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include"pairOfDice.h" #include&lt;iostream&gt; using namespace std; int main() { int rolls=0, total=0, snakeEyes=0, boxCars=0; pairOfDice dice; while(rolls&lt;1000) { total = dice.roll(); if(total==2) snakeEyes++; else if(total==6) boxCars++; else rolls++; } cout &lt;&lt; rolls &lt;&lt; " " &lt;&lt; snakeEyes &lt;&lt; " " &lt;&lt; boxCars &lt;&lt; endl; system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T05:54:49.600", "Id": "57908", "Score": "0", "body": "Where do you call `srand()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T15:19:50.283", "Id": "57943", "Score": "1", "body": "Prefer [std::uniform_int_distribution](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) to `rand` when it is available." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:45:13.053", "Id": "57995", "Score": "0", "body": "@Jamal i was calling it in the roll method of the dice class but i moved it right before the loop in the main program and that seemed to fix the problem. idk if thats the best solution though ..." } ]
[ { "body": "<p>That's not composition. That was inheritance, done poorly. The difference is, would you say that…</p>\n\n<ul>\n<li>A <code>pairOfDice</code> has two dice, but is not a die <em>(composition)</em>, or</li>\n<li>A <code>pairOfDice</code> is a loaded die <em>(inheritance)</em>?</li>\n</ul>\n\n<p>Since you declared <code>pairOfDice</code> to publicly inherit from <code>die</code>, you are treating a <code>pairOfDice</code> as a dodecahedron that is somehow weighted to produce a random distribution biased towards 6 or 7. I don't think you could produce such a physical object with just the right weight distribution. It could exist in your imagination though. Therefore, saying that <code>pairOfDice</code> <em>is</em> a <code>die</code> would be controversial modeling at best.</p>\n\n<h3>Composition</h3>\n\n<p>With composition, a <code>pairOfDice</code> contains two <code>die</code> members, but does not necessarily inherit from anything.</p>\n\n<pre><code>class pairOfDice {\nprivate:\n die die1;\n die die2;\npublic:\n pairOfDice() {};\n int roll();\n};\n\nint pairOfDice::roll() {\n int value1 = die1.roll();\n int value2 = die2.roll();\n return value1 + value2;\n}\n</code></pre>\n\n<p>That's all. Note that you should not store <code>value1</code>, <code>value2</code>, or <code>total</code>. All of that state is handled by the constituent <code>die1</code> and <code>die2</code> members.</p>\n\n<h3>Private Inheritance</h3>\n\n<p>C++ has a private inheritance feature, which could let you inherit the code for just one die, without letting anyone else know that you did so.</p>\n\n<pre><code>class pairOfDice : private die\n{\nprivate:\n die die2;\npublic:\n pairOfDice() {};\n int roll();\n};\n\nint pairOfDice::roll()\n{\n int value2 = die2.roll();\n return ((die *)this)-&gt;roll() + value2;\n}\n</code></pre>\n\n<p>The code above acts like the composition example. Attempting to do <code>pairOfDice dice; die *diePtr = &amp;dice;</code> would be a compilation error, since <code>pairOfDice</code> is not publicly a subclass of <code>die</code>. Private inheritance is an odd feature, and you would be better off doing pure composition instead.</p>\n\n<h3>Public Inheritance</h3>\n\n<p>With public inheritance, you would be treating <code>pairOfDice</code> as a kind of <code>die</code> — a loaded 12-sided die.</p>\n\n<pre><code>class pairOfDice : public die\n{\nprivate:\n die die2;\npublic:\n pairOfDice() {};\n int roll();\n};\n\nint pairOfDice::roll()\n{\n int value2 = die2.roll();\n return faceValue = ((die *)this)-&gt;roll() + value2;\n}\n</code></pre>\n\n<p>Note that <code>pairOfDice</code> must now support every operation that <code>die</code> supports, including <code>print()</code>. To ensure that <code>pairOfDice::print()</code> works, you must assign <code>faceValue</code> when rolling, and therefore the <code>faceValue</code> member of <code>die</code> must be changed from <code>private</code> to <code>protected</code> to support that. That illustrates a kind of fragility that comes with sharing code through inheritance: the subclass might accidentally inherit code that doesn't work quite right, and in a sense the subclass is patching the superclass code.</p>\n\n<p>The fragility of such an inheritance relationship is also a symptom of the fact that the inheritance was a long stretch of the imagination to start with (as discussed in the beginning of this review). Let's just say, inheritance, whether of the public or private sort, is not really appropriate for this situation.</p>\n\n<h3>A better hierarchy</h3>\n\n<p>Perhaps it would be best to have a virtual base class representing number generators.</p>\n\n<pre><code>template &lt;class T&gt;\nclass randgen {\npublic:\n virtual T roll() = 0;\n virtual void print() = 0;\n};\n\nclass die : public randgen&lt;int&gt; {\n ...\n};\n\nclass pairOfDice : public randgen&lt;int&gt; {\nprivate:\n die die1;\n die die2;\npublic:\n ...\n};\n</code></pre>\n\n<p>Everyone would agree that a <code>die</code> <em>is</em> a <code>randgen&lt;int&gt;</code> and that a <code>pairOfDice</code> also <em>is</em> a <code>randgen&lt;int&gt;</code>. With a common base class, it would be possible to have a <code>randgen&lt;int&gt;*</code> pointer that points to either a <code>die</code> or a <code>pairOfDice</code>. Finally, <code>pairOfDice</code> could be implemented using composition, which is the least error-prone way to reuse code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:07:30.333", "Id": "57912", "Score": "1", "body": "Regarding *\"Therefore, you would be better off using composition instead of inheritance as a code-reuse mechanism whenever possible\"* - I'd say if you use inheritance for the sole purpose of code reuse your abstraction is broken" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:00:08.163", "Id": "35668", "ParentId": "35663", "Score": "2" } }, { "body": "<p>Some miscellaneous remarks unrelated to object-oriented design:</p>\n\n<ul>\n<li><strong>Die face numbering:</strong> Your die face values are 0, 1, 2, 3, 4, 5. That's not how most people expect a six-sided die to be labeled. It also makes an exceptionally weird definition of rolling snake eyes!</li>\n<li><strong>Biased die:</strong> Since 6 is not a power of 2, if you just do <code>rand() % 6</code> then you have a <a href=\"https://stackoverflow.com/q/10984974/1157100\">slightly biased die</a>.</li>\n<li><strong>Roll miscount:</strong> You aren't rolling a pair of dice 1000 times. You're rolling a pair of dice until you get 1000 results other than 2 or 6. You could probably have avoided this bug if you had used a for-loop instead of a while-loop, since for-loops impose a standard structure on your code.</li>\n<li><strong>Variable declaration:</strong> In <code>main()</code>, the variable <code>total</code> is only used within the while-loop, so it should be declared at the point of use: <code>int total = dice.roll();</code></li>\n<li><strong>Seeding:</strong> You didn't actually call <code>srand()</code>.</li>\n<li><strong>Portability:</strong> <code>system(\"pause\")</code> is unportable.</li>\n<li><strong>ostream support:</strong> Consider implementing <code>std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, ...)</code> for printing.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:51:46.570", "Id": "57911", "Score": "0", "body": "Avoiding the roll miscount is a matter of putting `rolls++` on its own line, not part of the if statement. It's not a matter of a for loop being better or worse than a while loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:10:56.883", "Id": "57913", "Score": "1", "body": "@MichaelShaw: In this context a for loop is better because it puts the loop invariants in one place where it's easy to see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:18:44.887", "Id": "57914", "Score": "0", "body": "@MichaelShaw Of course you can fix the bug, but it would be better to address the root cause of the bug, so that you would be less likely to make such mistakes in the future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:28:48.053", "Id": "57916", "Score": "0", "body": "@200_success: But the root cause of the bug was not lack of a for loop or presence of a while loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:36:03.943", "Id": "35671", "ParentId": "35663", "Score": "5" } }, { "body": "<p>As mentioned, composition must be implemented in terms of members, not parents.</p>\n\n<p>You could use default arguments and only have one constructor rather than two. It would make the code simpler.</p>\n\n<p>The assignment also requested an accessor for face value. Make such side-effect free method <code>const</code>.</p>\n\n<p>I suggest not putting <code>Die</code> and <code>PairOfDice</code> in the same class hierachy. The only interface they could possibly share is <code>roll()</code>, and that is only if the return type is void. Use class hierachies for things that are polymorphic, i.e. where you intend for instances of both classes to be used the same way in the same code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:54:14.457", "Id": "35675", "ParentId": "35663", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T05:40:08.170", "Id": "35663", "Score": "1", "Tags": [ "c++", "object-oriented", "random", "dice" ], "Title": "Modeling a pair of dice using composition in C++" }
35663
<p>I've attempted to write a program to find the largest palindrome in a sentence. Spaces are included and characters are case-sensitive. Can you suggest better ways of doing this?</p> <pre><code>//public static void main(String args[])-- String source = "my malayalam is beautiful"; //Find the the largest palindrom in this sentence StringBuilder sb = new StringBuilder( source); String p = sb.reverse().toString(); System.out.println(p); System.out.println(source); int largest = 0; try{ for (int start=0; start &lt;=source.length(); start++ ){ for (int end=start+2; end &lt; source.length(); end++){ if (largest &lt; (end-start)){ String sub = source.substring(start, end); if (p.indexOf(sub) &gt; 0){ largest = sub.length(); System.out.println(sub+" "+largest); } } } } } catch(Exception e){ System.out.println("2"); e.printStackTrace(); } </code></pre>
[]
[ { "body": "<p>There are two things that can be criticized here: Your coding style and your algorithm.</p>\n\n<h3>Code Style</h3>\n\n<ul>\n<li><p>There are unnecessary spaces inside some parens: <code>new StringBuilder( source)</code>, <code>for (…; start++ ){</code>. Make a conscious decision to follow <em>one</em> style and follow it through.</p></li>\n<li><p>Improve readability by consistently putting a space around most operators like <code>=</code>, <code>-</code>, <code>+</code> and <code>&lt;=</code>.</p></li>\n<li><p>Never <em>ever</em> <code>catch (Exception e)</code>! If there is a <em>specific</em> exception you would like to catch, then please do, but specify the appropriate class or interface. But often it is better to just let the exception bubble up through the call stack.</p>\n\n<p>Do not catch exceptions you are not interested in actually handling. Do not catch exceptions you have no idea where they would come from. Why are you currently catching an…</p>\n\n<ul>\n<li>… <code>ArithmeticException</code>? Is there any chance e.g. for a division by zero in your code?</li>\n<li>… <code>ArrayIndexOutOfBoundsException</code>? Where are you using arrays?</li>\n<li>… <code>ArrayStoreException</code>? Where are you storing stuff into an array?</li>\n<li>… <code>ClassCastException</code>? Your code does not contain a single cast.</li>\n<li>… <code>ClassNotFoundException</code>? You have no dynamic class loading in your code.</li>\n<li>… <code>CloneNotSupportedException</code>? You don't call <code>clone</code> on any object.</li>\n<li>…</li>\n</ul></li>\n<li><p>Use good variable names that make it clear what a certain variable means. Shouldn't <code>p</code> be <code>reversed</code> or something like that?</p></li>\n<li><p>I would not introduce a <code>sb</code> variable for the <code>StringBuilder</code>, but rather: </p>\n\n<pre><code>String reversed = new StringBuilder(source).reverse().toString();\n</code></pre></li>\n<li><p>The palindrome finding code is not callable as a method. Extracting code into sensible methods improves testability, and can make it easier to design good programs.</p></li>\n</ul>\n\n<h3>Bugs</h3>\n\n<ul>\n<li><p>Some bounds you choose are rather weird. For example, <code>start &lt;=source.length()</code> should be <code>start &lt; source.length()</code> or even better <code>start &lt;= source.length() - largest</code>.</p></li>\n<li><p>The <code>indexOf</code> method returns an index on success, and <code>-1</code> on failure. The snippet <code>if (p.indexOf(sub) &gt; 0)</code> is therefore misleading. Anyway, you should be actually using <code>if (p.contains(sub))</code>.</p></li>\n<li><p>Your logic just asserts that the source string contains both a substring and the reversed substring. It does not assert that it contains any palindrome. For example, <code>computers return</code> will cause your code to output <code>uter</code>. You would have to check the actual indices, or better: that the substring equals itself reversed.</p></li>\n</ul>\n\n<h3>Algorithm</h3>\n\n<p>Your current algorithm works by extracting all possible substrings of length <code>2</code> or longer, and then checks whether the substring reversed is contained in the source string. As explained above, this is wrong. It is also quite inefficient, because your algorithm runs in <em>O(n²)</em> (two nested loops).</p>\n\n<p>The problem could be solved in a fraction of the code by a recursive regular expression, e.g. in Perl/PCRE: <code>(.)(?:(?R)|.?)\\1</code>. Sadly, the regex implementation of the Java standard library does not support this.</p>\n\n<p>According to <a href=\"https://en.wikipedia.org/wiki/Longest_palindromic_substring\">the Wikipedia article on <em>Longest Palindromic Substrings</em></a>, it is possible to find them in <em>linear</em> time. You may want to implement such an existing algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T05:21:43.307", "Id": "58065", "Score": "0", "body": "Thank you so much. Just the kind of answer i was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:38:47.617", "Id": "35710", "ParentId": "35664", "Score": "5" } } ]
{ "AcceptedAnswerId": "35710", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T05:55:48.193", "Id": "35664", "Score": "2", "Tags": [ "java", "strings", "palindrome" ], "Title": "Finding largest string palindrome" }
35664
<p>Please review my <code>FindMovie</code> and <code>AddMovie</code> methods.</p> <pre><code>public static boolean FindMovie(String movietofind, String[] ArrayMovie) { movie Movieobject = new movie(); for (String ArrayMovie1 : ArrayMovie) { if (ArrayMovie1.equals(movietofind)) { return true; } } return false; } public static void AddMovie(int i, String[] ArrayMovie, String[] UserRating, int[] UserReview) { int addmovie, userrating; boolean Movie1; String MPAA; Scanner console = new Scanner(System.in); System.out.println("Please give me the name of the movie you want to add."); String Movie = console.next(); Movie1 = FindMovie(Movie, ArrayMovie); if (Movie1 = false) { System.out.println("Do you want to add this movie to the collection? Please select 1 for Yes or 2 for No"); addmovie = console.nextInt(); if (addmovie == 1) { ArrayMovie[i] = Movie; System.out.println("What is the type of MPAA rating of the movie?"); System.out.println("Please enter G, PG, PG13, or R"); MPAA = console.next(); UserRating[i] = MPAA; System.out.println("What is your rating for movie?"); System.out.print("please choose 1, 2, 3, 4, or 5"); userrating = console.nextInt(); UserReview[i] = userrating; } else if (addmovie == 2) { } } } </code></pre>
[]
[ { "body": "<p>Quick pointers:</p>\n\n<ol>\n<li>What is the point of <code>movie Movieobject = new movie();</code> ?</li>\n<li>According to Java naming conventions, your use of camel cases is inverted. Variable and method names should start with a lower case, and classes (e.g. <code>movie</code>) should start with an upper case.</li>\n<li><p>The <code>for loop</code> for <code>findMovie</code> can be replaced by one line for brevity, although there are still a couple more ways to optimize this part:</p>\n\n<pre><code>return Arrays.asList( movieArray ).contains( searchMovie );\n</code></pre></li>\n<li><p>Since option 2 is not meant to do anything, there is no need to include</p>\n\n<pre><code>} else if (addmovie == 2) {\n</code></pre>\n\n<p>at all. </p></li>\n<li>What is the purpose of passing in so many <code>String</code> arrays for the <code>addMovie</code> method?</li>\n<li><p>You can inline the <code>findMovie</code> call from this:</p>\n\n<pre><code>Movie1 = FindMovie(Movie, ArrayMovie);\nif (Movie1 = false) {\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>if (!findMovie(movie, arrayMovie)) {\n</code></pre></li>\n</ol>\n\n<p>I feel a bit more background to your question is needed here.</p>\n\n<p>Edit: Of course, going by OOP practices, you really should be creating <code>Movie</code> instances to check for its existence in the <code>ArrayList</code> etc., but I'll defer such bigger changes until there is more information given to support your use cases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:29:38.457", "Id": "35670", "ParentId": "35665", "Score": "2" } }, { "body": "<p><strong>Technical</strong></p>\n\n<ol>\n<li>Your naming conventions are inconsistent - you mix PascalCase with alllowercase (don't know if that convention has it's own name). In Java types (like classes and interfaces) are PascalCase and method and variable names are camelCase.</li>\n<li>Declare variables where they are used and not all at the top of the function.</li>\n<li><code>Movie1</code> one is not a good name for a variable. The variable name should express the meaning of it. In this case it should be <code>movieExists</code>.</li>\n<li><code>FindMovie</code> won't compile due to the first line in the function (there is no <code>movie</code> type in your source code and nothing actually references a <code>movie</code> type except that one line of code). It should be removed (<code>Movieobject</code> is never used)</li>\n<li>There is no need to prefix the variable name with the type of the variable it just adds clutter and no real value. So <code>ArrayMovie</code> should be <code>movies</code> as that's what the collection represents (a collection of movies).</li>\n<li>If you use <code>ArrayList</code> instead of arrays you get automatic resizing when adding new movies and a whole bunch of nice utility functions like <code>contains</code> which reduce a lot of code clutter and does not impose the limitation of fixed sized arrays.</li>\n<li><code>AddMovie</code> requires the caller to pass in the index in the array where the movie should be stored. This is bad as it requires the caller to keep information about the structure of the list. It should just add a new movie to the end of a list (see previous point about <code>ArrayList</code>).</li>\n<li><p>You can reduce nesting by breaking early when hitting the negative condition, for example:</p>\n\n<pre><code>bool movieExists = FindMovie(Movie, ArrayMovie);\nif (movieExists)\n{\n return;\n}\n\nSystem.out.println(\"Do you want to add this movie to the collection? Please select 1 for Yes or 2 for No\");\nbool userAction = console.nextInt();\nif (userAction != 1)\n{\n return;\n}\n\n// add the movie\n</code></pre></li>\n</ol>\n\n<p><strong>Design</strong></p>\n\n<p>It seems like you had the right idea at some point about having a <code>movie</code> class (although it should be named <code>Movie</code>) encapsulating the properties of a movie like name, rating and reviews. Right now you seem to pass them around as 3 independent lists and the only connection is that the index in each list refers to the same movie. This is easy to get out of sync and you always have to pass around 3 lists - not to mention what happens when you want to add a 4th or 5th property.</p>\n\n<p><code>AddMovie</code> should just accept an <code>ArrayList&lt;Movie&gt;</code> as input to which you can add a new movie after you have gathered all the user input.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:52:04.210", "Id": "35673", "ParentId": "35665", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T06:25:38.213", "Id": "35665", "Score": "3", "Tags": [ "java", "array" ], "Title": "A menu option that receives input from users and then performs actions" }
35665
<p>Here's my code:</p> <pre><code>let rem x y = let rec aux acc i n = if i=n then acc else if acc+1=y then aux 0 (i+1) n else aux (acc+1) (i+1) n in aux 0 0 x;; </code></pre> <p>I'm just learning OCaml and I wonder:</p> <ol> <li>Is this tail recursive? </li> <li>Is there a more efficient algorithm, i.e., operating in better than linear time?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:27:55.263", "Id": "57915", "Score": "0", "body": "I do not clearly understand what are you trying to achieve. If you want to implement `mod` function using sequence of additions your solution can be cheaper for when `x div y` is low and more expensive than `x mod y` when `x div y` is large because built-in `mod` probably can be very fast if suitabe processor instruction exists." } ]
[ { "body": "<p>I don't know OCaml, but I know enough similar languages that I think I can read that well enough to answer. Still, take this with a grain of salt. </p>\n\n<p>That is tail recursive. You either return a value, or return the result of a recursive call that depends only on its input parameters that are known at the time of the call. </p>\n\n<p>There is a more efficient algorithm. Hint: repeated subtraction. (That may not be the most efficient algorithm.)</p>\n\n<p>You don't actually use the parameter n, you could just use x directly in the same way you use y directly. The name <code>rem</code> isn't the most descriptive; <code>remainder</code> would be better, but that particular function is mostly known as <code>mod</code> or <code>modulus</code>. </p>\n\n<p>I would find this formatting more readable:</p>\n\n<pre><code>if i = n \nthen acc \nelse if acc+1 = y \n then aux 0 (i+1) n \n else aux (acc+1) (i+1) n \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T07:36:38.587", "Id": "35672", "ParentId": "35666", "Score": "3" } } ]
{ "AcceptedAnswerId": "35672", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T23:39:19.763", "Id": "35666", "Score": "6", "Tags": [ "recursion", "ocaml" ], "Title": "I've written remainder(x,y) in OCaml. Is there more efficient than O(n)?" }
35666
<p>I've created a module that implements a basic "Document at a time" algorithm for inverted index querying (<a href="http://fontoura.org/papers/vldb2011.pdf">more background here</a>). There are many algorithm improvements possible, but I'm now interested in feedback on the structure of the Erlang code, specifically:</p> <ul> <li>Unneeded verbosity / code </li> <li>Erlang 'style' mistakes</li> <li>Things that can be done more elegantly</li> <li>(and yes, it's missing documentation)</li> </ul> <p></p> <pre><code>-module(search_daat). -export([get_top/2]). -record( heap, { heap :: list({integer(), integer()}), min_score :: integer() } ). -record( postings, { docs :: list({integer(),integer()}), max_score :: integer(), name :: string() } ). -spec get_top( integer(), list(#postings{}) ) -&gt; #heap{}. get_top(N, Postings) -&gt; get_top(N, Postings, #heap{ heap = [], min_score = 0}, 0, 0). -spec get_top( integer(), list(#postings{}), #heap{}, integer(), integer() ) -&gt; #heap{}. get_top(N, Postings, Heap, CurrentDocId, UpperBound) -&gt; Result = next(Postings, CurrentDocId, UpperBound), case Result of {error, not_found} -&gt; Heap; {{NextDocId, _Score}, NewPostings} -&gt; FullScore = full_score(NextDocId, NewPostings), NewHeap = heap_insert(Heap, N, NextDocId, FullScore), get_top(N, NewPostings, NewHeap, NextDocId, NewHeap#heap.min_score) end. -spec heap_insert(#heap{}, integer(), integer(), integer()) -&gt; #heap{}. heap_insert(Heap, MaxHeapSize, DocId, FullScore) -&gt; case length(Heap#heap.heap) &lt; MaxHeapSize of true -&gt; Heap1 = Heap#heap.heap ++ [{DocId, FullScore}], Heap2 = [{_,MinScore} | _Rest] = lists:keysort(2, Heap1), Heap#heap{ heap = Heap2, min_score = MinScore}; false -&gt; case Heap#heap.min_score &gt; FullScore of true -&gt; Heap; false -&gt; Heap1 = lists:keydelete( Heap#heap.min_score, 2, Heap#heap.heap ) ++ [{DocId, FullScore}], Heap2 = [{_, MinScore} | _Rest] = lists:keysort(2, Heap1), Heap#heap{ heap = Heap2, min_score = MinScore} end end. -spec full_score(integer(), list(#postings{})) -&gt; integer(). full_score(DocId, Postings) -&gt; lists:foldl(fun(Posting, Acc) -&gt; [{CurrentDocId, Score} | _] = Posting#postings.docs, case CurrentDocId == DocId of true -&gt; Acc + Score; false -&gt; Acc end end, 0, Postings). -spec next( list(#postings{}), integer(), integer() ) -&gt; {error, not_found} | {{integer(), integer()}, list(#postings{})}. next(Postings, CurrentDocId, UpperBound) -&gt; case find_pivot(Postings, UpperBound) of {error, not_found} -&gt; {error, not_found}; Pivot -&gt; [{PivotDocId, PivotDocScore} | _] = Pivot#postings.docs, [HeadPosting | _Rest] = Postings, [{HeadPostingDocId, _}| _] = HeadPosting#postings.docs, case PivotDocId =&lt; CurrentDocId of true -&gt; NewPostings = skip_to(Postings, CurrentDocId + 1), next(NewPostings, CurrentDocId, UpperBound); false -&gt; case PivotDocId == HeadPostingDocId of true -&gt; {{PivotDocId, PivotDocScore}, Postings}; false -&gt; NewPostings = skip_to(Postings, PivotDocId), next(NewPostings, CurrentDocId, UpperBound) end end end. -spec skip_to(list(#postings{}), integer()) -&gt; list(#postings{}). skip_to([HeadPosting | Postings], SkipToDocId) -&gt; [_ | Docs] = HeadPosting#postings.docs, case skip_to(Docs, HeadPosting, SkipToDocId) of {error, no_docs_left} -&gt; Postings; %% remove head NewHeadPosting -&gt; sort_by_head([NewHeadPosting | Postings]) end. -spec skip_to( list({integer(),integer()}), list(#postings{}), integer() ) -&gt; {error, no_docs_left} | #postings{}. skip_to([], Posting, SkipToDocId) -&gt; {error, no_docs_left}; skip_to([{DocId, Score} | NewDocs], Posting, SkipToDocId) -&gt; case DocId &gt;= SkipToDocId of true -&gt; #postings{ docs = [{DocId, Score} | NewDocs], max_score = Posting#postings.max_score, name = Posting#postings.name }; false -&gt; skip_to(NewDocs, Posting, SkipToDocId) end. -spec find_pivot( list(#postings{}), integer() ) -&gt; {error, not_found} | #postings{}. find_pivot(Postings, UpperBound) -&gt; find_pivot(Postings, UpperBound, 0). -spec find_pivot( list(#postings{}), integer(), integer()) -&gt; {error, not_found} | #postings{}. find_pivot([], UpperBound, _TestBound) -&gt; {error, not_found}; find_pivot([Posting | Postings], UpperBound, TestBound) -&gt; Weight = 1, NewTestBound = TestBound + Weight * Posting#postings.max_score, case NewTestBound &gt;= UpperBound of true -&gt; Posting; false -&gt; find_pivot(Postings, UpperBound, NewTestBound) end. -spec sort_by_head(list(#postings{})) -&gt; list(#postings{}). sort_by_head(Postings) -&gt; lists:sort( fun( P1, P2 ) -&gt; [{DocId1, _} | _] = P1#postings.docs, [{DocId2, _} | _] = P2#postings.docs, DocId1 =&lt; DocId2 end, Postings ). </code></pre>
[]
[ { "body": "<p>I'm not sure writing explicit type specifications is idiomatic Erlang. In all programming languages that support inference, type specifications are used in specific cases, eg. when you want to restrict the possibles types, but not by default. Even if the <a href=\"http://www.erlang.org/doc/reference_manual/typespec.html\" rel=\"nofollow\">doc on specifications</a> explain a few advantages, the <a href=\"http://www.erlang.se/doc/programming_rules.shtml\" rel=\"nofollow\">Erlang programming rules</a> don't even mention it. Make sure you know why you're using them!</p>\n\n<pre><code>-record(\n postings,\n { \n docs :: list({integer(),integer()}),\n max_score :: integer(),\n name :: string()\n }\n ).\n</code></pre>\n\n<p>Please document your records: types help but I also want to know that the first integer is the document id, and that the second integer is the score, and I want to know it in the record definition. :) Also, watch out your indentation for the last brace.</p>\n\n<p>Names: <code>heap</code> describes the container, but not what it contains: be more specific. The same applies for <code>next</code>, I think you could name it <code>nextposting</code> or <code>next_posting</code>, but I'm not sure. <a href=\"http://www.erlang.se/doc/programming_rules.shtml#REF10726\" rel=\"nofollow\">Names are hard!</a></p>\n\n<p>In <code>full_score</code>, I wouldn't alter the logic of your <code>foldl</code> call just to remove the score of <code>DocId</code>. I would pass the whole tuple to <code>full_score</code>, and remove the score after the sum has been made. More generally, it makes sense to have function interfaces that get one or multiple 'document' rather than just document ids just because you need that right now. Defining a specific document type, for example, would help too.</p>\n\n<p>If you changed <code>full_score</code> to get a full document including its score, you can call <code>lists:map</code> to retrieve scores and <code>lists:sum</code> to get the sum. That would probably be easier to read but would require two passes: that's up to you!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T09:56:56.500", "Id": "36280", "ParentId": "35679", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:18:43.417", "Id": "35679", "Score": "7", "Tags": [ "erlang" ], "Title": "Improving clarity and style of this \"Document at a time\" algorithm" }
35679
<p>I am relatively new to Java, but have been reading up on how to improve the quality of my code.</p> <p>I am writing a system where I take in a series of points from a file with x and y co-ordinates and by checking slopes relative to each other, am calculating and drawing a line if there is four or more co-linear points on the line. The code works and is doing what is required, but I would like to tidy up this method by reducing the <code>if</code> statements, but am not sure on how to, or if it is even necessary. The parameters being passed in is an array of <code>double</code>s, which are slopes relative to an origin. I am iterating this array to look for 3 or more equal slopes in a row which would give a line and adding the corresponding points and any further equal points to a set. Once a line has been found, the rest of the slopes in array are checked in similar fashion. Any advice would be appreciated.</p> <p>I think it's messy, but not sure how to rectify it.</p> <pre><code>public static void checkForLines(Double[] arrayOfSlopes, Point[] tempArray) { int count = 0; // Keeps track of number of duplicates int i = 1; while (i &lt; arrayOfSlopes.length - 1) { Double first = arrayOfSlopes[i]; Double next = arrayOfSlopes[i + 1]; if (first.equals(next)) // Compares two consecutive indexes in array for equality { count = count + 1; // If match found increase the count if (count == 2) // At this point a line has been found { SortedSet&lt;Point&gt; line = new TreeSet&lt;Point&gt;(); //Create a set to store points from this line line.add(tempArray[0]); line.add(tempArray[i - 1]); line.add(tempArray[i]); line.add(tempArray[i + 1]); //Store four found points int j = i + 1; while (j + 1 &lt; arrayOfSlopes.length - 1 &amp;&amp; (arrayOfSlopes[j].equals(arrayOfSlopes[j + 1]))) { line.add(tempArray[j + 1]); //Store any other further duplicates if exist j++; } if (arrayOfSlopes[j].isInfinite() &amp;&amp; arrayOfSlopes[arrayOfSlopes.length - 1].isInfinite() || arrayOfSlopes[arrayOfSlopes.length - 1].equals(first)) { line.add(tempArray[tempArray.length - 1]); //Check the last element for equality } if (lines.isEmpty()) { lines.add(line); } else { lines.add(0, line); ; weedDuplicates(line); } i = j + 1; //Continue iteration from this point } if (count &lt; 2) { i++; } } else if (first.equals(next) == false) { count = 0; i++; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:46:21.823", "Id": "57955", "Score": "1", "body": "You should give your question a more descriptive title - even simply that it looks for lines in a set of points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:35:22.160", "Id": "57958", "Score": "4", "body": "Well, to start, you should indent/format your code properly/consistently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:42:28.487", "Id": "58032", "Score": "1", "body": "Small thing, but nobody's mentioned it yet - I'd replace `count = count + 1;` with either `count++;` or maybe `++count;`. (Some people prefer the latter, and in some cases it makes for slightly more efficient code. Shouldn't make a difference here though.) Also, instances of `if(___ == false)` should be replaced with `if(!___)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T07:33:19.633", "Id": "80983", "Score": "0", "body": "looks like the task is an assignment from Coursera's \"Algorithms and Data Structures, part 1\" — https://class.coursera.org/algs4partI-004/assignment/view?assignment_id=4" } ]
[ { "body": "<p>Several comments</p>\n\n<p>1) according to java coding conventions we write <code>{</code> at the same line where operator is, i.e.</p>\n\n<pre><code>if () {\n}\n</code></pre>\n\n<p>and not </p>\n\n<pre><code>if () \n{\n{\n</code></pre>\n\n<p>2) If you do not have special reason to use primitive wrapper (e.g. <code>Double</code>) use primitive <code>double</code></p>\n\n<p>The next comments are not about java but about general programming style</p>\n\n<p>3) avoid writing so complicated conditions into <code>while</code> loop\n4) try to simplify conditions. I think that <code>list.add(0, element)</code> works exactly like <code>list.add(element)</code> when list is empty. Therefore code:</p>\n\n<pre><code> if (lines.isEmpty())\n {\n\n lines.add(line);\n }\n\n else\n {\n lines.add(0, line);;\n weedDuplicates( line);\n }\n</code></pre>\n\n<p>Can be re-written as:</p>\n\n<pre><code>if (!lines.isEmpty()) {\n weedDuplicates( line);\n}\nlines.add(0, line);;\n</code></pre>\n\n<p>5) the code</p>\n\n<p><code>if (first.equals(next) == false)</code> </p>\n\n<p>is the same as:</p>\n\n<p><code>if (!first.equals(next))</code> </p>\n\n<p>Well, I frankly speaking I did not understand exactly what are you doing in this code fragment but probably the algorithm can be simplified too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:54:21.997", "Id": "57960", "Score": "1", "body": "Also im using Double because Im returning infinity in some instances" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:46:13.190", "Id": "35701", "ParentId": "35693", "Score": "3" } }, { "body": "<p>My first observation is that there are too many \"This code is doing X\" comments. If you feel the need to put those comments in, try refactoring the code out into a descriptive function.</p>\n\n<pre><code>if (concurrentPointsAreEqual(first, next))\n{\n ...\n}\n\nprivate bool concurrentPointsAreEqual(Double first, Double second)\n{\n return first.equals(second);\n}\n</code></pre>\n\n<p>This will remove the comments and portray the intent right in the code.</p>\n\n<p>I would also rename <code>count</code> to <code>numberOfDuplicates</code> thus removing the need for comments on it, and it will be more descriptive in your code.</p>\n\n<p>This line <code>else if (first.equals(next) == false)</code> is redundent. An <code>else</code> will capture this condition because <code>first</code> is either equal or not equal to <code>next</code>.</p>\n\n<p>I believe in Java, the standard is to put the opening bracket on the same line as the statement</p>\n\n<pre><code>if (concurrentPointsAreEqual(first, next)) {\n</code></pre>\n\n<p>I don't like the variable name <code>tempArray</code>, it tells me nothing of the data it is storing. Maybe something like <code>pointsInLine</code>.</p>\n\n<p>Similar to the if statement I mentioned, extracting the points should be moved to its own function:</p>\n\n<pre><code>private TreeSet&lt;Point&gt; extractLineFromPoint(Point[] points) {\n\n TreeSet&lt;Point&gt; line = new TreeSet&lt;Point&gt;();\n\n line.add(points[0]);\n line.add(points[1]);\n line.add(points[2]);\n line.add(points[3]);\n\n return line;\n}\n</code></pre>\n\n<p>You can then grab a sub-list from the original points an pass it in, removing the comments from the original call.</p>\n\n<p>Your loops freak me out, especially with all the + 1, and increments on the loop counters. I'm not sure why its being done, or how to fix them, they just smell really bad.</p>\n\n<p>I'm not sure what the <code>weedDuplicates</code> function does, but I think you should just be adding everything to the <code>lines</code>, then removing duplicates, otherwise you could potentially be iterating the <code>lines</code> list every iteration of the main loop. This will also remove one of the <code>if</code> statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:20:20.187", "Id": "57962", "Score": "0", "body": "Okay, thanks I will edit the code. Thanks for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:31:31.623", "Id": "58049", "Score": "0", "body": "Good answer, just one thing that bothers me: Java method names should start with lowercase letters as per the coding convention! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T16:38:20.453", "Id": "58153", "Score": "0", "body": "Good point, leave it to a mainly C# to capitalize the methods. More than likely it was Resharper (I used it to reformat the code) ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:18:01.380", "Id": "35702", "ParentId": "35693", "Score": "3" } }, { "body": "<p>The easiest way to flatten this kind of a structure is to reverse the sense of the if. That is, where you have</p>\n\n<pre><code>if (first.equals(next)) {\n // do stuff\n}\n</code></pre>\n\n<p>Instead write</p>\n\n<pre><code>if (!first.equals(next)) {\n continue;\n}\n// do stuff\n</code></pre>\n\n<p>This only works where you don't have an <code>else</code> clause (so unfortunately I chose a bad example), but it can work wonders in bringing your code closer to the left margin.</p>\n\n<p>From there I would start seeing where I could extract methods, especially but not exclusively where there is duplication in the code. The block of code beginning with </p>\n\n<pre><code>SortedSet&lt;Point&gt; line = new TreeSet&lt;Point&gt;();\n</code></pre>\n\n<p>looks like a good candidate for this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:21:21.617", "Id": "35703", "ParentId": "35693", "Score": "5" } }, { "body": "<p>I'm not convinced that the code does what you claim.</p>\n\n<p>First, let's <strong>clarify the parameters</strong>. Is there a relationship between <code>arrayOfSlopes</code> and <code>tempArray</code>? Your description suggests that <code>arrayOfSlopes</code> can be derived from <code>tempArray</code>, with each <code>arrayOfSlopes[i]</code> being the slope of a line between the origin and <code>tempArray[i]</code>. If that is so, then your function should only take a <code>Point[]</code> argument, named better (<code>points</code> will do for a name). This being a <code>public</code> function, you should make the interface as caller-friendly as possible, and requiring the caller to pass in two arrays that obey some unwritten consistency rule between them is inappropriate.</p>\n\n<p>It appears that <code>arrayOfSlopes</code> and <code>tempArray</code> must follow <strong>rules about the ordering of their elements</strong> — elements must be sorted by slope? That's not obvious from the non-existent <strong>JavaDoc</strong>. You also <strong>treat <code>tempArray[0]</code> specially</strong>, though I can't tell why.</p>\n\n<p>Next, what is <strong><code>lines</code></strong>? It appears to be a <code>static</code> class variable (it's the only way I can imagine to make this code compile). Putting the answer in a class variable makes no sense. Either you <code>return lines</code> as a result from this function, or you make this code a non-public instance method and store the result in an instance variable.</p>\n\n<p>If <code>arrayOfSlopes</code> contains the slope of each point relative to the origin, then matching slopes will <strong>only yield lines that pass through the origin</strong>.</p>\n\n<p>Does <code>Point</code> refer to <code>java.awt.Point</code>? You store them in a <code>SortedSet</code>, though, which means that they must be <code>Comparable</code> to each other. How is the comparison function defined?</p>\n\n<p>Your <strong><code>else if</code> is redundant</strong> — a simple <code>else</code> would be equivalent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:21:59.423", "Id": "57972", "Score": "0", "body": "Yeah this is only one method that I wanted to clean up from all of the classes in the project, hence the statement \"The code works and is doing what is required, but I would like to tidy up this method by reducing the if statements\". So having already stated the code works and does what is required, why are you not convinced the code works and does what is required?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:47:27.283", "Id": "57979", "Score": "0", "body": "Skeptical because 1) You only find lines that intersect the origin — a limitation that was not apparent in your description; 2) The parameters have to satisfy surprisingly specific preconditions that aren't documented; 3) `tempArray[0]` is mysteriously special; 4) You haven't provided complete runnable code with test cases to prove that it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:54:50.757", "Id": "57983", "Score": "0", "body": "No but I have said it works, tempArray[0] is where I have set the origin to. If a number of points make the same slope with a point they are on the one line and collinear, correct? Hence by checking for consecutive equal slopes of the sorted array Im finding points on that line. I didn't say the code was perfect thats why I was looking for help. I did however say it works and also that I am new to programming. So be skeptical all you want, I wasn't asking anyone did they think the code worked, I asked how I could tidy it up. A point the two previous answers helped me with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:04:12.560", "Id": "57985", "Score": "0", "body": "In that case, my review boils down to this: your code is _fragile_ because it relies on many hidden assumptions. Either document all of those preconditions, or better yet, find a way to relieve the caller from having to satisfy them. (Please don't be offended by the review. If I really thought your code was broken, I would have nominated the question to be closed for being non-working code instead of reviewing it.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:12:00.957", "Id": "35706", "ParentId": "35693", "Score": "2" } } ]
{ "AcceptedAnswerId": "35702", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:36:57.283", "Id": "35693", "Score": "3", "Tags": [ "java", "beginner", "computational-geometry" ], "Title": "Refactor code to find four co-linear points" }
35693
<p>I have a tree of objects.</p> <pre><code>Object id:0 Object type:0 Object id:1 Object type:0 Object id:3 Object type:0 Object id:2 Object type:0 Object id:4 Object type:0 Object id:5 Object type:0 </code></pre> <p>For each object I have a method that returns its "index" in the tree down to the root item.</p> <p>Indices: </p> <pre><code>0 - 0 1 - 0 0 2 - 0 1 3 - 0 0 0 4 - 0 1 0 5 - 0 1 1 </code></pre> <p>I need to be able to check for "visibility" from one object to another object, with the rules being pretty much identical to those of C/C++ scopes. E.g. the root item is like a global, so it should be visible to every other items, and items are only visible to items on their level or higher as long as they are in the same branch.</p> <p>In short:</p> <pre><code>0 - visible to all 1 - visible to 2, 3, 4, 5 2 - visible to 4, 5 3 - visible to none 4 - visible to 5 5 - visible to none </code></pre> <p>After some trial and error I came up with this code, and it does seem to work as expected given the above tree hierarchy.</p> <pre><code>bool isVisibleTo(Node * accessor) { QList&lt;uint&gt; accessedI = getIndex(); QList&lt;uint&gt; accessorI = accessor-&gt;getIndex(); if (accessedI.size() &gt; accessorI.size()) return false; // item is deeper than its accessor else if (accessedI.size() == accessorI.size()) { // same size - check if all but the last are compatible for (int i = 0; i &lt; accessedI.size() - 1; ++i) if (accessedI.at(i) != accessorI.at(i)) return false; // indecies not identical if (accessedI.last() &gt; accessorI.last()) return false; // identical, but accessor index is larger } for (int i = 0; i &lt; accessorI.size() - (accessorI.size() - accessedI.size()); ++i) { if (accessedI.at(i) &gt; accessorI.at(i)) return false; // wrong subtree } return true; } </code></pre> <p>test output:</p> <pre><code>node 0 is visible to node 0 node 0 is visible to node 1 node 0 is visible to node 2 node 0 is visible to node 3 node 0 is visible to node 4 node 0 is visible to node 5 node 1 is visible to node 1 node 1 is visible to node 2 node 1 is visible to node 3 node 1 is visible to node 4 node 1 is visible to node 5 node 2 is visible to node 2 node 2 is visible to node 4 node 2 is visible to node 5 node 3 is visible to node 3 node 4 is visible to node 4 node 4 is visible to node 5 node 5 is visible to node 5 </code></pre> <p>But still, I am fairly new and inexperienced to programming, so any notes, corrections and recommendations are welcome.</p>
[]
[ { "body": "<p>I came up with a cleaner looking solution:</p>\n\n<pre><code>bool isVisibleTo(Node * accessor) {\n Node * node = accessor;\n while (node) {\n if (node == this) return true;\n if (node-&gt;_parent) {\n uint i = node-&gt;_parent-&gt;_children.indexOf(node);\n while (i) if (node-&gt;_parent-&gt;_children.at(--i) == this) return true;\n } node = node-&gt;_parent;\n } return false;\n}\n</code></pre>\n\n<p>But it will be inevitably slower in a scenario with lots of children. While the first \"messy\" solution uses the relative tree indices and only traverses the object tree from child to parent, this cleaner solution goes through all children nodes before going to the parent. I will have to do some profiling with a bigger tree to verify if that is the case.</p>\n\n<p>EDIT: I take it back, despite what appeared as an obvious performance penalty this method is actually about 4 times faster consistently. I tested with a whooping 10 million nodes</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T12:51:26.447", "Id": "35828", "ParentId": "35694", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:37:16.573", "Id": "35694", "Score": "1", "Tags": [ "c++", "algorithm", "scope" ], "Title": "Order and visibility tracking algorithm (e.g. scope visibility)" }
35694
<p>This method finds the smallest positive number that is evenly divisible by all numbers from 1 to 20.</p> <p>I am wondering if there is a better way to test if all iterations of a <code>for</code> loop completed successfully. When I put the found boolean outside the <code>for</code> loop, it was terminating my <code>while</code> loop prematurely since the break in the <code>for</code> loop goes to the end and executes whatever is below the <code>for</code> loop inside the <code>while</code> loop. It also seems a bit sloppy to subtract the number that is given and then add 1 to it inside the <code>while</code> loop. But if I put the number++ below the <code>for</code> loop after found is set true and I don't need to increment the number anymore. It increments one last time.</p> <p>For example, for the number 20, the answer is 232792560. But due to the last increment it would return 232792561, which is an incorrect answer.</p> <pre><code>public int getLowestDiv(int n) { //initialize found variable, as we havent found the number yet boolean found = false; /* initilize the number as what was passed to this method minus 1, since we will increment below*/ int number = n - 1; while (found != true) { number++; for (int i = 1; i &lt;= n; i++) { //for 1 to int that was passed divide the current number and see if its divisible if (number % i != 0) { break; } else if (i == n) found = true; } } return number; } </code></pre> <p>I have looked through <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html" rel="nofollow">the specs for Java's loops</a> and didn't find anything about handling these type of situations. Specifically, I will loop for a certain number of iterations, testing if something is true, and if not, break, but only execute a particular statement if the <code>for</code> loop passed the condition on all iterations. I would like to see what the status-quo is when it comes to this as I've run into it before.</p>
[]
[ { "body": "<p>There are two parts to my initial assessment of your code.</p>\n\n<p>Firstly, often the 'best' way to solve a problem where you are tempted to have a <code>found = true</code> type situation is to call a seperate method for that part of the work, and to simply 'return value' when you find the value... for example, your code:</p>\n\n<pre><code> for (int i = 1; i &lt;= n; i++) {\n //for 1 to int that was passed divide the current number and see if its divisible\n if (number % i != 0) {\n break;\n\n } else if (i == n)\n found = true;\n\n }\n</code></pre>\n\n<p>would be easily written as:</p>\n\n<pre><code>private static final boolean checkValue(final int value, int n) {\n while (n &gt; 1) {\n if (value % n != 0) {\n return false;\n }\n n--;\n }\n return true;\n}\n</code></pre>\n\n<p>then your main loop becomes:</p>\n\n<pre><code>int number = n;\n\nwhile (!checkValue(number, n)) {\n number++;\n}\nSystem.out.printf(\"Number %d is divisible by all positive values up to %d\\n\", number, n);\n</code></pre>\n\n<p>The second issue I have is for performance..... you should not be using <code>number++</code>, you will save a lot of time if you only check the multiples of the largest number, so:</p>\n\n<pre><code>number += n; // instead of number++;\n</code></pre>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>If you look at the math, you will see that, we can do much better than <code>number += n</code>, and can determine that if we find a value that is a multiple of both <code>n</code> and <code>n - 1</code> that the final result will be a multiple of that value. If we can use that value as the 'step' then we will go faster than just using <code>n</code>. Similarly, if we can find a multiple of all <code>n</code>, <code>n - 1</code>, and <code>n - 2</code> then that would be a good step too.</p>\n\n<p>So, consider the following:</p>\n\n<pre><code>private static final int checkValue(final long value, int n) {\n while (n &gt; 1) {\n if (value % n != 0) {\n return n;\n }\n n--;\n }\n return 1;\n}\n</code></pre>\n\n<p>This loop now returns the value at which the expression fails....</p>\n\n<p>and we can use that in our main loop as follows:</p>\n\n<pre><code> final int n = 23;\n\n long number = n;\n\n long step = n;\n int fact = n;\n int bestfact = fac;\n while (number &gt; 0 &amp;&amp; (fact = checkValue(number, n)) &gt; 1) {\n if (bestfac &gt; fact) {\n bestfac = fact;\n step = number;\n }\n number += step;\n }\n\n if (number &lt; 0) {\n System.out.println(\"No values were found (overflow) divisible by all \" + n + \" factors\");\n }\n</code></pre>\n\n<p>On my computer, the difference between this optimization and a naieve step, is 0.022ms vs 4961.271ms (or 225000 times faster!!!!!!!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:12:38.943", "Id": "57970", "Score": "0", "body": "I should add, that I tested the code with `n = 23` and it overflows. I recommend adding `while (number > 0 && !checkValue(number, n)) {...}` as a check on the loop, and only report success if `number > 0` (i.e. no overflow). If you convert `number` to a `long`, then it get a solution for 23 at `5354228880`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:20:26.643", "Id": "57971", "Score": "2", "body": "I am a sucker for performance problems, so I thought I would update you with a change to the algorithm which makes it much faster...... see my edit:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:29:58.380", "Id": "57974", "Score": "2", "body": "It wasn't mentioned, but looping from n downwards gives a performance increase, since things are less likely to be divisible by 20 or 19 than by 2 or 3. Also, a completely different approach using the prime factorization of everything < n would let you calculate the result directly (this would replace the code with something else entirely, though)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:39:36.347", "Id": "35705", "ParentId": "35699", "Score": "5" } } ]
{ "AcceptedAnswerId": "35705", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:15:33.967", "Id": "35699", "Score": "2", "Tags": [ "java", "interval" ], "Title": "Finding the smallest positive number evenly divisible by a range of numbers" }
35699
<p>This tag should not be confused with <a href="/questions/tagged/template-meta-programming" class="post-tag" title="show questions tagged &#39;template-meta-programming&#39;" rel="tag">template-meta-programming</a>.</p> <p>Templates are pieces of code that are written with the intention of being used over and over again as a "cookie cutter" for multiple pieces of code. </p> <p>The template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:14:26.150", "Id": "35712", "Score": "0", "Tags": null, "Title": null }
35712
a design structure for creating several things that are almost identical but need different values. Not template-meta-programming.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:14:26.150", "Id": "35713", "Score": "0", "Tags": null, "Title": null }
35713
<p>I've written this simple JavaScript application for a homework assignment and I've received feedback saying it could be written better.</p> <p>Can I get some feedback on how to write this differently? It works for me and returns the results I need, but I would like some more specific feedback. It was meant to be simple and not meant to require more than 2 hours on it.</p> <p>The requirements were...</p> <blockquote> <ol> <li>You can only edit app.js, you cannot touch index.html. jQuery is provided.</li> <li>index.html contains two elements: one for the search term and one for the results.</li> <li>The results should show as a list with each item in an "owner/name" format.</li> <li>When a result is clicked, display an alert with the repo's <code>language</code>, <code>followers</code>, <code>url</code> and <code>description</code>.</li> <li>The search term should be cached so duplicate searches do not trigger further requests. </li> <li>Solution does not need to support older browsers.</li> </ol> </blockquote> <p>Here are the <code>app.js</code> I submitted and the <code>index.html</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>(function(window){ // Setup the variables for the application var search, results, textFieldValue, requestBaseUrl = 'https://api.github.com/legacy/repos/search/'; // Enable browser caching for the application $.ajaxSetup({ cache: true}); function applyPageStyling(){ $( "&lt;style&gt;body { background-image:url(http://n2.9cloud.us/766/a_beautiful_large_scale_shot_for_th_100120255.jpg); font-size:20px; font-family:'Arial, Helvetica', sans-serif;}&lt;/style&gt;" ).appendTo( "head" ); setTimeout(function(){alertInstructions();},1000); }; // Alert the user what to do function alertInstructions(){ alert("Please type the term to search GitHub for in the text field and hit the ENTER key."); }; // Function to query the github API function gitSearch(){ // Get the value from the search field textFieldValue = $('#search').val(); // Error handling for search box if (textFieldValue == ""){ alert("Please enter a term to search for"); } else { // Make the ajax call with the text field value appended to the url. The callback will // output the results or alert the error message $("&lt;ul&gt;").appendTo('#results'); $.getJSON(requestBaseUrl+textFieldValue, function(json, status){}) // Success then append items to #results div .done(function(json){ $.each(json.repositories, function(i, repositories){ $("&lt;li&gt;"+json.repositories[i].owner+" / "+json.repositories[i].name+"&lt;/li&gt;") .appendTo('#results ul') // Add a little styling, just a little. .css({'cursor': 'pointer','list-style-type':'none', 'width':'500px'}) .hover( function(event) { $(this).css({'color':'#ffffff'}); }, function(event) { $(this).css({'color':'#000000'}); } ) .click(function(event){ alert("Repo Lanuage is : "+json.repositories[i].language +"\n"+ "There are "+ json.repositories[i].followers +" followers of this repo.\n"+ "The URL of the repo is : "+ json.repositories[i].url +"\n"+ "The description of the repo : "+ json.repositories[i].description); }); }); }) // Log the error message .fail(function(status){ console.log(status); }); } }; // Enter key event handler $(document).keypress(function(e) { if(e.which == 13) { gitSearch(); } }); applyPageStyling(); }(window));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-type" content="text/html; charset=utf-8"&gt; &lt;title&gt;Search&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input id="search" type="text"/&gt; &lt;div id="results"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Looks good to me. You could cache the ul:</p>\n\n<pre><code>var repoList = $(\"&lt;ul&gt;\").appendTo('#results');\n</code></pre>\n\n<p>So you don´t have to query the dom again when appending the list items.\nAlso it is better to build the list items in memory and only append the complete list to the dom. This way you only trigger one reflow.</p>\n\n<p>So in the $.each loop I would </p>\n\n<pre><code>repoList.append($(\"&lt;li&gt;somerepo&lt;/li&gt;\"))\n</code></pre>\n\n<p>and then outside the loop</p>\n\n<pre><code>$(\"#results\").html(repoList);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:49:35.627", "Id": "35715", "ParentId": "35714", "Score": "5" } }, { "body": "<p>I second user1777136's suggestion of not appending to the DOM in a loop. </p>\n\n<p>Additional suggestions:</p>\n\n<ul>\n<li><p>Get rid of your <code>setTimeout</code> function. Instead, create a <code>$(document).ready</code> handler and prepend your instructions to the <code>body</code>.</p></li>\n<li><p>Change your <code>keypress</code> handler to <code>$('#search').change</code>, which would also go inside <code>$(document).ready</code>. Perform input validation inside the handler to simplify your <code>gitSearch</code> function:</p>\n\n<pre><code>// Get the value from the search field\n$('#search').change(function(e) {\n if (!$(this).val()) {\n alert(\"Please enter a term to search for\");\n } else {\n gitSearch($(this).val());\n }\n});\n</code></pre></li>\n<li><p>Instead of having individual <code>click</code> listeners defined inside the <code>each</code> loop, store the data for each element and retrieve it with a delegated listener in <code>$(document).ready</code>:</p>\n\n<pre><code>$('#results').on('click', 'li', function(event) {\n alert(\"Repo Language is : \" + $(this).data('language') + \"\\n\" +\n \"There are \" + $(this).data('followers') + \" followers of this repo.\\n\" +\n \"The URL of the repo is : \" + $(this).data('url') + \"\\n\" +\n \"The description of the repo : \" + $(this).data('description'));\n });\n</code></pre></li>\n<li><p>Keep one string containing all your CSS, including the styles for your <code>li</code>'s; you don't need inline CSS for these and this will remove the need for <code>hover</code> listeners. So in addition to your body styles you'd have</p>\n\n<pre><code>styles += \"#results li { cursor: pointer; list-style-type: none; color: #fff; }\";\nstyles += \"#results li:hover { color: #000; }\";\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:44:54.433", "Id": "58013", "Score": "0", "body": "Minor notes: you're declaring vars `search` and `results` at the top, but I don't think you're using them. Also, when you call `gitSearch`, set the content of `#results` to \"Loading..\" to signal to the user that something is happening in the background." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:49:07.887", "Id": "58015", "Score": "0", "body": "I can see how appending to the DOM would increase performance. Thanks for the pointers on that. The other tips make for good performance housekeeping too. Some of the feedback I got regarding the caching, which as far as I can tell is a \"coding style\" issue is to store the response in an object that uses the search term as a key. The way I coded this was deemed incorrect even though the jquery getJSON is supposed to cache the response even without setting the $.ajaxSetup({ cache: true}); Thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:07:27.260", "Id": "58018", "Score": "0", "body": "Turning on caching does cache the response, but still makes an XHR call. Sounds like you need to supersede that by declaring an object (e.g., `results = {}`), then saving your results in that object (e.g., `results[inputText] = json`). Then before making your ajax request, see if `results[inputText]` exists and if it does, use the stored json to create your output. This will require some refactoring, like moving everything in `done` into a separate function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:16:52.253", "Id": "58021", "Score": "0", "body": "Yeah VLS, that seems to be the method that was the desired outcome." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:21:51.300", "Id": "35724", "ParentId": "35714", "Score": "4" } }, { "body": "<p>I have a few other suggestions on how this could be even \"better\", but after looking it over, it appears <a href=\"https://codereview.stackexchange.com/questions/35714/how-could-i-write-this-simple-javascript-app-better#answer-35724\">another answer</a> here gives some of those suggestions. However, if you'd like me to rewrite the below code using said suggestions, lemme know and I'll update the code.</p>\n\n<p>The suggestions are simple little things like keeping all CSS in one place and discontinuing the hover functions for CSS <code>:hover</code>. As I noted in my comments, I left some of this as was to stay \"close\" to the train of thought you appeared to be on with your code. While I did introduce some different concepts, I'm hoping the basic flow I tried to stay with will make it easier for you to read through the comments there and see how all these wonderful parts work together!</p>\n\n<hr>\n\n<p>I would suggest some of the following || this is how I might do it and why:</p>\n\n<p><a href=\"http://jsfiddle.net/SpYk3/XA4PP/\" rel=\"nofollow noreferrer\"><h1>ExAmPlE</h1></a></p>\n\n<pre><code>// My own namespace for any global assignments, thus lowering chance of error of conflict with other code\nvar mySearch = {\n ajaxSearch: undefined, // variable for use with getJSON. useful if you want to stop the ajax call\n current: undefined, // variable for keeping up with current search term // this should also meet your requirements for \"cache search\"\n // Method for preforming search, the passing parameter should be the event variable from the action triggering the search\n gitSearch: function(e) {\n // i don't quite understand not touching the HTML as the input has no name, thus it can't post correctly to server,\n // tho I see in your example, you simply add the input value to the request url after a \"/\",\n // thus I assume the server has a rewrite method for proccessing.\n var query = $(this).val(); // because of how we call this method, we can simply use \"$(this)\" to get the input, since this IS the input\n if (mySearch.current == query) return; // ensure we're not preforming same search just performed, possibly less than second ago due to multiple ways of calling // no need to continue, we just did this work\n mySearch.current = query; // reset current search value\n if (!query) alert(\"Please enter a term to search for\");\n else {\n $('#results').html('Searching...'); // sets content of results area to show it's doing something\n $.getJSON(mySearch.requestBaseUrl + query)\n .done(function(json) {\n if (json['repositories']) {\n if (json.repositories.length) { // works if return is array (it is) and determines if ANY results were returned\n // clear results from previous search and add our new &lt;ul&gt;\n $('#results').empty().append($('&lt;ul /&gt;'));\n $.each(json.repositories, function(i, v) {\n // variable \"v\" is same as json.repositories[i]\n var txt = v.owner + \" / \" + v.name,\n css = 'cursor: pointer; list-style-type: none; width: 500px;',\n sb = [ // literal array for creating each Line of text\n \"Repo Lanuage is : \" + v.language,\n \"There are \" + v.followers + \" followers of this repo.\",\n \"The URL of the repo is : \" + v.url,\n \"The description of the repo : \" + v.description\n ],\n msg = sb.join('\\n'); // this joins our \"string builder\"/\"literal array\" into ONE string using \"\\n\" between each \"line\" (item in array)\n // easy syntax to make new element using jQuery\n $('&lt;li /&gt;', { text: txt, style: css })\n .attr('title', 'Created: ' + new Date(v.created))\n .data('msgAlert', msg) // assign msg for alert to this elements data for recall\n .appendTo($('#results ul'));\n });\n }\n else $('#results').html($('&lt;h2 /&gt;', { text: 'No results found.' }));\n }\n else alert('Could not find any values.');\n })\n .fail(function(status){ $('#results').html('ERROR: Please see console.'); console.log(status); });\n }\n },\n requestBaseUrl: 'https://api.github.com/legacy/repos/search/',\n tmrSearch: undefined // this will be used for my \"stopped typing\" search\n };\n\n$(function() { // same as doc.onready / (function(window)) keeps the window variable closer at hand, but i see no reason for it's use here\n // add your page styling.\n $('&lt;style /&gt;', { html: 'body { background-image:url(http://n2.9cloud.us/766/a_beautiful_large_scale_shot_for_th_100120255.jpg); font-size:20px; font-family:\"Arial, Helvetica\", sans-serif; }' }).appendTo(\"head\");\n\n // since we changed to onready, we can just alert the info, unless you want it to wait a second\n alert(\"Please type the term to search GitHub for in the text field and hit the ENTER key.\");\n // also, for future reference, when you use setTimeout with a function as you did, you can shortent he call to simply:\n // setTimeout(alertInstructions, 1000);\n\n // As for the calls to begin search, I will go 3 avenues.\n // First I will include using \"Enter\" key, but only on input focus\n // I will also want to preform search on input blur and after user stops typing for a second (like a google quick search)\n // \n // I, personally like to delegate my events to $(document), as this makes them readily available for dynamic elements,\n // however, this can be bad practice. If you attach to many events to the DOM as such, you can end up with overhead that\n // could crash your program. Since your base example gives us ID's of static elements, I will use those, but I suggest you\n // read jQuery docs about delegating events. Newer jQuery, as you're using, uses .on -&gt; http://api.jquery.com/on/\n $('#search') // the following structure is called \"chaining\". jQuery provides us this nice way to make multiple calls to one element without recalling that element\n .on('blur', mySearch.gitSearch) // this is all that's needed to register this method to this event // blur is when input loses focus (click on something else)\n .on('keypress', function(e) {\n // this will apply the Method as if it was the base function of this event\n // .apply is JS way to trigger a method and send, as params, what to use as \"this\" and what arguments to feed\n // note, arguments must be as an array. Doing [e], wraps our Event Argument passed from \"keypress\" onto the parameter of our method\n if (e.which == 13) mySearch.gitSearch.apply(this, [e]);\n })\n // the following is one easy way to determine when user stops typing and begin search.\n // The proccess is simple. Simply clear a timer on keydown, then reset it on keyup. When the timer reaches its end, it preforms the search!\n .on('keydown', function(e) {\n clearTimeout(mySearch.tmrSearch);\n })\n .on('keyup', function(e) {\n var $this = this; // needed to pass \"this\" variable on Timeout\n mySearch.tmrSearch = setTimeout(function() { mySearch.gitSearch.apply($this, [e]); }, 2000); // sets to 2 seconds.\n // if not cleared by keydown within the given time, then \"gitSearch\" will be preformed!\n })\n\n // in finally doing the \"gitSearch\" method, I noticed you do have a need for delegating events, thus I will delegate those events here\n // by doing this here, and assinging to document, we don't have to keep rebuilding those event methods everytime you get new search results.\n // Keep in mind, many, including jQuery recomend using a parent node. However, years of experience with this have taught me, it's not really neccessary\n // unless you're delegating A LOT of events to the Document. If you have a larger application, find static parents to delegate events too!\n // Also, I personally am not a big fan of hover. I've had problems in the past with upgrading jQuery and finding unexpected changes on hover methods,\n // thus I go back to good old mouse-movements\n $(document)\n .on('mouseenter', '#results li', function(e) { $(this).css({'color':'#ffffff'}); })\n .on('mouseleave', '#results li', function(e) { $(this).css({'color':'#000000'}); })\n .on('click', '#results li', function(e) {\n var msg = $(this).data('msgAlert');\n if (msg) alert(msg);\n alert(msg); // joins our \"string builder\", literal array into ONE string using \"/n\" between each \"line\" (item in array)\n });\n})\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/SpYk3/XA4PP/\" rel=\"nofollow noreferrer\"><h1>ExAmPlE</h1></a></p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:31:30.213", "Id": "58628", "Score": "0", "body": "This looks good, but I stand by a couple of notes in my comment: a. Don't append to the DOM in a loop, create the ul node and append to that and don't append `ul` to `#results` till the loop is done. b. No need for `mouseenter`/`mouseleave` styles in this case; that can be done in CSS. I would also put everything inside `$.each` into its own function because that's a lot of indents!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:34:57.253", "Id": "58630", "Score": "0", "body": "@VLS point taken, however, in 15 years I've yet to have one problem appending to Dom in a loop and have rarely (cept on long page docs) noticed a difference between that and \"createNwait\". I thought about the css idea, but figured i'd show the new person some more jQuery usage and explination for. Totally agree with .each to function, but again, trying to keep it readable enough for the OP to go through this line by line and hopefully follow along w/out too much difficulty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:38:31.220", "Id": "58632", "Score": "0", "body": "@VLS as a matter of fact, if i was 100% to do it \"my way\", ALL of the CSS would be posted in a `<style>` tag and pasted to header. Including the individual CSS on the `li`s" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:42:56.060", "Id": "58634", "Score": "0", "body": "Agreed, I had that in my note, just forgot about it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T16:06:47.790", "Id": "35929", "ParentId": "35714", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T19:26:09.760", "Id": "35714", "Score": "3", "Tags": [ "javascript", "jquery", "json", "dom" ], "Title": "JavaScript app to search GitHub using JSON API" }
35714
<p>I'm creating a chess engine and I'm currently in the stage of adding validation. I'm starting off with the major validationrule: checking if a piece can move to the given target destination.</p> <p>I have setup a system that allows me to very fluently define how a piece can move and validation is done on these rules. </p> <p>An example for a <code>Pawn</code>:</p> <pre><code>public class Pawn : Piece { public Pawn(Color color) : base(color) { Name = ChessPiece.Pawn; Worth = 1; } public override List&lt;Move&gt; GetPossibleMoves() { return new List&lt;Move&gt; { new Move { Amount = 1, Direction = Direction.Forwards, }, new Move { Amount = 2, Direction = Direction.Forwards, } }; } } </code></pre> <p>Or a <code>Rook</code>:</p> <pre><code> public override List&lt;Move&gt; GetPossibleMoves() { return new List&lt;Move&gt; { new Move { Amount = 7, Direction = Direction.Vertical, }, new Move { Amount = 7, Direction = Direction.Horizontal, }, }; } </code></pre> <p>My Tests to check the code:</p> <pre><code> [TestMethod] public void AllowedPawnMoveValidatorWithValidInput() { var chessboard = _testCaseProvider.GetChessboardForPawnMoves(); var validator = new AllowedMoveValidator(); // Test if a few pawns can move 1 spot ahead foreach (var location in chessboard.ToList().Where(x =&gt; x.Piece is Pawn)) { var endLocation = new Location { X = location.X, Y = location.Piece.Color == Color.White ? location.Y + 1 : location.Y - 1, Piece = null }; Assert.AreEqual(ValidationResult.Allowed, validator.Validate(chessboard, location, endLocation), "Move pawn 1 spot ahead. X = " + location.X + "; Y = " + location.Y); } // Test if a few pawns can move 2 spots ahead foreach (var location in chessboard.ToList().Where(x =&gt; x.Piece is Pawn)) { var endLocation = new Location { X = location.X, Y = location.Piece.Color == Color.White ? location.Y + 2 : location.Y - 2, Piece = null }; Assert.AreEqual(ValidationResult.Allowed, validator.Validate(chessboard, location, endLocation), "Move pawn 2 spots ahead. X = " + location.X + "; Y = " + location.Y); } } [TestMethod] public void AllowedPawnMoveValidatorWithInValidInput() { var chessboard = _testCaseProvider.GetChessboardForPawnMoves(); var validator = new AllowedMoveValidator(); // Test if a few pawns can move 1 spot ahead foreach (var location in chessboard.ToList().Where(x =&gt; x.Piece is Pawn)) { // Too far ahead var endLocation = new Location { X = location.X, Y = location.Piece.Color == Color.White ? location.Y + 3 : location.Y - 3, Piece = null }; Assert.AreEqual(ValidationResult.Forbidden, validator.Validate(chessboard, location, endLocation), "Move pawn 1 spot ahead. X = " + location.X + "; Y = " + location.Y); // Changes column endLocation = new Location { X = location.X + 2, Y = location.Piece.Color == Color.White ? location.Y + 1 : location.Y - 1, Piece = null }; Assert.AreEqual(ValidationResult.Forbidden, validator.Validate(chessboard, location, endLocation), "Move pawn 2 spots ahead. X = " + location.X + "; Y = " + location.Y); } } [TestMethod] public void AllowedRookMoveValidatorWithValidInput() { var chessboard = _testCaseProvider.GetChessboardForRookMoves(); var validator = new AllowedMoveValidator(); foreach (var location in chessboard.ToList().Where(x =&gt; x.Piece is Rook)) { // Horizontal movement var endLocation = new Location { X = location.X &gt;= 5 ? 2 : 8, Y = location.Y, Piece = null }; Assert.AreEqual(ValidationResult.Allowed, validator.Validate(chessboard, location, endLocation), "Move rook horizontally. X = " + location.X + "; Y = " + location.Y); // Vertical movement endLocation = new Location { X = location.X, Y = location.Y &gt;= 5 ? 1 : 7, Piece = null }; Assert.AreEqual(ValidationResult.Allowed, validator.Validate(chessboard, location, endLocation), "Move rook vertically. X = " + location.X + "; Y = " + location.Y); } } </code></pre> <p>The actual validation:</p> <pre><code>public class AllowedMoveValidator : IMoveValidator { public ValidationResult Validate(HashSet&lt;Location&gt; board, Location start, Location end) { var piece = start.Piece; var possibleMoves = piece.GetPossibleMoves(); foreach (var move in possibleMoves) { if (piece.Color == Color.White) { if (move.Direction == Direction.Vertical) { if (move.Orientation == Orientation.Forwards) { if ((end.Y &lt;= start.Y + move.Amount) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } else if (move.Orientation == Orientation.Downwards) { if ((end.Y &gt;= start.Y - move.Amount) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } else if (move.Orientation == Orientation.BothForwardsAndDownwards) { if (((end.Y &gt;= start.Y - move.Amount) || (end.Y &lt;= start.Y + move.Amount)) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } // End Vertical Direction } } else if (piece.Color == Color.Black) { if (move.Direction == Direction.Vertical) { if (move.Orientation == Orientation.Forwards) { if ((end.Y &gt;= start.Y - move.Amount) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } else if (move.Orientation == Orientation.Downwards) { if ((end.Y &lt;= start.Y + move.Amount) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } else if (move.Orientation == Orientation.BothForwardsAndDownwards) { if (((end.Y &gt;= start.Y - move.Amount) || (end.Y &lt;= start.Y + move.Amount)) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } // End Vertical Direction } } if (move.Direction == Direction.Horizontal) { if (move.Orientation == Orientation.Sideways) { if ((end.X &lt; start.X) &amp;&amp; end.Y == start.Y) { if (end.X &lt;= start.X - move.Amount) { return ValidationResult.Allowed; } } else if ((end.X &gt; start.X) &amp;&amp; end.Y == start.Y) { if (end.X &lt;= start.X + move.Amount) { return ValidationResult.Allowed; } } } // End Horizontal Direction } if (move.Direction == Direction.Diagonal) { if (move.Orientation == Orientation.BothForwardsAndDownwards) { // TODO } } } // End loop return ValidationResult.Forbidden; } } </code></pre> <p>How would you advice I rewrite the validation? The way it is right now works (I have only tested it with pawns but I expect it to work for any other piece as well). Diagonally hasn't been implemented yet. There is a lot of duplication of the validation code because </p> <p>White -> Forwards</p> <p>is the same as </p> <p>Black -> Backwards</p> <p>But this would require for every move to check if it's black or white which doesn't look like a big improvement.</p> <p>Suggestions?</p> <p>Thanks to the wonderful suggestion by Michael Shaw that one of enums is in fact obsolete, I have been able to slim down the code tremendeously. Below you will find the current code I'm working with (all tests pass). I believe it has been simplified a lot, it's definitely easier to work with.</p> <p>I will also swap my earlier versions of the test with a better formatted one. It takes a lot of unnecessary space, you can always look it up in the post history.</p> <pre><code>public class AllowedMoveValidator : IMoveValidator { public ValidationResult Validate(HashSet&lt;Location&gt; board, Location start, Location end) { var piece = start.Piece; var possibleMoves = piece.GetPossibleMoves(); foreach (var move in possibleMoves) { // Vertical moves - Rooks, Queens, Kings if (move.Direction == Direction.Vertical) { if (((end.Y &gt;= start.Y - move.Amount) || (end.Y &lt;= start.Y + move.Amount)) &amp;&amp; end.X == start.X) { return ValidationResult.Allowed; } } // Forward moves - Pawns if (move.Direction == Direction.Forwards) { if (end.X == start.X) { if (piece.Color == Color.White) { if (end.Y &lt;= start.Y + move.Amount) { return ValidationResult.Allowed; } } else if (piece.Color == Color.Black) { if (end.Y &gt;= start.Y - move.Amount) { return ValidationResult.Allowed; } } } } // Horizontal moves - Rooks, Queens, Kings if (move.Direction == Direction.Horizontal) { if (end.Y == start.Y) { if (end.X &lt; start.X) { if (end.X &gt;= start.X - move.Amount) { return ValidationResult.Allowed; } } else if (end.X &gt; start.X) { if (end.X &lt;= start.X + move.Amount) { return ValidationResult.Allowed; } } } } // Diagonal moves - Bishops if (move.Direction == Direction.Diagonal) { // TODO } } return ValidationResult.Forbidden; } } </code></pre> <p>Current <code>Move</code> definition and other enums:</p> <pre><code>public enum Direction { Horizontal, Vertical, Forwards, Diagonal } public class Move { public Direction Direction { get; set; } public int Amount { get; set; } } public enum Color { Black, White } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:25:07.380", "Id": "58022", "Score": "0", "body": "I have restructured the code a little. Since the horizontal and diagonal moves will not be influenced by black or white I have moved them outside the loop. The code is already easier to read, but it still doesn't feel entirely right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:24:55.493", "Id": "58028", "Score": "0", "body": "`Color` is a selfdefined enum ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:27:03.550", "Id": "58029", "Score": "0", "body": "I'll get back to this post, but for now I'll say that having the concept of *color* in your validation is rather annoying. And are you using `System.Drawing.Color` or a custom enum? (Ok good!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:15:56.833", "Id": "58038", "Score": "0", "body": "Could you include the listings for your custom enums? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:17:10.753", "Id": "58039", "Score": "0", "body": "@retailcoder: I'll add them in a moment. Take a look at the updated code though, I have removed one of the enums and it's looking a lot more slim now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:21:03.870", "Id": "58040", "Score": "0", "body": "That's awesome, but I think you should keep your original code in your post; otherwise @MichaelShaw's answer requires readers to [as you mentioned] look at your post's history - i.e. it makes his [very nice] answer sort of moot. Try not to update your original code with incoming ideas - you can always post another code review request (/question) later :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:22:56.140", "Id": "58044", "Score": "1", "body": "@retailcoder: Yeah, I've simply added the new version of my validator to the end. I figured I could overwrite the tests because all that changed was a little formatting (which is still reflected in Michael's post since he copied the original)." } ]
[ { "body": "<p>There are 33 if statements in your validation, all highly nested. There are lots of ways you could deal with that; what immediately comes to mind are helper functions. Don't be afraid to use helper functions, especially if you can give them a good, descriptive name. </p>\n\n<p>For instance, you could replace this:</p>\n\n<pre><code> if (piece.Color == Color.White) {\n // lots of stuff\n } else if (piece.Color == Color.Black) {\n // lots of other stuff\n }\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code> if (piece.Color == Color.White) {\n moveWhite();\n } else {\n moveBlack();\n }\n</code></pre>\n\n<p>and keep doing that for subdecisions. </p>\n\n<p>Looking at moveWhite() and moveBlack(), it seems like we're duplicating effort; move(Color) would be better. This would help prevent problems where there's a bug in one branch but not in the other. </p>\n\n<p>After looking at some of the nested ifs, it looks like a decision table might help, if not solve the whole problem. The idea is to make a (possibly multidimensional) array, and index into it to find the solution. So you could do something like <code>decisionTable[White][Vertical][Forwards]</code> and get back a function (or an object with a method named <code>.decide()</code>) that you could give <code>start</code>, <code>end</code>, and <code>move</code>, and it would tell you whether it validates. </p>\n\n<p>Some nitpicks: </p>\n\n<p>In the definition of a pawn, you have an amount, which is an integer. That seems like it will be problematic when it comes to pieces which can cross the board in a single move. You also have both a direction and an orientation for the move, which seems duplicative. Either get rid of one, or find a better name for one, so that it's clear why we need both. </p>\n\n<p>Making forwards for white different from forwards for black seems odd. Why not make forwards a single direction that applies differently to each color? Conceptually, pawns move forwards whether they're white or black. </p>\n\n<p><code>Orientation.BothForwardsAndDownwards</code> is a bit wordy and not quite clear. </p>\n\n<p>This:</p>\n\n<pre><code> Assert.AreEqual(ValidationResult.Forbidden,\n validator.Validate(chessboard,\n location,\n new Location {\n X = location.X,\n Y = location.Piece.Color == Color.White ? location.Y + 3 : location.Y - 3,\n Piece = null\n }\n ));\n</code></pre>\n\n<p>seems like it could be better formatted like this:</p>\n\n<pre><code> Assert.AreEqual(ValidationResult.Forbidden,\n validator.Validate(chessboard,\n location,\n new Location {\n X = location.X,\n Y = location.Piece.Color == Color.White \n ? location.Y + 3 \n : location.Y - 3,\n Piece = null\n })\n );\n</code></pre>\n\n<p>I'm not entirely sure that's an idiomatic C# way of formatting it, but it doesn't run off the page as much. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:50:47.013", "Id": "58033", "Score": "0", "body": "I'm rather hesitant to extract everything into different methods because this would rarely add any additional value. Most of the checks are 2 lines of code, including the `if` statement so the gain would be minimal. In fact it would be cumbersome because I'd have to check every method if I wanted to advance trough the tree to check for bugs. I just fixed a bug with horizontal movement (rooks now work, yay!) and I must say that finding a fix went fluently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:55:23.770", "Id": "58034", "Score": "0", "body": "The decision table looks very interesting though, I'll have to look into that. How is this typically implemented? Or is it more a mathematical concept? Could you clarify how the `int amount` causes issues? An amount of `2` should go two to the side and two to the front/back, there is an easy correlation. Good point about direction/orientation, I'll look into revising this. Forwards for white/black differ in the addition or subtraction of the `amount`. I have formatted the code by putting the new location in a separate variable. I appreciate your feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:36:21.843", "Id": "58057", "Score": "1", "body": "If you can give 2 lines of code a clear, simple name, it would still be worth extracting them to a helper function. I was thinking more of extracting larger chunks of nested stuff, though, especially if they're repeated. If you go with helper functions, the idea is to extract bits that make sense as a standalone unit, so to verify stuff works, you don't go down the tree looking for bugs, you look at individual functions, separately verify them, and then verify that the logic as a whole (using the functions) works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:56:01.137", "Id": "58060", "Score": "0", "body": "Decision tables are a generic idea (and an old one). It's usually implemented as an array of some kind, with the indices being what you want to decide based on, and the entries being what the decision is. I suggested having a bit of code in the entries, because I was assuming that there would be a lot of values for `end.X`, `start.Y`, `move.Amount` and so forth; if that's not the case (or things can be changed so that's not the case) then the table could just hold `True` or `False`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:57:35.893", "Id": "58061", "Score": "0", "body": "I was thinking `amount` would cause issues with rooks and knights, but looking at some other comments, it looks like you got around any possible issues." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:35:20.800", "Id": "35728", "ParentId": "35718", "Score": "5" } }, { "body": "<p>Let's recap what we have here:</p>\n\n<ul>\n<li>We have a <code>Pawn</code> which <em>is a</em> <code>Piece</code> that has a <code>Color</code> and a <code>Worth</code>, that knows what its possible <code>Moves</code> are.\n<ul>\n<li>I don't see <code>Name</code> nor <code>Color</code> defined as properties of your <code>Pawn</code>, so I'm assuming they're defined in the <code>Piece</code> class. If that's the case, you should pass them to the base constructor and make them <code>readonly</code> - it's not like a <code>Pawn</code> ever turns into a <code>Queen</code> right? (no, it shouldn't - if a <code>Pawn</code> gets to the end of the board you should spawn a new <code>Queen</code> and kill the <code>Pawn</code>).</li>\n<li>If <code>Worth</code> relates to how many points a piece is <em>worth</em>, I think <code>Value</code> or even <code>ScoreValue</code> could be a better name.</li>\n<li>The way you have it, it looks like <em>every move</em> can be 1 or 2 steps forward, which is wrong. Your <code>Pawn</code> is missing some <code>bool _hasPlayedFirstMove</code> so that <code>GetPossibleMoves()</code> can only return the 1-step forward move whenever that flag is <em>true</em>.</li>\n</ul></li>\n<li><p>We have a <code>Move</code> which has a <code>Direction</code> and an <code>Amount</code>.</p>\n\n<ul>\n<li>Such a small class could affort to be a <code>struct</code>.</li>\n<li><p>I wonder how the <code>Knight : Piece</code> will move... as a matter of fact you seem to have <em>saved the best for last</em>, right? It doesn't look like your code can actually support that piece very well, unless you added a couple more values to your <code>Direction</code> enum - consider using these values:</p>\n\n<ul>\n<li><code>Direction.Forward</code></li>\n<li><code>Direction.Backward</code></li>\n<li><code>Direction.Left</code></li>\n<li><code>Direction.Right</code></li>\n<li><code>Direction.ForwardLeft</code></li>\n<li><code>Direction.ForwardRight</code></li>\n<li><code>Direction.BackwardLeft</code></li>\n<li><code>Direction.BackwardRight</code></li>\n<li><code>Direction.KnightForwardLeft</code></li>\n<li><code>Direction.KnightForwardRight</code></li>\n<li><code>Direction.KnightLeftForward</code></li>\n<li><code>Direction.KnightLeftBackward</code></li>\n<li><code>Direction.KnightRightForward</code></li>\n<li><code>Direction.KnightRightBackward</code></li>\n<li><code>Direction.KnightBackwardLeft</code></li>\n<li><code>Direction.KnightBackwardRight</code></li>\n</ul></li>\n</ul></li>\n<li><p>Finally we have an <code>AllowedMoveValidator</code> with a <code>Validate</code> method that takes the game board and a <code>start</code> and <code>end</code> <em>locations</em>.</p>\n\n<ul>\n<li>I find it's a bit conceptually awkward that a <code>Location</code> <em>has a</em> <code>Piece</code>. I would have thought a <code>Piece</code> <em>has a</em> <code>Location</code>, which means I would have taken the board along with a <code>Piece</code> and a target <code>Location</code> for parameters.</li>\n<li>As I hinted in the comments, I don't think the color is relevant here. The easy-and-not-so-efficient way out would be to literally <em>flip the board</em> so that <code>Forward</code> mean the same thing whether you're playing a black or a white piece.</li>\n</ul></li>\n</ul>\n\n<p>Now to address the main issue here, which is the atrocious nesting of conditionals (seriously: <code>foreach/if/if/if/if</code>), I think it's worth noting that you're always branching on enum values. This looks like a job for a <code>Dictionary&lt;Direction, Action&gt;</code>, where <code>Action</code> points to <strong>a method that <em>does one thing</em></strong>: move a piece in a very specific direction.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:10:57.413", "Id": "58050", "Score": "0", "body": "Some great remarks! The `Worth` and `Name` are defined in the constructor of the subclass and uses a `protected set;` in the base class. I definitely overlooked pawns only being able to make two moves when they're at their start position, thanks! The knight will not use this method of move validation. Instead, I will create a separate validator that will hardcodedly check for the up-to-8 spots a knight can go to. It's only one piece and I don't expect the chess rules to change anytime soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:14:29.523", "Id": "58051", "Score": "0", "body": "I was under serious doubt with my approach of Location -> Piece or Piece -> Location. At first I wanted to do it the way you describe, but changed afterwards for a different reason. This reason became obsolete after I went with a different validation approach (the validators I have now). It's a matter of perspective: either you say that a piece has a location or you say that a board contains locations where pieces might be on. The way it is now works and I don't think I will gain anything by changing the perspective. Your last suggestion is spot on. Once everything works, I will refactor it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:15:16.303", "Id": "58053", "Score": "0", "body": "(RE: first comment) Right, but then you'll duplicate lots of code doing that - moving the knight is easy once you know you want it to go `KnightForwardLeft`: move it `Forward` x1 and then `ForwardLeft` x1. If you have *methods that do one thing* this should be a *piece* of cake :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:08:07.037", "Id": "58104", "Score": "1", "body": "Regarding the `Direction`s, why not let a `Direction` be two integers: `deltaX`, `deltaY`? Having 16 possible values for a `Direction` doesn't seem clean to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:24:33.290", "Id": "58107", "Score": "0", "body": "@SimonAndréForsberg the thought occurred to me, but that means a complete redesign of `Move`.. and I thought it'd be *good enough* to start with directions that support a `Knight`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:27:34.777", "Id": "58109", "Score": "0", "body": "@retailcoder \"good enough\" rarely satisfies me when it comes to code :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:02:04.480", "Id": "35735", "ParentId": "35718", "Score": "4" } } ]
{ "AcceptedAnswerId": "35728", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:45:09.633", "Id": "35718", "Score": "4", "Tags": [ "c#" ], "Title": "Rewriting an extensive validation method with duplication of code in different circumstances" }
35718
<p>I am having an issue with the following query returning results a bit too slow and I suspect I am missing something basic. My initial guess is the 'CASE' statement is taking too long to process its result on the underlying data. But it could be something in the derived tables as well. </p> <p>The question is, how can I speed this up? Are there any glaring errors in the way I am pulling the data? Am I running into a sorting or looping issues somewhere? The query runs for about 40 seconds, which seems quite long. C# is my primary expertise, SQL is a work in progress. Any tips would be greatly appreciated!</p> <pre><code> SELECT hdr.taker , hdr.order_no , hdr.po_no as display_po , cust.customer_name , hdr.customer_id , 'INCORRECT-LARGE ORDER' + CASE WHEN (ext_price_calc &gt;= 600.01 and ext_price_calc &lt;= 800) and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.01,2) THEN '-1%: $' + cast(cast(ext_price_calc * -.01 as decimal(18,2)) as varchar(255)) WHEN ext_price_calc &gt;= 800.01 and ext_price_calc &lt;= 1000 and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.02,2) THEN '-2%: $' + cast(cast(ext_price_calc * -.02 as decimal(18,2)) as varchar(255)) WHEN ext_price_calc &gt; 1000 and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.03,2) THEN '-3%: $' + cast(cast(ext_price_calc * -.03 as decimal(18,2)) as varchar(255)) ELSE 'OK' END AS Status FROM (myDb_view_oe_hdr hdr LEFT OUTER JOIN myDb_view_customer cust ON hdr.customer_id = cust.customer_id) LEFT OUTER JOIN wpd_view_sales_territory_by_customer territory ON cust.customer_id = territory.customer_id LEFT OUTER JOIN (select order_no, SUM(ext_price_calc) as ext_price_calc from (select hdr.order_no, line.item_id, (line.qty_ordered - isnull(qty_canceled,0)) * unit_price as ext_price_calc from myDb_view_oe_hdr hdr left outer join myDb_view_oe_line line on hdr.order_no = line.order_no where line.delete_flag = 'N' AND line.cancel_flag = 'N' AND hdr.projected_order = 'N' AND hdr.delete_flag = 'N' AND hdr.cancel_flag = 'N' AND line.item_id not in ('LARGE-ORDER-1%','LARGE-ORDER-2%', 'LARGE-ORDER-3%', 'FUEL','NET-FUEL', 'CONVENIENCE-FEE')) as line group by order_no) as order_total on hdr.order_no = order_total.order_no LEFT OUTER JOIN (select order_no, count(order_no) as convenience_count from oe_line with (nolock) left outer join inv_mast inv with (nolock) on oe_line.inv_mast_uid = inv.inv_mast_uid where inv.item_id in ('LARGE-ORDER-1%','LARGE-ORDER-2%', 'LARGE-ORDER-3%') and oe_line.delete_flag &lt;&gt; 'Y' group by order_no) as fee_count on hdr.order_no = fee_count.order_no INNER JOIN (select order_no, unit_price from oe_line line with (nolock) where line.inv_mast_uid in (select inv_mast_uid from inv_mast with (nolock) where item_id in ('LARGE-ORDER-1%','LARGE-ORDER-2%', 'LARGE-ORDER-3%'))) as fee_price ON fee_count.order_no = fee_price.order_no WHERE hdr.projected_order = 'N' AND hdr.cancel_flag = 'N' AND hdr.delete_flag = 'N' AND hdr.completed = 'N' AND territory.territory_id = ‘CUSTOMERTERRITORY’ AND ext_price_calc &gt; 600.00 AND hdr.carrier_id &lt;&gt; '100004' AND fee_count.convenience_count is not null AND CASE WHEN (ext_price_calc &gt;= 600.01 and ext_price_calc &lt;= 800) and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.01,2) THEN '-1%: $' + cast(cast(ext_price_calc * -.01 as decimal(18,2)) as varchar(255)) WHEN ext_price_calc &gt;= 800.01 and ext_price_calc &lt;= 1000 and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.02,2) THEN '-2%: $' + cast(cast(ext_price_calc * -.02 as decimal(18,2)) as varchar(255)) WHEN ext_price_calc &gt; 1000 and fee_price.unit_price &lt;&gt; round(ext_price_calc * -.03,2) THEN '-3%: $' + cast(cast(ext_price_calc * -.03 as decimal(18,2)) as varchar(255)) ELSE 'OK' END &lt;&gt; 'OK' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:11:09.967", "Id": "58008", "Score": "0", "body": "Have you indexed your tables properly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:11:52.710", "Id": "58010", "Score": "2", "body": "Yes the tables are all indexed properly. The database is part of our ERP system, not something I created. I'm sure its something in my query design... not the DB itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:16:22.437", "Id": "58020", "Score": "2", "body": "4 outer-joins, two of which contain sub-selects, joined regular to another subselect-with-its-own-subselect .... Then, many of these things are not tables, since they all have 'view' in the name. Wow....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:26:45.973", "Id": "58023", "Score": "0", "body": "What DBMS are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:33:20.647", "Id": "58024", "Score": "0", "body": "@FreshPrinceOfSO MS SQL Server Management Studio 2008, the DB is Sql Server 2008 instance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:44:44.750", "Id": "58025", "Score": "1", "body": "http://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan get a plan, figure out why it's slow from that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:55:22.000", "Id": "58026", "Score": "1", "body": "Thanks for all the comments, through some feedback and research on SO, I was able to determine that everyone was partially right. The LEFT OUTER JOIN's were unnecessary and could be replaced with INNER's. Also I was able to get rid of two of the sub-queries and replaced views with tables. 2 second execution now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:23:05.297", "Id": "58045", "Score": "0", "body": "You're not likely to get a good review with this question, because 1) It's a complex query; 2) We don't know your database schema; 3) You haven't stated the context or purpose of the query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:24:54.990", "Id": "58046", "Score": "1", "body": "Things to try: 1) Run the query with EXPLAIN SELECT …; 2) Distill the performance problem to a simple query that illustrates the bottleneck. (Try eliminating your `CASE` expressions, for example, and see what happens.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:38:18.497", "Id": "58207", "Score": "1", "body": "@Evanlewis Could you add your own solution, explaining what you have done and include your new query? (There's nothing wrong with answering a question yourself)" } ]
[ { "body": "<p>You need to pull some stuff out of your nested queries.</p>\n\n<p>You have aggregate functions inside of a Nested Select Statement for Join Tables. \nThat should be a temp table or a table variable, at the least.</p>\n\n<pre><code>select\n order_no,\n SUM(ext_price_calc) as ext_price_calc\nfrom \n (select\n hdr.order_no,\n line.item_id,\n (line.qty_ordered - isnull(qty_canceled,0)) * unit_price as ext_price_calc \n from myDb_view_oe_hdr hdr left outer join myDb_view_oe_line line\n on hdr.order_no = line.order_no\n where \n line.delete_flag = 'N'\n AND line.cancel_flag = 'N'\n AND hdr.projected_order = 'N'\n AND hdr.delete_flag = 'N'\n AND hdr.cancel_flag = 'N'\n AND line.item_id not in ('LARGE-ORDER-1%','LARGE-ORDER-2%', 'LARGE-ORDER-3%', 'FUEL','NET-FUEL', 'CONVENIENCE-FEE')) as line\ngroup by order_no) as order_total\n</code></pre>\n\n<p>This Query should be made into a Temp Table or a table Variable, so that you can call this table from the query without nesting 3-4 deep here. This is just plain messy.</p>\n\n<p>This is just one of the things that you can do to clean this up.</p>\n\n<p>When you clean it up, you should compare the execution plans to one another, a Select inside of a Select inside of a Select goes through all of those queries more times than is necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:01:27.143", "Id": "35775", "ParentId": "35721", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T21:02:53.973", "Id": "35721", "Score": "2", "Tags": [ "optimization", "sql", "sql-server", "t-sql" ], "Title": "Query too slow - Optimization" }
35721
<p>I'm working on implementing the stochastic gradient descent algorithm for recommender systems (see Funk) using sparse matrices with Scipy.</p> <p>This is how a first basic implementation looks like:</p> <pre><code>N = self.model.shape[0] #no of users M = self.model.shape[1] #no of items self.p = np.random.rand(N, K) self.q = np.random.rand(M, K) rows,cols = self.model.nonzero() for step in xrange(steps): for u, i in zip(rows,cols): e=self.model-np.dot(self.p,self.q.T) #calculate error for gradient p_temp = learning_rate * ( e[u,i] * self.q[i,:] - regularization * self.p[u,:]) self.q[i,:]+= learning_rate * ( e[u,i] * self.p[u,:] - regularization * self.q[i,:]) self.p[u,:] += p_temp </code></pre> <p>I have two questions and I am hoping some seasoned python coders / recommender systems experts here could provide me with some insight into this:</p> <p>1) How often should the error e be adjusted? It is not clear from Funk's and Koren's papers if it should be once for every rating or if it should be once per every factor. Meaning, should i take it out of the for loop, leave it there, or put it even deeper (over the k iterations) ?</p> <p>2) Unfortunately, my code is pretty slow, taking about 20 minutes on ONE iteration over a 100k ratings dataset. This means that computing the factorization over the whole dataset takes about 10 hours. I was thinking that this is probably due to the sparse matrix for loop. I've tried expressing the q and p changes using fancy indexing but since I'm still pretty new at scipy and numpy, I couldn't figure a better way to do it. Do you have any pointers on how i could avoid iterating over the rows and columns of the sparse matrix explicitly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-15T19:52:46.583", "Id": "401038", "Score": "0", "body": "Which matrix is the scipy sparse matrix?" } ]
[ { "body": "<p>There may be other optimizations available, but this one alone should go a long way...</p>\n\n<p>When you do <code>e = self.model - np.dot(self.p,self.q.T)</code>, the resulting <code>e</code> is a dense matrix the same size as your <code>model</code>. You later only use <code>e[u, i]</code> in your loop, so you are throwing away what probably are millions of computed values. If you simply replace that line with:</p>\n\n<pre><code>e = self.model[u, i] - np.dot(self.p[u, :], self.q[i, :])\n</code></pre>\n\n<p>and then replace <code>e[u, i]</code> with <code>e</code>, you will spare yourself a huge amount both of computations and memory accesses, which should boost performance by a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T16:21:02.687", "Id": "58149", "Score": "0", "body": "Thank you. That's a great improvement. I also did some other improvements. I transposed q from the very beginning and called the column directly, instead of calling and transposing the row. I also integrated the learning rate into the error , because it was being called three times. All in all, I manage to get one step to take only about 10 seconds now! Do you think it's worth optimising further with Cython?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T16:33:00.483", "Id": "58152", "Score": "0", "body": "Yes, it almost cetainly is... The problem is that you are updating your `p` and `q` vectors as you progress over the non-zero entries of `model`. This makes it very hard to get rid of the for loops, because `p` and `q` are different for every entry of `model`. If you could delay updating of `p` and `q` until the full `model` has been processed, then you would get different results, but you could speed things up a lot without Cython or C. With your algorithm, I cannot think of any way around that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T16:45:10.087", "Id": "58154", "Score": "0", "body": "Thank you for the insight. Time to learn myself some Cython then! I'll be tackling the Netflix dataset soon, so I need all the speed I can get. I'm going to mark this as answered then." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:52:32.993", "Id": "35731", "ParentId": "35727", "Score": "5" } }, { "body": "<p>Besides the recommendation that Jaime offered, it would be very easy to get performance improvements by using Numba.</p>\n\n<p>There is a tutorial on Numba and matrix factorization <a href=\"http://www.fico.com/en/blogs/analytics-optimization/a-moment-of-science-llvm-example/\" rel=\"nofollow\">here</a>. When Numba works, it requires much less effort than rewriting your code in Cython. In a nutshell, you need to import numba:</p>\n\n<pre><code>from numba.decorators import jit\n</code></pre>\n\n<p>And then add a decorator to your matrix factorization function, by simply adding this:</p>\n\n<pre><code>@jit\n</code></pre>\n\n<p>Before the method definition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T00:04:33.540", "Id": "111655", "ParentId": "35727", "Score": "1" } } ]
{ "AcceptedAnswerId": "35731", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:32:22.200", "Id": "35727", "Score": "4", "Tags": [ "python", "performance", "matrix" ], "Title": "Optimize Scipy Sparse Matrix Factorization code for SGD" }
35727
<p>I am trying to design an exception hierarchy for logging errors.<br> These logs will be used only by developers and not by users.<br> This is a base class that I came up with. </p> <pre><code>#ifndef TSTRING_TYPEDEF #define TSTRING_TYPEDEF typedef std::basic_string &lt;TCHAR&gt; tstring ; #endif struct BaseException // Derive from some standard exception { BaseException () ; BaseException (const tstring &amp;strWhat) ; BaseException (const tstring &amp;strWhat, const unsigned long ulErrorcode) ; // ...Omitted functions here void AddDetail (const tstring &amp;strWhat) ; void AddDetail (const tstring &amp;strWhat, const unsigned long ulErrorcode) ; tstring GetErrorString () const ; private: bool m_bValidErrorCode ; std::vector &lt;tstring&gt; m_vecDetails ; unsigned long m_ulErrorCode ; }; </code></pre> <p>The idea is that an inner function will not always have all the necessary details needed to give useful debugging information, so an inner function will load up an exception with whatever details it can and then throw the exception. The exception will be caught where it can be handled and more information may be added.</p> <p>The error code will usually just be whatever <code>::GetLastError()</code> returns (if applicable).</p> <p>Please note that I won't be catching/wrapping <code>bad alloc</code> calls with this, so I'm not worried about making heap allocations with <code>string</code> and <code>vector</code>.</p> <p>My questions:</p> <ol> <li>I've been searching online for exception class design, and haven't found anything like this. This worries me. Is there something wrong with designing exceptions this way?</li> <li>Are there any considerations to think about when deriving from one of the standard exceptions? Or should I just derive from std::exception and not worry about?</li> <li>One problem with this design is that the format of the string is dependent on this class. Is there any good way to decouple this?</li> </ol> <p>For example, let's a say we have files like this:</p> <p>MainProcess.h</p> <pre><code>class MainProcess { public: // ctors, dtor, functions, etc... private: Config m_config ; // ... }; </code></pre> <p>Config.h</p> <pre><code>class Config { public: // ctors, dtor, etc... std::string ReadValue (const tstring &amp;strFile, const tstring &amp;strSection, const tstring &amp;strKey, const bool bRequired = true, const tstring &amp;strDefault = _T ("")) const ; void WriteValue (const tstring &amp;strFile, const tstring &amp;strSection, const tstring &amp;strKey, const tstring &amp;strValue) const ; }; class ConfigReadException // Derive from something { // ctors, dtor, etc... private: tstring strFile ; tstring strSection ; tstring strKey ; tstring strDefault ; }; class ConfigWriteException // Derive from something { // ctors, dtor, etc... private: tstring strFile ; tstring strSection ; tstring strKey ; tstring strValue ; }; </code></pre> <p>In this case, these <code>ConfigExceptions</code> provide only relevant data and no specific format. But if we do this, then we may end up having to catch many different kinds of exceptions that would clutter our code.</p> <p>Is it a better practice to have exception classes similar to <code>BaseException</code> or is it better to have exception classes to similar to <code>ConfigReadException</code> and <code>ConfigWriteException</code>, or is there a middle ground?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:01:14.703", "Id": "58035", "Score": "1", "body": "Read this: http://programmers.stackexchange.com/a/118187/12917" } ]
[ { "body": "<blockquote>\n <p>1) I've been searching online for exception class design, and haven't found anything like this. This worries me. Is there something wrong with designing exceptions this way?</p>\n</blockquote>\n\n<p>Here is my opinion: <a href=\"https://softwareengineering.stackexchange.com/a/118187/12917\">What is a 'good number' of exceptions to implement for my library</a>?</p>\n\n<blockquote>\n <p>2) Are there any considerations to think about when deriving from one of the standard exceptions? Or should I just derive from std::exception and not worry about?</p>\n</blockquote>\n\n<p>You should probably derive from <code>std::runtime_error</code>.</p>\n\n<blockquote>\n <p>3) One problem with this design is that the format of the string is dependent on this class. Is there any good way to decouple this?</p>\n</blockquote>\n\n<p>Use the string in the exception solely for logging (not for generating a user error message). The exception will generally carry technical information that is not relevant to the user.</p>\n\n<p>But when displaying information to the user you should generate a formatted string at the catch point (not the throw point). This is because you can not tell what the output device is going to be used at the throw point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:26:09.690", "Id": "58132", "Score": "0", "body": "\"If all they can do is log the exception then it is best to just throw an error message rather than lots of data...\" But let's say you don't know what format the log messages will be in. The logging will be done at the catch sites, but you don't know where those catch sites will be. Anyways, that link provides a lot of good insight. I'll wait a couple of days and if no one else provides an answer, I'll mark this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T15:04:24.880", "Id": "58592", "Score": "0", "body": "I was hoping for more opinions, but I guess this site isn't active enough yet. As promised, I'm marking this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:18:39.527", "Id": "58620", "Score": "0", "body": "@jliv902: There are a few C++ people here (true). But its hard to make another argument. You can always try on http://stackoverflow.com or http://programmers.stackexchange.com" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:06:06.220", "Id": "35732", "ParentId": "35730", "Score": "4" } } ]
{ "AcceptedAnswerId": "35732", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T23:42:39.300", "Id": "35730", "Score": "3", "Tags": [ "c++", "exception-handling", "windows" ], "Title": "Exception Handling Design" }
35730
<p>Basically, find x and y given the product = xy and sum = x + y. I would like review on optimization, clean code, and complexity. It looks like O(1), but the <code>while</code> loop makes me wonder if it's something different.</p> <pre><code>/** * x will always be less than or equal to y. */ final class Variables { private final int x; private final int y; Variables(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public String toString() { return " x = " + x + " y = " + y; } } /** * @author SERVICE-NOW\ameya.patil */ public final class SimultaneousEquations { private SimultaneousEquations () {} /** * Provided we dont have positive product and -ve sum, * return value would be the smallest posive integer of the variable. * * @param product : product of x and y * @param sum : sum of x and y * @return : smallest positive integer of x and y. */ private static int getX(int product, int sum) { assert product != 0; assert product &lt; 0 || (product &gt; 0 &amp;&amp; sum &gt; 0); int x = 1; while (x*x != (sum * x - product)) { x++; } return x; } /** * Given a product and a sum, return two variables. * * @param sum : sum of two variables * @param product : product of two variables */ public static Variables getVariables(int product, int sum) { if (product == 0) { if (sum &lt; 0) { return new Variables(sum, 0); } else { return new Variables(0, sum); } } if (product &lt; 0) { int x = getX(product, sum); return new Variables(product/x, x); } if (sum &lt; 0) { int x = -getX(product, -sum); return new Variables(product/x, x); } int x = getX(product, sum); return new Variables(x, product/x); } public static void main(String[] args) { // 0 10 Variables v1 = SimultaneousEquations.getVariables(0, 10); boolean result1 = v1.getX() == 0 &amp;&amp; v1.getY() == 10; System.out.println(result1); // 2 5 Variables v2 = SimultaneousEquations.getVariables(10, 7); boolean result2 = v2.getX() == 2 &amp;&amp; v2.getY() == 5; System.out.println(result2); // -2 5 Variables v3 = SimultaneousEquations.getVariables(-10, 3); boolean result3 = v3.getX() == -2 &amp;&amp; v3.getY() == 5; System.out.println(result3); // 2 -5 Variables v4 = SimultaneousEquations.getVariables(-10, -3); boolean result4 = v4.getX() == -5 &amp;&amp; v4.getY() == 2; System.out.println(result4); // -2 -5 Variables v5 = SimultaneousEquations.getVariables(10, -7); boolean result5 = v5.getX() == -5 &amp;&amp; v5.getY() == -2; System.out.println(result5); } } </code></pre>
[]
[ { "body": "<p>Before we start guessing, lets solve the equations properly. We can substitute the equations so that we get <code>product = x · (sum - x) = -x² + sum·x ⇔ 0 = x² - sum·x + product</code>, with <code>y = sum - x</code>.</p>\n\n<p>The equation can be solved by <code>x = sum/2 ± √(sum²/4 - product)</code> (see <a href=\"https://en.wikipedia.org/wiki/Quadratic_equation#Reduced_quadratic_equation\"><em>Reduced Quadratic Equation</em></a>). Note that we get zero, one or two distinct solutions. For example the special case of <code>product = 0</code> leads to <code>x = sum/2 ± sum/2 ⇒ {x = 0, x = sum}</code>. It is up to you if you pick a specific solution or output both. We have no solutions in ℝ when the expression inside the square root is negative. However, there would still be complex solutions.</p>\n\n<p>Restricting yourself to integers only isn't valid, and will miss some solutions. Consider <code>product = 1, sum = 4</code>. This is solved by <code>x=3.73205, y=0.267949</code>.</p>\n\n<p>Note that as this equation can be solved arithmetically, there is no need for guessing via loops.</p>\n\n<hr>\n\n<p>Because you resort to guessing, your code contains various bugs, e.g. it will fail to handle parameters with no solution like <code>sum = 4, product = 5</code>. Instead, you will go into an unterminated loop.</p>\n\n<p>When unit-testing your code, you should be using a proper test harness instead of some test cases in a <code>main</code>. You might like <em>JUnit</em>. If you want to thoroughly test a method, do not only test a few simple cases:</p>\n\n<ul>\n<li>Explicitly test failure cases, e.g. parameters with no solution.</li>\n<li>Test especially large inputs to see if you correctly guarded against overflows (you didn't).</li>\n<li>Test random input (and record the seed!). It is easy to verify the correctness of the solution. This fuzzy testing may hit cases you didn't consider.</li>\n<li>Cover inputs around zero especially well, e.g. vary each parameter from <code>-2</code> to <code>2</code> by <code>0.5</code>-increments (after verifying manually that each parameter combination actually has a solution). Although this wouldn't hit another bug in your code, the combination <code>0, 0</code> is suspiciously absent. The combination <code>1, 0</code> would have exposed the bug that you don't handle inputs without solutions.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T09:35:09.053", "Id": "58081", "Score": "0", "body": "very useful input.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T09:30:05.407", "Id": "35749", "ParentId": "35744", "Score": "13" } } ]
{ "AcceptedAnswerId": "35749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T06:25:57.410", "Id": "35744", "Score": "5", "Tags": [ "java", "optimization", "algorithm", "mathematics" ], "Title": "Given sum and product, find the two variables" }
35744
<p><a href="http://lesscss.org/" rel="nofollow">LESS</a> is a dynamic stylesheet language that extends <a href="/questions/tagged/css" class="post-tag" title="show questions tagged &#39;css&#39;" rel="tag">css</a> with dynamic behavior such as variables, mixins, operations and functions.</p> <p>LESS runs on both the server-side (with <a href="/questions/tagged/node.js" class="post-tag" title="show questions tagged &#39;node.js&#39;" rel="tag">node.js</a> and Rhino) or client-side (modern browsers only).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T08:53:37.660", "Id": "35747", "Score": "0", "Tags": null, "Title": null }
35747
LESS is a dynamic stylesheet language that extends CSS with dynamic behavior such as variables, mixins, operations and functions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T08:53:37.660", "Id": "35748", "Score": "0", "Tags": null, "Title": null }
35748
<p>I just wrote the code to evaluate a postfix expression and would like it if someone reviews it for me, it works perfectly fine but I'm having trouble adding the character "=" at the end.</p> <pre><code> public static int evalPostfix(String exp) { int res = 0; myStack list = new myStack(); int n1; //result of 1st popping int n2; // result of 2nd popping for (int i = 0; i &lt; exp.length(); i++) { char ch = exp.charAt(i); if (ch == ' ') { } else { if (ch &gt; '0' &amp;&amp; ch &lt; '9') { list.push(ch); // list.printS(); } else { n1 = Integer.parseInt("" + list.pop()); n2 = Integer.parseInt("" + list.pop()); switch (ch) { case '+': list.push(n1 + n2); break; case '-': list.push(n1 - n2); break; case '*': list.push(n1 * n2); break; case '/': list.push(n1 / n2); break; default: System.out.println("Invalid operator order!"); } } } } res = Integer.parseInt("" + list.pop()); return res; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T12:54:15.223", "Id": "58100", "Score": "1", "body": "We are not here to *fix* your code. And it is also very unclear what you mean by \"adding the character `=` at the end\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-18T10:01:58.537", "Id": "260013", "Score": "0", "body": "There is a similar post, http://codereview.stackexchange.com/questions/138894/postfix-calculator/138936" } ]
[ { "body": "<p><strong>Conventions</strong></p>\n\n<p>According to coding conventions, Java class names should start with an uppercase letter. <code>myStack</code> should be <code>MyStack</code>.</p>\n\n<p><strong>Variable names</strong></p>\n\n<p>Whenever you have a comment after declaring a variable, <em>rename the variable to comment itself</em>.</p>\n\n<pre><code>int n1; //result of 1st popping\n</code></pre>\n\n<p>Can be renamed to make the variable name \"comment itself\".</p>\n\n<pre><code>int poppingResult1;\n</code></pre>\n\n<p><strong>If this, then do nothing, else do something</strong></p>\n\n<pre><code>if (ch == ' ') {\n} else {\n</code></pre>\n\n<p>To achieve the same effect, and make the code cleaner, write instead:</p>\n\n<pre><code>if (ch != ' ') {\n</code></pre>\n\n<p><strong>Integer.parseInt</strong></p>\n\n<p>Now, it's not clear which datatype you get from <code>list.pop()</code>. If it is an <code>int</code> (or <code>Integer</code>), then <code>variable = list.pop()</code> will be sufficient.</p>\n\n<p>If it is an Object, instead use <code>Integer.parseInt(String.valueOf(list.pop()))</code></p>\n\n<p>Anyway, <em>if possible</em>, change the values you store in your <code>list</code> to always be of the same type (<code>Integer</code>, preferably). This would make your code cleaner as you don't have to use <code>Integer.parseInt</code> every time you pop something of the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:03:21.107", "Id": "58102", "Score": "0", "body": "May I suggest that instead of 'int poppingResult1' he should name it 'int firstPoppingResult' as his comment suggests that it's the result of 1st popping" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:10:15.613", "Id": "58106", "Score": "0", "body": "@user1021726 Indeed possible, I was thinking that `poppingResult1` and `poppingResult2` would be more clear than having variations in the beginning like `firstPoppingResult` and `secondPoppingResult`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:10:40.240", "Id": "58122", "Score": "0", "body": "about the naming of my class, i was in a hurry and totally forgot about the convention :/" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T12:52:32.743", "Id": "35752", "ParentId": "35750", "Score": "2" } }, { "body": "<p>Consider using approach below where input string contains valid postfix expression.</p>\n\n<pre><code>static int evalPf(String str)\n{\n Scanner sc = new Scanner(str);\n Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;();\n\n while (sc.hasNext()) {\n if (sc.hasNextInt()) {\n stack.push(sc.nextInt());\n continue;\n }\n int b = stack.pop();\n int a = stack.pop();\n char op = sc.next().charAt(0);\n if (op == '+') stack.push(a + b);\n else if (op == '-') stack.push(a - b);\n else if (op == '*') stack.push(a * b);\n else if (op == '/') stack.push(a / b);\n else if (op == '%') stack.push(a % b);\n }\n\n sc.close();\n return stack.pop();\n}\n</code></pre>\n\n<p>In addition to simplifying the logic, I've dropped the <code>public</code> access modifier and used shorter names, with the goal of making the code shorter and easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T07:26:13.907", "Id": "126425", "Score": "0", "body": "Welcome to Code Review! While you have presented a very nice looking solution, your answer doesn't actually review the code. Your implementation contains quite a lot of differences from the original (dropping `public`; renaming to `evalPf`, `op`, `a`, and `b`; adding a modulo operator). Are all of your changes intentional, and could you discuss why you made them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-10T19:04:42.557", "Id": "126727", "Score": "0", "body": "Thank you. This is indeed an alternative approach that may be worth considering in relation to originally submitted code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-10T19:10:48.830", "Id": "126729", "Score": "0", "body": "Dropping public and using shorter names is intentional. The goal is to make code shorter and easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-18T10:03:48.607", "Id": "260015", "Score": "0", "body": "Then I would say the `evalPf` is less clear than `evalPostfix. You could also use a switch on `op` instead of `if .. else if`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-07T23:57:57.707", "Id": "69212", "ParentId": "35750", "Score": "0" } } ]
{ "AcceptedAnswerId": "35752", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T12:41:26.203", "Id": "35750", "Score": "2", "Tags": [ "java", "stack", "math-expression-eval" ], "Title": "Postfix evaluation using a stack" }
35750
<p>I have created a state diagram to show the different transitions and states. I could not find many examples of the state pattern in C, so I have taken an example from a Java state pattern and tried to convert it to C.</p> <p>Is there a way to create the state pattern in C? I'd like some tips or tricks in doing this better using the state pattern.</p> <p><img src="https://i.stack.imgur.com/o49Wp.jpg" alt="State diagram of what I am doing"></p> <p>This is compiled under gcc (GCC) 4.7.2.</p> <p><strong>watch_state.h (interface)</strong></p> <pre><code>#ifndef WATCH_STATE_H_INCLUDED #define WATCH_STATE_H_INCLUDED /* An incomplete type for the state representation itself */ typedef struct tag_watch_state watch_state_t; /* Function pointer to the implementation of the interface */ typedef void (*event_start_func_f)(watch_state_t *sw); typedef void (*event_stop_func_f)(watch_state_t *sw); typedef void (*event_split_func_f)(watch_state_t *sw); typedef enum states_tag states_e; enum states_tag { STOPPED, STARTED, SPLIT }; struct tag_watch_state { /* Events */ event_start_func_f start; event_split_func_f split; event_stop_func_f stop; /* States */ states_e current_state; int time; }; void initialize(watch_state_t *state); char* state_to_string(states_e state); #endif /* WATCH_STATE_H_INCLUDED */ </code></pre> <p><strong>watch_state.c (implementation of interface)</strong></p> <pre><code>#include &lt;stdio.h&gt; #include "watch_state.h" #include "started_state.h" #include "stopped_state.h" #include "split_state.h" static void default_start(watch_state_t *state); static void default_split(watch_state_t *state); static void default_stop(watch_state_t *state); void initialize(watch_state_t *state) { state-&gt;start = default_start; state-&gt;split = default_split; state-&gt;stop = default_stop; state-&gt;current_state = STOPPED; state-&gt;time = 0; } char* state_to_string(states_e state) { switch(state) { case STOPPED: return "STOPPED"; case STARTED: return "STARTED"; case SPLIT: return "SPLIT"; default: return "UNKNOWN"; } } static void default_start(watch_state_t *state) { printf("[ %s ] State [ %s ] time [ %d ] start event isn't supported in the concrete state\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } static void default_split(watch_state_t *state) { printf("[ %s ] State [ %s ] time [ %d ] split event isn't supported in the concrete state\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } static void default_stop(watch_state_t *state) { printf("[ %s ] State [ %s ] time [ %d ] stop event isn't supported in the concrete state\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } </code></pre> <p><strong>started_state.h</strong></p> <pre><code>#ifndef STARTED_STATE_H_INCLUDED #define STARTED_STATE_H_INCLUDED #include "watch_state.h" void start(watch_state_t *state); #endif /* STARTED_STATE_H_INCLUDED */ </code></pre> <p><strong>started_state.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include "started_state.h" #include "stopped_state.h" #include "split_state.h" void start(watch_state_t *state) { unsigned int secs = 5; unsigned int i = 0; /* Do some work here to simulate stop*/ for(i = 0; i &lt; secs; i++) { sleep(1); printf("Starting the stopwatch ...%u\n", i); } /* Initialize with default implementation */ initialize(state); /* Update state */ state-&gt;current_state = STARTED; state-&gt;time = 0; /* Next transition states */ state-&gt;stop = stop; state-&gt;split = split; printf("[ %s ] state [ %s ] time [ %d ]\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } </code></pre> <p><strong>stopped_state.h</strong></p> <pre><code>#ifndef STOPPED_STATE_H_INCLUDED #define STOPPED_STATE_H_INCLUDED #include "watch_state.h" void stop(watch_state_t *state); void start(watch_state_t *state); void split(watch_state_t *state); #endif /* STOPPED_STATE_H_INCLUDED */ </code></pre> <p><strong>stopped_state.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include "stopped_state.h" #include "started_state.h" void stop(watch_state_t *state) { unsigned int secs = 3; unsigned int i = 0; /* Do some work here to stop*/ for(i = 0; i &lt; secs; i++) { sleep(1); printf("Stopping the stopwatch ...%u\n", i); } /* Initialize with default implementation */ initialize(state); /* update current state */ state-&gt;current_state = STOPPED; state-&gt;time = 0; /* Next transition state */ state-&gt;start = start; printf("[ %s ] state [ %s ] time [ %d ]\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } </code></pre> <p><strong>split_state.h</strong></p> <pre><code>#ifndef SPLIT_STATE_H_INCLUDED #define SPLIT_STATE_H_INCLUDED #include "watch_state.h" void split(watch_state_t *state); #endif /* SPLIT_STATE_H_INCLUDED */ </code></pre> <p><strong>split_state.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include "split_state.h" #include "stopped_state.h" void split(watch_state_t *state) { unsigned int secs = 5; unsigned int i = 0; /* Do some work here to stop*/ for(i = 0; i &lt; secs; i++) { sleep(1); printf("Splitting the stopwatch ...%u\n", i); } /* Initialize with default implementation */ initialize(state); state-&gt;current_state = SPLIT; state-&gt;time = secs; /* Next transition states */ state-&gt;stop = stop; state-&gt;split = split; printf("[ %s ] state [ %s ] time [ %d ]\n", __func__, state_to_string(state-&gt;current_state), state-&gt;time); } </code></pre> <p>For context, I have this for testing the states:</p> <p><strong>client_sw.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "watch_state.h" #include "started_state.h" typedef struct tag_client_sw client_sw_t; struct tag_client_sw { watch_state_t state; }; client_sw_t* sw_create(void) { client_sw_t *sw = malloc(sizeof *sw); memset(sw, 0, sizeof *sw); initialize(&amp;sw-&gt;state); /* Next transition */ sw-&gt;state.start = start; return sw; } void sw_destroy(client_sw_t *sw) { free(sw); } void start_watch(client_sw_t *sw) { sw-&gt;state.start(&amp;sw-&gt;state); } void stop_watch(client_sw_t *sw) { sw-&gt;state.stop(&amp;sw-&gt;state); } void split_watch(client_sw_t *sw) { sw-&gt;state.split(&amp;sw-&gt;state); } int main(void) { client_sw_t *sw = NULL; printf("Start your stop watch, extended version\n"); sw = sw_create(); stop_watch(sw); stop_watch(sw); split_watch(sw); start_watch(sw); start_watch(sw); split_watch(sw); split_watch(sw); stop_watch(sw); split_watch(sw); start_watch(sw); stop_watch(sw); sw_destroy(sw); printf("Terminate your stop watch\n"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T10:55:29.287", "Id": "58108", "Score": "1", "body": "OO design patterns in C? Of course you *can* do it, but ick!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-23T03:55:04.557", "Id": "158598", "Score": "0", "body": "As a reference, I would definitely recommend the following article @stackoverflow\nhttp://stackoverflow.com/questions/4112796/are-there-any-design-patterns-in-c In one of the first answers you will find a link to Adam's tutorial in C-Programming state:\nhttp://adampetersen.se/Patterns%20in%20C%202,%20STATE.pdf" } ]
[ { "body": "<p>Looking at the <a href=\"http://en.wikipedia.org/wiki/State_pattern\">State Pattern on Wikipedia</a> I'd say it's more normal to replace the entire function table at once, rather than write individual function pointers.</p>\n\n<p>To this end, I would do this:</p>\n\n<pre><code>struct watch_state {\n event_start_func_f start;\n event_split_func_f split;\n event_stop_func_f stop;\n\n const char *name;\n};\n\nstruct watch_state started = {default_start, split, stop, \"Started\"};\nstruct watch_state stopped = {start, split, default_stop, \"Stopped\"};\nstruct watch_state splitted = {default_start, split, stop, \"Splitted\"};\n</code></pre>\n\n<p>And then this:</p>\n\n<pre><code>struct tag_watch_state {\n /* State */\n struct watch_state *state;\n\n int time;\n};\n</code></pre>\n\n<p>And implement your state switches like this:</p>\n\n<pre><code>static void start(watch_state_t *state)\n{\n unsigned int secs = 5;\n unsigned int i = 0;\n\n /* Do some work here to simulate stop*/\n for(i = 0; i &lt; secs; i++) { \n sleep(1);\n printf(\"Starting the stopwatch ...%u\\n\", i);\n }\n\n /* Update state */\n state-&gt;state = &amp;started;\n state-&gt;time = 0;\n\n printf(\"[ %s ] state [ %s ] time [ %d ]\\n\", __func__, state-&gt;name, state-&gt;time);\n}\n</code></pre>\n\n<p>You can then delete <code>initialize</code> and <code>state_to_string</code> (but make sure you set your initial state in the watch constructor).</p>\n\n<p>Finally, and this is just advice for C code in general, I would consolidate all the functions that really form one module into one .c file, define the private types inside that, and only expose the public facing types, perhaps as abstract structs, in a corresponding header.</p>\n\n<p>In this case I would expect you to have <code>client_sw.c</code>, <code>sw.c</code> and <code>sw.h</code> that exports only the constructor, <code>sw_create</code>, the methods <code>stop_watch</code>, <code>start_watch</code>, and <code>split_watch</code> (each of which I would rename according to the <code>sw_*</code> theme), and the destructor <code>sw_destroy</code>. You would also need to expose the abstract type <code>struct tag_watch_state</code>, but not the internal definition.</p>\n\n<p>My header would look like:</p>\n\n<pre><code>// sw.h\n\ntypedef struct tag_watch_state sw;\n\nsw *sw_create();\nvoid sw_start(sw *);\nvoid sw_split(sw *);\nvoid sw_stop(sw *);\nvoid sw_destroy(sw *);\n</code></pre>\n\n<p>However, if you have a big program, with a lot of states, each requiring a non-trivial amount of code, it would make sense to have one .c file for each state. Even then though, I would endeavour to present only one abstract header to the external callers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:17:07.340", "Id": "35755", "ParentId": "35754", "Score": "9" } }, { "body": "<p>Here are some observations that may help you improve your code. This list starts with some of the picky details and then moves to more substantive issues.</p>\n\n<h2>Turn on all compiler warnings</h2>\n\n<p>Your compiler can provide a useful opinion on the quality of your code, especially if you turn on all of the warnings. When I compile your code using gcc, it says:</p>\n\n<blockquote>\n <p>watch_state.h:12:14: warning: ISO C forbids forward references to ‘enum’ types [-Wpedantic]</p>\n</blockquote>\n\n<p>What it's complaining about is that the <code>typedef</code> is ahead of the <code>enum states_tag</code>. Simply swapping those two lines fixes the error.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>state_to_string()</code> routine returns a <code>char *</code> which points to a constant string. It should therefore have this function prototype:</p>\n\n<pre><code>const char* state_to_string(states_e state)\n</code></pre>\n\n<h2>Omit <code>return 0</code> from the end of <code>main</code></h2>\n\n<p>When a C (or C++) program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put <code>return 0;</code> explicitly at the end of <code>main</code>.</p>\n\n<h2>Use <code>calloc</code> instead of <code>malloc</code> and <code>memset</code></h2>\n\n<p>The current code contains this:</p>\n\n<pre><code>client_sw_t *sw = malloc(sizeof *sw);\nmemset(sw, 0, sizeof *sw);\n</code></pre>\n\n<p>However, that could be more simply written as:</p>\n\n<pre><code>client_sw_t *sw = calloc(1, sizeof *sw);\n</code></pre>\n\n<h2>Don't double-initialize objects</h2>\n\n<p>Contrary to the previous point, the better solution for that particular case would instead be to omit <code>memset</code> because the <code>initialize()</code> initializes all members of the struct. For that reason, there is no reason to write to that memory space before calling initialize.<br>\nAlong the same lines, the <code>stop()</code> routine calls <code>initialize</code> but then explicitly sets several of the <code>state</code> members to the exact same values that were just set in <code>initialize</code>.</p>\n\n<h2>Combine <code>typedef</code> and <code>struct</code> declaration</h2>\n\n<p>The code currently contains these lines:</p>\n\n<pre><code>typedef struct tag_client_sw client_sw_t;\nstruct tag_client_sw {\n watch_state_t state;\n};\n</code></pre>\n\n<p>There's technically nothing wrong with that construction but a more idiomatic way to express that would be to combine them:</p>\n\n<pre><code>typedef struct tag_client_sw {\n watch_state_t state;\n} client_sw_t;\n</code></pre>\n\n<p>Better still, see the next suggestion.</p>\n\n<h2>Avoid pointless wrappers</h2>\n\n<p>The way the <code>client_sw_t</code> structure is created, it's just a wrapper around a <code>watch_state_t</code> type and nothing more. This makes the syntax more complex with no real benefit. I'd recommend simply using a <code>watch_state_t</code> and further, creating it on the stack as an automatic variable rather than allocating it on the heap with <code>malloc</code>.</p>\n\n<h2>Avoid defining type names ending with <code>_t</code></h2>\n\n<p>Types ending with <code>_t</code> are reserved for use by POSIX, so for portability, you should avoid defining your own types that end with <code>_t</code>.</p>\n\n<h2>Clearly differentiate between states and events</h2>\n\n<p>There is a good representation of states in the code, but it's not as explicit for the events. I would recommend creating an <code>enum</code> and a set of names for the events.</p>\n\n<pre><code>typedef enum events_tag { STOP, START, SPLIT, EVENTS_COUNT } events_e;\n</code></pre>\n\n<p>Note that this also defines <code>EVENTS_COUNT</code> which will automatically be set to the number of events. This is handy to be able to write code like this:</p>\n\n<pre><code>static const char *events_name[] = { \"STOP\", \"START\", \"SPLIT\", \"UNKNOWN\" };\nstatic const char* event_to_string(events_e event)\n{\n return (event &lt; EVENTS_COUNT) ? events_name[event] : events_name[EVENTS_COUNT];\n}\n</code></pre>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>There three functions <code>default_start</code>, <code>default_split</code> and <code>default_stop</code> are really all error handlers and are nearly identical. Replace all three with a better named function:</p>\n\n<pre><code>static void sm_error(watch_state_t *state, events_e evt)\n{\n printf(\"[time: %d]: event %s is not allowed in state %s\\n\", \n state-&gt;time, \n event_to_string(evt),\n state_to_string(state-&gt;current_state) \n );\n}\n</code></pre>\n\n<h2>Avoid messy linkage among headers</h2>\n\n<p>A user of this state machine should only have to <code>#include \"watch_state.h\"</code> and not other files. Further, if each state needs to know about the other ones, there's not much point in making them separate files in the first place. In this case, it would make more sense to have just a single <code>watch_state.h</code> header and all of the required functions in <code>watch_state.c</code>.</p>\n\n<h2>Drive a state machine via data, not code</h2>\n\n<p>Generally speaking, a state machine can be implemented in C (or most other languages) via a set of generic functions that operate on a data structure representing the state transitions. If you find yourself writing code to handle the state transitions, question whether it's really necessary. With all state machines there are states and allowed transitions. There are also often actions (code) associated with either the states or the transitions or both. For a robust design, I like to make sure that all possible combinations of states and transitions are enumerated, even the ones that are \"illegal\". Here is the generic code to handle an event:</p>\n\n<pre><code>void handle_event(watch_state_s *state, events_e evt)\n{\n if (evt &gt;= EVENTS_COUNT || state-&gt;current_state &gt;= STATES_COUNT) {\n sm_error(state, evt);\n }\n sm[state-&gt;current_state].action[evt](state, evt);\n}\n</code></pre>\n\n<p>The <code>sm_error()</code> function and <code>sm</code> structure are defined like this:</p>\n\n<pre><code>static void sm_error(watch_state_s *state, events_e evt)\n{\n printf(\"[time: %d]: event %s is not allowed in state %s\\n\", \n state-&gt;time, \n event_to_string(evt),\n state_to_string(state-&gt;current_state) \n );\n}\n\nstatic state_s sm[] = {\n // state -&gt;STOP -&gt;START -&gt;SPLIT \n { STOPPED, { sm_error, sm_start, sm_error }},\n { STARTED, { sm_stop, sm_error, sm_split }},\n { SPLITTED, { sm_stop, sm_error, sm_error }}\n};\n</code></pre>\n\n<p>The <code>state_s</code> type is this:</p>\n\n<pre><code>typedef void (*action_fn)(watch_state_s *state, events_e evt);\n\ntypedef struct state {\n states_e tag;\n action_fn action[EVENTS_COUNT];\n} state_s;\n</code></pre>\n\n<p>Here's how I translated your existing <code>start</code> routine into <code>sm_start</code>:</p>\n\n<pre><code>static void sm_start(watch_state_s *state, events_e evt)\n{\n const unsigned int secs = 5;\n\n /* Do some work here to simulate stop*/\n for(unsigned i = 0; i &lt; secs; i++) { \n sleep(1);\n printf(\"Starting the stopwatch ...%u\\n\", i);\n }\n\n /* Update state */\n state-&gt;current_state = STARTED;\n state-&gt;time = 0;\n\n printf(\"[time: %d]: event %s moved us to state %s\\n\", \n state-&gt;time, \n event_to_string(evt),\n state_to_string(state-&gt;current_state)\n );\n}\n</code></pre>\n\n<p>Finally, here's the translation of <code>main()</code>:</p>\n\n<pre><code>int main(void)\n{\n watch_state_s sw;\n\n printf(\"Start your stop watch, extended version\\n\");\n initialize(&amp;sw);\n\n handle_event(&amp;sw, STOP);\n handle_event(&amp;sw, STOP);\n handle_event(&amp;sw, SPLIT);\n\n handle_event(&amp;sw, START);\n handle_event(&amp;sw, START);\n\n handle_event(&amp;sw, SPLIT);\n handle_event(&amp;sw, SPLIT);\n\n handle_event(&amp;sw, STOP);\n\n handle_event(&amp;sw, SPLIT);\n handle_event(&amp;sw, START);\n handle_event(&amp;sw, STOP);\n\n printf(\"Terminate your stop watch\\n\");\n}\n</code></pre>\n\n<p>It should be easy to see how to fill in the missing pieces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-23T18:07:21.607", "Id": "87777", "ParentId": "35754", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T05:20:24.880", "Id": "35754", "Score": "10", "Tags": [ "c", "design-patterns", "state" ], "Title": "Developing a better state pattern in C" }
35754
<p>I am slowly learning to master JavaScript and particularly the art of self-executing/invoking functions. I have developed a simple JavaScript plugin and I think I have followed the correct standards.</p> <p>It is pretty basic in what it does, it is to store information on a oData BATCH request, which provides functions to add to the batch request, get the string representation (which can then be used in a HTTP request), and I am expanding on it as we speak.</p> <p>However, the code is as follows. It was using jQuery but not any more due to resource constraint.</p> <p>I am generally after comments on what could have been done better. I am doing this in an attempt to reduce the window namespace. Therefore BatchInfo and BatchCacheRequest (which are a bit more specific to my code) are not clogging up the name space, nor do I have to keep an array anywhere do hold the BatchInfo objects.</p> <pre><code>(function () { var info = [], b = { clear: function () { info = []; }, get: function () { return info; }, add: function (command, url, data) { info.push(new BatchInfo(command, url, data)); return info; }, toString: function () { var batchString = ['--batchfull']; batchString.push('Content-Type: multipart/mixed; boundary=batchitems'); for (var i = 0; i &lt; info.length; i++) { batchString.push(''); batchString.push('--batchitems'); batchString.push('Content-Type: application/http'); batchString.push('Content-Transfer-Encoding: binary'); batchString.push(''); batchString.push(info[i].Command + ' ' + info[i].URL + ' HTTP/1.1'); if (info[i].Command !== 'DELETE') { batchString.push('Content-Type: application/json;type=entry'); } batchString.push(''); batchString.push(info[i].Data); } return batchString.join('\r\n') || ''; } }; function BatchInfo(command, url, data) { this.URL = url || ''; this.Command = command || ''; this.Data = data || ''; } function BatchCacheRequest(info, description) { this.Info = info || ''; this.Description = description || ''; this.SubmitDateTime = new Date().toString('yyyy-MM-dd HH:mm'); } window.batch = b; })(); </code></pre> <p>Usage is:</p> <pre><code>batch.add('POST', 'http://www.mywebsite.com', '[some data to post]'); </code></pre> <p>Then <code>toString()</code> will return me a string which is formatted like a BATCH request (which I will use later on in the code).</p> <p>Is there anything I'm doing stupidly bad here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:28:28.857", "Id": "58133", "Score": "1", "body": "your aside question should be posted on [StackOverflow.com](http://stackoverflow.com). the rest of the question seems to be on topic" } ]
[ { "body": "<blockquote>\n <p>Is there anything I'm doing stupidly bad here?</p>\n</blockquote>\n\n<p>Nothing I can see. It works and it seems well written. However, you don't appear to be using BatchCacheRequest?</p>\n\n<blockquote>\n <p>how would I reference functions in b, inside a separate function in b?</p>\n</blockquote>\n\n<p>Two ways (kind of 4) off the top of my head:</p>\n\n<ol>\n<li><code>this.toString()</code> or <code>this[\"toString\"]()</code></li>\n<li><code>b.toString()</code> or <code>b[\"toString\"]()</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:52:54.270", "Id": "58144", "Score": "0", "body": "Thanks Daniel! You are right about BatchCacheRequest - but I will be using that soon! And awesome; I'll give that a shot. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:41:16.767", "Id": "35759", "ParentId": "35756", "Score": "3" } }, { "body": "<p>The way to handle the namespace looks fine.</p>\n\n<p>Instead of putting the reference in the <code>window</code> object, you can just return it out to the global scope and declare it there. That makes it a little clearer that the entire goal for the function is to create a single identifier in the global scope.</p>\n\n<p>As you are only using the <code>b</code> reference once, you can just return the object directly:</p>\n\n<pre><code>var batch = (function(){\n\n var info = [];\n\n function BatchInfo(command, url, data) {\n ...\n }\n\n return {\n\n clear: function () {\n ...\n\n ...\n\n };\n\n}());\n</code></pre>\n\n<p>You might consider to return the object itself from the <code>add</code> method, instead of the <code>info</code> array. That way the method calls can be chained:</p>\n\n<pre><code>add: function (command, url, data) {\n info.push(new BatchInfo(command, url, data));\n return this;\n},\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>var s = batch.\n add('cmd1', 'url1', 'data1').\n add('cmd2', 'url2', 'data2').\n add('cmd3', 'url3', 'data3').\n add('cmd4', 'url4', 'data4').\n toString();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:29:16.323", "Id": "58164", "Score": "0", "body": "I understand the suggestion for `var batch = ...` but it seems like personal preference. Great suggestion for the chaining though. That could be quite handy, though in that case maybe it should be expanded to allow objects to be passed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:06:44.747", "Id": "35766", "ParentId": "35756", "Score": "2" } }, { "body": "<p>Not \"stupidly bad\", but you're invoking <code>.push()</code> far more times than needed. It's a variadic function, so group the items into single invocations.</p>\n\n<p>Additionally, I'd probably put a <code>toString()</code> method on the <code>BatchInfo.prototype</code> that will give back the string representation of the object.</p>\n\n<p>Then put the objects directly into what was the <code>batchString</code> array. That way the <code>.toString()</code> method will be invoked when you call <code>.join()</code>.</p>\n\n<p>I've included additional small changes below as well.</p>\n\n<pre><code>(function () {\n var info = [],\n b = {\n clear: function () {\n info.length = 0; // Clear all references\n },\n get: function () {\n return info;\n },\n add: function (command, url, data) {\n info.push(new BatchInfo(command, url, data));\n return info;\n },\n toString: function () {\n // Put the `BatchInfo` objects directly into the Array.\n // Now we don't need the `for` loop.\n return ['--batchfull',\n 'Content-Type: multipart/mixed; boundary=batchitems']\n .concat(info).join('\\r\\n'); // Not needed-- || '';\n }\n };\n function BatchInfo(command, url, data) {\n this.URL = url || '';\n this.Command = command || '';\n this.Data = data || '';\n }\n // Handle the `toString()` representation here\n BatchInfo.prototype.toString = function() {\n var parts = ['', '--batchitems',\n 'Content-Type: application/http',\n 'Content-Transfer-Encoding: binary',\n '', this.Command + ' ' + this.URL + ' HTTP/1.1'];\n\n if (this.Command !== 'DELETE') {\n parts.push('Content-Type: application/json;type=entry');\n }\n parts.push('', this.Data);\n return parts.join('\\r\\n');\n };\n function BatchCacheRequest(info, description) {\n this.Info = info || '';\n this.Description = description || '';\n this.SubmitDateTime = new Date().toString('yyyy-MM-dd HH:mm');\n }\n window.batch = b;\n})();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:39:43.780", "Id": "58169", "Score": "0", "body": "I really like the use of `BatchInfo.prototype.toString` as it allows each object to handle displaying itself. Great suggestion!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:09:09.903", "Id": "35767", "ParentId": "35756", "Score": "5" } } ]
{ "AcceptedAnswerId": "35767", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:23:07.660", "Id": "35756", "Score": "4", "Tags": [ "javascript", "library" ], "Title": "Developing a JavaScript library" }
35756
<p>The method <code>foo</code> gets a <strong>sorted list with different numbers</strong> as a parameter and returns the count of all the occurrences such that: <code>i == list[i]</code> (where <code>i</code> is the index <code>0 &lt;= i &lt;= len(list)</code>). </p> <pre><code>def foo_helper(lst, start, end): if start &gt; end: # end of recursion return 0 if lst[end] &lt; end or lst[start] &gt; start: # no point checking this part of the list return 0 # all indexes must be equal to their values if abs(end - start) == lst[end] - lst[start]: return end - start + 1 middle = (end + start) // 2 print(lst[start:end+1], start, middle, end) if lst[middle] == middle: #print("lst[" , middle , "]=", lst[middle]) return 1 + foo_helper(lst, middle+1, end) + \ foo_helper(lst, start, middle-1) elif lst[middle] &lt; middle: return foo_helper(lst, middle+1, end) else: return foo_helper(lst, start, middle-1) def foo(lst): return foo_helper(lst, 0, len(lst)-1) </code></pre> <p>My question is: is this code's <strong>worst-case complexity</strong> log(n)? If not, what should I do differently?</p>
[]
[ { "body": "<p>I don't know enough Python to comment on your code, but returning a count of where <code>array[index] == index</code>, should be O(n). And as I said, I dunno Python, but it looks like you are making this a lot more complicated than it is. It could be as simple as</p>\n\n<pre><code>function foo(array) {\n int count = 0;\n for(int i = 0; i &lt; array.length; i++) {\n if(array[i] == i) count++;\n }\n return count;\n}\n</code></pre>\n\n<p>Or maybe I just don't understand what you're trying to accomplish...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:27:21.143", "Id": "58136", "Score": "1", "body": "The function's complexity must be log(n) in the worse case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:30:39.937", "Id": "58137", "Score": "0", "body": "If you mean O(n), then yes. If you mean O(log n) then no. If you mean something else I'm not sure, sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T21:45:43.840", "Id": "58745", "Score": "0", "body": "What you're missing is that the list is sorted and its elements are unique integers. That allows a O(log n) solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:24:20.190", "Id": "35761", "ParentId": "35760", "Score": "-1" } }, { "body": "<p>Because you have a sorted list without numbers duplicates there are several things you can do to optimize the approach.</p>\n\n<p>If your list was not sorted then you would need to check every element <code>O(n)</code> (nothing sorts random list faster than that so you can't 'cheat' sort it first); or if duplicates were allowed then you there could be several independent sections of the list that are continuous and you would need to account for that in your implementation (which would dramatically affect performance).</p>\n\n<p>But as this is a sorted list without duplicates, we can know that there can only be a single section of the list that is continuous, the task then becomes an exercise in finding the start and end of this.</p>\n\n<p>To this end what you need to do is start in the middle of the array and then walk up/down the array moving by half the length of the array section at any time.</p>\n\n<p>By doing this approach you achieve <code>O(log n)</code> performance provided duplicates are not allowed, this is effectively what you have in your question.</p>\n\n<p>While you can sit down and prove this mathematically, but for more complex situations you can quickly verify your suspicions with a brute-force approach by thinking under what situations would your code perform worst, then do some benchmarks with greatly varying size of arrays, then compare the run-time versus the size of the array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:46:44.153", "Id": "58195", "Score": "0", "body": "Doesn't meet the constraints; the code presented has to be O(log n) or faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T03:17:10.010", "Id": "58242", "Score": "0", "body": "why the -1? this code is considered `O(log n)` because that is the average time, and the worst case is `O(n)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T21:55:57.817", "Id": "59144", "Score": "0", "body": "because the problem as stated asks for O(log n) worst-case time" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T16:15:36.350", "Id": "35762", "ParentId": "35760", "Score": "0" } }, { "body": "<p>Ignoring the print, I believe the offered code does operate in O(log n) time. Here's what I see the code doing. It assumes the list it receives is sorted, and consists of no repeated integers (I believe this is what you meant by <em>\"sorted list with different numbers\"</em>)</p>\n\n<ol>\n<li>Constant time checks on the beginning, end, and middle of its range</li>\n<li>An extraneous print (ignoring this, as I think it makes it O(n log n); certainly the first hit will read and copy the entire list taking O(n))</li>\n<li>Up to two recursive calls that evaluate half or fewer of the elements in the existing range; this results in O(log n) calls</li>\n</ol>\n\n<p>Other comments:</p>\n\n<ul>\n<li>I would be strongly tempted to cut down on the quantity of code by omitting the checks related to <code>middle</code>. I would let the first three checks suffice as base cases, and always recurse on both full halves of the list.</li>\n<li>Consider using a single function by defining default argument values, e.g. <code>def foo(lst, start=0, end=-1): ...</code> and handling -1 specially (<code>if end == -1: end = len(lst)-1</code>).</li>\n<li>Consider matching python's half open ranges for your <code>start</code> and <code>end</code> parameters (passing <code>len(lst)</code> instead of <code>len(lst)-1</code> and adjusting the offsets accordingly). This might make things better or might make them worse. I'm not sure.</li>\n<li>Use a more descriptive name than <code>foo</code> for your function.</li>\n</ul>\n\n<p>Note that the first two comments are probably trading away performance for simplicity of code. While I almost always prefer this trade-off, there are cases where performance is more important.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:16:51.683", "Id": "35772", "ParentId": "35760", "Score": "-1" } }, { "body": "<ol>\n<li><p>You have a bug in the code. You should check both start and end values, not the absolute difference.</p>\n\n<pre><code># all indexes must be equal to their values\nif end == lst[end] and start == lst[start]:\nreturn end - start + 1\n</code></pre></li>\n<li><p>The worst-case complexity can't be <code>O(n)</code> because for each iteration, you can't guarantee that the algorithm will call only half. For each iteration, it can call <code>1+foo_helper(fist half)+foo_helper(second half)</code>, which is two halves, many times. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:44:57.380", "Id": "58193", "Score": "0", "body": "Yeah, but how many is \"many\"? By its very nature the partitioning will bottom out quite quickly either in the \"the two ends match\" case or the \"way off\" caase." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:21:05.920", "Id": "35773", "ParentId": "35760", "Score": "0" } }, { "body": "<p>Now let's see if I understand your problem: Given a sorted list of unique numbers you want to find all instances where <code>list[i] == i</code> (the important part is the <em>unique</em>).</p>\n\n<ol>\n<li><p>This means each number in the list is at least 1 larger than the previous number.</p></li>\n<li><p>Assume that <code>list[k] == x &lt; k</code>. Because the numbers are strictly increasing it must be that <code>list[k-1] &lt;= x-1 &lt; k-1</code>, <code>list[k-2] &lt;= x-2 &lt; k-2</code>, ... <code>list[k-l] &lt;= x-l &lt; k-l</code>. So if you have an index where the value is smaller than the index then this must also be the case for all previous indices.</p></li>\n<li><p>Assume that <code>list[k] == x &gt; k</code>. Because the numbers are strictly increasing it must be that <code>list[k+1] &gt;= x+1 &gt; k+1</code>, <code>list[k+2] &gt;= x+2 &gt; k+2</code>, ... <code>list[k+l] &gt;= x+l &gt; k+l</code>. So if you have an index where the value is larger than the index then this must also be the case for all following indices.</p></li>\n</ol>\n\n<p>The conclusion from these points is that a list with the given properties can be divided into three parts</p>\n\n<ol>\n<li>Start <code>0 &lt;= s &lt; ms</code> with <code>list[s] &lt; s</code></li>\n<li>Middle <code>ms &lt;= m &lt; me</code> with <code>list[m] == m</code></li>\n<li>End <code>me &lt;= e &lt; n</code> with <code>list[e] &gt; e</code></li>\n</ol>\n\n<p>Your problem is to find the middle part. The number of items where <code>list[i] == i</code> is then <code>me - ms</code>.</p>\n\n<p>This can be solved by finding the largest index for which <code>list[k] &lt; k</code> and the smallest index for which <code>list[k] &gt; k</code> (or the smallest and largest indices for which <code>list[k] == k</code> - depends on how you want to write the search criteria).</p>\n\n<p>Using two binary searches should yield the desired results which will guarantee a worst case complexity of <code>O(log(n))</code></p>\n\n<p><strong>Update</strong>: Your original implementation is effectively a binary search which will find both end and start point of the middle sequence so you implementation is <code>O(log(n))</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T08:13:44.950", "Id": "58293", "Score": "0", "body": "Where did you get that the numbers are 0 or positive? Dropping that restriction does not break your reasoning: it would just be necessary to find both the smallest and the largest index for which `list[k] == k`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T08:14:52.113", "Id": "58294", "Score": "0", "body": "@JanneKarila: Hm, true good point, I'll adjust my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:36:35.193", "Id": "58422", "Score": "0", "body": "+1, but this does not seem to show that the posted code has a worst case complexity of O(log *n*)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:55:53.280", "Id": "58431", "Score": "0", "body": "@GarethRees: Good point, totally forgot about it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T02:28:12.307", "Id": "58665", "Score": "0", "body": "Disagreed with your Update; the third return skips checking the middle items when examining a fully-matched subrange, so avoids counting each element. Similarly the other returns skip checking ranges that are fully unmatched. In cases that are neither, it splits it in half and tries each half; why aren't most ranges one or the other? (I.e. what sequence characteristics would provoke O(n) runtime?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T07:02:15.937", "Id": "58679", "Score": "0", "body": "Yes, I missed that check for the entire range, so it is O(log n)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T07:55:24.940", "Id": "35812", "ParentId": "35760", "Score": "4" } } ]
{ "AcceptedAnswerId": "35812", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:05:04.517", "Id": "35760", "Score": "3", "Tags": [ "python", "array", "recursion", "binary-search", "complexity" ], "Title": "count all array[index] == index occurrences" }
35760
<p>What I'm basically wondering is if there's anything that is possible to improve in this C++ code:</p> <pre><code>#include &lt;cstddef&gt; #include &lt;string&gt; bool is_palindromic(std::string s) { std::size_t i = 0; std::size_t j = s.length() - 1; while (i &lt; j) { if (s[i++] != s[j--]) { return false; } } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:08:57.570", "Id": "58160", "Score": "2", "body": "Yep. Try a for loop. Learn how to use references. Consider accidental mutation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:13:17.967", "Id": "58199", "Score": "1", "body": "Stepping outside the C++ code a bit, make sure you have a clear definition of what qualifies as a palindrome. Are there things (such as spaces or punctuation or letter case) that should be ignored: \"Sir, I’m Iris.\" or just \"SIRIMIRIS\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:20:44.363", "Id": "58621", "Score": "3", "body": "\"A man a plan a canal Panama\" also considered a palindrome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T12:04:45.493", "Id": "59440", "Score": "0", "body": "\"A man a plan a canal Panama\" that's not a palindrome..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:52:54.920", "Id": "59530", "Score": "0", "body": "@Max Yes it is. http://meta.stackoverflow.com/users/155556/amanap-lanac-a-nalp-a-nam-a" } ]
[ { "body": "<p>First of all, you should pass the <code>std::string</code> by const reference and not by value, therefore, replace <code>std::string s</code> by <code>const std::string&amp; s</code>, otherwise you will make a whole copy of the string everytime you invoke the function.</p>\n\n<p>Also, you program may crash if the <code>std::string</code> is empty since you're doing <code>std::size_t j = s.length() - 1;</code>. If <code>s.length() == 0</code>, <code>j</code> will probably be a big number and you will end up with a segfault due to an out of range index.</p>\n\n<p>As suggested by Loki in the comments, you could also use a <code>for</code> loop instead of a <code>while</code> loop in order for your code to look cleaner.</p>\n\n<p>Yet another suggestion by Jamal: using <code>std::string::size_type</code> instead of <code>std::size_t</code> (and removing <code>#include &lt;cstddef&gt;</code> by the way) would be more idiomatic. The type returned by <code>std::string::length</code> is not required to be <code>std::size_t</code> but <code>std::string::size_type</code>.</p>\n\n<p>Therefore, I would rewrite it as:</p>\n\n<pre><code>bool is_palindromic(const std::string&amp; s)\n{\n if (s.empty())\n {\n // You can return true if you think that\n // an empty string is a palyndrome\n return false;\n }\n for (std::string::size_type i=0, j=s.length()-1\n ; i &lt; j ; ++i, --j)\n {\n if (s[i] != s[j]) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:31:55.527", "Id": "58165", "Score": "1", "body": "+1 looks good. Just one nitpick: use `std::string::size_type` instead of `std::size_t`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:22:05.610", "Id": "58171", "Score": "2", "body": "Looks like you want `--j` instead of `++j`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T14:40:02.230", "Id": "59068", "Score": "0", "body": "+1 for it's proximity to the original version and for catching the **empty case** !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T14:41:06.437", "Id": "59069", "Score": "0", "body": "...BTW: isn't an empty string a palindrome?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T18:47:05.740", "Id": "59126", "Score": "0", "body": "I'd agree, if there was something special referred in the question, maybe a definition like [this](http://www.cs.umd.edu/class/fall2002/cmsc214/Projects/P0/proj0.faq.html#ques18). In lack of such, I prefer the idea of empty strings as palindromes." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:23:19.773", "Id": "35769", "ParentId": "35764", "Score": "8" } }, { "body": "<p>I wanted to offer a different angle of better. This code could be more generic. Why is it tied to exactly <code>std::string</code> - what if I need to check palindromic nature of <code>std::wstring</code> or the contents of a <code>std::vector&lt;T&gt;</code>? How about <code>std::list&lt;T&gt;</code> or <code>std::map&lt;T&gt;</code> (if palindromic can even mean anything on a <code>std::map</code>)? Here's how you can handle all of those with a single function:</p>\n\n<pre><code>template &lt;typename Sequence&gt;\nbool is_palindromic(const Sequence&amp; seq)\n{\n auto count = seq.size() / 2; // rounded down is fine, as a middle element matches itself\n auto i = seq.begin(); // prefer std::begin(seq) in C++14\n auto j = seq.rbegin(); // prefer std::rbegin(seq) in C++14\n\n for (Sequence::size_type c = 0; c &lt; count; ++c, ++i, ++j)\n {\n if (*i != *j)\n return false;\n }\n return true; // considers sequences without mismatched characters to be palindromes\n}\n</code></pre>\n\n<p>Note that I incorporated the other comments I agree with - in particular passing by const reference, and using the sequence's <code>size_type</code>. I'm not sure how to best support arrays, however; while <code>std::[r]begin</code> will handle arrays, I don't believe arrays have a <code>.size()</code> or <code>::size_type</code> to use. I guess that means they need their own overload, or at least some overloaded helpers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:58:00.530", "Id": "58177", "Score": "0", "body": "Use `std::distance(std::begin(seq), std::end(seq))` if you want to have a generic way to handle the size. With it, you can handle arrays. I don't know whether it is specialized for random-access iterators; if not, your code may be slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T19:14:39.867", "Id": "58179", "Score": "0", "body": "Ah, `std::distance` sounds great for random access and thus supporting arrays. However it's linear on non-random access, so would be slower on `std::list` (though no worse algorithmically). Thanks for the idea at least!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:42:39.420", "Id": "35774", "ParentId": "35764", "Score": "11" } }, { "body": "<p>I just wanted to chime in with the \"lazy\" (if not performant) way of doing this, using reverse iterators:</p>\n\n<pre><code>bool is_palindrome(const std::string&amp; s)\n{\n return s == std::string(s.rbegin(), s.rend());\n}\n</code></pre>\n\n<p>This is very simple and very readable. You could expand this to do things like remove punctuation if you want, but it gets a bit trickier (although it's still short):</p>\n\n<pre><code>// Note that the pass by value is intentional here, so we don't modify\n// the original string when using std::remove_if\nbool is_palindrome(std::string s)\n{\n auto it = std::remove_if(s.begin(), s.end(), [](char c) { return !std::isalpha(c); });\n return std::equal(s.begin(), it, std::reverse_iterator&lt;std::string::iterator&gt;(it));\n}\n</code></pre>\n\n<p>This can likewise be made into a template that will work with any sequence with very little effort.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T06:06:46.110", "Id": "35900", "ParentId": "35764", "Score": "7" } }, { "body": "<p>Searching for something as <strong>symmetrical</strong> as palindromes themselves, I came to this somewhat picturesque solution, that doesn't handle the empty string in a specific way, but as palindromic:</p>\n\n<pre><code>#include &lt;string&gt;\n\nbool is_palindromic(const std::string&amp; s)\n{\n std::string::const_iterator start = s.begin();\n std::string::const_iterator end = s.end();\n while (start &lt; end) {\n if (*(start++) != *(--end)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Its <strong>major drawback</strong> is the redundant check for self-equality of the central char.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T14:58:38.297", "Id": "36139", "ParentId": "35764", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:02:20.787", "Id": "35764", "Score": "12", "Tags": [ "c++", "c++11", "palindrome" ], "Title": "Checking for a palindrome" }
35764
<p>I created this module, and I'm wondering if I did a good job. How would an experienced JavaScript developer improve this simple slider module further? Like, let's say that you want to use this module on 3 sliders on the same page.</p> <p><a href="http://jsfiddle.net/W9rEu" rel="nofollow">Here</a> is a jsFiddle.</p> <p><strong>Module</strong></p> <pre><code>var sliderTest = (function(){ /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ✚ private variables :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ var expoElement = document.querySelector(".test") var expoCanvas = expoElement.querySelector(".canvas") var expoSlides = expoCanvas.querySelectorAll(".slide") var controlPrev = expoElement.querySelector(".control.prev") var controlNext = expoElement.querySelector(".control.next") /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ✚ private functions :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ function whereIsActive(){ var y = {} for(var i = 0; i &lt; expoSlides.length; i++){ if(expoSlides[i].classList.contains("active")){ y.current = i; if(expoSlides[i+1]){ y.next = i+1; } else { y.next = 0; } if(expoSlides[i-1]){ y.prev = i-1; } else { y.prev = expoSlides.length-1; } } } return y } function removeActiveClasses(){ for(var i = 0; i &lt; expoSlides.length; i++){ expoSlides[i].classList.remove("active") } } /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ✚ public methodes :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ var publicMethod = { nextSlide:function(ev){ ev.preventDefault(); var nextIndex = whereIsActive().next; removeActiveClasses(); expoSlides[nextIndex].classList.add("active"); }, prevSlide:function(ev){ ev.preventDefault(); var prevIndex = whereIsActive().prev; removeActiveClasses(); expoSlides[prevIndex].classList.add("active") }, sendInTheClone:function(){alert(whereIsActive().current)} } /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ✚ event listners :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ controlNext.addEventListener("click", publicMethod.nextSlide) controlPrev.addEventListener("click", publicMethod.prevSlide) /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ✚ return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ return publicMethod; })(); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class="test"&gt; &lt;div class="canvas"&gt; &lt;div class="slide "&gt;1&lt;/div&gt; &lt;div class="slide "&gt;2&lt;/div&gt; &lt;div class="slide active"&gt;3&lt;/div&gt; &lt;div class="slide "&gt;4&lt;/div&gt; &lt;/div&gt; &lt;a class="control prev" href="" data-control="prev"&gt;prev&lt;/a&gt; &lt;a class="control next" href="" data-control="next"&gt;next&lt;/a&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:08:53.740", "Id": "58170", "Score": "2", "body": "your comments and white space are very distracting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:52:41.083", "Id": "58176", "Score": "0", "body": "Agreed about the whitespace, it makes it much harder to read the code.\nI tried adding this to jsFiddle and it didn't work. I assume it does?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T00:37:30.133", "Id": "58220", "Score": "0", "body": "@kevnius, please provide a [JSFiddle](http://www.jsfiddle.net) of this code so we can test it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:32:58.083", "Id": "58332", "Score": "0", "body": "Here is a jsFiddle: http://jsfiddle.net/W9rEu/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:38:50.500", "Id": "58335", "Score": "0", "body": "Why are the comments distracting? I just divided the script into it's logical parts (private variables, private functions, public methods, event listeners, return statement)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:45:23.267", "Id": "58337", "Score": "0", "body": "@kevinius The comments are distracting because comments generally are not read unless the code doesn't make sense. We are trying to review the code, and the comments are essentially noise. Much worse is all the whitespace. Adding an additional line between each line requires a lot of vertical scrolling and is really excessive if the line is just `}`. Also FYI, your fiddle doesn't work in my browser: IE 9" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:50:33.797", "Id": "58341", "Score": "0", "body": "The script doesn't work in <IE10 because i'm using the element.classList API https://developer.mozilla.org/en-US/docs/Web/API/Element.classList" } ]
[ { "body": "<h1><code>document.querySelector</code></h1>\n<p>While it is a great function to use, you are using in the wrong situations.</p>\n<p>For every time you use it, you are getting an array of elements with a class that you passed in to the function. Why not just use <code>document.getElementsByClassName</code>?</p>\n<p>Sure, it takes a little bit longer to type but it's faster.</p>\n<p>This about it: the <code>querySelector</code> function has to read the argument passed in and, based on it's syntax ('.' for classes, '#' for ids, and a few more), scan the document in a way unique to each type of identification (id, class, etc).</p>\n<p>Wouldn't it be easier for the function to know that it was going to look for one class and for one class only?</p>\n<h1>Semicolons</h1>\n<p>They aren't entirely necessary, and the interpreter probably adds them in for you, but your code looks like JavaScript when you put them in (at least in my opinion).</p>\n<h1>HTML indentation</h1>\n<p>Your <code>div</code>s are perfectly indented, but when you go down to your <code>a</code>s, you start to try and clump them on to one line.</p>\n<p>Originally, when I was looking at the <code>a</code> tag(s), I thought it was one really long <code>a</code> tag.</p>\n<h1>JavaScript indentation</h1>\n<p>For the most part, it's really good. But there is one section that is bothering me: your <code>public methods</code> section.</p>\n<p>I actually had to post this in to JSFiddle and click &quot;Tidy up&quot; to understand what was going on there.</p>\n<p>I believe the problem is the closing bracket of <code>nextSlide</code>; it is too far back, and it looks like it is closing <code>publicMethod</code>.</p>\n<h1>Built in output</h1>\n<p>In the <code>sendInTheClone</code> method of <code>publicMethod</code>, it uses the function <code>alert</code>.</p>\n<p>Not everyone using this module may want an alert popping up on their screen; maybe they want it written to the DOM, or maybe they use custom pop-up boxes.</p>\n<p>(Excuse this section (&quot;Built in output&quot;) if I misunderstood your <code>sendInTheClone</code> function)</p>\n<h1>Good things:</h1>\n<ol>\n<li><p>Contrary to what people have been commenting, I think that the big comments going across your code to split it up is a good idea. In my opinion, it helps with legibility.</p>\n</li>\n<li><p>The use of <code>publicMethod</code>. It's a pretty good idea; I like it.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T23:56:58.283", "Id": "84436", "ParentId": "35768", "Score": "5" } } ]
{ "AcceptedAnswerId": "84436", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:10:52.397", "Id": "35768", "Score": "4", "Tags": [ "javascript", "modules" ], "Title": "Slider module and extending it further" }
35768
<p>My question is to find the longest DNA sub-sequence that appears at least twice. The input is only one DNA string, NOT TWO strings as other LCS programs.</p> <p>I have done my 4th program and it seems to be working and efficient (computes 10k strings in 4 seconds). But I don't know if this is 100 % correct. This is a really important project for me and I have really tried to make it.</p> <p>Kindly provide your suggestions regarding my logic and program implementation in Java (I don't know advanced program techniques involving stacks, queues and linked lists in Java).</p> <p>Logic:</p> <ol> <li>Enter string;</li> <li>Make new strings from the original string - start from beginning-- at each step increasing by one letter;</li> <li>Put these strings in an array;</li> <li>Sort the array in alphabetical order;</li> <li>Compare the prefixes between each string in the sorted array --looking for similar substrings ;</li> <li>Print the longest one(s).</li> </ol> <p></p> <pre><code>import java.util.*; /** * * @author Pavin */ public class dna3 { public static String check(String a,String b) { String f=""; if (a.length()&lt;b.length()) { String h=""; // String f =""; int r=a.length(); int t=b.length(); // } String c=""; // String f =""; if ((a==null)||(b==null)) { c=""; } else { for (int i=0;i&lt;a.length();i++) { //for (int j=0;j&lt;b.length();j++) { char d=a.charAt(i); char e=b.charAt(i); if (d==e) { c=String.valueOf(e); f=f+c; } if (d!=e) { break; } } } } } if (a.length()&gt;b.length()) { String h=""; // String f =""; int r=a.length(); int t=b.length(); // } String c=""; // String f =""; if ((a==null)||(b==null)) { c=""; } else { for (int i=0;i&lt;b.length();i++) { //for (int j=0;j&lt;b.length();j++) { char d=a.charAt(i); char e=b.charAt(i); if (d==e) { c=String.valueOf(e); f=f+c; } if (d!=e) { break; } } } } } return f; } /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter DNA string"); String a=sc.nextLine(); String c; String d; int b=a.length(); String arr[]=new String [b+1]; int i; for (i=0;i&lt;b;i++) { c=a.substring(i,b); arr[i]=c; } /* System.out.println("Before sort&gt;&gt;&gt; "); for (i=0;i&lt;b;i++) { System.out.println(arr[i]); }*/ String temp; for(int x=1;x&lt;b;x++) { for(int y=0;y&lt;b-x;y++) { if(arr[y].compareTo(arr[y+1])&gt;0) { temp=arr[y]; arr[y]=arr[y+1]; arr[y+1]=temp; } } } /* System.out.println("After sort&gt;&gt;&gt; "); for(i=0;i&lt;b;i++){ System.out.println(arr[i]); } */ System.out.println("Longest substring with frequency equal to two or more &gt;&gt;&gt; "); String v1; String v2; String v3; // dnabxcfnabionabxuinab int w=1; for (i=0;i&lt;b-1;i++) { v1= arr[i]; v2=arr[i+1]; v3=check(v1,v2); int q=v3.length(); if (q&gt;=w) { w=q; } } String v4=""; for (i=0;i&lt;b-1;i++) { v1= arr[i]; v2=arr[i+1]; v3=check(v1,v2); int s=v3.length(); if ((s==w)&amp;&amp;(v4.compareTo(v3)!=0)) { v4=v3; System.out.println(v3); } } // TODO code application logic here } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:19:07.020", "Id": "58183", "Score": "1", "body": "What is the expected bahaviour with overlaps... i.e. is the longest sequence in this string `ababa` the value `aba` or just `ab` or `ba` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:31:18.457", "Id": "58184", "Score": "0", "body": "The answer to \"ababa\" should be \"aba\". With Overlaps, yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:46:30.933", "Id": "58194", "Score": "0", "body": "When providing sequence \"abcd\", the array of substrings does not include some of the valid combinations. Excluded values include \"abc\" and \"bc\". Single loop is not sufficient to extract all the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:59:37.733", "Id": "58209", "Score": "0", "body": "@Origineil I thought so as well, at first, but the 'second' loop is actually inside the check() method... I believe it does actually work" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T20:56:11.187", "Id": "58744", "Score": "0", "body": "Is it just me, or does this look like it's either NP-hard or wrong? You're essentially matching the regex `(.+).*\\1`, so if you could do it in P time, you could also solve regex with back-references in P time, which is known to be NP-hard. Honestly, I can't read this code, please use real variable names, so I can't really analyze its complexity, but if it runs in polynomial time, and the problems are equivalent, there's some input for which it will fail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T18:48:35.167", "Id": "58792", "Score": "0", "body": "@sqykly . Yes , it failed for 20k DNA string." } ]
[ { "body": "<p>There are a number of items which concern me in your code.</p>\n\n<p>First up, when I pull your code in to eclipse, it immediately gives me lots of warnings.... which are easy to fix, but make the code cumbersome. Also there's a couple of other items:</p>\n\n<ol>\n<li><code>Scanner sc ....</code> is not closed (always close IO streams when you are done with them).</li>\n<li>Many variables are not used: in <code>main()</code> there's <code>d</code>, and in <code>check()</code> there's <code>h</code>, <code>r</code>, and <code>t</code> (which are unused both places they occur - both in the 'if' side and 'else' side of the condition).</li>\n<li>The remaining variable names are not very reader-friendly... apart from <code>sc</code> for 'scanner', <code>arr</code>, and <code>temp</code>, all the other variables are single-letter: <code>a</code>, <code>b</code>, <code>d</code>, <code>h</code>, <code>i</code>, <code>j</code>, <code>q</code>, <code>w</code>, <code>x</code>, and <code>y</code>. Oh, there is also <code>v0</code>, <code>v1</code>, <code>v2</code>, <code>v3</code>, and <code>v4</code>. This all makes it <strong>very hard to read/understand your code</strong>. </li>\n<li>While it's a personal preference, the official Java code-style guide recommends putting the open brace <code>{</code> on the same line as the block introduction, not on the following line. For example:<br> <code>if (...) {</code> <br>is all on one line.</li>\n</ol>\n\n<hr>\n\n<p>Going through things in order of execution....</p>\n\n<p>The <code>Scanner</code> should be closed. The best way to do this is (in Java7) to use a 'try-with-resource' structure:</p>\n\n<pre><code>try (Scanner scanner = new Scanner(System.in)) {\n .... all your code goes in here ....\n}\n</code></pre>\n\n<p>Next up, why is the <code>arr</code> size <code>b + 1</code> and not <code>b</code> ? It should be:</p>\n\n<pre><code>String[] arr = new String[b];\n</code></pre>\n\n<p>You have a few blocks of code which are unnecessarily complicated. For example:</p>\n\n<pre><code> for (i=0;i&lt;b;i++)\n {\n c=a.substring(i,b);\n arr[i]=c;\n\n }\n</code></pre>\n\n<p>This has a few problems:</p>\n\n<ol>\n<li>unless you have a good reason, when you use a loop like this, do not declare the loop variable outside the loop (in this case, the <code>i</code>). It makes things confusing.</li>\n<li>Using <code>b</code> in the substring leads to confusion. <code>b</code> is the full string length, and it implies that you are going to get more characters than there actually are. In this case, the <code>substring</code> method silently ignores your request for too many characters. You should do this explicitly by using <code>a.substring(i)</code> instead of <code>a.substring(i, b)</code></li>\n<li>the <code>c</code> variable is completely unnecessary - use <code>arr[i] = a.substring(i);</code></li>\n</ol>\n\n<p>The code should look like:</p>\n\n<pre><code>for (int i = 0; i &lt; a.length(); i++) {\n arr[i] = a.substring(i);\n}\n</code></pre>\n\n<p>The following block is also unnecessary:</p>\n\n<pre><code> String temp;\n for(int x=1;x&lt;b;x++)\n {\n for(int y=0;y&lt;b-x;y++)\n {\n if(arr[y].compareTo(arr[y+1])&gt;0)\n {\n temp=arr[y];\n arr[y]=arr[y+1];\n arr[y+1]=temp;\n\n }\n }\n }\n</code></pre>\n\n<p>This is a sort, so sort it! Use the Collections API:</p>\n\n<pre><code>Arrays.sort(arr);\n</code></pre>\n\n<p>Now, I am not sure why the code splits at this point in to the two sections.... but, when <del>I looked in to the check() method, the first thing that I noticed was that if <code>a</code> and <code>b</code> are both the same length, it immediately returns a 'no-match' even if they may be the same.</del> (never mind, no two strings will have the same length). Instead of <code>if (a.length() &gt; b.length()) ...</code> and <code>if (b.length() &gt; a.length())</code> you should simply use an <code>if (....) {....} else {....}</code></p>\n\n<p>There are other problems I am sure, but that's enough for the moment.</p>\n\n<hr>\n\n<p>EDIT Part 2: (had dinner)....</p>\n\n<p>The next item I would criticize is the code duplication in the <code>check()</code> method. There is <strong>no</strong> need to have the length-checks in that method. Consider renaming the check method to have:</p>\n\n<pre><code>public static String check(String big, String small) {...}\n</code></pre>\n\n<p>and then, outside the method, you do:</p>\n\n<pre><code>// check the values, using the longest one first....\nString v3= v1.length() &gt; v2.length() ? check(v1,v2) : check(v2, v1);\n</code></pre>\n\n<p>Finally, inside the check method, you should not need to check for null values in the input, because you should not have added nulls when initializing the <code>arr</code> array. This strips a bit of code out.</p>\n\n<p>Also, the String concatenation <code>f = f + c</code> line is 'bad form'. You should, instead, simply be able to do something like:</p>\n\n<pre><code>if (d!=e) {\n return small.substring(0, i - 1);\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:23:47.037", "Id": "58205", "Score": "0", "body": "Instead of using `Collections.sort(Arrays.asList(arr));`, there is also `Arrays.sort`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:24:44.633", "Id": "58206", "Score": "0", "body": "And THANK YOU for mentioning the variable names, that was the first I could think of. You'll get an upvote as soon as I have some [ammo](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission) again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:56:01.847", "Id": "58208", "Score": "0", "body": "@SimonAndréForsberg - of course, `Arrays.sort(...)` ... I was temporarily muddled by another problem I have seen recently where I wanted `Arrays.shuffle(...)` and that does not exist!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:08:45.863", "Id": "58436", "Score": "0", "body": "Thank You for the suggestions. I'm implementing it right now.BTW, will I get any performance increase by changing from bubble sort in my program to the sort API. Or should I try using quick sort?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:25:06.363", "Id": "58440", "Score": "0", "body": "@Dobby Surely you can just snap your fingers .... oh, never mind. The `Arrays.sort()` uses a 'timsort' algorithm (in Java7) which is faster than QuickSort in almost all circumstances. It is essentially a high-level quick-sort with a merge-sort when the chunks become smaller. You won't (easily) beat `Arrays.sort()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:25:44.650", "Id": "58441", "Score": "0", "body": "See TimSort here: http://en.wikipedia.org/wiki/Timsort" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:35:03.370", "Id": "58445", "Score": "1", "body": "Timsort is definitely better than all the sorts I know. As for snapping my fingers .. It never worked since Bellatrix, the b**** threw that knife at my chest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:50:41.793", "Id": "58451", "Score": "0", "body": "Success!! Used Timsort as you mentioned, and now it computes 10k DNA string in 1 second. Now I have just 1 question -- Is my program correct (as in my logic and implementation). Does it do what it's supposed to do. For smaller strings I guess I can find the answer, but the program is assessed based on the 100 char and 10k char dna strings. You can find both of those here -> https://service.felk.cvut.cz/courses/XE36ALG/DNA/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:55:32.260", "Id": "58452", "Score": "0", "body": "Out of interest, what were your answers?\ngagag\nggaagattagagg" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:57:23.420", "Id": "58453", "Score": "0", "body": "Answer was \"agag\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:59:50.380", "Id": "58454", "Score": "0", "body": "Your answers are wrong then .... ;-) 'My' version of the problem gets the above two answers for 100 and 10K. And I can confirm those values are duplicates by searching the text file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:08:50.993", "Id": "58457", "Score": "0", "body": "Oh, looks like I interpreted your question wrong. I thought you asked the answer to \"gagag ggaagattagagg\" as the input.My output for 100 char string is \"aacga agaga gagag gcaaa ggggg\" and for 10k char string is \"cgagctcttcgcg\nggaagattagagg\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:20:20.737", "Id": "58458", "Score": "0", "body": "just a quick comment/question to both of you. You seem to imply that sorting array of strings will yield well-known O(N*logN) complexity. However, as far as I remember this is generally true (for example for quicksort, mergesort) when comparison is O(1), however comparison of two strings of size N is O(N) itself, therefore I am afraid that sorting of array of strings is not that obvious. Am I missing something ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:51:17.553", "Id": "58464", "Score": "0", "body": "@kiruwka I don't think the discussions had gotten in to complexities yet... and for the current purposes, the datasets are small enough (and will never be large enough) for more than the current optimizations to be useful. Certainly, from my side, I have not optimized that much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:33:57.593", "Id": "58473", "Score": "0", "body": "Yes, I don't think time complexity will be an issue with the current version of the program used within the above mentioned parameters,especially since it computes the 10k dna string within 1 second." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:35:52.787", "Id": "35780", "ParentId": "35776", "Score": "5" } }, { "body": "<p>I have some doubts about correctness of your code, particularly I am concerned with the fact that implementing <code>step 2</code> &amp; <code>step 3</code> of your <em>Logic</em> (from description in your post), you populate array declared as :</p>\n\n<pre><code>String arr[]=new String [b+1];\n</code></pre>\n\n<p>by only suffixes of your input string, and you don't consider substrings in the middle (non-suffixes). Did you check if your program produces correct results for inputs, such as \"123ababa456\" ?</p>\n\n<p>Anyway, I decided to put alternative solution below, which is quite easy to follow.<br>\nThe idea :</p>\n\n<p>Lets denote maximum length of possible solution as <code>currentLen</code>.<br>\n<code>currentLen</code> equals <code>n</code> - 1 in the beginning, where <code>n</code> is the length of input.</p>\n\n<ol>\n<li>you start by examining all substrings of input with length = <code>currentLen</code></li>\n<li>If you find two duplicate strings -> return the result</li>\n<li>If no results for length <code>currentLen</code> are found - decrement it and go back to step 1.</li>\n<li>Repeat this loop 1-3 until you found something or your <code>currentLen</code> reached 0</li>\n</ol>\n\n<p>Finding duplicate strings at step 2 is implemented using <code>Set</code> of Strings, which is, very simply put : a data structure which keeps your Strings (with very quick lookup) and tells you if you try to insert a string which was already stored.</p>\n\n<p>I tried to make the code very verbose, but it is still very readable.\n<br>\nI really hope you try to understand it, usage of <code>Set</code> is limited to couple of lines, don't be startled by it.</p>\n\n<pre><code>static String longestRepeatedDna(String input) {\n\n // set containing distinct possible candidates\n // when examine new candidate we check if it is already in the set\n // if it is -&gt; we found our longest dna!\n // in not -&gt; we add the candidate to set and continue\n Set&lt;String&gt; dnaSet = new HashSet&lt;String&gt;(); \n\n for (int currentLen = input.length() - 1; currentLen &gt; 0; --currentLen) {\n\n // empty before we start processing sub-strings of currentLen\n dnaSet.clear(); \n\n // examine all substrings of length currentLen\n for (int i = 0; i + currentLen &lt;= input.length(); ++i) {\n // take substring of length currentLen starting at index i\n String possibleDna = input.substring(i, i + currentLen);\n if (dnaSet.contains(possibleDna)) {\n // hooray! we found it!\n return possibleDna;\n } else {\n dnaSet.add(possibleDna);\n }\n }\n }\n\n // found nothing\n return null; // or return \"\";\n}\n</code></pre>\n\n<p>and test code :</p>\n\n<pre><code>public static void main(String... args) {\n String[] testCases = {\"ababa\", \"mababa123\", \"mytest\",};\n for (String test : testCases) {\n System.out.println(\"longest dna for input \" + test + \" = \" + \n longestRepeatedDna(test));\n }\n}\n</code></pre>\n\n<p>Run-time complexity of this solution is O(n^2), and I believe can still be improved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:08:25.897", "Id": "58223", "Score": "0", "body": "It took me a bit to figure out the algorithm, but, it is right. Your \"doubts about the correctness\" are unfounded... I believe it produces the correct results, and actually the algorithm is quite elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:18:56.533", "Id": "58298", "Score": "0", "body": "@rolfl \"It took me a bit to figure out the algorithm\" - you mean OP's algorithm ? About correctness - since actual processing is done on sorted array of suffixes (`arr`), and that requires searching for duplicate longest substring in that arr, I am curios what is the current complexity of that operation ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T11:17:22.800", "Id": "58312", "Score": "0", "body": "Yes, I mean the OP algorithm. The complexity is messy. I tried an alternate way, but I used 3 loops, although they were all significantly limited. An interesting problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:15:27.553", "Id": "58438", "Score": "0", "body": "Thank You for the different approach. As for the correctness of the program, I am getting the desired answer of \"aba\" when giving your input \"123ababa456\". Yes, both my original program and the one you suggested are O(n^2) complexity but if I use quick sort, I think I can improve performance since its average case complexity is O(nlogn)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:35:59.480", "Id": "35788", "ParentId": "35776", "Score": "5" } }, { "body": "<p>It looks to me that the running time is O(|<em>S</em>|<sup>2</sup>), (where |<em>S</em>| is the length of the string), which would probably make it unusable for analyzing longs strings of DNA.</p>\n\n<p>The standard approach to solving the <a href=\"http://en.wikipedia.org/wiki/Longest_repeated_substring_problem\" rel=\"nofollow\">longest repeated substring problem</a> is to use a <a href=\"http://www.cise.ufl.edu/~sahni/dsaaj/enrich/c16/suffix.htm\" rel=\"nofollow\">suffix tree</a>. The running time of that algorithm should be O(|<em>S</em>|).</p>\n\n<hr>\n\n<p>To be honest, I found your code difficult to follow, so I haven't read all of it, but there are also some serious issues that I've found.</p>\n\n<p>You do a variant of bubble sort to sort <code>arr</code>. First, bubble sort should be avoided because it is inefficient — O(<em>n</em><sup>2</sup>). Second, why is that code cluttering <code>main()</code>? Anything that can be considered a namable operation should be extracted into its own function. Third, common operations like sorting would already be provided by the standard Java library. Take the time to <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28java.lang.Object%5b%5d%29\" rel=\"nofollow\">look for it</a> so that you don't reinvent the wheel.</p>\n\n<p>Your <code>check(String a, String b)</code> function is incredibly repetitive. Surely you could find a way to avoid writing the same code twice? (Either swap <code>a</code> and <code>b</code> early in the function, or have the function call itself with the arguments reversed.) Also, what happens if <code>a</code> and <code>b</code> are the same length?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:34:18.393", "Id": "58266", "Score": "0", "body": "Ditto to most of your comments. As for the 'a' and 'b' being the same length, I saw that one too, but then realized that, due to the way the values are constructed, it's not possible for them to be the same length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:22:25.527", "Id": "58270", "Score": "0", "body": "Then an `assert a.length() != b.length()` would be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:20:58.173", "Id": "58439", "Score": "0", "body": "@200_success ->Thank You for the suggestions.Yes, I will definitely change my bubble sort to quick sort to improve efficiency. And, my professor too told us the best way was to solve it using suffix tree , but unfortunately my knowledge of Java is too limited for that. After changing to quick sort I think the program will be okay since the suffix tree is complexity O(n) and my program will be O(n log n). It should be enough for the 10k input given. On bubble sort it takes 4 seconds. Maybe I can cut that down to 3 or even 2 with quick sort." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:23:03.297", "Id": "35802", "ParentId": "35776", "Score": "2" } } ]
{ "AcceptedAnswerId": "35780", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:06:15.287", "Id": "35776", "Score": "2", "Tags": [ "java", "strings", "bioinformatics" ], "Title": "Longest DNA sequence that appears at least twice (only one DNA string as input)" }
35776
<p>I have written some example code to test object inheritance, but I'm not sure if it's really the best way for an object to inherit another's functions (like Java's <code>extends</code>).</p> <pre><code>function Class() { console.log("Created class"); // The base class } Class.prototype.test = function() { console.log("Testing class"); // Add an un-overridden method, to test inheritance }; Class.prototype.overrideMe = function() { console.log("Not overridden"); // Add a method to override }; function SubClass() { console.log("Created subclass"); // This object will 'extend' Class. } // SubClass.prototype = new Class(); also works here, but the constructor is called SubClass.prototype = Object.create(Class.prototype); // Copy the prototype SubClass.prototype.overrideMe = function() { console.log("Overridden"); // Override the method }; /* Testing */ var sub = new SubClass(); sub.test(); // Prints out "Testing class" sub.overrideMe(); // Prints out "Overridden" if (sub instanceof Class) { console.log("SubClass is an instance of Class"); } else { console.log("SubClass is not an instance of Class"); } </code></pre> <p>Are there any better ways to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:07:42.267", "Id": "58186", "Score": "0", "body": "Not to take away from the question at hand, but more of an aside: [MooTools](http://mootools.net/) ([Wikipedia Entry](http://en.wikipedia.org/wiki/MooTools)) facilitates OOP javascript" } ]
[ { "body": "<p>my first impression is that this is a good design and it functions well. I don't know much about the way that Java does Extension, but your code looks well planned and looks like you know the basics of Extension. when you put this into practice on something bigger you should post it as an additional follow-up question (as long as it works) so we can see more of it in action.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:15:21.167", "Id": "35785", "ParentId": "35777", "Score": "2" } }, { "body": "<p>I'm sorry, I just can't resist...</p>\n\n<pre><code>if (sub instanceof Class) {\n console.log(\"SubClass is an instance of Class\");\n} else {\n console.log(\"SubClass is not an instance of Class\");\n}\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>console.log(\"SubClass is \" + ((sub instanceof Class) ? \"\" : \"not \") + \"an instance of Class\");\n</code></pre>\n\n<p>(Whether this is cleaner or not is subjective of course) Whether this suggestion is actually <em>useful</em> is doubtful.</p>\n\n<p>But that's not the big point that I want to make here. When working with polymorphism, you should <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=31\" rel=\"nofollow noreferrer\">avoid using the <code>instanceof</code> operator</a> to check which class one of your Objects is. If you find yourself doing things like \"if a instanceof SomeClass then do something, otherwise do something else\", then instead create a common <code>dosomething</code> method for the both classes and call that. Then there's no need to check which <code>instanceof</code> an object is. <a href=\"https://softwareengineering.stackexchange.com/questions/184109/replacement-for-instanceof-java\">The object itself knows what to do</a>. (Although the links are mainly about Java, if you want to do it the OOP way in JavaScript, the same principles still applies)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T23:42:35.777", "Id": "58211", "Score": "1", "body": "the OP was just using that to show that their code works, and not as an actual part of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T23:44:24.743", "Id": "58213", "Score": "0", "body": "@Malachi is correct, I was just showing that the inheritance works as expected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T00:13:47.490", "Id": "58216", "Score": "1", "body": "@jackwilsdon I was quite sure that the `((sub instanceof Class) ? \"\" : \"not \")`-part was not necessary, but the things about `instanceof` can be a good thing to keep in mind for later." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:54:38.620", "Id": "35790", "ParentId": "35777", "Score": "4" } }, { "body": "<p><strong>Using Class.extend</strong></p>\n\n<p>By including John Resig's code snippet to enable Class-ical inheritance, you could write this as follows : </p>\n\n<pre><code>var ExampleBaseClass = Class.extend({\n init : function() {\n console.log(\"Created class\");\n },\n test : function() {\n console.log(\"Testing class\"); // Add an un-overridden method, to test inheritance \n },\n overrideMe : function() {\n console.log(\"Not overridden\"); // Add a method to override\n }\n});\n\nvar ExampleSubClass = ExampleBaseClass.extend({\n overrideMe : function() {\n console.log(\"Overridden\"); // Override the method\n }\n});\n</code></pre>\n\n<p>JS Fiddle here <a href=\"http://jsfiddle.net/z4Z7J/\" rel=\"nofollow\">http://jsfiddle.net/z4Z7J/</a>, <em>I've put the full code for the implementation of the generic Class function there, so scroll down to see how you'd use it. Normally that would just be included as a seperate JS file.</em></p>\n\n<p>Its super neat, and handy because it takes all the <code>prototype</code> calls out and hides them nicely. Passing in the object literal to the extend method also allows us to group the definition of the class nicely so this appeals to folks from a classical OO background. </p>\n\n<p>It goes through some fairly involved work to make <code>instanceof</code> work (by ensuring prototype chain is correctly maintained), does some slicing and dicing of the object literals and remapping of the <code>this</code> context. (Take a look at <em>Some Useful References</em> below this answer).</p>\n\n<p>If you don't care about <code>instanceof</code> you free yourself up a bit and can use alternate patterns, but for the quickest hit to get the <code>extend</code> functionality, my vote is with John Resig's snippet.</p>\n\n<p><strong>Some Useful References</strong></p>\n\n<p>There are a number of code libraries and snippets that you can use as the basis for implementing a Class-ical type of inheritance pattern in JavaScript. For example the already mentioned <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"nofollow\">John Resig's Class implementation</a> or <a href=\"http://dean.edwards.name/weblog/2006/03/base/\" rel=\"nofollow\">Dean Edwards' Base</a>.</p>\n\n<p>They're really worth taking a look at and reading through. Another interesting perspective is <a href=\"http://www.crockford.com/javascript/inheritance.html\" rel=\"nofollow\">Douglas Crockford's Classical inheritance in JavaScript</a>.</p>\n\n<p>Especially the part at the end where he says :</p>\n\n<blockquote>\n <p>I have been writing JavaScript for 8 years now, and I have never once\n found need to use an uber function. The super idea is fairly important\n in the classical pattern, but it appears to be unnecessary in the\n prototypal and functional patterns. <strong>I now see my early attempts to\n support the classical model in JavaScript as a mistake</strong>. ~ Douglas Crockford</p>\n</blockquote>\n\n<p>So theres a lot to weigh up and a lot of it is highly subjective!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:49:58.247", "Id": "36511", "ParentId": "35777", "Score": "5" } } ]
{ "AcceptedAnswerId": "36511", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T20:07:03.883", "Id": "35777", "Score": "6", "Tags": [ "javascript", "object-oriented", "inheritance", "extension-methods" ], "Title": "Object inheritance" }
35777
<p>I have an image upload form with which I call multiple functions before uploading the file such as checking the size and dimensions, and that it is in a valid image. The code works, but calling the functions and dealing with the results seems quite cumbersome and complex.</p> <p>Is there a tidier way of structuring the code?</p> <p>This is what I currently have:</p> <pre><code>//Upload an image if(checkvalidfile("img",$ext)){ if(checksize($size, 524288)) { if(checkdimensions($tmp, 300)) { $newfilename = renamefile($ext); recordfileindb($brand_id, $newfilename, $mysqli); uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3); header('Location: ./message.php?action=newlogo'); } else { echo "Your image can't be bigger than 300 x 300px"; die; } } else { echo "File size is too big!"; die; } } else { echo "Not a valid file"; die; } </code></pre>
[]
[ { "body": "<p>Yes, there's room for a lot of improvement here!</p>\n\n<p>First of all, you can \"break early\" to avoid excessive indentation. Since <code>die</code> terminates the script, you can check if the file is <strong>not</strong> valid.</p>\n\n<p>Secondly, instead of <code>echo</code>ing first and <code>die</code> later, you can call <code>die</code> with a parameter.</p>\n\n<p>This code works in the same way, but is cleaner:</p>\n\n<pre><code>if (!checkvalidfile(\"img\",$ext)) {\n die(\"Not a valid file\");\n}\nif (!checksize($size, 524288)) {\n die (\"File size is too big!\");\n}\n\nif (!checkdimensions($tmp, 300)) {\n die(\"Your image can't be bigger than 300 x 300px\");\n}\n\n$newfilename = renamefile($ext);\nrecordfileindb($brand_id, $newfilename, $mysqli);\nuploadfile($tmp, $bucket, \"user_docs/agency_\".$agency_id.\"/brand_logos/\", $newfilename, $s3);\nheader('Location: ./message.php?action=newlogo'); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:18:09.317", "Id": "35787", "ParentId": "35782", "Score": "2" } } ]
{ "AcceptedAnswerId": "35787", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T21:58:40.830", "Id": "35782", "Score": "2", "Tags": [ "php" ], "Title": "Calling multiple functions in image upload form" }
35782
<p>I have this jQuery function I wrote up to set the size of an input based off of its data. In this case I have already figured out the widths for each character based off of a 12px font size for Helvetica.</p> <p>It's not super flexible or anything, but I would like to know if there is any good way to take what I have and maybe make it more elegant (or fewer lines of code).</p> <p><strong>HTML:</strong></p> <pre><code>&lt;input value="Some really long string about nothing important"" /&gt; </code></pre> <p><strong>CSS:</strong> </p> <pre><code>body { font-family:Helvetica; font-size:12px; } span { padding:0; margin:0; } input { border:0; } </code></pre> <p><strong>JavaScript / jQuery:</strong></p> <pre><code>// Helvetica, 12px or 1.2em at 62.5% var str = $('input').val(); var length = str.length; var charWidth = 0; for ( var i = 0; i &lt; length; i++ ) { console.log(str[i]); if ( str[i] == "f" || str[i] == "i" || str[i] == "I" || str[i] == "j" || str[i] == "l" || str[i] == "t" ) { charWidth += 3; } if ( str[i] == "r" ) { charWidth += 4; } if ( str[i] == "v" || str[i] == "x" || str[i] == "y" || str[i] == "z" ) { charWidth += 5; } if ( str[i] == "c" || str[i] == "k" || str[i] == " " ) { charWidth += 6; } if ( str[i] == "a" || str[i] == "A" || str[i] == "b" || str[i] == "d" || str[i] == "e" || str[i] == "F" || str[i] == "g" || str[i] == "h" || str[i] == "J" || str[i] == "L" || str[i] == "n" || str[i] == "o" || str[i] == "p" || str[i] == "q" || str[i] == "s" || str[i] == "T" || str[i] == "u" || str[i] == "V" || str[i] == "X" || str[i] == "Y" || str[i] == "Z" || str[i] == "0" || str[i] == "1" || str[i] == "2" || str[i] == "3" || str[i] == "4" || str[i] == "5" || str[i] == "6" || str[i] == "7" || str[i] == "8" || str[i] == "9" ) { charWidth += 7; } if ( str[i] == "B" || str[i] == "E" || str[i] == "K" || str[i] == "P" || str[i] == "S" ) { charWidth += 8; } if ( str[i] == "C" || str[i] == "D" || str[i] == "G" || str[i] == "H" || str[i] == "M" || str[i] == "N" || str[i] == "O" || str[i] == "Q" || str[i] == "R" || str[i] == "U" || str[i] == "w" ) { charWidth += 9; } if ( str[i] == "m" || str == "W") { charWidth += 11; } } $('input').css({'width': charWidth}); </code></pre> <p><a href="http://jsfiddle.net/cr2je/6/" rel="nofollow"><strong>jsFiddle</strong></a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:15:42.277", "Id": "58201", "Score": "1", "body": "I'd suggest an array of widths so you can just get the charcode of the character and look it's width up in the array. This would be a lot faster and more elegant than the giant `if/else`. You could also make this function a jQuery plugin so you could just so `$('input').autoSize();`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:21:48.383", "Id": "58204", "Score": "0", "body": "Yeah I had thought about using an array, but wasn't quite sure how to implement it." } ]
[ { "body": "<p>Here's how you could use a table array for the widths. I didn't fill in all the character widths (I just did lowercase) because it's tedious to build, but you can extend it to contain all the typeable characters that you want to support. I also made it a jQuery method that you can call like this: </p>\n\n<pre><code>$(\"input\").autoSize();\n</code></pre>\n\n<p>Here's the code (also in a <a href=\"http://jsfiddle.net/jfriend00/mL4fq/\" rel=\"nofollow\">jsFiddle</a>):</p>\n\n<pre><code>(function() {\n var widths = [\n // a, b, c, d, e, f, g\n 7, 7, 6, 7, 7, 3, 7,\n // h, i, j, k, l, m, n\n 7, 3, 3, 6, 3, 11, 7,\n // o, p, q, r, s, t, u\n 7, 7, 7, 4, 7, 3, 7,\n // v, w, x, y, z\n 5, 9, 5, 5, 5\n ];\n\n // character code our table starts with\n var lowWidth = 97;\n\n $.fn.autoSize = function() {\n return this.each(function() {\n var val = this.value;\n var totalWidth = 0, charIndex, ch;\n for (var i = 0, len = val.length; i &lt; len; i++) {\n // get char code and see if it's in our width table\n charIndex = val.charCodeAt(i) - lowWidth;\n ch = val.charAt(i);\n if (charIndex &gt;= 0 &amp;&amp; charIndex &lt; widths.length) {\n totalWidth += widths[charIndex];\n } else if (ch == ' ') {\n // special case for space char \n // until the table contains all codes we need\n totalWidth += 6;\n }\n }\n $(this).css(\"width\", totalWidth + \"px\");\n });\n }\n})();\n</code></pre>\n\n<hr>\n\n<p>FYI, jQuery will also measure the natural width of any DOM element for you so you could also have a span that is styled with the right font that you insert this text into and then ask jQuery what it's width is. jQuery will temporarily make it position absolute (so it will layout to it's natural width) and then let the browser tell you how wide it is. This would be much, much more accurate than what you are doing.</p>\n\n<p>Letting jQuery measure it for you would look like this:</p>\n\n<pre><code>$.fn.autoSize = function() {\n var testItem = $(\"#testWidth\");\n return this.each(function() {\n // put the text into our test span\n testItem.text(this.value);\n $(this).width(testItem.width());\n });\n}\n</code></pre>\n\n<p>And, you'd have appropriate CSS for a testItem span (see the jsFiddle demo for details):</p>\n\n<p>jsFiddle demo: <a href=\"http://jsfiddle.net/jfriend00/jQ93f/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/jQ93f/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T00:28:59.227", "Id": "58218", "Score": "0", "body": "@KrisHollenbeck - Added simpler way that uses the system to measure the text for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T16:43:01.703", "Id": "58370", "Score": "0", "body": "I appreciate the time you put into this answer and you gave me some good ideas. But I ended up doing it slightly different. Feel free to add comments to my answer if you see areas of improvement. I will leave this open for a while before I choose an answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T23:30:53.013", "Id": "35792", "ParentId": "35784", "Score": "5" } }, { "body": "<p>jfriend Got me thinking about arrays / objects as an option. End the end this is where I went with it. I am not sure if it is any better or more elegant than jfriend's answer. But I like the idea of an object so I will have the ability to expand to other fonts and sizes. Also this seems like less code, but it may not be faster. Which is also important. So anyways I am open to criticism / ideas.</p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>&lt;input value=\"Some really long string about nothing. And some other characters !@#$%&amp;*():;/\" /&gt;\n</code></pre>\n\n<p><strong>JS:</strong></p>\n\n<pre><code> // Helvetica, 12px or 1.2em at 62.5%\n\n var characters = {\n \"a\" : 7, \"A\" : 7, \"b\" : 7, \"B\" : 8, \"c\" : 6, \"C\" : 9,\n \"d\" : 7, \"D\" : 9, \"e\" : 7, \"E\" : 8, \"F\" : 7, \"f\" : 3,\n \"g\" : 7, \"G\" : 9, \"h\" : 7, \"H\" : 9, \"i\" : 3, \"I\" : 3,\n \"j\" : 3, \"J\" : 7, \"k\" : 5, \"K\" : 8, \"l\" : 3, \"L\" : 7, \n \"m\" : 11, \"M\" : 9,\"n\" : 7, \"N\" : 9, \"o\" : 7, \"O\" : 9,\n \"p\" : 7, \"P\" : 8, \"q\" : 7, \"Q\" : 9, \"r\" : 4, \"R\" : 9,\n \"s\" : 7, \"S\" : 8, \"t\" : 3, \"T\" : 7, \"u\" : 7, \"U\" : 9,\n \"v\" : 5, \"V\" : 7, \"w\" : 9, \"W\" : 11,\"x\" : 5, \"X\" : 7,\n \"y\" : 5, \"Y\" : 7, \"z\" : 5, \"Z\" : 7, \"0\" : 7, \"1\" : 7,\n \"2\" : 7, \"3\" : 7, \"4\" : 7, \"5\" : 7, \"6\" : 7, \"7\" : 7,\n \"8\" : 7, \"9\" : 7, \" \" : 5, \".\" : 3, \",\" : 3, \";\" : 3,\n \"'\" : 2, \"\\\"\" : 4, \"!\" : 3, \"@\" : 12, \"\\/\" : 3, \"$\" : 7,\n \"%\" : 11, \"&amp;\" : 8, \"*\" : 5, \"(\" : 4, \")\" : 4, \"-\" : 4,\n \"_\" : 7, \"+\" : 7, \"=\" : 7, \"?\" : 7, \"|\" : 3, \"#\" : 7,\n \":\" : 3\n };\n\n$.fn.dataWidth = function() {\n var length = str.length;\n var charWidth = 0;\n for ( var i = 0; i &lt; length; i++ )\n {\n var elWidth = characters[str[i]];\n charWidth += elWidth;\n }\n\n $(this).css('width', charWidth);\n}\n\nvar str = $('input').val();\n$('input').dataWidth(str);\n</code></pre>\n\n<p><strong>FIDDLE:</strong></p>\n\n<p><a href=\"http://jsfiddle.net/krishollenbeck/z9hhvhe3/1/\" rel=\"nofollow\">http://jsfiddle.net/krishollenbeck/z9hhvhe3/1/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:28:32.330", "Id": "58442", "Score": "0", "body": "I would at least put the initialization of the object outside of the function, init it once. Also your object misses some punctuation chars (!?,-'\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T23:00:41.823", "Id": "58483", "Score": "0", "body": "Good point. And yeah I figured I was going to have to add some more characters. I have updated my answer to reflect that change." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T16:45:54.623", "Id": "35854", "ParentId": "35784", "Score": "3" } }, { "body": "<p>It seems to me that the approach is wrong, you really should let the browser calculate the width, it's what is is good at.</p>\n\n<p>From an <a href=\"https://stackoverflow.com/a/5047712/7602\">SO answer</a>, I would use this:</p>\n\n<pre><code>function textWidth(font)\n{\n var f = font || '12px arial',\n o = $('&lt;div&gt;' + this + '&lt;/div&gt;')\n .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})\n .appendTo($('body')),\n w = o.width();\n o.remove();\n return w;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:13:00.850", "Id": "35856", "ParentId": "35784", "Score": "0" } }, { "body": "<p>I would agree with jonijin's answer, as there are many things, zoom level, font-size overrides, browser vendor and even OS that could skew the actual widths of a string. Not to mention, the other non DOM+Browser methods, won't work for all font-families or other non Latin characters.</p>\n\n<p>Also, based on all the answers above, i don't see any checks to prevent \"over sizing\" the input fields...</p>\n\n<p>I've solved this type of thing with CSS in the past here is a simple jsbin demonstrating the basic concept <a href=\"https://jsbin.com/wakabadeni/edit?html,css,output\" rel=\"nofollow noreferrer\">https://jsbin.com/wakabadeni/edit?html,css,output</a></p>\n\n<p>Of course I'm not sure that would work for your use case, just an idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-03T14:28:28.200", "Id": "302630", "Score": "0", "body": "You can embed executable JavaScript in your post (Ctrl+M), instead of having it off-site behind an eventual rotted link. As answers must relate to the OP's code, please take the time to explain *how* that independent solution solves \"this type of thing\". Code-only answers that consist of independent solutions, are subject to deletion... and that's with the code embedded in the post..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-31T19:28:40.803", "Id": "159474", "ParentId": "35784", "Score": "1" } } ]
{ "AcceptedAnswerId": "35792", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:13:14.183", "Id": "35784", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Input text sizing function" }
35784
<p>I'm fairly new to Python and am going to be parsing hundreds of thousands of names eventually. What I wanted to do was take individual CSV files, and create new CSV files with only the info I wanted. Then to take the whole lot and combine it into one big file.</p> <p>This code does that, but I feel I have typed way too much of it.</p> <pre><code>import csv csv1 = 'dictionary//first_names.csv' csv2 = 'dictionary//last_names.csv' csv3 = 'dictionary//last_name_prefixes.csv' csv4 = 'dictionary//profanities.csv' csv5 = 'dictionary//suffixs.csv' csv6 = 'dictionary//titles.csv' csv7 = 'dictionary//symbols.csv' csv8 = 'dictionary//businesses.csv' csv9 = 'dictionary//initials.csv' csv10 = 'dictionary//numbers.csv' csv11 = 'dictionary//removable.csv' def cleanupCSVFiles(csvFile, uniqueName): with open(csvFile) as csvfile: reader = csv.reader(csvfile) names = [line[0] for line in reader] with open('MyOutput//'+uniqueName+'.csv', 'w') as f: for name in names: f.write('{0}\n'.format(name)) def mergeCSVFiles(): fout=open('MyOutput//AllCSVFiles.csv', 'a') for num in range (1,11): for line in open('MyOutput//csv'+str(num)+'.csv'): fout.write(line) fout.close() cleanupCSVFiles(csv1, "csv1") cleanupCSVFiles(csv2, "csv2") cleanupCSVFiles(csv3, "csv3") cleanupCSVFiles(csv4, "csv4") cleanupCSVFiles(csv5, "csv5") cleanupCSVFiles(csv6, "csv6") cleanupCSVFiles(csv7, "csv7") cleanupCSVFiles(csv8, "csv8") cleanupCSVFiles(csv9, "csv9") cleanupCSVFiles(csv10, "csv10") cleanupCSVFiles(csv11, "csv11") mergeCSVFiles() </code></pre>
[]
[ { "body": "<p>What is the purpose of those intermediate \"output\" csv files with a single column of name?</p>\n\n<p>I don't see the purpose of it. So I removed it:</p>\n\n<pre><code>import csv\n\nFILES = [\n 'dictionary/first_names.csv',\n 'dictionary/last_names.csv',\n 'dictionary/last_name_prefixes.csv',\n 'dictionary/profanities.csv',\n 'dictionary/suffixs.csv',\n 'dictionary/titles.csv',\n 'dictionary/symbols.csv',\n 'dictionary/businesses.csv',\n 'dictionary/initials.csv',\n 'dictionary/numbers.csv',\n 'dictionary/removable.csv',\n]\n\ndef read_names(filename):\n with open(filename) as csvfile:\n reader = csv.reader(csvfile)\n return [line[0] + '\\n' for line in reader]\n\nfout = open('MyOutput/AllCSVFiles.csv', 'a')\n\nfor f in FILES:\n fout.writelines(read_names(f))\n\nfout.close()\n</code></pre>\n\n<p>If you don't want to type in all the files manually you can use <code>os.listdir</code> to find the files:</p>\n\n<pre><code>FILES = ['dictionary/' + filename\n for filename in os.listdir('dictionary/')\n if filename.endswith('.csv')]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T02:11:00.117", "Id": "58513", "Score": "0", "body": "I also just made a function out of the call, but other than that it works great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T08:09:04.870", "Id": "58536", "Score": "0", "body": "I am not familiar with python coding structure. So a question - Shouldn't these file i/o operations be wrapped inside try/catch ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:37:08.150", "Id": "58556", "Score": "0", "body": "You can wrap anything with try/catch if you want to handle errors in certain way. What is common in python maybe is to wrap file operations using `with open() as file:`, which makes sure that file will be closed in the end of `with` statement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:01:47.420", "Id": "35794", "ParentId": "35789", "Score": "2" } }, { "body": "<p>It's very important that you do not duplicate your logic, or your data. See my minor changes to the way you work with your data. You could even take it further seeing as you construct the filename using a sequence.</p>\n\n<pre><code>import csv\n\nDICT_SUB_FOLDER = 'dictionary'\nCSV_EXTENSION = 'csv'\nOUTPUT_DIR = 'MyOutput'\nFINAL_CSV_FILENAME = 'AllCSVFiles'\n\nCSV_DATA_FILES = {\n 'csv1': 'first_names',\n 'csv2': 'last_names',\n 'csv3': 'last_name_prefixes',\n 'csv4': 'profanities',\n 'csv5': 'suffixs',\n 'csv6': 'titles',\n 'csv7': 'symbols',\n 'csv8': 'businesses',\n 'csv9': 'initials',\n 'csv10': 'numbers',\n 'csv11': 'removable'\n}\n\n\ndef GetNames(csvFile):\n with open(csvFile) as csvfile:\n reader = csv.reader(csvfile)\n names = [line[0] for line in reader]\n return names\n\n\ndef cleanupCSVFiles(csvFile, uniqueName, mainFileFH):\n names = GetNames(csvFile)\n with open('%s//%s.%s' % (OUTPUT_DIR, uniqueName, CSV_EXTENSION), 'w') as fh:\n fh.writelines(names)\n mainFileFH.writelines(names)\n\n\ndef SplitAndConsolidate(outputFile):\n mainFileFH = open(outputFile, 'a')\n for csvFile in CSV_DATA_FILES:\n outputCSVFileName = \"%s//%s.%s\" % (DICT_SUB_FOLDER, csvFile, CSV_EXTENSION)\n cleanupCSVFiles(outputCSVFileName, csvFile, mainFileFH)\n mainFileFH.close()\n\n\nSplitAndConsolidate('%s//%s.%s' % (OUTPUT_DIR, FINAL_CSV_FILENAME, CSV_EXTENSION))\n</code></pre>\n\n<p>Don't feel bad about typing out too much code, or too many lines. The only thing you should feel bad or dirty about when programming is if you duplicate things. Once you remove duplicates, you start seeing the common patterns in your code, and everything flows naturally from that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:23:19.463", "Id": "58226", "Score": "0", "body": "I don't like the thing that you construct filenames. This kind of stuff makes it harder to look through the code. Lets say I have a big code base. I have a bug and I have a clue: a file name. Now with your kind of code it will be much harder to find it. And you don't really win anything apart from few characters by constructing the path of the files. Also if you type in full relative path to python file in many power editors and IDE's you can click on the file name to jump to the file. If you construct the file again you loose this ability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:31:23.157", "Id": "58229", "Score": "0", "body": "@Skirmantas I construct them because I have the future in mind. Unfortunately, I do succumb to the YAGNI problem, that's true. You could say it boils down to a matter of style. Personally, if I have a bug with a specific file as a clue, I will search for the important-seeming part of the filename. I won't copy-paste the whole path to look for it. E.g. I will search for \"first_names\" instead of \"dictionary/first_names.csv\". Common sense, because searching for \"first_names\" I could also find important functions/names/comments/etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:34:09.690", "Id": "58231", "Score": "0", "body": "You'll get lots of matches instead of 1 then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:36:33.340", "Id": "58232", "Score": "0", "body": "This case is simple. But so many times I had a hard time finding the stuff I need from the debugging info simply because someone was too smart in inventing dynamic name constructions where simple static definitions would have been good enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:36:36.590", "Id": "58233", "Score": "0", "body": "And if you were searching through my code, you would have found 0 matches, because you failed to anticipate that some people don't hard-code filenames into their code. I prefer false-positives over no results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:38:15.457", "Id": "58234", "Score": "0", "body": "Agreed, no need to obfuscate the generation of the filename, sure. Supporting your code is always a consideration when programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T02:04:32.797", "Id": "58236", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11616/discussion-between-skirmantas-and-zoran-pavlovic)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T01:11:39.027", "Id": "35795", "ParentId": "35789", "Score": "0" } }, { "body": "<ul>\n<li><code>mergeCSVFiles()</code> should take some parameters, such as the output filename.</li>\n<li>It is a good practice to open files by <code>with</code> statements. In one function you do so already, in the other you don't.</li>\n<li>If the output file is supposed to be a csv file, use <code>csv.writer</code> to ensure proper quoting. If on the other hand you actually need a plain text file, you should not name it .csv.</li>\n<li>Why do you create the numbered intermediate files instead of writing directly to the final file?</li>\n<li>A generator function is a nice way to process the input files.</li>\n<li>Using an <code>if __name__ == '__main__':</code> guard makes possible to import this module in other script to reuse the functions.</li>\n</ul>\n\n<p>My proposal:</p>\n\n<pre><code>import csv\n\ndef names_from_csv(filename):\n with open(filename, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n yield line[:1]\n\ndef merge_csv_files(filenames, output_filename):\n with open(output_filename, 'ab') as csvfile:\n writer = csv.writer(csvfile)\n for filename in filenames:\n writer.writerows(names_from_csv(filename))\n\nif __name__ == '__main__':\n FILES = [\n 'dictionary/first_names.csv',\n 'dictionary/last_names.csv',\n 'dictionary/last_name_prefixes.csv',\n 'dictionary/profanities.csv',\n 'dictionary/suffixs.csv',\n 'dictionary/titles.csv',\n 'dictionary/symbols.csv',\n 'dictionary/businesses.csv',\n 'dictionary/initials.csv',\n 'dictionary/numbers.csv',\n 'dictionary/removable.csv',\n ]\n merge_csv_files(FILES, 'MyOutput/AllCSVFiles.csv')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T01:59:37.200", "Id": "58511", "Score": "0", "body": "Great solution, this does create an extra space between each line it looks like." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T07:35:11.663", "Id": "58533", "Score": "0", "body": "@Airborne Oh, yes, the `csv` module wants you to open the files in binary mode on Python 2, and with `newline=''` on Python 3. Otherwise the line endings go wrong on Windows." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T07:52:30.697", "Id": "35811", "ParentId": "35789", "Score": "0" } } ]
{ "AcceptedAnswerId": "35794", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:47:48.260", "Id": "35789", "Score": "1", "Tags": [ "python", "optimization", "design-patterns", "csv" ], "Title": "CSV file cleanup" }
35789
<pre><code>public static StringBuffer infixToPostfix(StringBuffer infix) throws InvalidCharacterException { StringBuffer postfix = new StringBuffer(""); Stack&lt;String&gt; myStack = new Stack&lt;String&gt;(); myStack.push("("); infix.append(')'); for(int i = 0; i &lt; infix.length(); i++) { if(infix.charAt(i) == ' ') { //System.out.println("Space!"); } else if(Character.isDigit(infix.charAt(i)) == true) { postfix.append(infix.charAt(i) + " "); } else if(infix.charAt(i) == '(') { myStack.push("("); } else if(infix.charAt(i) == ')') { while(myStack.peek()!="(") { postfix.append(myStack.pop() + " "); } myStack.pop(); } else if(isOperator(infix.charAt(i) + "") == true) { String peekedItem = myStack.peek(); if(isOperator(peekedItem) == true) { if(getPrecedence(infix.charAt(i) + "") &lt;= getPrecedence(peekedItem)) { String poppedOp = myStack.pop(); if(poppedOp == "+") { postfix.append("+ "); } else if(poppedOp == "-") { postfix.append("- "); } else if(poppedOp == "*") { postfix.append("* "); } else if(poppedOp == "/") { postfix.append("/ "); } else if(poppedOp == "%") { postfix.append("% "); } String op = String.valueOf(infix.charAt(i)); myStack.push(op); } } else if(isOperator(peekedItem)==false) { String op = String.valueOf(infix.charAt(i)); myStack.push(op); } } else throw new InvalidCharacterException(infix.charAt(i)); } return postfix; } public static double evaluatePost(StringBuffer postfix) { String str = new String(postfix); str = str.replaceAll(" ", ""); postfix = new StringBuffer(str); postfix.append(")"); Stack&lt;Double&gt; anotherStack = new Stack&lt;Double&gt;(); double answer = 0; for(int k = 0; postfix.charAt(k) != ')'; k++) { if(Character.isDigit(postfix.charAt(k)) == true) { anotherStack.push(Double.parseDouble(postfix.charAt(k)+"")); } else if(isOperator(postfix.charAt(k)+"")==true) { double x = anotherStack.pop(); double y = anotherStack.pop(); char op = postfix.charAt(k); if(op=='+') { answer = (x+y); anotherStack.push(answer); answer = 0; } else if(op=='-') { answer = (y-x); anotherStack.push(answer); answer = 0; } else if(op=='*') { answer = (x*y); anotherStack.push(answer); answer = 0; } else if(op=='/') { answer = (y/x); anotherStack.push(answer); answer = 0; } else if(op=='%') { answer = (x%y); anotherStack.push(answer); answer = 0; } } } double finalAnswer = anotherStack.pop(); return finalAnswer; } </code></pre>
[]
[ { "body": "<p>When doing String comparisons, *<em>DO NOT USE <code>==</code> *</em></p>\n\n<p>Change your lines:</p>\n\n<pre><code>if(poppedOp == \"+\") {\n postfix.append(\"+ \");\n}\n.....\n</code></pre>\n\n<p>to be</p>\n\n<pre><code>if(\"+\".equals(poppedOp)) {\n postfix.append(\"+ \");\n}\n.....\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:01:19.637", "Id": "35801", "ParentId": "35798", "Score": "1" } }, { "body": "<p>Instead of those cascade ifs, use switches</p>\n\n<p>Replace all the <code>if(foo == true)</code> with <code>if(foo)</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:56:29.487", "Id": "35822", "ParentId": "35798", "Score": "0" } } ]
{ "AcceptedAnswerId": "35801", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T03:31:55.240", "Id": "35798", "Score": "-6", "Tags": [ "java", "strings", "stack", "converting" ], "Title": "Code review: infix to postfix converter" }
35798
<p>Here is a simple webpage that I wrote to test HTML code in real time as typed, what are some ways that I can Improve my code? part of the code is reused from a previous project, I believe that it may now be causing problems. I am still learning about CCS and in places i used both the HTML width tag and the CCS property to set the width of the item. </p> <p>When searching stackoverflow I found Quite a few questions about how HTML code can be loaded into an iframe, this seems to be a common problem, Am I properly loading a HTML string into an iframe?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;title&gt;Live HTML tester&lt;/title&gt; &lt;h1 id="Pagetitle"&gt;Live HTML tester&lt;/h1&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;style&gt; h1 { text-align: center; } textarea { vertical-align: top; width:100%; } iframe { vertical-align: bottom; width:100%; } &lt;/style&gt; &lt;body&gt; &lt;input id="browseOpen" type="file" accept=".html"/&gt; &lt;textarea rows="20" id="HTMLdata" placeholder="Enter HTML code" onKeyPress="edValueKeyPress() "onKeyUp="edValueKeyPress()"&gt; &lt;/textarea&gt; &lt;iframe id="test_iframe" src="about:blank" width="100%" height=400&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;script language="javascript"&gt; var fileInput = document.getElementById("browseOpen"); fileInput.onchange = function() { var fr = new FileReader(); fr.onloadend = function() { var result = this.result; html_string = result; //alert(result); var TheText = document.getElementById("HTMLdata"); TheText.innerText=result; edValueKeyPress(); }; fr.readAsBinaryString(this.files[0]); }; function edValueKeyPress(){ var edValue = document.getElementById("HTMLdata"); var html_string = edValue.value; var iframe = document.getElementById('test_iframe'); var iframedoc = iframe.document; if (iframe.contentDocument) iframedoc = iframe.contentDocument; else if (iframe.contentWindow) iframedoc = iframe.contentWindow.document; if (iframedoc){ iframedoc.open(); iframedoc.writeln(html_string); iframedoc.close(); } else { alert('Cannot inject dynamic contents into iframe.'); } } &lt;/script&gt; &lt;/html&gt; </code></pre> <p>Here is where the page is being hosted <a href="http://kylelk.github.io/html-examples/liveHTML.html" rel="nofollow">LiveHTML.html</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:17:54.680", "Id": "58263", "Score": "0", "body": "I have retracted my close vote, and upvoted - I'm no javascript writer but this looks like pretty trivial code, I'm sure you'll get answers pretty soon. Good luck!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:18:50.273", "Id": "58264", "Score": "0", "body": "@retailcoder Thank you for alerting me of my error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T16:22:25.830", "Id": "62717", "Score": "0", "body": "This is a similar application to give you good ideas: http://www.onlinehtmleditor.net/" } ]
[ { "body": "<p>Try rewriting your script with an addEventListener instead of an onChange method.</p>\n\n<p>However, keep in mind that an addEventListener is not compatible with IE lower then IE9. So don't use this yet in live sites.</p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener?redirectlocale=en-US&amp;redirectslug=DOM%2FEventTarget.addEventListener\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener?redirectlocale=en-US&amp;redirectslug=DOM%2FEventTarget.addEventListener</a></li>\n<li><a href=\"http://coding.smashingmagazine.com/2013/11/12/an-introduction-to-dom-events/\" rel=\"nofollow\">http://coding.smashingmagazine.com/2013/11/12/an-introduction-to-dom-events/</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:47:44.620", "Id": "35839", "ParentId": "35799", "Score": "1" } }, { "body": "<p><a href=\"https://stackoverflow.com/q/2947082/1157100\">StackOverflow 2947082</a> suggests:</p>\n\n<pre><code>var iframedoc = iframe.contentDocument ||\n iframe.contentWindow.document ||\n iframe.document;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T19:06:24.260", "Id": "62727", "Score": "1", "body": "Looks wrong, if `iframe.document` is the way to go, then contentWindow will be undefined and access document from it will error out. @Dangnabit mentions the same in the SO post. So probably `iframe.document || iframe.contentDocument || iframe.contentWindow.document` should do it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:24:28.610", "Id": "35846", "ParentId": "35799", "Score": "1" } }, { "body": "<p>I think that using the Html Width attribute is okay for an iframe, but I wouldn't use it for other tags, because you have CSS for that.</p>\n\n<p>anything that can/will be considered styling should be done in CSS, that is what it is there for, don't style in HTML, HTML is for Data Transport, use CSS to style the HTML the way you want it, CSS is more powerful than the outdated HTML Styling. </p>\n\n<p>saying that I would probably see if CSS Styling works on the Iframe in all browsers, and if it does, then you can completely separate your style from your HTML, which in Many cases is preferable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T18:39:57.330", "Id": "35939", "ParentId": "35799", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T03:33:58.230", "Id": "35799", "Score": "4", "Tags": [ "javascript", "html", "css" ], "Title": "Real time HTML tester" }
35799
<p>I've recently been learning about design patterns. Now I decided that I know enough to be able to refactor my inventory code. The question solely exist so I could show my fellow programmers the kind of destructive and lame mindset you'd get out of OOP, SOLID etc. <code>Adder.Add&lt;CoolAdd&gt;(new CoolAddArgs(1, 2, 3, etc)</code> instead of the simple function <code>CoolAdd(1, 2, 3, etc)</code> is just absurd.</p> <p>In an inventory, there are items. Wherever there are items, there's adding and swapping items. In my inventory, there's more than one way to add or swap items - <code>NormalAdd</code>, <code>ForceAdd</code>, <code>MouseSwapAdd</code>, etc. <code>SnapSwap</code>, <code>HoldSwap</code>, etc. (<a href="http://www.youtube.com/watch?v=cgrwLQE4bBs" rel="noreferrer">Video</a>)</p> <p>Currently, I have all those methods in my <code>ItemsBag</code>. I decided to move them outside, to an <code>Adder</code>/<code>Swapper</code>.</p> <p>I came up with an interesting system, which I think is SOLID. It's a mixture of the strategy and a bit of factor method patterns.</p> <p><strong>Usage:</strong></p> <pre><code>Adder adder = new Adder(); adder.Add&lt;NormalAdd&gt;(new NormalAddArgs(1, item, slot)); adder.Add&lt;ForceAdd&gt;(new ForceAddArgs(index)); Swapper swapper = new Swapper(); swapper.Swap&lt;SnapSwap&gt;(new SnapSwapArgs(1, 2, 3, etc)); swapper.Swap&lt;HoldSwap&gt;(new HoldSwapArgs(&quot;&quot;, 1)); </code></pre> <p>The idea, is that you have a <code>Strategy</code> that does something, given an <code>Args</code>. Now <code>Adder</code> and <code>Swapper</code> are <code>StrategyImplementers</code>.</p> <ul> <li><code>Adder</code> is an <code>AddingStrategy</code> implementer.</li> <li><code>NormalAdd</code> and <code>ForceAdd</code> are <code>AddingStrategy</code>.</li> <li><code>Swapper</code> on the other hand, is a <code>SwappingStrategy</code> implementer.</li> </ul> <p>Different strategies have different arguments, that's why a custom <code>Args</code> object has to be created.</p> <p><strong>Diagram</strong>:</p> <p><img src="https://i.stack.imgur.com/DWUj4.png" alt="enter image description here" /></p> <p><strong>Code:</strong></p> <p>(This is the main part - the bottom left part of the diagram)</p> <pre><code>public abstract class Args { } public abstract class Strategy { public abstract bool Implement(Args args); } public static class StrategyCreator { static public T Create&lt;T&gt;() where T : Strategy, new() { return new T(); } } public abstract class StrategyImplementor&lt;T&gt; where T : Strategy { private Dictionary&lt;Type, T&gt; dic = new Dictionary&lt;Type, T&gt;(); protected bool Implement&lt;TStrategy&gt;(Args args) where TStrategy : T, new() { Type type = typeof(TStrategy); T strategy = GetStrategy(type); if (strategy == null) { strategy = StrategyCreator.Create&lt;TStrategy&gt;(); // lazy dic[type] = strategy; } return strategy.Implement(args); } private T GetStrategy(Type type) { T strategy; return dic.GetValue(type, out strategy); } } </code></pre> <p>(Here's the adding stuff - swapping is pretty much the same)</p> <pre><code>public class Adder : StrategyImplementor&lt;AddingStrategy&gt; { public bool Add&lt;T&gt;(AddArgs args) where T : AddingStrategy, new() { return Implement&lt;T&gt;(args); } } /* &lt;&lt;&lt; Adding Strategies &gt;&gt;&gt; */ #region public abstract class AddingStrategy : Strategy { } public class NormalAdd : AddingStrategy { public override bool Implement(Args args) { if (!(args is NormalAddArgs)) throw new Exception(&quot;NormalAdd: Invalid args!&quot;); Console.WriteLine(&quot;Normal add&quot;); return true; } } public class ForceAdd : AddingStrategy { public override bool Implement(Args args) { if (!(args is ForceAddArgs)) throw new Exception(&quot;ForceAdd: Invalid args!&quot;); Console.WriteLine(&quot;Force add&quot;); return true; } } #endregion /*&lt;&lt;&lt; Strategy Args &gt;&gt;&gt; */ #region public abstract class AddArgs : Args { } public class NormalAddArgs : AddArgs { public int row; public int col; public Etc etc; public NormalAddArgs() { } public NormalAddArgs(int row, int col, etc) { this.row = row; this.col = col; } } public class ForceAddArgs : AddArgs { public int id; public Etc etc; public ForceAddArgs(int id, etc) { this.id = id; } } #endregion </code></pre> <p>So as you can see it's very easily to extend and create new strategies without affecting any existing code. All I have to do to add a new <code>CoolAdd</code> strategy is write <code>CoolAdd</code> and <code>CoolAddArgs</code> and that's it! Now I can:</p> <pre><code>Adder.Add&lt;CoolAdd&gt;(new CoolAddArgs(1, 2, 3, etc); </code></pre> <p>The one thing I didn't like about it, is imagine how many arrows will come out of the consumer - i.e. the class that's gonna use the code in the Usage section above. It's gonna have to know about all these stuff... <code>Adder</code>, <code>NormalAdd</code>, <code>ForceAddArgs</code>, etc</p> <p>Me and my buddy (J), who is helping me with my design patterns study, decided that there has to be something done to reduce dependency, maybe to be able to write <code>Adder.Add&lt;NormalAdd&gt;(1, &quot;string&quot;, item, etc);</code>. But there wasn't a clear way of doing so...</p> <p>But then he told me, why not just create an <code>Adder</code> with the adding methods inside, and then when the user wants to add/extend the existing behavior, they he just extends <code>Adder</code> and add his methods there!</p> <pre><code>public class Adder { public void NormalAdd() { } public void ForceAdd() { } etc } </code></pre> <p>Later on:</p> <pre><code>public class MyAdder : Adder { public void CoolAdd() { } } </code></pre> <p>I care so much about extending the behavior, without modifying existing code because I will be shipping this inventory. If a user does that and I release an update, his changes will be overwritten. I think both our systems guard against that.</p> <p>Now, my friend's system was very easy to overlook for me because I was so focused on implementing/finding use of design patterns.</p> <p>I thought a lot about which system is better and why, here are my thoughts in terms of:</p> <ol> <li><p><strong>Single responsibility (S in SOLID):</strong></p> <p>I think my system wins, since I have very focused and highly cohesive modules, that each does a very specific thing and nothing else. In his system, it's not very focused. In real code, there might be some adding methods, that does a lot of calculations that they require some helper methods, where would you put those helper methods then? What if <code>ForceAdd</code> had <code>helper1</code>, <code>helper2</code> and <code>helper3</code>? Where would you put those? In the <code>Adder</code> itself? Do so and the S is broken. In my system, any <code>ForceAdd</code>-related stuff, is in the <code>ForceAdd</code>.</p> </li> <li><p><strong>Open/closed principle (O in SOLID):</strong></p> <p>There is no doubt that my system follows this rule to the bone! How about his? Well, even though every time a new adding method needs to be added, the Adder programmer has to go and add the method to the Adder thus he's modifying the Adder in a way. But I don't think the O is broken here, since he's not modifying any of the pre-existing adding methods. If a user wants to add extra adding methods, he'd extend the original adder and add his methods there, not affecting anything.</p> </li> <li><p><strong>Liskov substitution principle (L in SOLID):</strong></p> <p>Who cares? let's light some flares! I didn't really know how to compare the two in terms of L.</p> </li> <li><p><strong>Interface segregation principle (I in SOLID):</strong></p> <p>I think my system wins again. It's true we don't have interfaces, but the idea behind I, is not to carry extra luggage that you ain't gonna need (YAGNI). In his system, if I wanted to add <code>CoolAdd</code> I'd have to make a new adder that extend the original adder just so that I could use <code>CoolAdd</code>. In other words, I don't really care about the other adding methods that my new adder will have, due to inheritance from the original adder! Extra luggage.</p> </li> <li><p><strong>Dependency inversion principle (D in SOLID):</strong></p> <p>I'm not sure, but I think we both play nice with this. Since we both allow the user to inject the parameters needed for something to work.</p> </li> <li><p><strong>Simplicity/Less complexity:</strong></p> <p>Obviously, my system if far more complex and sophisticated.</p> </li> <li><p><strong>Less/fewer dependencies and loose coupling:</strong></p> <p>He wins here again, since there's very little that the consumer has to know about things. In fact, the consumer only knows about Adder - <code>adder.NormaAdd(1, 2, etc);</code>.</p> </li> <li><p><strong>Less garbage:</strong></p> <p>That's an obvious win for him, since I got a lot of <code>new</code>ing going on.</p> </li> <li><p><strong>Less code, fewer classes, less bothersome:</strong></p> <p>Obviously, in his system you write less code, fewer class thus you're less bothered. But is that an important factor?</p> </li> <li><p><strong>Testing:</strong></p> <p>I'm not a unit testing expert, but from what I know, when you make separate focused modules that have single responsibilities, they are easier to test - So it's easy to test each strategy and see how it behaves, since it's a separate object. In his system, all the adding methods is in one class - the Adder. I'm not sure if that will make it hard to test...</p> </li> <li><p><strong>Readability:</strong></p> <p>Both are readable, I guess.</p> </li> <li><p><strong>Maintainability:</strong></p> <p>I think mine is easy to maintain since it's divided to separate components. In his, the Adder could get messy if a lot of adding methods were added...</p> </li> <li><p><strong>Performance:</strong></p> <p>I can't tell without benchmarking, but I'm gonna give this to him. Since I take some time in my casts and <code>new</code>ing.</p> </li> <li><p><strong>Re-Usability:</strong></p> <p>I think I currently fail here, since if I wanted to create an adding strategy that takes the same arguments that another adding strategy takes, I can't do that. I have to create a custom args object. So I can't make use of my existing args. In fact, I should look to fix that. I'm not sure about his system...</p> </li> </ol> <p><strong>Summary:</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>________________________________________ | | V | J | ---------------------------------------- |S | 1 | 0 | |O | 1 | 0.5 | |L | ? | ? | |I | 1 | 0 | |D | 1 | 1 | |Simplicty/Less complexity | 0 | 1 | |Less depe/Loose coupling | 0 | 1 | |Less garbage | 0 | 1 | |Less code, fewer classes | 0 | 1 | |Testing | 1 | 0 | |Readability | 1 | 1 | |Maintainability | 1 | 0 | |Performance | 0 | 1 | |Reusability | 1 | 0.5 | |______________________________________| |Final Score | 8 | 8 | </code></pre> </blockquote> <ol> <li>What do you think about the two approaches?</li> <li>Which system would you use? Which system you think is best and why?</li> <li>Are my assessments correct?</li> <li>Is there an important factor I missed that will make a big difference?</li> <li>Is there a disadvantage to either systems that you see I missed?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:59:32.550", "Id": "58303", "Score": "0", "body": "Since you acknowledged that you are not sure about **D**, you should '?' in the comparison table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:07:18.087", "Id": "58346", "Score": "3", "body": "`swapper.Swap<SnapSwap>(new SnapSwapArgs(1, 2, 3, etc));` That's a lot of repetition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:35:30.097", "Id": "58524", "Score": "0", "body": "Thanks for that! - your statement inspired me a better solution - I came up with it while taking a bath - taking a bath is nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:06:05.080", "Id": "58553", "Score": "1", "body": "A system should be primarily evaluated on how well it meets the requirements, not how many ticks it gets on a list of design patterns/principles. In your question the actual requirements are very unclear, so it's very difficult for us to evaluate your code. It's clear there's a lot of complexity in your solution (both of them), but without the bigger picture we cannot determine whether this is intrinsic complexity or [accidental complexity](http://en.wikipedia.org/wiki/Accidental_complexity)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T12:00:28.633", "Id": "58566", "Score": "0", "body": "Thanks for your comment. You are right. I think they both kinda meet the requirements (which is, providing an extensible way of adding/swapping items), that's why I wanted to look at other factors to help me determine which should I go for, since they both take me there. \"the actual requirements are very unclear\" hmm? I thought that was clear, unless you meant something else. You mean the requirements from these systems, or all my requirements in the whole inventory project?" } ]
[ { "body": "<p>I think I came up with a way to halve dependencies, and reduce the amount of code required to add items to just:</p>\n\n<pre><code>AddItems(new NormalAdd(1, 2, 3, etc));\n</code></pre>\n\n<p>I don't know how I missed this, but the key is to leave the <code>Implement</code> method abstract in the base <code>Strategy</code> class <strong>parameterless</strong>, and introduce the necessary arguments in the concrete classes themselves!</p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>Rotate(new NormalRotate(1, 2, \"\", etc);\nRotate(new SmoothRotate( stuff );\nRotate(new SoftRotate( other stuff );\n\npublic bool Rotate(RotationStrategy s)\n{\n return s.Implement();\n}\n</code></pre>\n\n<p>A lot simpler eh?</p>\n\n<pre><code>public abstract class SimpleStrategy\n{\n public abstract bool Implement();\n public static T Create&lt;T&gt;() where T : SimpleStrategy, new()\n {\n return new T();\n }\n}\npublic abstract class RotateStrategy : SimpleStrategy { }\npublic class NormalRotate : RotateStrategy\n{\n public int arg1 { protected set; get; }\n public float arg2 { protected set; get; }\n public string arg3 { protected set; get; }\n\n public NormalRotate() { }\n public NormalRotate(int arg1, float arg2, string arg3)\n {\n Set(arg1, arg2, arg3);\n }\n\n public NormalRotate Set(int arg1, float arg2, string arg3)\n {\n this.arg1 = arg1;\n this.arg2 = arg2;\n this.arg3 = arg3;\n return this;\n }\n\n public override bool Implement()\n {\n // do something with arg1, arg2 and arg3\n Console.WriteLine(\"rotating normally\");\n return true;\n }\n}\npublic class SmoothRotate : RotateStrategy\n{\n public string[] args { private set; get; }\n\n public SmoothRotate(string[] args)\n {\n Set(args);\n }\n public SmoothRotate() { }\n\n public SmoothRotate Set(string[] args)\n {\n this.args = args;\n return this;\n }\n\n public override bool Implement()\n {\n // do something with args\n Console.WriteLine(\"smooth rotation\");\n return true;\n }\n}\npublic class SoftRotate : SmoothRotate\n{\n public int i { private set; get; }\n\n public SoftRotate() { }\n public SoftRotate(string[] args, int i) : base(args)\n {\n this.i = i;\n }\n\n public SoftRotate Set(string[] args, int i)\n {\n Set(args);\n this.i = i;\n return this;\n }\n\n public override bool Implement()\n {\n // do something with i\n Console.WriteLine(\"damn we're soft!\");\n return base.Implement();\n }\n}\n</code></pre>\n\n<p>Why the <code>return this;</code> in the setters? Well, the only thing that I don't like now about my system, is that every time I add/rotate/swap/whatever, I still have to new up stuff. Previously, I had the strategies cached in a nice lazy way. Wouldn't it be nice to have this kind of thing here as well?</p>\n\n<p>We can do this:</p>\n\n<pre><code>var cache = new Cache&lt;SimpleStrategy&gt;();\nvar normal = cache.Request&lt;NormalRotate&gt;();\nRotateItem(normal.Set(1, 2, \"\"));\n// Or\nRotateItem(cache.Request&lt;SoftRotate&gt;().Set(new[] { \"\" }, 10));\n</code></pre>\n\n<p><strong>Code:</strong></p>\n\n<pre><code>public class Cache&lt;T&gt; where T : SimpleStrategy\n{\n private List&lt;T&gt; list = new List&lt;T&gt;();\n public void Add(T strategy)\n {\n list.Add(strategy);\n }\n public void Add(T[] strategies) // if you don't wanna be lazy\n {\n foreach (var strategy in strategies) {\n Add(strategy);\n }\n }\n public void Remove(T strategy)\n {\n list.Remove(strategy);\n }\n public TStrategy Request&lt;TStrategy&gt;() where TStrategy : T, new()\n {\n var strategy = list.FirstOrDefault(s =&gt; s.GetType() == typeof(TStrategy)) as TStrategy;\n if (strategy == null) {\n strategy = SimpleStrategy.Create&lt;TStrategy&gt;(); // lazy\n Add(strategy);\n }\n return strategy;\n }\n}\n</code></pre>\n\n<p>So it's up to the user really. Do you wanna cache and allocate/deallocate memory less often? Using the cache, do you want less keystorkes? Instantiate a new strategy each time you want one.</p>\n\n<p><img src=\"https://i.stack.imgur.com/qSFy7.png\" alt=\"enter image description here\"></p>\n\n<p>This implementation solves most if not all the problems my previous implementation had:</p>\n\n<ol>\n<li>Less garbage</li>\n<li>Less keystrokes, less code, fewer classes</li>\n<li>Less dependencies</li>\n<li>More reusable</li>\n<li>Less complex</li>\n</ol>\n\n<p>About resuability - notice how <code>SoftRotation</code> inherits <code>SmoothRotation</code>. Why not if it uses the same arguments? This is a problem we had before, when I said what if <code>ForceAdd</code> requires the same arguments as <code>NormalAdd</code>? I previously had to create a separate arguments object for it. Now I don't; I just inherit.</p>\n\n<p><strong>New summary:</strong></p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>________________________________________\n| | V | J |\n----------------------------------------\n|S | 1 | 0 |\n|O | 1 | .5 |\n|L | ? | ? |\n|I | 1 | 0 |\n|D | 1 | 1 |\n|Simplicty/Less complexity | .5 | 1 |\n|Less depe/Loose coupling | .5 | 1 |\n|Less garbage | .5 | 1 |\n|Less code, fewer classes | .5 | 1 |\n|Testing | 1 | 0 |\n|Readability | 1 | 1 |\n|Maintainability | 1 | 0 |\n|Performance | .5 | 1 |\n|Reusability | 1 | .5 |\n|______________________________________|\n|Final Score |10.5| 8 |\n</code></pre>\n</blockquote>\n\n<p>I guess that's a win for me.</p>\n\n<p>But no system is perfect. The only thing I don't like about it now, is the fact that <code>Set</code> is not abstracted - each concrete strategy has to write its own. I would rather have <code>Set</code> an abstract method inside <code>SimpleStrategy</code> but since the arguments are different, I would have to rollback to creating argument objects. Then we'd have something similar to what we had before: <code>Set(Args)</code> and then each strategy define it's own args.</p>\n\n<p>It's less complex, but less robust as well. Pretty much a matter of give and take.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T09:47:08.460", "Id": "58874", "Score": "1", "body": "\"I guess that's a win for me :)\" - Please do not take this as criticism, but I think you need a slight attitude readjustment. It seems you marvel at the novelty of your own code, and there is a little too much ego in there. It is not a competition. A good developer sees every line of code he writes as a burden, not a triumph. He understands that \"clever\" code is rarely *good* code, as \"clever\" often conflicts with maintainability (arguably the most important factor of good code, even more important than correctness). A truly good developer can solve complex problems with simple code.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T09:48:13.777", "Id": "58875", "Score": "0", "body": "I hope you do not take that comment as criticism. Every developer goes through the self-marvel stage at some point - it is a sign of enthusiasm. You have already demonstrated that you are open to honest constructive-feedback by visiting this site :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:22:04.887", "Id": "59084", "Score": "0", "body": "I don't know why you interpreted what I said like that - I never meant it that way. I was never looking for ways to make my code better so that I could 'win' - Maybe I used the wrong word. Every programmer has the tendency to like what he writes more - since he spent his time and sweat on it, but if the other code is better then by all means I'll give up mine. I wasn't holding on my code, just because it's mine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:47:25.830", "Id": "59092", "Score": "0", "body": "\"A good developer sees every line of code he writes as a burden\" - well that's the main reason I'm trying to come up with a better system than what I had - I don't think I agree with you in that a good dev thinks immediately of what he writes as a burden. I think it's natural to feel good about yourself, about what you write - But then after some time you learn and improve yourself - Then you automatically feel that your old codes are burden, since your standards are now higher than before cause of what you learn. This should remain a circle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:51:05.533", "Id": "59096", "Score": "0", "body": "There is no better feeling than knowing that you came up with something better than what you had (knowing that you're improving) - It's a victory in a way. No one could argue that. And this is what keeps us programmers 'alive' - The good feeling of achievement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:03:14.857", "Id": "59101", "Score": "0", "body": "Maybe you were right about my attitude being not the most suitable. I didn't even think about it when I wrote it. Didn't even know that it would have such an interpolation. But it's not something new to me - This happens to me a lot in real-life. Maybe I think think more before I say/write something... Idk. Maybe I exaggerated with \"design battle\" - I didn't mean a battle nor competition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T19:32:13.947", "Id": "59133", "Score": "2", "body": "Is there a reason that the `Strategy` implementations can't be re-used as they are, instead of caching their arguments? Other than that, this is a really big improvement over the original, and very much useable. Although, I still think I would rather have had one `Adder` and one `Swapper` ahead of schedule. Matter of priorities, I guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T03:20:50.470", "Id": "59179", "Score": "0", "body": "No there's no reason you can't do that. But I just thought it would be nice to put everything into one place - a bit organized. Another improvement I thought of would be: instead of Setting and then implementing, how about an Implement method that takes the args, and does the Set and Implement internally? - I think the extension method idea I posted down below is even better than all this :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:28:17.847", "Id": "35897", "ParentId": "35807", "Score": "4" } }, { "body": "<p>As an exercise, I think your evaluation is fair - by all means, carry on. I think it's worth mentioning, though, that in terms of production, the factors you've enumerated aren't all weighted equally.</p>\n\n<p><strong>At the end of the day, if your code is totally DRY, you can go home happy.</strong> DRY (don't repeat yourself) implies that every datum about how your system works is located in exactly one place in your source. You can't make readable, DRY code difficult to extend - there's only one place to make a change. The \"code inertia\" as I like to call it, as measured in keystrokes per behavior difference, is at its minimum.</p>\n\n<p>Beyond that point, <strong>any addition of complexity should be driven by necessity only.</strong> If the system outside of your adders and swappers evolves such that the simpler design cannot logically suffice, that's when you can think about picking apart the simplest thing that could possibly work. If your simpler design is DRY, there is minimal risk in leaving it alone. Complexity, on the other hand, is always a cost - it's work expanding to fill available time, and it's more time you have to spend training someone when you get promoted before they can test/maintain/extend your code.</p>\n\n<p>Since I don't see egregious repetition in either design, I would therefore prefer the simpler one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T04:58:39.110", "Id": "58763", "Score": "0", "body": "Thanks for your reply. \"I would therefore prefer the simpler one\" - over the complex system in my question, or the simplified one in my answer, or both?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T11:26:09.610", "Id": "58774", "Score": "0", "body": "I don't think that DRYness is the only measure of good code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T18:19:36.603", "Id": "58788", "Score": "1", "body": "@svick sure, it's not the only one. There are multiple designs for any given system that are DRY, after all. My point is that it's the point of diminishing returns. DRY code can certainly be an inadequate design in other respects - maybe those concerns will manifest as problems, maybe they won't. If they do, you can permute any DRY design into another with minimal work to address them. vexe: primarily the one in the question - it seems that adding a strategy has become more complicated than adding a method, and it's unclear what that abstraction is protecting me from." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:31:13.047", "Id": "59105", "Score": "0", "body": "\"any addition of complexity should be driven by necessity only\" True. TBH, if I was a consumer of this system, it's kinda tough to come up with an adding/swapping method, since I'm already covering all the possible ways. I'm not saying it won't happen that a user would come up with something, just saying it's rare. I certainly tend to easily think of stuff I might not need just because I think I 'might' need them (bad habit). I like the simplicity of `Adder.AddNormally(stuff)` in the simpler design, also like the flexibility in my answer. I really don't know which to choose, very confused." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-23T20:32:41.880", "Id": "35985", "ParentId": "35807", "Score": "7" } }, { "body": "<p>Try creating unit tests first that define what it is you need to accomplish. You need unit tests to prove that your code and ideas work anyway, so why not start with them? Writing the tests first will give you incentive to keep your code simple and testable - if you find the tests difficult to write, or are confusing in how you have to use your class, then you've actually exercised this interface you've created, and you will have learned of its potential deficiencies.</p>\n\n<p>Once you've written the unit tests, you should be able to post them here. We could use them as a walk-through document that says \"if the user wants to rotate items normally, this is how we accomplish it. If the user changes rotation strategies, this is how we do that. </p>\n\n<p>Unit tests make for very readable, very practical documentation. If I find it hard to understand a unit test, the class is too hard to use. If I have to know a lot of magic setup things to use the class, it's too hard to use. And if it's too hard to use, it's too hard to reuse, and fails the SOLID principles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T20:33:47.590", "Id": "58939", "Score": "0", "body": "Welcome to Code Review, if you have any questions there are a few of us more than happy to give you some links or answers, you can find a few of us in [Code Review General Chat](http://chat.stackexchange.com/rooms/8595/code-review-general-room)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T02:58:39.947", "Id": "58982", "Score": "0", "body": "+1! I can't believe I did all that pontificating without mentioning TDD/BDD. Good call, John." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:33:57.097", "Id": "59087", "Score": "0", "body": "Thanks for your answer. Unfortunately, unit testing in Unity3d isn't as simple your normal unit tests - there are some plugins that gives you the ability to unit test - but not sure of their effectiveness. I'm not even sure how to unit test this whole adding/swapping thing... I mean, you got an inventory and items the users could mess with by interacting with the inventory (via mouse) - so... Idk. I'm a self learner and still new to TDD." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:17:07.637", "Id": "59104", "Score": "0", "body": "ah, you never mentioned you were using Unity3D. I would like to say, most good design principles go out of the window when you're talking about games development. The vast majority of design patterns & practices you read on the 'net were not forged in that fire. Something to bare in mind :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:38:57.503", "Id": "59106", "Score": "0", "body": "Right. I learned that the hard way btw. I got smacked when I went for a full object hierarchy design and not going for a component-based one. But now I know. I'm getting better.\n\n\"you never mentioned you were using Unity3D.\" - I linked a video in the beginning of my question - it clearly shows that I'm using Unity3d, perhaps you read the question a little quickly? (Btw you should turn off your F2 silent bomber mode :D - since I'm not getting notified of your comments for some reason)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T18:58:18.847", "Id": "59129", "Score": "1", "body": "I've never used Unity3d, but SharpUnit supposedly works with it. http://wiki.unity3d.com/index.php?title=SharpUnit Another option you could take would be to test these in a standalone program without trying to complicate it with Unity. TDD is intended to motivate you to creating code without external dependencies, so that would actually fit well here. You could test your ideas without worrying about mice, Unity, or whatever. Once you see that Dependency Injection solves the problem, it kind of hits you how modularity should work in your favor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T19:00:48.657", "Id": "59130", "Score": "0", "body": "Just saw your previous comment: \"I linked a video...\". Keep in mind this is a code review, and is not really about learning how your product appears to the end user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T03:26:02.557", "Id": "59180", "Score": "0", "body": "@JohnDeters +1 right. About the video, I think it gives answers a concrete idea of what's this all about. Instead of having to 'imagine' it." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T20:22:10.623", "Id": "36073", "ParentId": "35807", "Score": "4" } }, { "body": "<p>I've totally missed something else! The simpler design is actually MUCH better had I considered <em>extension methods</em>! Don't know how I missed that, since I cared so much about \"extending\" the behavior... with this, I could \"KISS\" my fancy diagrams goodbye!</p>\n\n<pre><code>public class Adder\n{\n public bool NormalAdd(arg1, arg2, etc) { }\n public bool ForceAdd(arg1, etc) { }\n etc...\n}\n</code></pre>\n\n<p>When somebody wants to add something, it's as simple as adding an extension method!</p>\n\n<pre><code>public static class AdderExtensions\n{\n public static bool SwapAdd(this Adder a, arg1, etc) { }\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>var adder = new Adder();\nadder.NormalAdd(stuff);\nadder.ForceAdd(stuff);\nadder.SwapAdd(stuff);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:52:39.300", "Id": "36149", "ParentId": "35807", "Score": "0" } } ]
{ "AcceptedAnswerId": "36149", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:40:02.030", "Id": "35807", "Score": "8", "Tags": [ "c#", "design-patterns", "comparative-review" ], "Title": "Comparison between two design battle approaches" }
35807
<p>I've written a small function for solving simple quadratic equations:</p> <pre><code>class EquationSolver def solve(x, *args) args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element } end end </code></pre> <p>To calculate <code>f(3)</code> for <code>f(x)=3x3−2x2−x+5</code>, one would write:</p> <pre><code>puts EquationSolver.new.solve(3, 3, -2, -1, 5) </code></pre> <p>However, is there a more elegant version of my function, more like <code>reduce.with_index</code> or something similar?</p>
[]
[ { "body": "<p>Yes, there is a more elegant version. Here it is:</p>\n\n<pre><code>class EquationSolver\n def solve(x, *args)\n args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }\n end\nend\n</code></pre>\n\n<p>It's possible to do this because iterator methods like <code>each_with_index</code>, when called without a block, return an Enumerator object on which you can call all the methods of the Enumerable.</p>\n\n<p>In fact, an even shorter solution is obtained by using a variation of reduce to use a symbolic operator:</p>\n\n<pre><code>class EquationSolver\n def solve(x, *args)\n args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:32:05.860", "Id": "58301", "Score": "0", "body": "10x, I had figured out the first version you proposed, but I didn't pass a `0` to `reduce` as a starting parameter, so it was giving me `no implicit conversion of Fixnum into Array`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:36:21.853", "Id": "58302", "Score": "0", "body": "Yep, it tends to happen. I'd any day prefer my second variation since it makes for an easy reading." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T08:45:38.727", "Id": "35815", "ParentId": "35810", "Score": "2" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li>If you use a OOP approach, it seems more logical to use methods.</li>\n<li>Use arrays to group values that go together.</li>\n<li>I don't think <em>solve</em> is the correct term, that's when you are finding the roots of a function, here you're just <em>evaluating</em> it at a given point.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>class Polynomial\n attr_accessor :coefficients \n\n def initialize(coefficients)\n self.coefficients = coefficients.reverse\n end\n\n def evaluate(x)\n coefficients.map.with_index { |k, power| k * (x**power) }.reduce(0, :+)\n end\nend\n\npolynomial = Polynomial.new([3, -2, -1, 5])\nputs polynomial.evaluate(3) #=&gt; 65\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:38:42.177", "Id": "58308", "Score": "0", "body": "Pretty good. Btw, I think you don't need the 0 in `reduce(0, :+)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:46:43.570", "Id": "58309", "Score": "1", "body": "@AlexPopov: Well, it's just to consider the case `f(x) = 0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:50:40.720", "Id": "58310", "Score": "0", "body": "Good point, didn't think about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:59:06.090", "Id": "58311", "Score": "0", "body": "Btw, if you have `zero = Polynomial.new 0`, the code throws `undefined method \\`reverse' for 0:Fixnum (NoMethodError)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:38:44.587", "Id": "58322", "Score": "0", "body": "zero = Polynomial.new [0]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:36:21.720", "Id": "58334", "Score": "0", "body": "Yes, I figured that out, or the other option being `def initialize(*coefficients)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:40:46.450", "Id": "58336", "Score": "1", "body": "@Alex: Yes. Personally I don't like this because it makes difficult to add extra arguments. IMHO the coefficients should be grouped, and an array is the most obvious way to do it." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:35:52.453", "Id": "35825", "ParentId": "35810", "Score": "2" } } ]
{ "AcceptedAnswerId": "35825", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T07:47:25.183", "Id": "35810", "Score": "3", "Tags": [ "ruby", "mathematics" ], "Title": "Polynomial equation solver in Ruby" }
35810
<p>I'm learning Python, and found a fun little video on YouTube called "Learn Python through public data hacking". In essence it uses the CTA unofficial API to do some parsing of XML data. In taking things further than inline code, I'm chunking behaviors into modules and classes to further understand how Python works.</p> <p>The XML from the API looks something like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;buses rt="22"&gt; &lt;time&gt;1:40 AM&lt;/time&gt; &lt;bus&gt; &lt;id&gt;4194&lt;/id&gt; &lt;rt&gt;22&lt;/rt&gt; &lt;d&gt;East Bound&lt;/d&gt; &lt;dd&gt;Northbound&lt;/dd&gt; &lt;dn&gt;E&lt;/dn&gt; &lt;lat&gt;41.88327006970422&lt;/lat&gt; &lt;lon&gt;-87.62828115689553&lt;/lon&gt; &lt;pid&gt;5421&lt;/pid&gt; &lt;pd&gt;Northbound&lt;/pd&gt; &lt;run&gt;P238&lt;/run&gt; &lt;fs&gt;Howard&lt;/fs&gt; &lt;op&gt;49875&lt;/op&gt; &lt;dip&gt;5314&lt;/dip&gt; &lt;bid&gt;7323287&lt;/bid&gt; &lt;wid1&gt;0P&lt;/wid1&gt; &lt;wid2&gt;238&lt;/wid2&gt; &lt;/bus&gt; &lt;!-- bus... n --&gt; &lt;/buses&gt; </code></pre> <p>I'm using the python-requests module for the HTTP side, and once the XML is downloaded, I parse each <code>&lt;bus&gt;</code> node into a <code>Bus</code> class, assign each of the child nodes into a dictionary, and make that visible with a <code>get(prop)</code> statement, so I can just call <code>bus.get('lat')</code> to retrieve the latitude, etc. However, in order to do the correct calculations on it (i.e. arithmetic) each node's value needs to be returned as the correct type. By default, they're all read as strings.</p> <p>Considering that Python doesn't have a "switch" statement like most other languages, someone at SO said to use a dictionary. Is this the/a correct way of doing something like this? Or is there some nifty builtin that I don't know of?</p> <pre class="lang-py prettyprint-override"><code>def dyncast(value): _type = type(value) types = { "FloatType": (r'^[\d]{2}\.[\d]+$', lambda f : float(f)), "IntType" : (r'^[\d]+$', lambda i : int(i)), "StrType" : (r'^[a-zA-z]+$', lambda s : str(s)) } for typeval in types: pattern = types[typeval][0] fn = types[typeval][1] match = re.match(pattern, value) # if it matches a regex and has a group(), return the # lambda calculation (typecast) if match and match.group(): return fn(value) # return straight up if no matches return value # Called via: for elm in node: self._data[elm.tag] = dyncast(elm.text) # where node is the bus node, and elm are the child nodes </code></pre> <p>It seems to work well, as I get returns such as:</p> <pre class="lang-py prettyprint-override"><code># print bus.get('fs'), type(bus.get('fs')) Harrison &lt;type 'str'&gt; # print bus.get('lat'), type(bus.get('lat')) 41.9027030677 &lt;type 'float'&gt; </code></pre>
[]
[ { "body": "<p>Makes sense to me. A couple small things:</p>\n\n<p><code>lambda f: float(f)</code> should be equivalent to just <code>float</code> if I'm not mistaken. You can simplify the loop a bit too since you're not actually using the dictionary keys.</p>\n\n<pre><code>types = [\n (r'(regex)', float),\n (r'(regex)', int),\n (r'(regex)', str),\n]\nfor pattern, fn in types:\n match = ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:19:29.133", "Id": "58419", "Score": "0", "body": "\"`lambda f: float(f)` should be equivalent to just `float`\" ⟶ It's known as [η-conversion](https://en.wikipedia.org/wiki/Lambda_calculus#.CE.B7-conversion)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T08:11:14.753", "Id": "35814", "ParentId": "35813", "Score": "4" } }, { "body": "<ul>\n<li>It is not necessary to match StrType as your fallback is anyway to return the original string.</li>\n<li>The float regex does not accept a sign, as in <code>&lt;lon&gt;-87.62828115689553&lt;/lon&gt;</code>, or exponential notation.</li>\n<li>You can use just <code>if match:</code> instead of <code>if match and match.group():</code> as the regexes do not match empty strings.</li>\n<li>MatrixFrog's approach for streamlining the code is good.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T18:15:57.863", "Id": "58638", "Score": "0", "body": "Thanks. Yea I'll go in and modify the regex to match all possibilities. This was just a milestone point to and wanted to make sure it wasn't overkill." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:40:41.557", "Id": "35820", "ParentId": "35813", "Score": "2" } }, { "body": "<p>There is no need to redefine <code>types</code> each time the function is called. Also the use of the name <code>types</code> isn't declarative enough - the reader can't gain much info from the name.</p>\n\n<p>The name <code>dyncast</code> I guess stands for dynamic cast? be more declarative in the function name. E.g, <code>unserialise</code>.</p>\n\n<p>There may be gains to be made by compiling the regex once.</p>\n\n<p>The code defines <code>_type</code>, but don't use it.</p>\n\n<p>The code iterates over a dict in an inefficient way: instead its better to use the .iteritems() method instead of iterating the keys and then getting the value from the dict. However, saying that - you don't need a dict at all - this can be achieved with a humble tuple. Its a good habit to use better performing data types.</p>\n\n<p><code>match</code> evaluates to truthy or falsey so there is no need to do <code>if match and match.groups...</code></p>\n\n<p>The regex patterns can miss values that should be matches - e.g, float of 1.1 or 123.4 would not be matched. Moreover, you don't need to match for string because dyncast returns the unchanged value if not matched (which is a string).</p>\n\n<p>So given all the above, instead consider</p>\n\n<pre><code>PATTERN_TO_TYPE = (\n (compile(r'^[\\d]+\\.[\\d]+$'), float),\n (compile(r'^[\\d]+$'), int),\n}\n\ndef unserialise(value):\n for regex, fn in PATTERN_TO_TYPE:\n if regex.match(value):\n return fn(value)\n return value\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T18:17:18.073", "Id": "58639", "Score": "0", "body": "Thanks for the cleanup! As for the match statement I was getting errors about None Type, the and check removed. I'll revisit. Some of the vars were leftover from debug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T13:42:12.467", "Id": "58776", "Score": "0", "body": "for debugging - use pdb - its an interactive debugger where you set a breakpoint at the line you are interested in with `from pdb import set_trace; set_trace()`.\n\nthen when you run your script you will be given an interactive shell of the script \"paused\" at that line so you can introspect.\n\nAso, post the error in a comment here, maybe I can help" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:31:11.673", "Id": "35831", "ParentId": "35813", "Score": "1" } } ]
{ "AcceptedAnswerId": "35814", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T07:57:42.127", "Id": "35813", "Score": "3", "Tags": [ "python", "regex", "casting" ], "Title": "Limited typecasting with regex" }
35813
<p>Is there a way to make this smarter?</p> <p>Here is the complete code <a href="http://jsbin.com/uzuJUSE/5/edit?html,js,output" rel="nofollow" title="jsbin link">jsbin link</a></p> <p>the code needs to filter the table, and show in the parameters list, only the filters that remain in the table, and with the number aside the parameter.</p> <pre><code>&lt;div class="filterColumn"&gt; &lt;h2&gt;size&lt;/h2&gt; &lt;span class="filter" data-filterby="size" data-count="0" data-val="1"&gt;1(1)&lt;/span&gt; &lt;span class="filter" data-filterby="size" data-count="0" data-val="2"&gt;2(3)&lt;/span&gt; &lt;span class="filter" data-filterby="size" data-count="0" data-val="3"&gt;3(4)&lt;/span&gt; &lt;span class="filter" data-filterby="size" data-count="0" data-val="4"&gt;4(2)&lt;/span&gt; &lt;/div&gt; &lt;div class="filterColumn"&gt; &lt;h2&gt;height&lt;/h2&gt; &lt;span class="filter" data-filterby="height" data-count="0" data-val="7"&gt;7(3)&lt;/span&gt; &lt;span class="filter" data-filterby="height" data-count="0" data-val="8"&gt;8(3)&lt;/span&gt; &lt;span class="filter" data-filterby="height" data-count="0" data-val="11"&gt;11(4)&lt;/span&gt; &lt;/div&gt; &lt;div class="filterColumn"&gt; &lt;h2&gt;weight&lt;/h2&gt; &lt;span class="filter" data-filterby="weight" data-count="0" data-val="22"&gt;22(2)&lt;/span&gt; &lt;span class="filter" data-filterby="weight" data-count="0" data-val="45"&gt;45(5)&lt;/span&gt; &lt;span class="filter" data-filterby="weight" data-count="0" data-val="88"&gt;88(1)&lt;/span&gt; &lt;span class="filter" data-filterby="weight" data-count="0" data-val="90"&gt;90(1)&lt;/span&gt; &lt;span class="filter" data-filterby="weight" data-count="0" data-val="11"&gt;11(1)&lt;/span&gt; &lt;/div&gt; &lt;div class="filterColumn"&gt; &lt;h2&gt;color&lt;/h2&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="red"&gt;red(2)&lt;/span&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="green"&gt;green(2)&lt;/span&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="blue"&gt;blue(2)&lt;/span&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="grey"&gt;grey(2)&lt;/span&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="black"&gt;black(1)&lt;/span&gt; &lt;span class="filter" data-filterby="color" data-count="0" data-val="white"&gt;white(1)&lt;/span&gt; &lt;/div&gt; &lt;table id="productTable"&gt; &lt;tr&gt; &lt;th&gt;Model&lt;/th&gt; &lt;th&gt;size&lt;/th&gt; &lt;th&gt;height&lt;/th&gt; &lt;th&gt;weight&lt;/th&gt; &lt;th&gt;color&lt;/th&gt; &lt;/tr&gt; &lt;tr data-size="1" data-height="7" data-weight="22" data-color="red"&gt; &lt;td&gt;111az&lt;/td&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;22&lt;/td&gt; &lt;td&gt;red&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="2" data-height="7" data-weight="45" data-color="red"&gt; &lt;td&gt;111as&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;red&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="2" data-height="7" data-weight="45" data-color="green"&gt; &lt;td&gt;111af&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;green&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="2" data-height="8" data-weight="45" data-color="green"&gt; &lt;td&gt;111ag&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;green&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="3" data-height="8" data-weight="45" data-color="blue"&gt; &lt;td&gt;111ah&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;blue&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="3" data-height="8" data-weight="45" data-color="blue"&gt; &lt;td&gt;111aj&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;blue&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="3" data-height="11" data-weight="22" data-color="grey"&gt; &lt;td&gt;111az&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;td&gt;22&lt;/td&gt; &lt;td&gt;grey&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="3" data-height="11" data-weight="88" data-color="grey"&gt; &lt;td&gt;111az&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;td&gt;88&lt;/td&gt; &lt;td&gt;grey&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="4" data-height="11" data-weight="90" data-color="black"&gt; &lt;td&gt;111ak&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;td&gt;90&lt;/td&gt; &lt;td&gt;black&lt;/td&gt; &lt;/tr&gt; &lt;tr data-size="4" data-height="11" data-weight="11" data-color="white"&gt; &lt;td&gt;111al&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;td&gt;11&lt;/td&gt; &lt;td&gt;white&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div id="reset"&gt;reset&lt;/div&gt; </code></pre> <h2>the jQuery code</h2> <pre><code>var thisfiltertitle = ["size","height","weight","color"]; $("#reset").click(function() { $("#productTable tr:hidden").show(); $(".filterColumn").find("span").show(); UpdateData(); }); $(".filter").click(function() { var filterby = $(this).data("filterby").trim(); var val = $(this).data("val"); var rows = $("#productTable tr:visible:gt(0)"); rows.each(function(index) { var row = $(this); if ($(this).data(filterby) == val) { row.show(); }else{ row.hide(); } }); UpdateData(); }); function UpdateData() { $(".filterColumn").find("span").each(function(index) { $(this).attr("data-count",0); $(this).html($(this).attr("data-val") + "(0)"); }); for(i=0; i&lt;thisfiltertitle.length; i++) { $("tr[data-" + thisfiltertitle[i] + "]:visible").each(function(index) { thisoption = $("span[data-filterby=" + thisfiltertitle[i] + "][data-val='" + $(this).data(thisfiltertitle[i]) + "']"); thisoption.attr("data-count",parseInt(thisoption.attr("data-count"),10)+1); }); } $(".filterColumn").find("span[data-count=0]").hide(); $(".filterColumn").find("span").each(function(index) { $(this).html($(this).attr("data-val") + "(" + $(this).attr("data-count") + ")"); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:48:24.067", "Id": "58561", "Score": "1", "body": "Already quite smarter than a lot of JS I see these days, if you ask me :) A lead for improvement would be to separate more clearly presentation from business logic (too much data in data-attributes) : refactor this to hold all data in an array of objects, perform searches on this array instead of the DOM, and create & update filters / table dynamicly using this array. Apart of that, such code would be a perfect candidate for an [AngularJS Directive](http://angularjs.org/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:50:15.043", "Id": "58562", "Score": "1", "body": "ps: using an architecture based on an array will make your life easier if you want to add AJAX actions later. pps: you might also want to use a js templating system for this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T12:08:49.120", "Id": "59441", "Score": "0", "body": "what approach are you taking to render this? ie. are you generating your initial filter elements through some server side logic, or would you be happy to look at solutions which involve creating these elements on the fly, clientside, based on a viewmodel?" } ]
[ { "body": "<p>Overall I think it works pretty well. There are just a few minor issues with the existing implementation that I could highlight : </p>\n\n<p><strong>Ensuring State \"Safety\"</strong></p>\n\n<p>On first render filter items have a <code>data-count</code> value of <code>0</code>, which only gets updated after the first call to UpdateData, nevertheless on first render they are technically in an incorrect state.</p>\n\n<p><code>data-val</code> is set correctly (hard-coded) in the code though on first render, but also gets updated with calls to UpdateData. The concern here is there are two independant things which are responsible for the rendering of these attributes (the hard-coded or server rendering of the <code>.filter</code> elements, and the script) which leaves room for error. By making sure only one thing is responsible for the state of those attributes will make sure they don't get muddled.</p>\n\n<p>I would opt to not hard-code or render the <code>data-</code> attributes on the server, but rather to generate them on the clientside <em>only</em> and so to make sure that <code>UpdateData()</code> is called when the page loads.</p>\n\n<p><strong>One directional</strong></p>\n\n<p>Because this process only scans the rows that are visible (by using the <code>tr[data-\" + thisfiltertitle[i] + \"]:visible</code> selector) the outcome is that you can't ever undo a filtered value without resetting the entire filter.</p>\n\n<p>If you ever wanted to add your filter options as checkboxes, not spans, and allow for filtered options to be undone, you'd have to change things up a bit to get around this.</p>\n\n<p><strong>Repeated Selectors</strong></p>\n\n<p>This is only relevant if you're fine combing through your performance, but its worth noting that you could improve the code a little bit by storing the results of jquery selectors that you use more than once in variables for more efficient re-use.</p>\n\n<p>Also to minimise the number of event handlers registered, you could use jQuery's <code>delegate</code> on the container of the <code>span.filter</code> elements, rather than having click events on each element.</p>\n\n<p><strong>Client-Side Templating</strong></p>\n\n<p>*m_x mentioned this in their comment, but just to expand on this a little*</p>\n\n<p>Your example contains a fair amount of repeated content, ie state is maintained both in <code>data-*</code> attributes and naturally in the display of element text values. Absolutely nothing wrong with this, but it does make things a bit tricky to modify this state. ie. When you want to pull that state out quickly to work with it or look at it, you have to loop through the dom elements and grab their data attributes and build up that model each time.</p>\n\n<p>If you used some client side templating, or something like KnockoutJS, you would just have to update the model (an array of objects in memory) and the HTML on the page would update in response to the changes, due to the publish-subscribe nature of the template (and in the case of KnockoutJS, observables).</p>\n\n<p><em>Hope that helps, your code's smart code already, but wanted to mention the few things I could find or suggest!</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T14:22:12.003", "Id": "36290", "ParentId": "35818", "Score": "1" } } ]
{ "AcceptedAnswerId": "36290", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T09:11:08.477", "Id": "35818", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "code review: filter table with filter parameters" }
35818
<p>I have a fairly ugly controller method I would like to refactor / extract. I can only test this in an integration-type test which kind of signals a code smell.</p> <p>The method processes the form and needs to do one of 5 things, depending on which button was pressed</p> <ol> <li>if submitted and valid (button 1) => update some values on the entity and re-render the form</li> <li>if submitted and valid (button 2) => perform another controller action that shows a .pdf print of the entity</li> <li>if submitted and valid (button 3) => save entity and redirect</li> <li>if not submitted or not valid => render form (plus errors)</li> </ol> <p>In code it looks kind of like this:</p> <pre><code>protected function processForm(Request $request, MyEntity $entity) { $form = $this-&gt;createForm(new MyEntityType, $entity); if ($form-&gt;handleRequest($request)-&gt;isValid()) { $alteredEntity = SomeClass:performStuffOnEntity($entity); if ($form-&gt;get('button1')-&gt;isClicked()) { $form = $this-&gt;createForm( new MyEntityType, $alteredEntity ); } else if ($form-&gt;get('button2')-&gt;isClicked()) { return $this-&gt;pdfPreview($alteredEntity); } else if ($form-&gt;get('button3')-&gt;isClicked()) { return $this-&gt;persistAndRedirectToEntity( $alteredEntity ); } } return $this-&gt;render( 'MyBundle:MyEntity:new.html.twig', array( 'form' =&gt; $form-&gt;createView(), )); } </code></pre> <p>There are actually two buttons like <code>button1</code>; I left one out for brevity of the example.</p> <p>Ideas:</p> <ol> <li><p>I have tried to extract this into a <code>EntityFormWizard</code> of some sort but this ended up as a cluttered Object with too many dependencies (Router, Templating, Form) which was also a pain to test.</p></li> <li><p>Using <code>FormEvents</code> I wanted to extract at least the altering of the entity depending on which button was pressed into a <code>FormEventListener</code>, but the only place where I can alter the <code>Entity</code> is the <code>FormEvents::PRE_SET_DATA</code> event, but in there I have problems figuring out which button was clicked.</p></li> </ol> <p>Do I have to live with my integration test for this behavior or is there a way to extract it and test it with a unit test?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:49:39.930", "Id": "58525", "Score": "0", "body": "This question appears to be off-topic because it seems like you are asking us how to write code for you, or how to do something other than increase readability, performance, speed, etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T06:54:58.623", "Id": "58528", "Score": "1", "body": "I disagree; I think that rearranging code for testability is on topic. However, we haven't been given enough context to understand the problem. This might be a situation where it makes sense to post the code of greatest concern here, and the rest on GitHub or something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:03:06.770", "Id": "58551", "Score": "0", "body": "Hi, not trying to get my code written for me. Everything in here exists already. Just looking for a better abstraction or advice how to extract that method cleverly. If I extract it as it is I end up with exactly the same dependencies as in the controller. So I wouldnt really gain anything." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:34:09.603", "Id": "35824", "Score": "1", "Tags": [ "php", "mvc", "symfony2" ], "Title": "Form-processing controller action" }
35824
<p>The class takes an input of a game-id from the ESPN soccer website. The code then has to grab the commentary, process that and also grab the player names/ids and create a small dictionary of those.</p> <p>I understand the premise of OOP when shown in basic examples but I cannot get my head around using it in actual programs/applications. I have tried here, but to me it seems to not achieve anything extra (so I must be doing it wrong).</p> <p>I end up with a list of lists containing each of the key events (corners, shots etc) and a dictionary of players, so it works. But it just seems so inelegant and I would love some tips on improving it (however small/focused they are).</p> <pre><code>import urllib2 from scrapy.selector import HtmlXPathSelector import re import codecs import timeit start = timeit.default_timer() class game: def __init__(self,game_id): self.game_id = game_id self.comms_url = 'http://espnfc.com/uk/en/gamecast/%d/gamecast.html?soccernet=true&amp;cc=5739' % self.game_id self.data_text = urllib2.urlopen(self.comms_url).read() self.corners = [] self.shots = [] self.fouls = [] self.shots_on_target = [] self.offsides = [] self.goals = [] self.extractCommentaries() self.extractPlayers() self.extractTeams() self.findAction('^Corner', self.corners) self.findAction('^Foul by', self.fouls) self.findAction('^Attempt', self.shots) self.findAction('^Attempt saved', self.shots_on_target) self.findAction('^Offside', self.offsides) self.findAction('^Goal!', self.goals) def extractCommentaries(self): self.hxs = HtmlXPathSelector(text=self.data_text) self.match_comments = self.hxs.select("//div[@id='convo-window']/ul[@id='convo-list']/li/div[@class='comment']/p/text()") self.match_timestamps = self.hxs.select("//div[@id='convo-window']/ul[@id='convo-list']/li/div[@class='timestamp']/p/text()") self.events = zip(self.match_timestamps.extract(), self.match_comments.extract()) self.cleanclean = [] for time,event in self.events: time = re.search('\d+', time) if time: time = time.group() time = int(time) self.cleanclean.append((time,event)) self.dumdum = range(len(self.events)) self.clean_events = {} for key, event in enumerate(self.cleanclean): self.clean_events[key] = event def extractPlayers(self): self.player_names = self.hxs.select("//table[@class='stat-table']/tbody//a/text()") self.player_urls = self.hxs.select("//table[@class='stat-table']/tbody//a/@href") self.player_ids = [] for url in self.player_urls.extract(): digit = [] for s in url: if s.isdigit(): digit.append(s) self.placeholder = ''.join(digit) self.placeholder = int(self.placeholder) self.player_ids.append(self.placeholder) self.players = dict(zip(self.player_ids, self.player_names.extract())) def extractTeams(self): self.dummy = ['home','away'] self.zero = [0,0] self.team_names = self.hxs.select("//li[@class='country']/h2/text()") self.teams = dict(zip(self.dummy,self.team_names.extract())) def findAction(self, keyword, storage): for key, value in self.clean_events.iteritems(): action = re.search(keyword, value[1]) if action: for ha, team in self.teams.iteritems(): if keyword == '^Goal!': split_up_action = value[1].split('.') found = re.search(team, split_up_action[1]) else: found = re.search(team, value[1]) if found: temp_holder = [value[0], team, self.game_id] storage.append(temp_holder) a = game() stop = timeit.default_timer() print stop - start </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:36:45.793", "Id": "58321", "Score": "0", "body": "It would help to fix the indentation on the code sample. Paste the code, highlight it all, and hit the \"Code Sample\" button." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:10:07.410", "Id": "58347", "Score": "0", "body": "Sorry about that, I was having quite a lot of trouble with that for some reason, should be fixed now." } ]
[ { "body": "<ul>\n<li>There are no docstrings, so a user of your class is left wondering which methods could be useful to call. In fact, after studying the code, it looks like all the methods are meant to be called by <code>__init__</code>, in a specific order. Makes me wonder if this should be a class at all.</li>\n<li>You set very many instance attributes, even a <code>self.dummy</code>, but use very few outside the method where they are set. Most of them should be local variables instead. Again, I'm thinking that you don't need a class -- all the methods could be simple functions that take one or two parameters instead.</li>\n<li>The purpose of the class seems to be to initialize six lists, eg. <code>self.corners</code>. So, to get an overview of the game, one has to access six variables. It would be better to use a single data structure that can be easily looped over and queried. Perhaps a dictionary with keys like <code>\"corners\"</code> could suit you, but I'm thinking that most useful would be to keep the events in a chronological list and provide a function to filter that list by type of event.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:26:09.100", "Id": "58560", "Score": "0", "body": "Thanks for this. Basically as I thought. I decided to try and write it using a class but could tell that it wasn't really necessary. I need to do more reading on OOP as I really just don't get it. I think I will try and combine all those lists into one big dictionary as you say, definitely makes more sense. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:11:21.003", "Id": "35855", "ParentId": "35830", "Score": "5" } }, { "body": "<p>I'm having trouble following this code, so I'm going to focus on maintainability. Here are some things you can consider changing:</p>\n\n<ul>\n<li>Some members are currently initialized in <code>__init__</code>, some are only initialized in other methods. It's typically good to define invariants of your class that will remain true at all observable times. Since <code>__init__</code> calls everything that's still mostly true for external users, but it makes it harder for you to remember what's ready in <code>game</code>'s methods.</li>\n<li>Echoing Janne Karila, some members are being used where there's no need for anything else to see them. Locals should be used instead. Maybe fixing this would remove most of the weird cases of the previous bullet.</li>\n<li><p>There's a special case in <code>findAction</code> for one of the many parameters it's called with.\nI find <code>findAction</code> very hard to follow. But I also don't like how it takes a list by reference and appends to it. It's typically more pythonic to return a value. If <code>findAction</code> created and returned a list, then your caller could be <code>self.corners = self.findAction('^Corner')</code>. This would even clean up some of <code>__init__</code>.</p></li>\n<li><p>There are a number of magic values mixed in with the rest of the code. Sometimes it's nice to extract these to a single location and give them a meaningful name. For example the URL format string, or the XPath strings, or even the regex pattern strings. As these are immutable values I would consider placing these on the class:</p>\n\n<pre><code>class game:\n COMMS_URL_FMT = 'http://...%s...'\n COMMENT_XPATH = \"//div/...\"\n\n def __init__(self, game_id):\n self.data_text = urllib2.urlopen(self.COMMS_URL_FMT % game_id).read()\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T13:26:40.013", "Id": "35918", "ParentId": "35830", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:05:43.640", "Id": "35830", "Score": "3", "Tags": [ "python", "scrapy", "xpath" ], "Title": "Using Scrapy/Xpath to scrape ESPN for football (soccer) commentaries" }
35830
<p>I am just trying to convert each list of values to String by index one by one. My Code is running fine. But I am thinking that I can write better code than this. I Need your good coding possibilities here to convert from list to String.</p> <p>I am using the code below to convert:</p> <pre><code>CarComment[] list = form.getCarDataJaxb().getCarCommentList(); JSONObject obj = new JSONObject(); JSONArray comments = new JSONArray(); for (int i=0;i&lt;list.length;i++){ if (notEmpty(list[i].getText())){ JSONArray commObj = new JSONArray(); String str = list[i].getText(); str = str.replaceAll("&lt;", "&amp;lt;"); commObj.put(str); comments.put(commObj); } } obj.put("carcomm", comments); response.setContentType("text/json"); response.getWriter().write(obj.toString()); </code></pre> <p>I am trying to write good coding technique while converting from list to String at line <code>String str = list[i].getText();</code> </p>
[]
[ { "body": "<p>I have modified the loop. Here is the code --</p>\n\n<pre><code>for (CarComment carComment : list) {\n String text = carComment.getText();\n if (isEmpty(text)) { continue; }\n\n JSONArray commObj = new JSONArray();\n commObj.put(text.replaceAll(\"&lt;\", \"&amp;lt;\"));\n\n comments.put(commObj);\n}\n</code></pre>\n\n<p>you can provide <code>CarComment</code> class to see how it looks like and how is the <code>getText</code>? Those can be improved by looking the original code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:14:36.937", "Id": "58357", "Score": "1", "body": "it is an interface with setters and getters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T04:04:38.063", "Id": "58519", "Score": "1", "body": "would you please explain your answer?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:37:53.540", "Id": "35837", "ParentId": "35835", "Score": "0" } }, { "body": "<p>There actually isn't so much to improve here (at least not that I can think of).</p>\n\n<p>Instead of using an index to iterate by, you can use a Java for-each loop. Since you only used the iterator variable to read the index of the list, it is usually more readable to use a for-each loop.</p>\n\n<p>You were not indenting your code correctly (before the edit of your question), which I also fixed below.</p>\n\n<p>And, below I use the opposite way of checking if the text is empty, by using <code>continue</code> if the if-statement is <strong>not</strong> true, you can avoid having to indent the code an extra step.</p>\n\n<pre><code>CarComment[] list = form.getCarDataJaxb().getCarCommentList();\nJSONObject obj = new JSONObject();\nJSONArray comments = new JSONArray();\nfor (CarComment carComment : list) {\n if (!notEmpty(carComment.getText()))\n continue;\n JSONArray commObj = new JSONArray();\n commObj.put(carComment.getText().replaceAll(\"&lt;\", \"&amp;lt;\"));\n comments.put(commObj);\n}\nobj.put(\"carcomm\", comments);\nresponse.setContentType(\"text/json\");\nresponse.getWriter().write(obj.toString());\n</code></pre>\n\n<p>Preferably, to avoid double-negation, you should use <code>if (isEmpty(...))</code> instead of <code>if (!notEmpty(...))</code></p>\n\n<p>However, there's no way of having to do a method call to <code>getText</code> (or a similar method call) on your line.</p>\n\n<pre><code>String str = list[i].getText();\n</code></pre>\n\n<p>What I did was to skip the declaration of a local variable and process the string (by calling <code>replaceAll</code>) directly when adding it to it's destination.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:54:59.907", "Id": "58342", "Score": "0", "body": "Hi Simon, i didn't use double-negation..!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:59:58.273", "Id": "58344", "Score": "2", "body": "@Mdhar9e basically isEmpty is available in java's String api. Use it when it is applicable and as told by Simon(the negation thing). Otherwise do you have the code which you wrote for notEmpty or its just a pseudo code ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:06:17.157", "Id": "58345", "Score": "1", "body": "@Mdhar9e I know you didn't, but I did. And I'm telling you to not do it ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:40:46.540", "Id": "35838", "ParentId": "35835", "Score": "5" } } ]
{ "AcceptedAnswerId": "35838", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:23:16.433", "Id": "35835", "Score": "2", "Tags": [ "java", "strings", "collections" ], "Title": "Assigning list index values to String" }
35835
<p>I've a requirement to find sum of an attribute of each JSON row and then add another attribute to show percentage of corresponding attribute. The JSON is as follows -</p> <pre><code>[ {"value":150, ...}, {"value":125, ...}, {"value":100, ...}, {"value":60, ...}, {"value":30, ...} ] </code></pre> <p>Now, I've written following code.</p> <pre><code>var totalVal = 0; $.each(data, function(index, value) { totalVal += value.value; }); $.each(data, function(index, value) { value.label = Math.round((value.value / totalVal) * 10000) / 100 + "%"; }); </code></pre> <p>I've to use 2 loops to achieve the result. Is there any way to do this in single loop?</p> <p>EDIT: The code I've written works perfectly. Since I'm contributing back to publicly available GitHub project, I really want to know if the method is most efficient.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:48:40.213", "Id": "58348", "Score": "0", "body": "Since you need totalValue to compute the label, it seems like it might be hard to stick one loops." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:48:50.013", "Id": "58349", "Score": "2", "body": "I don't think it is possible.. because first you need to find the total then the percentage" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:49:31.267", "Id": "58350", "Score": "0", "body": "No. The result will be all wrong.\nSee in loop execution totalValue will vary as 150, 275, ... So your percentage vary as 100%, 45.45%, ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:52:49.780", "Id": "58351", "Score": "0", "body": "@Bart care to explain more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:53:11.403", "Id": "58352", "Score": "0", "body": "create a jsfiddle for that.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:55:33.027", "Id": "58353", "Score": "0", "body": "@ahren I had no idea what codereview is. I do think this question should go there. Can I move this question, or should I ask there again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:56:49.510", "Id": "58354", "Score": "0", "body": "@BikasVaibhav - Yeah it's a new stackexchange site still in beta. I'll flag the question and see if one of the mod's will move it for you." } ]
[ { "body": "<p>No, <code>totatVal</code> won't be a <code>totalVal</code> until you loop through all the rows to find it.\nIt might be solved by a single loop with some fancy standard functions but at the end it will come down to 2 loops. </p>\n\n<p>It's pure math - you need to count your total value first in order to find a correct % of each of your values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:51:56.513", "Id": "35843", "ParentId": "35842", "Score": "5" } } ]
{ "AcceptedAnswerId": "35843", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:44:44.183", "Id": "35842", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Can only one loop be used to calculate percentage?" }
35842
<p>Can someone help me make this code more professional? I'm trying my best to find something similar, but I wasn't successful.</p> <p>I want to avoid the repeat of the code for every single value and also I can't find a solution to avoid select. I only get it run when I repeat the code and count <code>rng</code>, <code>rng1</code>, <code>rng2</code> etc.</p> <pre><code>Sub a() Dim cell As Range, i As Integer, wks As Worksheet Dim rng As Range Dim rng1 As Range Dim rng2 As Range Dim rng3 As Range Set Bereich = Sheets("Tabelle1").Range("B2:B" &amp; Cells(Rows.Count, 1).End(xlUp).Row) For Each cell In Bereich If cell.Value = "EURUSD" Then If Not rng Is Nothing Then Set rng = Union(rng, Rows(cell.Row)) Else Set rng = Rows(cell.Row) End If End If Next cell rng.EntireRow.Select With Selection ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count) Sheets(ActiveSheet.Name).Name = "EURUSD" rng.EntireRow.Copy Worksheets("EURUSD").Cells(5, 1) End With '-------------------------------------------------------------------------------- Sheets("Tabelle1").Select For Each cell In Bereich If cell.Value = "GBPUSD" Then If Not rng1 Is Nothing Then Set rng1 = Union(rng1, Rows(cell.Row)) Else Set rng1 = Rows(cell.Row) End If End If Next cell rng1.EntireRow.Select With Selection ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count) Sheets(ActiveSheet.Name).Name = "GBPUSD" rng1.EntireRow.Copy Worksheets("GBPUSD").Cells(5, 1) End With '-------------------------------------------------------------------------------- Sheets("Tabelle1").Select For Each cell In Bereich If cell.Value = "AUDUSD" Then If Not rng2 Is Nothing Then Set rng2 = Union(rng2, Rows(cell.Row)) Else Set rng2 = Rows(cell.Row) End If End If Next cell rng1.EntireRow.Select With Selection ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count) Sheets(ActiveSheet.Name).Name = "AUDUSD" rng2.EntireRow.Copy Worksheets("AUDUSD").Cells(5, 1) End With '-------------------------------------------------------------------------------- Sheets("Tabelle1").Select For Each cell In Bereich If cell.Value = "NZDUSD" Then If Not rng3 Is Nothing Then Set rng3 = Union(rng3, Rows(cell.Row)) Else Set rng3 = Rows(cell.Row) End If End If Next cell rng1.EntireRow.Select With Selection ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count) Sheets(ActiveSheet.Name).Name = "NZDUSD" rng3.EntireRow.Copy Worksheets("NZDUSD").Cells(5, 1) End With End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:24:37.400", "Id": "58359", "Score": "3", "body": "sounds like you need to create a function or two." } ]
[ { "body": "<p>Doing <kbd>Copy</kbd>+<kbd>Paste</kbd> in your IDE should raise a big red flag and then there should be a neural inhibitor that prevents your left hand from doing it, causing your right hand to move your mouse further down the module and then start typing <code>Private Function...</code></p>\n\n<p>Now the first thing you need to do <em>before you write any code</em>, is <em>\"What is it exactly that I need to be doing?\"</em> - don't think in terms of <em>\"well I need to loop all cells in that range and check if its value matches a certain specific string, then I need to do [xyz]\"</em>; rather, think at one or two <em>levels of abstraction</em> above that, like <em>\"well I need to copy all the rows with the same currency code to a new worksheet that's named after the currency code in question\"</em>.</p>\n\n<p>If I understand what you're doing, you could consider starting with something like this:</p>\n\n<pre><code>Private Function GetRowsForCurrency(ByVal SourceRange As Range, ByVal CurrencyName As String) As Range\n Dim Cell As Range\n Dim Result As New Range\n\n For Each Cell In SourceRange\n If Cell.Value = CurrencyName Then Set Result = Union(Result, Rows(Cell.Row))\n Next\n\n Set GetRowsForCurrency = Result\nEnd Function\n</code></pre>\n\n<p>Then you want to select all these rows and copy them to a new worksheet that you name after the \"currency name\":</p>\n\n<pre><code>Private Sub CopyToNewWorksheet(ByVal SourceRange As Range, ByVal CurrencyName As String)\n Dim Result As Worksheet\n Set Result = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))\n Result.Name = CurrencyName\n SourceRange.EntireRow.Copy Result.Cells(5, 1) 'comment why (5,1) here\nEnd Sub\n</code></pre>\n\n<p>Notice I'm using the <a href=\"http://msdn.microsoft.com/en-us/library/office/ff839847.aspx\"><code>Add</code> function</a>'s return value, which represents the sheet that was added.</p>\n\n<p>With a function to get the cells and a procedure to copy them to a new sheet, all that's left to do is to call them:</p>\n\n<pre><code>Set Bereich = Sheets(\"Tabelle1\").Range(\"B2:B\" &amp; Cells(Rows.Count, 1).End(xlUp).Row)\nCopyToNewWorksheet GetRowsForCurrency(Bereich, \"EURUSD\"), \"EURUSD\"\nCopyToNewWorksheet GetRowsForCurrency(Bereich, \"GBPUSD\"), \"GBPUSD\"\nCopyToNewWorksheet GetRowsForCurrency(Bereich, \"AUDUSD\"), \"AUDUSD\"\nCopyToNewWorksheet GetRowsForCurrency(Bereich, \"NZDUSD\"), \"NZDUSD\"\n</code></pre>\n\n<p>Now this might be made cleaner if you defined and used constants instead of magic strings:</p>\n\n<pre><code>Const EURUSD As String = \"EURUSD\"\nConst GBPUSD As String = \"GBPUSD\"\n...\n</code></pre>\n\n<hr>\n\n<p><H3>Couple points</h3></p>\n\n<ul>\n<li><strong>NEVER</strong> call a procedure <code>a()</code> - <em>give it a meaningful name</em> that starts with a <em>verb</em> and that says what the code does. If you can't easily give it a name, it's probably doing too many things.</li>\n<li><strong>Indent</strong> your code properly: anything between <code>XXXXX</code> and <code>End XXXXX</code> should be 1 <kbd>Tab</kbd> further to the right. If your code starts to look like <em><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">arrow code</a></em>, you've got a code smell (follow that link!).</li>\n<li>Those <code>With</code> blocks are absolutely useless - you're never using your <em>with block variable</em>, which means you've <em>set</em> an object reference for no reason.</li>\n<li>If you feel the need to add a number at the end of a variable name, stop right there, take your hands off the keyboard and study what your code is doing that's redundant - refactor as needed.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:58:19.623", "Id": "58364", "Score": "4", "body": "That would be nice. I am just beginning (3 Weeks) with programming VBA in Excel and read as much as I could to help my self, but here is the point where my knowledge is much overstressed. I will take a look if I can find something to start with Procedure and function. Take the time you need, I am glad that there is someone out there who is willing to help me out and is spending his freetime to explain me what to do and where to look for more information\n\nRegards, Adam" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T02:12:32.440", "Id": "58514", "Score": "0", "body": "@user3016646 Edited; feel free to mark your question as *accepted*, [we're on a mission](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission) to get this beta site into a full-fledged graduated StackExchange site that will be *the* place to come for peer reviews :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T03:29:29.137", "Id": "58517", "Score": "1", "body": "@user3016646 *Take the time you need, I am glad that there is someone out there who is willing to help me out and is spending his freetime to explain me what to do and where to look for more information* - just so you know, reading this made my day and totally makes up for [much less positive feedback](http://meta.codereview.stackexchange.com/questions/1033/complaint-about-rollback-policy-bug-fixes) this site got today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:53:59.173", "Id": "58564", "Score": "0", "body": "That was a quick response, thank you very much. Now I have to study the Basics over private functions and private sub. Because I want to understand it, so that I know what I am doing. At least I hope so -:)\n\nAlso must I look what to do with your answer, wich button to puch and what else, but I will find that somewhere on this site. I will give you a feedback when I got it to work.\n\nRegards, Adam" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T12:04:44.330", "Id": "58567", "Score": "0", "body": "No problem. Just noticed I have renamed the function `GetCellsForCurrency` to `GetRowsForCurrency` and forgot to rename it in the bottom snippet, I'll edit again to make it clearer. A `Public` procedure is \"visible\" from the *outside*, a `Private` one can only be used from within the module where it's declared. Post on StackOverflow if you're stumped and can't find an answer (after a thorough search that is - odds are you'll find an answer on SO anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T12:09:37.723", "Id": "58568", "Score": "1", "body": "Functions *return a value* and procedures (/\"subs*) just run. If you declare them in a *code module*, you can call a function from a cell function (which is utterly cool), and a procedure can be called as a \"macro\" /assigned to a button that the user can click to execute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T12:10:24.150", "Id": "58569", "Score": "0", "body": "Ok. I forgot to answer to this. \"why (5,1) here\"? I want to do some calculation there, so that I don't always need to scroll down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T14:18:29.947", "Id": "58585", "Score": "0", "body": "Wasn't really a question. Rather, a remark about putting relevant comments in your code, that explain *why* the code is doing something (rather than *what* the code is doing) - the in-code comment is for your future self to know *why* it was coded this way. :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:32:42.237", "Id": "35847", "ParentId": "35844", "Score": "18" } }, { "body": "<p>A couple of things that @Mat's Mug didn't mention.</p>\n\n<ol>\n<li><p>Use <code>Option Explicit</code></p>\n\n<p>You set <code>Betreich</code> equal to a range, but the variable isn't declared anywhere. You'll nip a lot of runtime errors in the bud if you let the compiler catch the lack of variable declaration.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select\">Avoid Select and Activate</a></p>\n\n<p>Again, we're looking to avoid runtime errors, but there is a style issue here as well. You use worksheet and range objects elsewhere in your code. Why not here? Be consistent.</p>\n\n<pre><code>rng.EntireRow.Select\nWith Selection\nActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)\nSheets(ActiveSheet.Name).Name = \"EURUSD\"\nrng.EntireRow.Copy Worksheets(\"EURUSD\").Cells(5, 1)\nEnd With\n</code></pre>\n\n<p>Which brings me to..</p></li>\n<li><p>Properly indent your code. </p>\n\n<p>Ok, so it was already mentioned, but it's a biggie for readability.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T16:59:31.513", "Id": "51922", "ParentId": "35844", "Score": "7" } } ]
{ "AcceptedAnswerId": "35847", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:15:38.243", "Id": "35844", "Score": "14", "Tags": [ "vba", "excel" ], "Title": "Avoiding repeated code in worksheet" }
35844
<p>I'm fetching some values from the memory. I would like to create some custom events that I can listen to for each value. Since there are no existing events regarding memory changes, I've decided to go with a polling solution. I'm restarting the timer below manually just to make certain the work is finished.</p> <p>Would this be an okay solution (considering the circumstances) to my problem? Do you see any issues with creating multiple timers? As far as I know, each instance will run on its own thread.</p> <p>This was the best I could come up with right off the bat. I would like to hear your input regarding possible improvements:</p> <pre><code>var vc = new ValueChange(1000, Blah.GetMemoryValue()); vc.PropertyChanged += OnPropertyChanged; void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { Console.WriteLine("prop change"); } public class ValueChange : INotifyPropertyChanged { private int _val; private readonly System.Timers.Timer _timer; private int Value { set { _val = value; RaisePropertyChanged("Val"); } get { return _val; } } public ValueChange(double polingInterval, int val) { _val = val; _timer = new System.Timers.Timer { AutoReset = false, Interval = polingInterval }; _timer.Elapsed += TimerElapsed; _timer.Start(); } private void TimerElapsed(object sender, ElapsedEventArgs e) { var newValue = Blah.GetMemoryValue(); if (Value != newValue) { Value = newValue; } _timer.Start(); } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string caller) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(caller)); } } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Having a private property is quite unusual. It's especially weird since you only use it once in <code>TimerElapsed</code>. I would probably just use the field directly and call <code>RaisePropertyChanged()</code> manually when necessary.</p></li>\n<li><p>Why is the initial value passed in the constructor? I think the class should retrieve the initial value by itself.</p></li>\n<li><p><code>PropertyChanged</code> should be raised for a property that's readable from the outside and the name in the event args should be the same as the name of that property.</p></li>\n<li><p>Your code is a prime candidate for making it more generic: you could change <code>ValueChange</code> to <code>ValueChange&lt;T&gt;</code> and <code>int _val</code> to <code>T _val</code>. (But if you do this, be careful with equality, <code>!object.Equals(_val, newValue)</code> is probably the simplest way to do it correctly.)</p>\n\n<p>Also, <code>Blah.GetMemoryValue</code> should be configurable by the caller. You could achieve this by accepting a <code>Func&lt;T&gt;</code> delegate in the constructor. Something like:</p>\n\n<pre><code>private readonly Func&lt;T&gt; _getValue;\n\npublic ValueChange(double polingInterval, Func&lt;T&gt; getValue)\n{\n _getValue = getValue;\n\n …\n}\n\nprivate void TimerElapsed(object sender, ElapsedEventArgs e)\n{\n var newValue = _getValue();\n\n …\n}\n</code></pre></li>\n<li><p>I like to avoid <code>null</code> checks on events by making sure there always is at least one subscriber:</p>\n\n<pre><code>public event PropertyChangedEventHandler PropertyChanged = delegate { };\n</code></pre>\n\n<p>But this is not really a common technique.</p></li>\n<li><p>Creating multiple timers is okay, they execute on thread pool threads. This means that if several timers tick at the same time, they will be (most likely) executed concurrently by different threads.</p></li>\n<li><p>In general, polling like this is not ideal. It would be better if you could get a notification whenever the value actually changes. But it seems like this is not possible in your case.</p></li>\n<li><p>You shouldn't shorten the names of your variables. So, <code>_value</code> is better than just <code>_val</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:32:24.860", "Id": "58444", "Score": "0", "body": "Thanks a lot for the feedback - much appreciated! I do have a couple of questions though. Could you show me how to pass a `Func<T>` to the constructor, and make use of it in the timer event? I can't get it to work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:35:50.650", "Id": "58446", "Score": "0", "body": "@Johan See edit (it assumes you already successfully changed the class to `T` instead of `int`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:41:43.427", "Id": "58449", "Score": "0", "body": "Could you show me an example when instantiating `ValueChange`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:05:24.763", "Id": "58455", "Score": "1", "body": "@Johan `new ValueChange<int>(1000, Blah.GetMemoryValue)` (note the missing `()`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:07:55.933", "Id": "58456", "Score": "0", "body": "Thank you, I did `() => Blah.GetMemoryValue()` before you answered. I guess the end result would be the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:32:22.327", "Id": "58462", "Score": "1", "body": "You might also want to have a clean way of stopping the timer and tearing it down (i.e. stop watching)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:34:26.960", "Id": "58463", "Score": "0", "body": "I kinda like the idea of the non-null event handler. Means some minor overhead if no-one is subscribed but I doubt it will even be measurable." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:27:53.950", "Id": "35869", "ParentId": "35845", "Score": "3" } } ]
{ "AcceptedAnswerId": "35869", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:23:57.287", "Id": "35845", "Score": "5", "Tags": [ "c#", "multithreading", "timer" ], "Title": "Listening for values changed by the memory" }
35845
<p>Here's some code of mine that I don't like (this was my very first attempt at DI/IoC!). It's a small C# application that runs scheduled on one of our servers and is responsible for fetching the latest version of a VB6 codebase, compiling it and packaging an installer for it.</p> <p>There's an <code>Execute</code> method in there that smells like... well <em>you tell me</em> what it smells like:</p> <pre><code> /// &lt;summary&gt; /// Executes the build process. /// &lt;/summary&gt; public override void Execute() { var errors = new List&lt;string&gt;(); var logger = _logProvider.GetLogger(GetType().Name); DoArchiveOldInstallers(errors, logger); if (Properties.Settings.Default.StopOnBackupCurrentInstallerFailure &amp;&amp; !DoBackupCurrentVersion(errors, logger)) { OnExecutedCompleted(false); return; } if (Properties.Settings.Default.StopOnUpdateCodeBaseFailure &amp;&amp; !DoGetLatestVersion(errors, logger)) { OnExecutedCompleted(false); return; } if (Properties.Settings.Default.StopOnCompileFailure &amp;&amp; !DoCompileCodeBase(errors, logger)) { OnExecutedCompleted(false); return; } if (Properties.Settings.Default.StopOnBuildInstallerFailure &amp;&amp; !DoBuildInstaller(errors, logger)) { OnExecutedCompleted(false); return; } OnExecutedCompleted(true); } private void OnExecutedCompleted(bool success) { if (Completed != null) Completed(this, new CompletedEventArgs(success)); } </code></pre> <hr> <h3>Mea Culpa</h3> <p>Sorry this was posted like this. The conditions should read as follows:</p> <pre><code>if (!DoXXXXX(errors, logger) &amp;&amp; !settings.StopOnXXXXXFailure) </code></pre> <p>This was a last-minute untested change I made just minutes prior to posting, without realizing it would totally mess up the method's logic.</p>
[]
[ { "body": "<p>I would create a helper method for returning the value you want to give to <code>OnExecutedCompleted</code>, and also store the value of <code>Properties.Settings.Default</code> in a variable.</p>\n\n<pre><code>bool TodoRenameMeToWhatYouThinkSuitsYou()\n{\n SomeType settings = Properties.Settings.Default;\n if (settings.StopOnBackupCurrentInstallerFailure &amp;&amp; !DoBackupCurrentVersion(errors, logger))\n return false;\n if (settings.StopOnUpdateCodeBaseFailure &amp;&amp; !DoGetLatestVersion(errors, logger)) \n return false;\n if (settings.StopOnCompileFailure &amp;&amp; !DoCompileCodeBase(errors, logger))\n return false;\n if (settings.StopOnBuildInstallerFailure &amp;&amp; !DoBuildInstaller(errors, logger)) \n return false;\n return true;\n}\n</code></pre>\n\n<p>Then you can replace the smelly part in your original method with</p>\n\n<pre><code>OnExecutedCompleted(TodoRenameMeToWhatYouThinkSuitsYou());\n</code></pre>\n\n<p><em>(I apoligize for not following the coding conventions in this answer, I am not a C# developer)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:33:00.463", "Id": "58391", "Score": "1", "body": "I don't think `executeIsCompleted` is a good name for that method, because it doesn't just test whether execution is complete, it also performs the execution itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:34:29.507", "Id": "58393", "Score": "1", "body": "Smells like Java code :) (sees edit and LOL!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:35:40.340", "Id": "58394", "Score": "0", "body": "@svick I agree, as I currently can't come up with a better name, I renamed it to `todoRenameMeToWhatYouThinkSuitsYou` (I didn't put much thought into the naming of the method as that wasn't the most important part of the question)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:38:36.723", "Id": "58400", "Score": "1", "body": "@retailcoder Java code doesn't smell (at least not my code :P). I hope this solves the multiple return statements for you though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:39:23.393", "Id": "58401", "Score": "0", "body": "@SimonAndréForsberg yes it does: you can tell because you haven't named it `TodoRenameMeToWhatYouThinkSuitsYou()` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:41:39.473", "Id": "58404", "Score": "0", "body": "@retailcoder That better? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:58:17.610", "Id": "58411", "Score": "3", "body": "Also, `obj` is a very bad name for a variable. I would use something like `settings`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:31:24.677", "Id": "35860", "ParentId": "35849", "Score": "3" } }, { "body": "<p>First thing I noticed, I do not like the <code>Do</code> in the function names. For instance, in <code>DoArchiveOldInstallers</code> there are two verbs. The idea is to mimic english, I never say \"Do go for a run\" when I'm talking to people. The code should be the same. <code>ArchiveOldInstallers</code> works perfectly well, and the verb describing what is going on is still there.</p>\n\n<p>Second, the if statements get a little confusing. I'm not sure what to do with them right now, but they need to be changed.</p>\n\n<p>Other than that, the white space, capitalization, and formatting look good.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:35:57.870", "Id": "35861", "ParentId": "35849", "Score": "6" } }, { "body": "<p>First of all, I would question whether this code works correctly. Based on the names in your code, I assume that for example <code>DoCompileCodeBase()</code> should execute even when <code>StopOnCompileFailure</code> is <code>false</code>, but its result should be ignored. But that's not what happens: when <code>StopOnCompileFailure</code> is <code>false</code>, <code>DoCompileCodeBase()</code> doesn't even execute, because of short-circuiting evaluation of <code>&amp;&amp;</code>.</p>\n\n<p>If what the code does is really what it should do (which is what I'm going to assume in the following text), then you should probably rename the settings properties.</p>\n\n<p>Second, you can extract the checks and the <code>Do</code> method calls into a separate method (Simon's answer already suggested something similar):</p>\n\n<pre><code>// may need a better name\nprivate bool ExecuteInternal()\n{\n var errors = new List&lt;string&gt;();\n var logger = _logProvider.GetLogger(GetType().Name);\n var settings = Properties.Settings.Default;\n\n DoArchiveOldInstallers(errors, logger);\n\n if (settings.StopOnBackupCurrentInstallerFailure &amp;&amp; !DoBackupCurrentVersion(errors, logger))\n return false;\n\n if (settings.StopOnUpdateCodeBaseFailure &amp;&amp; !DoGetLatestVersion(errors, logger))\n return false;\n\n if (settings.StopOnCompileFailure &amp;&amp; !DoCompileCodeBase(errors, logger))\n return false;\n\n if (settings.StopOnBuildInstallerFailure &amp;&amp; !DoBuildInstaller(errors, logger))\n return false;\n\n return true;\n}\n\npublic override void Execute()\n{\n bool success = ExecuteInternal();\n OnExecutedCompleted(success);\n}\n</code></pre>\n\n<p>Third, since all the <code>Do</code> methods are on the same object, you could change <code>errors</code> and <code>logger</code> into fields, so that you don't have to pass them around. Though I'm not completely convinced this is actually better, especially if <code>Execute()</code> is a method that's called over and over.</p>\n\n<p>Fourth, you might consider associating all the settings properties with the right <code>Do</code> method using some kind of data structure:</p>\n\n<pre><code>private readonly Tuple&lt;bool, Func&lt;bool&gt;&gt;[] action;\n\n// in constructor:\nactions = new Tuple&lt;bool, Func&lt;bool&gt;&gt;[]\n{\n new Tuple&lt;bool, Func&lt;bool&gt;&gt;(settings.StopOnBackupCurrentInstallerFailure, DoBackupCurrentVersion),\n new Tuple&lt;bool, Func&lt;bool&gt;&gt;(settings.StopOnUpdateCodeBaseFailure, DoGetLatestVersion),\n new Tuple&lt;bool, Func&lt;bool&gt;&gt;(settings.StopOnCompileFailure, DoCompileCodeBase),\n new Tuple&lt;bool, Func&lt;bool&gt;&gt;(settings.StopOnBuildInstallerFailure, DoBuildInstaller)\n}\n\nprivate bool ExecuteInternal()\n{\n var errors = new List&lt;string&gt;();\n var logger = _logProvider.GetLogger(GetType().Name);\n var settings = Properties.Settings.Default;\n\n DoArchiveOldInstallers();\n\n foreach (var action in actions)\n {\n if (action.Item1 &amp;&amp; !action.Item2())\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>The syntax to initialize the list of <code>Tuple</code>s is not great. You could improve that by having a special type <code>TupleList&lt;T1, T2&gt; : List&lt;Tuple&lt;T1, T2&gt;&gt;</code>, which would have a method like <code>void Add(T1 item1, T2 item2)</code>. That way, the initialization simplifies to:</p>\n\n<pre><code>actions = new TupleList&lt;bool, Func&lt;bool&gt;&gt;\n{\n { settings.StopOnBackupCurrentInstallerFailure, DoBackupCurrentVersion },\n { settings.StopOnUpdateCodeBaseFailure, DoGetLatestVersion },\n { settings.StopOnCompileFailure, DoCompileCodeBase },\n { settings.StopOnBuildInstallerFailure, DoBuildInstaller }\n}\n</code></pre>\n\n<p>The next step after this could be encapsulating each action into its own object, so that you could do something like:</p>\n\n<pre><code>foreach (var action in actions)\n{\n if (!action.Execute())\n return false;\n}\n</code></pre>\n\n<p>And each action would be responsible for checking the right setting, if appropriate. (Actions that don't do any checks, like <code>DoArchiveOldInstallers</code> could be represented by a different type that inherits from the same base, or something like that.) But I'm not sure doing that would be worth it in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:02:57.303", "Id": "58412", "Score": "0", "body": "BTW, I also considered using calling `OnExecutedCompleted()` once in a `finally`, but I think that would be an abuse of the feature." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:03:03.383", "Id": "58413", "Score": "0", "body": "Upvote in 6 hours... I apologize for the stupid bug, that was a last-minute change that I did just minutes prior to posting, hadn't even tested it and I feel as stupid as the bug itself..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:06:44.313", "Id": "58415", "Score": "0", "body": "Your answers covered it all I believe, well done!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:40:10.367", "Id": "58424", "Score": "1", "body": "I think I'd rather have a `Dictionary<bool, Func<bool>>` than a `Tuple<bool, Func<bool>>[]`. Wow you guys don't see it, but the rest of this code is so ugly, it's unreal! Can't believe I wrote that crap less than 6 months ago!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:47:07.257", "Id": "58428", "Score": "1", "body": "@retailcoder Nope, `Dictionary` wouldn't work here, because it could have only one `Func` for `true` and one for `false`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:11:59.087", "Id": "58437", "Score": "0", "body": "Ok now I got it right: `return executionSteps.All(executionStep => executionStep.Item2() || !executionStep.Item1);` (off a `var executionSteps = new List<Tuple<bool, Func<bool>>>{...}`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:28:56.993", "Id": "58443", "Score": "2", "body": "@retailcoder Yeah, I considered something like that. But I think that in this case, the `foreach` is clearer. LINQ works best for *queries*, i.e. when there are no side effects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:56:45.243", "Id": "58465", "Score": "1", "body": "As for *what type of smell?* The code smells of **REPETITION** and **RIGIDITY**. Both covered nicely by the rewrites suggested." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:54:11.327", "Id": "35863", "ParentId": "35849", "Score": "12" } } ]
{ "AcceptedAnswerId": "35863", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T15:53:27.107", "Id": "35849", "Score": "10", "Tags": [ "c#" ], "Title": "Multiple return statements smells like what?" }
35849
<p>Timers can be used in a variety of ways.</p> <p>Software timers as described on <a href="http://en.wikipedia.org/wiki/Timer#Software_timers" rel="nofollow">Wikipedia</a>:</p> <blockquote> <p>As the number of hardware timers in a computer system or processor is finite and limited, operating systems and embedded systems often use a single hardware timer to implement an extensible set of software timers. In this scenario, the hardware timer's interrupt service routine would handle house-keeping and management of as many software timers as are required, and the hardware timer would be set to expire when the next software timer is due to expire. At expiry, the interrupt routine would update the hardware timer to expire when the next software timer is due, and any actions would be triggered for the software timers that had just expired. Expired timers that are continuous would also be reset to a new expiry time based on their timer interval, and one-shot timers would be disabled or removed from the set of timers.</p> <p>Compared to hardware timers, software timers typically offer considerably lower levels of time precision. Nevertheless, while simple in concept, care must be taken with software timer implementation if issues such as timer drift and delayed interrupts is to be minimized. In modern operating systems, software timer precision can be traded off further for CPU power savings, using a technique called timer coalescing.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T16:22:59.840", "Id": "35850", "Score": "0", "Tags": null, "Title": null }
35850
This tag is for questions about using timers in code to make things happen in a certain order or for gathering amount of time elapsed.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T16:22:59.840", "Id": "35851", "Score": "0", "Tags": null, "Title": null }
35851
<p>This is a stored procedure that takes 5-30+ minutes to run depending on the parameter they select.</p> <p>It also has a nasty side effect of clogging down our SQL Server.</p> <pre><code>SET NOCOUNT ON; DECLARE @clients TABLE (customer varchar(200)) IF (NULLIF(@startdate, '') IS NULL) set @startdate = getdate()-7 IF (NULLIF(@enddate, '') IS NULL) set @enddate = getdate() IF (ISNULL(@clientName,'') = 'ALL') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) ELSE IF(ISNULL(@clientName,'') = 'Capital One') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000380','0000611','0000541','0000715') ELSE IF(ISNULL(@clientName,'') = 'PRA') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000411') ELSE IF(ISNULL(@clientName,'') = 'Midland') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000584') ELSE IF(ISNULL(@clientName,'') = 'Trak') INSERT INTO @clients SELECT customerid FROM fact (NOLOCK) WHERE customgroupid=25 ELSE IF(ISNULL(@clientName,'') = 'Hanna') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000644','0000647','0000648','0000665','0000697','0000726','0000773','0000803','0000804','0000814') ELSE INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer = @clientName -- Insert statements for procedure here select distinct m.number as FileNumber ,isnull(dbi.bankname, '') as Bank ,c.name as ClientName ,CONVERT(VARCHAR(10),m.received,101) as ReceivedByFirm ,'' as ChargeOffDate ,datediff(d, m.received, getdate()) as AgeOfDebt ,0 as DebtAmount ,case when d.lastname = '' then d.name else d.lastname end as DebtorLastName -- show d.name if debtor last name is blank ,CONVERT(VARCHAR(10),m.dob,101) as DateOfBirth ,dbo.stripnondigits(d.zipcode) as DebtorZipcode ,d.state as DebtorState ,d.homephone ,d.workphone ,'' as MobilePhone -- no mobile phone ,case when d.ssn != '' then 1 else 0 end as HasSSN ,case when pe.verified is not null then 1 else 0 end as Employed ,(select dbo.mmSddSyyyy(max(lr.DateProcessed)) from LetterRequest lr WHERE lr.DateProcessed&gt;'' AND lr.DateRequested&lt;GETDATE() AND Deleted=0 AND LetterCode in ('40029','50046','09997','09998','09999','10001','10002','10003','10004','10005','10006','10010','10011','10014','10015','50050','50041','50042','50001','50030','50040','50045','50060','50090','11001') AND lr.AccountID=m.number) as FirstLetterDate --Date letter sent to debtor by law firm ,(select min(created) from notes where number=m.number AND action like 'T%') as FirstCall ,(select count(created) from notes where number=m.number and created between @startdate and @enddate and action like 'T%') as TotalCalls ,(select case when count(created) &gt; 0 then 1 else 0 end from notes where number=m.number and created between @startdate and @enddate and action = 'DT') as DebtorCalledFirm ,(select isnull(max(dbo.mmsddsyyyy(created)), '') from notes where number=m.number and created between @startdate and @enddate and action = 'DT') as DebtorCalledFirmDate ,case when m.status in ('PIF', 'SIF') then 1 when m.qlevel in (998,999) then 3 else 2 end as CollectionStatus ,m.desk as CollectorName ,isnull((select isnull(dbo.mmSddSyyyy(cc.DateFiled), '') from courtcases cc where cc.accountid = m.number and cc.DateFiled&gt;'1900-01-01 00:00:00' and isnull(cc.casenumber,'')!='' and (m.current1+m.current2+m.current3+m.current4+m.current5+m.current6+m.current7+m.current8+m.current9+m.current10)&gt;0), '') as SuitDate ,(select isnull(dbo.mmSddSyyyy(cc.ServiceDate), '') from courtcases cc where cc.accountid = m.number) as ServiceDate ,(select isnull(dbo.mmSddSyyyy(cc.JudgementDate), '') from courtcases cc where cc.accountid = m.number) as JudgmentDate ,isnull((select max(dbo.mmSddSyyyy(s.DateChanged)) from statushistory s inner join courtcases cc on s.accountid=cc.accountid inner join debtors d on d.number = cc.accountid where s.accountid=m.number and isnull(cc.JudgementDate,'')!='' and s.DateChanged &gt;'1900-01-01 00:00:00' and s.newstatus in ('LNG','LXG','WGS','WGW','GIL','GNG') and isnull(cc.ServiceDate,'')!='' and isnull(d.jobname,'')!='' and s.id not in (select historyid from statuserror where accountnumber = m.number)), '') as GarnishmentDate ,getdate() as Today ,(select case when count(number) &gt; 0 then 1 else 0 end from payhistory ph where ph.number = m.number and batchtype in ('PU', 'PC')) as PaymentMade ,isnull(datediff(d, m.received, getdate()) - (select datediff(d, min(ph.datepaid), getdate()) from payhistory ph where ph.number = m.number and batchtype in ('PU', 'PC')), '') as DaysElapsed ,case when m.status = 'PIF' then 'PIF' when m.status = 'SIF' then 'SIF' when m.status = 'PPA' then 'PPA' else '' end as PaymentMethod ,m.paid+m.paid1+m.paid2+m.paid3+m.paid4+m.paid5+m.paid6+m.paid7+m.paid8+m.paid9+m.paid10 as TotalPaid ,m.score as CollectionScore ,m.original as OriginalClaim ,isnull(datediff(d, m.received, m.chargeoffdate), '') as ChargeOff ,case when (isnull((select isnull(dbo.mmSddSyyyy(cc.DateFiled), '') from courtcases cc where cc.accountid = m.number and cc.DateFiled&gt;'1900-01-01 00:00:00' and isnull(cc.casenumber,'')!='' and (m.current1+m.current2+m.current3+m.current4+m.current5+m.current6+m.current7+m.current8+m.current9+m.current10)&gt;0), '')) = '' then 1 else 0 end as SuitFiled ,case when (select isnull(dbo.mmSddSyyyy(cc.JudgementDate), '') from courtcases cc where cc.accountid = m.number) = '' then 1 else 0 end as JudgmentObtained ,'' as JudgmentInOurFavor ,case when (isnull((select max(dbo.mmSddSyyyy(s.DateChanged)) from statushistory s inner join courtcases cc on s.accountid=cc.accountid inner join debtors d on d.number = cc.accountid where s.accountid=m.number and isnull(cc.JudgementDate,'')!='' and s.DateChanged &gt;'1900-01-01 00:00:00' and s.newstatus in ('LNG','LXG','WGS','WGW','GIL','GNG') and isnull(cc.ServiceDate,'')!='' and isnull(d.jobname,'')!='' and s.id not in (select historyid from statuserror where accountnumber = m.number)), '')) = '' then 1 else 0 end as Garnishment from master m inner join customer c on c.customer = m.customer inner join debtors d on d.number = m.number inner join jm_people p on p.accountid = m.number left outer join jm_peopleemployment pe on pe.pid = p.pid left outer join debtorbankinfo dbi on dbi.acctid = m.number where m.customer IN (SELECT customer from @clients) order by m.number </code></pre>
[]
[ { "body": "<p>performance review of SQL code without knowing the cardinality of the data, and the indexes used, is a real challenge, but, I would recommend that you try two things:</p>\n\n<p>first, try make <code>@customer</code> table a top-level item in the Join:</p>\n\n<pre><code>from @customer csub\ninner join master m on csub.customer = m.customer\ninner join customer c on csub.customer = c.customer\n.....\n</code></pre>\n\n<p>The other item that concerns me is that you use the DISTINCT keyword. This automatically implies a temp-table and a sort. This could be a 'killer' for this query because it has to compute and save all the select-value calculations. From what I can tell, there is no reason why you should get duplicate data anyway.</p>\n\n<p>The 'order-by' may be possible to solve without a temp table (perhaps the query-plan can be tweaked to query off the master table in <code>number</code> order using an index (is the data clustered by <code>number</code>?), but I would consider removing it (the order-by) as well, unless you really need the data sorted by that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:51:29.300", "Id": "58409", "Score": "0", "body": "There are no indexes to my knowledge. I will try the @customer and removing distinct and see how much of an improvement that gives me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:11:26.030", "Id": "58417", "Score": "0", "body": "No indexes? Check the execution plan!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:15:43.410", "Id": "58418", "Score": "0", "body": "@PeterKiss I will try that, I should stipulate I am not the best at sql. I can do just about anything with a general knowledge, not having the advanced stuff is probably why this is running slow. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:33:48.477", "Id": "58420", "Score": "1", "body": "Adding that top level join really sped it up. A query that took 5 minutes before is now taking 40 seconds. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:39:12.203", "Id": "58423", "Score": "1", "body": "@JamesWilson - good indexes will make it even better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:56:54.130", "Id": "58433", "Score": "0", "body": "I don't even know how or when to set up an index. The execution plan said index missing and did something with a clustered index. I don't think any of the three developers here know about setting up indexes. We use a third party tool with an ancient database and I think there all too weary about changing anything with their tables as their support is horrible." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:45:41.630", "Id": "35862", "ParentId": "35858", "Score": "4" } }, { "body": "<p>Instead of if statements you could try using a Case statement instead</p>\n\n<p>so this: </p>\n\n<blockquote>\n<pre><code> IF (ISNULL(@clientName,'') = 'ALL')\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK)\n ELSE IF(ISNULL(@clientName,'') = 'Capital One')\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000380','0000611','0000541','0000715')\n ELSE IF(ISNULL(@clientName,'') = 'PRA')\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000411')\n ELSE IF(ISNULL(@clientName,'') = 'Midland')\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000584')\n ELSE IF(ISNULL(@clientName,'') = 'Trak')\n INSERT INTO @clients SELECT customerid FROM fact (NOLOCK) WHERE customgroupid=25\n ELSE IF(ISNULL(@clientName,'') = 'Hanna')\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000644','0000647','0000648','0000665','0000697','0000726','0000773','0000803','0000804','0000814')\n ELSE\n INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer = @clientName\n</code></pre>\n</blockquote>\n\n<p>should look like this:</p>\n\n<pre><code>INSERT INTO @clients \nCASE (ISNULL(@clientName, ''))\n WHEN 'All'\n THEN SELECT customer FROM customer (NOLOCK)\n WHEN 'Capital One' \n THEN SELECT customer FROM customer (NOLOCK) WHERE customer IN ('0000380','0000611','0000541','0000715')\n WHEN 'PRA'\n THEN SELECT customer FROM customer (NOLOCK) WHERE customer = '0000411'\n WHEN 'Midland'\n THEN SELECT customer FROM customer (NOLOCK) WHERE customer = '0000584'\n WHEN 'Trak'\n THEN SELECT customerid FROM fact (NOLOCK) WHERE customgroupid = 25\n WHEN 'Hanna'\n THEN SELECT customer FROM customer (NOLOCK) WHERE customer IN ('0000644','0000647','0000648','0000665','0000697','0000726','0000773','0000803','0000804','0000814')\n ELSE SELECT customer FROM customer (NOLOCK) WHERE customer = @clientName\n</code></pre>\n\n<p>This makes it a little cleaner, I don't know how it will affect the performance of the Query, you would have to run an <code>EXPLAIN</code> on it.</p>\n\n<p>You should always be thinking DRY or <strong>Don't Repeat Yourself</strong> </p>\n\n<p>This pretty much takes that <code>ISNULL(@clientName,'')</code> and turns it into a variable almost, so now it is either <code>''</code> or it is a value that was given.\nsince it will not match anything if it is <code>''</code>, we should put in a <code>WHEN</code> statement at the beginning to match <code>''</code> and dump out so it doesn't waste resources</p>\n\n<p>Something like:</p>\n\n<pre><code>WHEN ''\n THEN SELECT customer FROM customer (NOLOCK) WHERE customer = @clientName\n</code></pre>\n\n<p>I am not sure exactly what you want to do if no <code>clientName</code> was given but it seems to me that it would fall into the <code>ELSE</code> statement so I figured that is what you wanted to do with it. Again, this should be the first <code>CASE</code> in our Case Statement.</p>\n\n<hr>\n\n<p>If you don't have to use a special function, don't. When there is only one thing in the list you want to match, just use an <code>=</code> sign instead of using the <code>IN</code> operator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T05:09:53.003", "Id": "64301", "Score": "2", "body": "Well, I wouldn't expect a `CASE` statement to really be any faster/slower, not for something like this. And it's only marginally cleaner. An `IN()` clause with only one element is functionally identical to `=` (and maybe optimized that way). Really, the best solution to deal with this part of the query is likely a translation table (although dealing with `'Trak'` would be tricky) - this won't necessarily help with speed, but should help readability immensely. However, the author's real problem is no indices. And possibly some iffy design choices..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T19:13:46.333", "Id": "38533", "ParentId": "35858", "Score": "2" } } ]
{ "AcceptedAnswerId": "35862", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T17:21:51.867", "Id": "35858", "Score": "1", "Tags": [ "sql", "sql-server", "time-limit-exceeded" ], "Title": "Stored procedure to run a credit-card debt query" }
35858
<blockquote> <p>“There are only two hard things in Computer Science: cache invalidation and naming things.” -- Phil Karlton</p> </blockquote> <p>That being said, I created this SimpleCache class which I intend to use to cache database queries and results over a relatively short period of time. </p> <p>I'm just asking if there are any immediate faults or errors with this?</p> <p>(The class is <code>internal</code> because I'm using it inline in another class)</p> <pre><code>internal sealed class SimpleCache { private static Dictionary&lt;string, CacheItem&gt; _cache = new Dictionary&lt;string, CacheItem&gt;(); public void Add(string key, object value) { _cache.Add(key, new CacheItem() { Value = value, Created = DateTime.Now.Ticks }); } public object this[string key] { get { if(_cache.ContainsKey(key)) { if ((_cache[key].Created + 30000) &gt; DateTime.Now.Ticks) //30000 was chosen by magic { return _cache[key].Value; } _cache.Remove(key); } return null; } } internal sealed class CacheItem { public object Value { get; set; } public long Created { get; set; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:14:26.217", "Id": "58429", "Score": "4", "body": "Use the built in [MemoryCache](http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache%28v=vs.110%29.aspx) class!" } ]
[ { "body": "<ol>\n<li>You have a static dictionary as backing store which means that all cache instances share it. Not saying that this is wrong and it might be intended but you should be aware of it.</li>\n<li>Your cache apparently is not thread-safe. You need to protect access to the dictionary with locks or if you are using .NET 4 or later use <a href=\"http://msdn.microsoft.com/en-us/library/dd287191%28v=vs.100%29.aspx\" rel=\"nofollow\"><code>ConcurrentDictionary</code></a>. If you make the backing dictionary non-static then you might not need to make it thread-safe if you can ensure that you never access the same cache instance from multiple threads at the same time.</li>\n<li>Items only get evicted when they are being accessed again. This means if you only ever access items once they will stay in there forever.</li>\n<li>Make the magic number <code>30000</code> at least a const member or maybe even a tunable property/field (in which case you should prefer making it a <code>TimeSpan</code> as it's easier to use than plain ticks)</li>\n<li>Your <code>Add</code> method will throw an exception if the entry in the cache already exists. You either need to check if it exists and just update the entry (or do nothing, whatever makes sense) or replace the entry by using <code>_cache[key] = ..</code> rather than <code>_cache.Add()</code>. </li>\n<li>Depending on your use case you might want to rename <code>Created</code> into <code>LastAccessed</code> and update it whenever someone accesses the entry (read/write) with the same key (which means items will be evicted a certain period after they have been last accessed rather than created).</li>\n<li>Last but not least you might want to look into the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache%28v=vs.100%29.aspx\" rel=\"nofollow\"><code>MemoryCache</code></a> class if you are using .NET 4 or later.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:01:07.647", "Id": "58434", "Score": "2", "body": "Not all classes have to be thread-safe. Though `static` things should." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T09:37:22.053", "Id": "58546", "Score": "0", "body": "Good points all of them. I actually implemented bullet point #1 (changed it to non-static), #2, #4 (except I kept it as a long) and #6. Making it a ConcurrentDictionary also takes care of #5 as in .TryAdd() will return false if the key already exists." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:45:03.613", "Id": "35871", "ParentId": "35864", "Score": "8" } } ]
{ "AcceptedAnswerId": "35871", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:10:18.663", "Id": "35864", "Score": "7", "Tags": [ "c#", "database", "cache" ], "Title": "A Simple Cache class" }
35864
<p>For code that aims to solve problems in all branches of mathematics. Related tags include:</p> <ul> <li><a href="/questions/tagged/algorithm" class="post-tag" title="show questions tagged &#39;algorithm&#39;" rel="tag">algorithm</a></li> <li><a href="/questions/tagged/primes" class="post-tag" title="show questions tagged &#39;primes&#39;" rel="tag">primes</a></li> <li><a href="/questions/tagged/matrix" class="post-tag" title="show questions tagged &#39;matrix&#39;" rel="tag">matrix</a></li> <li><a href="/questions/tagged/integer" class="post-tag" title="show questions tagged &#39;integer&#39;" rel="tag">integer</a></li> <li><a href="/questions/tagged/floating-point" class="post-tag" title="show questions tagged &#39;floating-point&#39;" rel="tag">floating-point</a></li> <li><a href="/questions/tagged/computational-geometry" class="post-tag" title="show questions tagged &#39;computational-geometry&#39;" rel="tag">computational-geometry</a></li> <li><a href="/questions/tagged/combinatorics" class="post-tag" title="show questions tagged &#39;combinatorics&#39;" rel="tag">combinatorics</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:23:13.783", "Id": "35867", "Score": "0", "Tags": null, "Title": null }
35867
For code that aims to solve problems in all branches of mathematics. (Please do NOT use this tag for incidental trivial use of arithmetic. A simple test to apply is: would an amateur or professional mathematician take an interest in the question?)
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:23:13.783", "Id": "35868", "Score": "0", "Tags": null, "Title": null }
35868
<p>In most computer languages, the implementation of floating-point arithmetic is based on the <a href="http://en.wikipedia.org/wiki/IEEE_floating_point" rel="nofollow">IEEE 754 standard</a>. The standard specifies four formats, with the 32-bit ("single precision") and 64-bit ("double precision") formats being most commonly used. Since floating-point numbers are stored in a base-2 representations, many numbers cannot be represented exactly. Therefore, code that performs floating-point arithmetic should take care to minimize concerns such as:</p> <ul> <li>accuracy and precision of calculations</li> <li>handling of 0, infinity, and over/underflow</li> <li>input/output and binary representation</li> </ul> <p>Some languages, such as Java, only <a href="http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf" rel="nofollow">partially adhere</a> to the IEEE 754 standard — a potential source of bugs.</p> <p>Related tags include:</p> <ul> <li><a href="/questions/tagged/integer" class="post-tag" title="show questions tagged &#39;integer&#39;" rel="tag">integer</a></li> <li><a href="/questions/tagged/mathematics" class="post-tag" title="show questions tagged &#39;mathematics&#39;" rel="tag">mathematics</a></li> <li><a href="/questions/tagged/statistics" class="post-tag" title="show questions tagged &#39;statistics&#39;" rel="tag">statistics</a></li> <li><a href="/questions/tagged/gpgpu" class="post-tag" title="show questions tagged &#39;gpgpu&#39;" rel="tag">gpgpu</a></li> <li><a href="/questions/tagged/computational-geometry" class="post-tag" title="show questions tagged &#39;computational-geometry&#39;" rel="tag">computational-geometry</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:05:32.050", "Id": "35873", "Score": "0", "Tags": null, "Title": null }
35873
For questions with concerns specifically related to the usage of floating point, such as accuracy and precision of calculations, handling of 0, infinity, and over/underflow, input/output, and binary representation. Not for code that casually happens to use floating point.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:05:32.050", "Id": "35874", "Score": "0", "Tags": null, "Title": null }
35874
<p><strong>Background</strong></p> <p>Today at work, I had to bring a component that used to load CSV data into MySQL, and perform calculations as result of SQL queries. I was tasked with replicating that in a programming language.</p> <p>The general example is like:</p> <p>There's a 2D array (a table) with columns "Name", "Age", "Grade" and "Total". Produce counts like "Unique Ages", "Unique Ages &amp; Grade", "Unique Ages for which Grade = 3" etc.</p> <p><strong>My Work</strong></p> <p>So, I chose Python to do this job. There's a class that takes two parameters: 2D array and columns, and allows for performing some <strong>very basic</strong> querying capability.</p> <p><strong>Environment: Python 2.x</strong></p> <pre><code>class From: def __init__(self, array, columns): self.columns = columns self.array = array def where(self, column, data): return From(filter(lambda x: x[self.columns.index(column)] == data, self.array), self.columns) def whereNot(self, column, data): return From(filter(lambda x: x[self.columns.index(column)] != data, self.array), self.columns) def select(self, *columns): return From([[arrayItem[self.columns.index(col)] for col in columns] for arrayItem in self.array], columns) def unique(self, *columns): # This function filters those rows which have a unique combination of the columns # specified as parameter. If there are 2+ rows with same combination of values # under the column, then the last one will be chose. Example use case: Extract a # subset of rows that have a unique combination of "first name" &amp; "second name" # Invocation: From(&lt;array&gt;,&lt;cols&gt;).unique("first_name","second_name") return From({tuple(row[self.columns.index(col)] for col in columns): row for row in self.array}.values(), self.columns) def length(self): return len(self.array) def get(self): if len(self.columns) == 1: return [x[0] for x in self.array] return self.array </code></pre> <p><strong>Example Usage</strong>:</p> <pre><code>&gt;&gt;&gt; array = [ ... ["ben", "son", 23, 10, 93], ... ["gun", "dad", 21, 9, 99], ... ["sam", "mom", 19, 11, 92] ... ] &gt;&gt;&gt; cols = ["name1","name2", "age", "grade", "marks"] &gt;&gt;&gt; From(array, cols).where("name1","sam").get() [['sam', 'mom', 19, 11, 92]] </code></pre> <p>The querying that is being done in the real code is quite complex beyond the scope of this question. The <code>From</code> class works, for now.</p> <p><strong>Questions</strong></p> <ul> <li>Can this be improved, maybe made more pythonic from an overall perspective (Please excuse those ugly filter/lambda expressions. I know they are just <strong>not</strong> pythonic.)?</li> <li>The <code>From.unique(..)</code> function looks like a dirty hack. Is there any cleaner way to do it? (Please check my comment under the unique function declaration.)</li> <li>Is there any non-edge case when the above will not work? Anywhere it might just go wrong?</li> <li>Am I reinventing the wheel?</li> </ul>
[]
[ { "body": "<p>Consider loading the 2D list into an in-memory SQLite database (aka. <code>sqlite3</code> package) created on-the-fly. Given that there is an existing codebase of well-defined SQL queries, you can reuse the query expressions in your python code with the in-memory SQLite database. And for sufficiently large datasets, the efficiency of SQLite queries should out-perform brute-force search via <code>filter()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T05:58:44.313", "Id": "58527", "Score": "0", "body": "Thanks a lot for your response! I agree, this is the correct way to head. But I am actually a bit curious about my specific question/code here. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T23:04:54.823", "Id": "35888", "ParentId": "35875", "Score": "5" } }, { "body": "<p>I totally agree with <a href=\"https://codereview.stackexchange.com/a/35888/11728\">liuyu</a> that a proper in-memory database like <a href=\"http://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow noreferrer\"><code>sqlite3</code></a> will be much more efficient and useful than what you have here.</p>\n\n<p>But just reviewing your code as it is:</p>\n\n<ol>\n<li><p>There's no documentation. How are we supposed to use this class?</p></li>\n<li><p>There are no test cases. You could use the <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code> module</a> to make your example code into a runnable test case.</p></li>\n<li><p>You don't follow the Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>). In particular, if you kept to the <a href=\"http://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">maximum line length</a> of 79 columns, then we could read your code here without having to scroll the window.</p></li>\n<li><p><code>From</code> is a poor name: it doesn't clearly communicate the meaning of the class. An instance of the <code>From</code> class represents an table of records, so I would give the class a name like <code>Table</code>.</p></li>\n<li><p>Unless you have a particular reason to make an old-style class, you should write:</p>\n\n<pre><code>class From(object):\n</code></pre>\n\n<p>so that you get a new-style class which is portable to Python 3. See \"<a href=\"http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes\" rel=\"nofollow noreferrer\">new-style and classic classes</a>\" in the docs.</p></li>\n<li><p>Instead of providing methods <code>length</code> to get the length of the table, and <code>get</code> to get the table itself, why not make your class into a <em>sequence</em>? That is, instead of <code>length</code> you'd provide <code>__len__</code> and instead of <code>get</code> you'd provide <code>__iter__</code> and <code>__getitem__</code>. Then callers could just iterate over your <code>From</code> items in the usual way:</p>\n\n<pre><code>for record in From(...):\n</code></pre></li>\n<li><p>If you derived your class from the abstract base case <a href=\"http://docs.python.org/2/library/collections.html#collections.Sequence\" rel=\"nofollow noreferrer\"><code>collections.Sequence</code></a>, you'd also get <code>__contains__</code>, <code>__iter__</code>, <code>__reversed__</code>, <code>index</code>, and <code>count</code> methods for free.</p></li>\n<li><p>It would be most natural to return each record as a <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>collections.namedtuple</code></a> object, so that the caller can refer to the columns by name:</p>\n\n<pre><code>for record in From(...).select('description', 'count'):\n print('Part: {0.description}. Number: ${0.count}'.format(record))\n</code></pre></li>\n<li><p>The special case in <code>get</code> seems like a bad idea. It is generally best for functions to have simple and clear specifications. If you want a convenient method for returning a single column as a list, then you should write that as a separate method.</p></li>\n<li><p>The <code>index</code> method on a list has to scan along the whole list comparing with each element in turn. You should consider building a dictionary in which you can look up the column name and get its index. (Or if you use <code>namedtuple</code> you can write <code>getattr(row, column)</code>.)</p></li>\n<li><p>There's very little error checking. For example, in <code>__init__</code>, wouldn't it be worth checking that the array has the right number of columns?</p></li>\n<li><p>There are a couple of problems with your <code>unique</code> method: (i) The comment should be a docstring; (ii) by using a dictionary you don't guarantee to get the records out in the order they went in. I would use <a href=\"http://docs.python.org/2/library/collections.html#collections.OrderedDict\" rel=\"nofollow noreferrer\"><code>collections.OrderedDict</code></a> to ensure that order of rows is preserved.</p></li>\n</ol>\n\n<p>So I'd write something like this:</p>\n\n<pre><code>from collections import namedtuple, OrderedDict, Sequence\n\nclass Table(Sequence):\n \"\"\"Table(name, data, columns) represents a 2-dimensional table of data\n whose column names are given by the columns argument.\n\n &gt;&gt;&gt; from operator import attrgetter\n &gt;&gt;&gt; planets = Table('Planet', [\n ... ('Mercury', 58, 88),\n ... ('Venus', 108, 225),\n ... ('Earth', 150, 365),\n ... ('Mars', 228, 687),\n ... ('Jupiter', 779, 4333),\n ... ('Saturn', 1433, 10759),\n ... ('Uranus', 2877, 30799),\n ... ('Neptune', 4503, 60190)],\n ... ('name', 'semi_major_axis', 'period'))\n\n Iterating over the table yields the rows as namedtuple objects:\n\n &gt;&gt;&gt; max(planets, key=attrgetter('semi_major_axis'))\n Planet(name='Neptune', semi_major_axis=4503, period=60190)\n\n You can filter the table to get a subset of the rows:\n\n &gt;&gt;&gt; planets.filter(lambda p: p.period &gt; 10000)\n ... # doctest: +NORMALIZE_WHITESPACE\n Table('Planet',\n [Planet(name='Saturn', semi_major_axis=1433, period=10759),\n Planet(name='Uranus', semi_major_axis=2877, period=30799),\n Planet(name='Neptune', semi_major_axis=4503, period=60190)],\n ['name', 'semi_major_axis', 'period'])\n\n Or select a subset of the columns:\n\n &gt;&gt;&gt; planets.select('name')\n ... # doctest: +NORMALIZE_WHITESPACE\n Table('Planet',\n [Planet(name='Mercury'),\n Planet(name='Venus'),\n Planet(name='Earth'),\n Planet(name='Mars'),\n Planet(name='Jupiter'),\n Planet(name='Saturn'),\n Planet(name='Uranus'),\n Planet(name='Neptune')],\n ['name'])\n\n If you just want the values from a column, use the column method:\n\n &gt;&gt;&gt; ' '.join(planets.column('name'))\n 'Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune'\n\n \"\"\"\n def __init__(self, name, table, columns):\n self.name = name\n self.columns = list(columns)\n Row = namedtuple(self.name, self.columns)\n self.column_set = set(self.columns)\n self.table = [Row(*row) for row in table]\n\n def __len__(self):\n return len(self.table)\n\n def __getitem__(self, key):\n return self.table[key]\n\n def __iter__(self):\n return iter(self.table)\n\n def __repr__(self):\n return '{0}({1.name!r}, {2!r}, {1.columns!r})'.format(\n self.__class__.__name__, self, list(self))\n\n def column(self, column):\n \"\"\"Generate the values in the given column.\"\"\"\n assert(column in self.column_set)\n for row in self:\n yield getattr(row, column)\n\n def filter(self, condition):\n \"\"\"Return a new Table containing only the rows satisfying\n condition.\n\n \"\"\"\n return Table(self.name, filter(condition, self), self.columns)\n\n def where(self, column, value):\n \"\"\"Return a new Table containing the rows from this table for which\n the given column has the given value.\n\n \"\"\"\n assert(column in self.columns)\n return self.filter(lambda row: getattr(row, column) == value)\n\n def whereNot(self, column, value):\n \"\"\"Return a new Table containing the rows from this table for which\n the given column does not have the given value.\n\n \"\"\"\n assert(column in self.columns)\n return self.filter(lambda row: getattr(row, column) != value)\n\n def select(self, *columns):\n \"\"\"Return a new Table consisting only of the given columns of this\n table.\n\n \"\"\"\n assert(all(c in self.columns for c in columns))\n return Table(self.name,\n ((getattr(row, c) for c in columns) for row in self),\n columns)\n\n def unique(self, *columns):\n \"\"\"Return a new Table containing one row for each unique combination\n of values in the given columns. (If there are multiple rows\n with the same combination of values, the last one is\n included.)\n\n \"\"\"\n assert(all(c in self.columns for c in columns))\n result = OrderedDict((tuple(getattr(row, c) for c in columns), row)\n for row in self)\n return Table(self.name, result.values(), self.columns)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:07:12.473", "Id": "58559", "Score": "0", "body": "You, sir, are awesome. Thanks a ton, really! :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T10:55:12.783", "Id": "35910", "ParentId": "35875", "Score": "6" } } ]
{ "AcceptedAnswerId": "35910", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T20:40:20.263", "Id": "35875", "Score": "4", "Tags": [ "python" ], "Title": "Basic querying on Python 2D arrays" }
35875
<p>I think I have fixed the issues which caused this program to not be functional.</p> <p>Now I believe the design of my code is somewhat bad and may be causing problems with the number of processes that are created (I would think 10 processes would be created when 20 are?). I am unsure what may be causing this, but I probably have lots of other issues in cleanliness of my code as well.</p> <p><strong>What I am Trying to do:</strong></p> <p>I am trying to get a GUI to allocate processes to a bunch of tabs (number of tabs is determined by the user in the real program) and then having each tab display results of each process in real time.<br> My hope is to have the user be able to start/stop a long process on each tab's data at will, and then be able to manually change the data in between starting/stopping the automated data manipulation process.</p> <p>Here is a simple script:</p> <pre><code>from PyQt4 import QtCore, QtGui import multiprocessing as mp import sys import time # Just make some data to manipulate and process def make_data(): data = {'num': 3, 'num2': 4} return data # Some function which tries to process the data # which can be stopped and allows the adjustment of the data by the user def f(data, can_run): for i in range(data['num'], data['num'] + 10**5): can_run.wait() data['num'] += 1 data['num2'] += 100 # Each tab holds a set of data which shows the manipulation of it's contents # can be started and stopped to adjust the data with a button class Tab(QtGui.QTabWidget): def __init__(self, parent, data_init): # GUI junk QtGui.QTabWidget.__init__(self, parent) self.top_level_layout = QtGui.QGridLayout(self) self.frame = QtGui.QFrame(self) self.top_level_layout.addWidget(self.frame) self.step_label = dict() self.step_stacked = dict() self.step_text = dict() self.step_input = dict() for wdgts in data_init.keys(): self.step_label[wdgts] = QtGui.QLabel(str(wdgts)) self.step_stacked[wdgts] = QtGui.QStackedWidget() self.step_text[wdgts] = QtGui.QLabel(str(data_init[wdgts])) self.step_input[wdgts] = QtGui.QLineEdit() self.step_stacked[wdgts].addWidget(self.step_text[wdgts]) self.step_stacked[wdgts].addWidget(self.step_input[wdgts]) self.top_level_layout.addWidget(self.step_stacked[wdgts]) self.top_level_layout.addWidget(self.step_label[wdgts]) # Each tab gets a button to start or stop a process self.process_button = QtGui.QPushButton("Process") self.top_level_layout.addWidget(self.process_button, 1, 1) QtCore.QObject.connect(self.process_button, QtCore.SIGNAL("clicked()"), self.start_process) # setup a managet to hold the data to pass between the GUI and the process self.manager = mp.Manager() self.data = self.manager.dict(make_data()) self.Event = self.manager.Event() self.process = mp.Process(target=f, args=(self.data,self.Event,)) self.process.daemon = True self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_GUI) self.first_start = True def update_GUI(self): try: for wdgt in self.data.keys(): self.step_label[wdgt].setText(str(wdgt)) self.step_input[wdgt].setText(str(self.data[wdgt])) self.step_text[wdgt].setText(str(self.data[wdgt])) except EOFError: print 'have reached the end of the file' QtCore.QObject.disconnect(self.process_button, QtCore.SIGNAL("clicked()"), self.stop_process) QtCore.QObject.disconnect(self.process_button, QtCore.SIGNAL("clicked()"), self.start_process) self.timer.stop() self.process.join() return def start_process(self): for wdgt in self.step_stacked.keys(): self.step_stacked[wdgt].setCurrentWidget(self.step_text[wdgt]) if self.first_start==True: print 'first start' self.process.start() self.first_start = False else: for wdgt in self.data.keys(): self.data[wdgt] = int(self.step_input[wdgt].text()) print 'start process again' self.process_button.setText('Stop Processing - (manually adjust data)') QtCore.QObject.disconnect(self.process_button, QtCore.SIGNAL("clicked()"), self.start_process) QtCore.QObject.connect(self.process_button, QtCore.SIGNAL("clicked()"), self.stop_process) self.timer.start(100) self.Event.set() return def stop_process(self): print 'stopping proccess' self.Event.clear() for wdgt in self.step_stacked.keys(): self.step_stacked[wdgt].setCurrentWidget(self.step_input[wdgt]) self.timer.stop() self.process_button.setText('Start Processing Again Using Data') QtCore.QObject.disconnect(self.process_button, QtCore.SIGNAL("clicked()"), self.stop_process) QtCore.QObject.connect(self.process_button, QtCore.SIGNAL("clicked()"), self.start_process) return # More GUI stuff class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self) screen_height = app.desktop().screenGeometry().height() screen_width = app.desktop().screenGeometry().width() self.resize(int(screen_width*0.2), int(screen_height*0.2)) self.tab_list = [] self.setTabShape(QtGui.QTabWidget.Rounded) self.centralwidget = QtGui.QWidget(self) self.top_level_layout = QtGui.QGridLayout(self.centralwidget) self.tabWidget = QtGui.QTabWidget(self.centralwidget) self.top_level_layout.addWidget(self.tabWidget, 1, 0, 25, 25) self.setCentralWidget(self.centralwidget) self.centralwidget.setLayout(self.top_level_layout) self.process_all__button = QtGui.QPushButton("Start All Processes") self.top_level_layout.addWidget(self.process_all__button, 0, 0) QtCore.QObject.connect(self.process_all__button, QtCore.SIGNAL("clicked()"), self.start_all_process) # Make Tabs in loop from button for i in range(0,10): super_cool_data = make_data() name = 'tab ' + str(i) self.tab_list.append(Tab(self.tabWidget, super_cool_data)) self.tabWidget.addTab(self.tab_list[-1], name) # All Processes can be started and stopped together def start_all_process(self): self.process_all__button.setText('Stop All Processing') QtCore.QObject.disconnect(self.process_all__button, QtCore.SIGNAL("clicked()"), self.start_all_process) QtCore.QObject.connect(self.process_all__button, QtCore.SIGNAL("clicked()"), self.stop_all_process) for i in self.tab_list: i.start_process() def stop_all_process(self): self.process_all__button.setText('Start All Processing') QtCore.QObject.disconnect(self.process_all__button, QtCore.SIGNAL("clicked()"), self.stop_all_process) QtCore.QObject.connect(self.process_all__button, QtCore.SIGNAL("clicked()"), self.start_all_process) for i in self.tab_list: i.stop_process() # Get rid of the processes after closing the GUI, no matter where they are in process stage def closeEvent(self, event): for tab in self.tab_list: tab.process.terminate() if __name__ == "__main__": app = QtGui.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_()) </code></pre>
[]
[ { "body": "<p>This question appears to be off topic for Code Review, because the code does not work.\n<hr>\n<em>(Regarding <a href=\"https://codereview.stackexchange.com/revisions/35876/1\">original revision</a>:)</em><br>\nBut anyway, I don't think using <code>psutils</code> to suspend a subprocess is a good idea. That could freeze the pipe in way that disturbs the main process. Instead, look into the <a href=\"http://docs.python.org/2/library/multiprocessing.html#synchronization-primitives\" rel=\"nofollow noreferrer\">synchronization primitives</a> provided by <code>multiprocessing</code>.\n<hr>\n<em>(Regarding <a href=\"https://codereview.stackexchange.com/revisions/35876/4\">current revision</a>:)</em></p>\n\n<p>You are using <code>Event</code> the wrong way. <code>wait()</code> waits while the event is in clear state, so the the event should be set when the subprocess may run.</p>\n\n<p>Start the subprocess in <code>Tab.__init__</code>, set event in <code>start_process</code>, clear it in <code>stop_process</code> and change <code>some_complex_processing</code> to</p>\n\n<pre><code>def some_complex_processing(data, can_run):\n for i in range(data['num'], data['num'] + num):\n can_run.wait()\n data['num'] = i\n data['num2'] = i+100\n time.sleep(0.1)\n</code></pre>\n\n<p>The sleep is there to prevent this demo from using much CPU. Feel free to reduce and eventually eliminate the sleep when you get everything working.</p>\n\n<p>After the above changes the start/stop all processes button seems to work fine. The button inside the tab stops working after a couple of clicks, however, but that seems unrelated to multiprocessing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T15:11:59.330", "Id": "58595", "Score": "0", "body": "Thanks for the help! Sorry if this was out of place, I will edit the question after it's working so that it fits. I will check out the synchronization primitives and hopefully something will work out well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T23:14:19.343", "Id": "58655", "Score": "0", "body": "I added a `multiprocessing.Manager()` which allows a much simpler design by sharing the data between the Tab and the process. \n\nHowever, I don't see any method of pausing/resuming the execution of the process such that the user can manipulated the shared data and then resubmit the data to the process from where it left off.\nAm I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T09:56:23.327", "Id": "58878", "Score": "0", "body": "@chase You can use an `Event` to signal the worker process that it is allowed to run. The worker needs to check the state periodically by calling `.wait()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T04:12:15.573", "Id": "58997", "Score": "0", "body": "I added the code with the `Event` in my question, but it's still not working so well. It doesn't appear to be updating the values at all and the start/stop only works some of the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T17:52:51.030", "Id": "59109", "Score": "0", "body": "Thank you for your help, it is much appreciated! I made the changes to the script; although, as you stated, it is still not responding so well to button clicks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-22T23:27:17.800", "Id": "141967", "Score": "0", "body": "@chase it seems this answer helped you a lot. Maybe you can mark it as accepted." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T08:16:15.027", "Id": "35906", "ParentId": "35876", "Score": "1" } } ]
{ "AcceptedAnswerId": "35906", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:03:45.710", "Id": "35876", "Score": "2", "Tags": [ "python", "multithreading", "gui" ], "Title": "Pausing and Manipulating Data in a Process with a GUI" }
35876
<p>I have a select case that checks against a string variable. It's starting to get large and I am wondering if there is a better way of doing this?</p> <p>Here is a sample of the <code>Select Case</code> statement:</p> <pre><code>Select Case Param.ToLower Case "dashboard_home_vm" Return _Locator.DashboardHome_VM Case "job_list_vm" Return _Locator.JobList_VM Case "job_add_vm" Return _Locator.JobAdd_VM Case "client_add_vm" Return _Locator.ClientAdd_VM Case "client_list_vm" Return _Locator.ClientList_VM Case "client_report_vm" Return _Locator.ClientReport_VM Case "employee_add_vm" Return _Locator.EmployeeAdd_VM Case "employee_certification_vm" Return _Locator.EmployeeCertification_VM Case "employee_list_vm" Return _Locator.EmployeeList_VM Case "employee_report_vm" Return _Locator.EmployeeReport_VM Case "employee_role_vm" Return _Locator.EmployeeRole_VM Case "employee_timeslip_vm" Return _Locator.EmployeeTimeslip_VM Case "product_add_vm" Return _Locator.ProductAdd_VM Case "product_category_vm" Return _Locator.ProductCategory_VM Case "product_list_vm" Return _Locator.ProductList_VM Case "product_type_vm" Return _Locator.ProductType_VM Case "product_unit_vm" Return _Locator.ProductUnit_VM Case "tracking_stock_vm" Return _Locator.TrackingInStock_VM Case "tracking_list_vm" Return _Locator.TrackingList_VM Case "tracking_site_vm" Return _Locator.TrackingOnSite_VM Case "vendor_add_vm" Return _Locator.VendorAdd_VM Case "vendor_list_vm" Return _Locator.VendorList_VM Case "vendor_report_vm" Return _Locator.VendorReport_VM Case Else Return Nothing End Select </code></pre> <p>This actual list will be about 50 - 80 comparisons. Is this the fastest way to do this or is there a better way?</p>
[]
[ { "body": "<p>A classic solution to this problem is to use a data table - in your case probably in form of a dictionary. It depends of what type your values are - I assume they are some sort of view models? I'm also going to assume they have a common base class:</p>\n\n<p>One time setup:</p>\n\n<pre><code>Dim dict As New Dictionary(Of String, ViewModelBase)\ndict.Add(\"dashboard_home_vm\", _Locator.DashboardHome_VM)\n...\n</code></pre>\n\n<p>You can look them up simply by</p>\n\n<pre><code>Dim vm As ViewModelBase\nIf (dict.TryGetValue(Param.ToLower, vm)) Then\n return vm\nEnd If\nreturn Nothing\n</code></pre>\n\n<p>Adding a new view model would be achieved by simply adding a new entry to the dictionary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T00:13:28.760", "Id": "58490", "Score": "0", "body": "awesome, I knew there had to be cleaner way, also bonus points for correctly guessing that I was referring to view models. You even got the base class name right!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T22:29:35.220", "Id": "35882", "ParentId": "35877", "Score": "12" } }, { "body": "<p>Cant you just use the output of param.tolower after _locator.?</p>\n\n<pre><code>return _locator.(Param.ToLower)\n</code></pre>\n\n<p>try if that works</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:58:34.383", "Id": "36362", "ParentId": "35877", "Score": "-1" } }, { "body": "<p>A dictionary is definitely the way to go, but I think you can improve on /u/ChrisWue's answer.</p>\n\n<p>Since I'm assuming you don't need to change it at runtime, you can use a <a href=\"http://msdn.microsoft.com/en-us/library/dd293617.aspx\" rel=\"nofollow\">collection initializer</a> to create it in a single syntactic line. Like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private ReadOnly viewModelLocator As New Dictionary(Of String, ViewModelBase) From {\n {\"dashboard_home_vm\", _Locator.DashboardHome_VM},\n {\"job_list_vm\", _Locator.JobList_VM},\n {\"job_add_vm\", _Locator.JobAdd_VM}\n }\n</code></pre>\n\n<p>Initializing it without using the <code>Add</code> method is quicker and allows us to mark this as <code>ReadOnly</code> for clarity. Plus fitting it into a single line means we can initialize it outside of the flow of our constructor.</p>\n\n<p>Don't just call it <code>dict</code> since we already know it's a dictionary from it's type. Use a nice name to describe what <em>this particular</em> dictionary is doing, like <code>viewModelLocator</code>. </p>\n\n<p>When using <a href=\"http://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Dictionary.TryGetValue</code></a>:</p>\n\n<blockquote>\n <p>When this method returns, it contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter</p>\n</blockquote>\n\n<p>Since you want to return <code>Nothing</code> if the key is not found and the associated value when it is, and since the <em>default value</em> of your ViewModelBase is Nothing, you don't need to specifically handle the the boolean returned by <code>TryGetValue</code>. You should add another function to read the dictionary that looks like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function GetViewModel(ByVal viewModelName) As ViewModelBase\n Dim vm As ViewModelBase\n viewModelLocator.TryGetValue(viewModelName.ToLower, vm)\n Return vm\nEnd Function\n</code></pre>\n\n<p>Again, don't call this <code>Param</code>. Use good variable names like <code>viewModelName</code> or something similar.</p>\n\n<hr>\n\n<p>If you had fewer cases you needed to run through, and you were only returning a single item per case, I think it's slightly more readable to put the entire case on the same line by using the colon (<code>:</code>) as the <a href=\"http://msdn.microsoft.com/en-us/library/xxda45fy.aspx#sectionToggle1\" rel=\"nofollow\">VB line terminator</a> like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Select Case Param.ToLower\n Case \"dashboard_home_vm\" : Return _Locator.DashboardHome_VM\n Case \"job_list_vm\" : Return _Locator.JobList_VM\n Case \"job_add_vm\" : Return _Locator.JobAdd_VM\n '....\nEnd Select\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T21:31:26.340", "Id": "107144", "Score": "0", "body": "You can mark it as `ReadOnly` whether or not you use the collection initializer syntax. `ReadOnly` marks the variable `viewModelLocator` as not being able to be assigned to after construction. However, it does not make the contents read-only as `Add`, `Remove`, etc. can be called on it. That being said, I recommend `ReadOnly` for that purpose: prevents accidental re-assignment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T20:54:58.640", "Id": "46848", "ParentId": "35877", "Score": "2" } } ]
{ "AcceptedAnswerId": "35882", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:07:56.920", "Id": "35877", "Score": "4", "Tags": [ ".net", "strings", "vb.net" ], "Title": "Select case string comparison" }
35877