body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>For the purpose of this problem, the BST is defined to allow duplicates, and the duplicate values will always follow to the right-side of the parent nodes with the same value. For example, with the data:</p>
<pre><code> 1, 2, 2, 2, 2
</code></pre>
<p>if the root node has the value 2 (as opposed to 1) then the tree will look like:</p>
<pre><code> 2
/ \
1 2
\
2
\
2
</code></pre>
<p>The following code scans the tree, identifies any values that are duplicated, and prints the duplicate values, as well as how many times that value is duplicated.</p>
<pre><code>public class DuplicateCountInBST {
private TreeNode root;
private class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode (TreeNode left, int item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private class DuplicateInfo {
int item;
int count;
public DuplicateInfo(int item, int count) {
this.item = item;
this.count = count;
}
}
public void print () {
if (root == null) {
return;
}
// find right most node.
TreeNode rightMostNode = root;
while (rightMostNode.right != null) {
rightMostNode = rightMostNode.right;
}
printHelper (root, root.item, new DuplicateInfo(0, 0), rightMostNode);
}
// inorder traversal
// rightmostnode is a guard against skewed trees.
private void printHelper (TreeNode node, int prevValue, DuplicateInfo duplicateInfo, TreeNode rightMostNode) {
if (node == null) {
return;
}
printHelper(node.left, node.item, duplicateInfo, rightMostNode);
if (node.item == duplicateInfo.item) {
duplicateInfo.item = node.item;
duplicateInfo.count++;
}
if (node.item != duplicateInfo.item || node == rightMostNode) {
if (duplicateInfo.count > 1) {
System.out.println(duplicateInfo.item + " : " + duplicateInfo.count);
}
duplicateInfo.item = node.item;
duplicateInfo.count = 1;
}
printHelper(node.right, node.item, duplicateInfo, rightMostNode);
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>General</h2>\n\n<p>Your code style here is good, the variable names are nice and descriptive, and the algorithm you implement is easy to identify and follow. This is good-looking code. There are a few of nit-picks:</p>\n\n<ul>\n<li>the <code>TreeNode</code> class should be a 'static' class ... <code>private static ...</code> because it has no reason to keep a reference to the outer class.</li>\n<li>Your <code>TreeNode.item</code> should be <code>final</code> even though it is an internal class. <code>final</code> variables make for more apparent logic.</li>\n<li>this is an opinion thing, but I prefer there to be getter/setter methods <em>even on internal classes</em>. With modern IDE's like Eclipse, IntelliJ and NetBeans, there really is no 'lazy' excuse for it. I prefer methods like <code>node.getRight()</code> instead of <code>node.right</code></li>\n<li>your method <code>print()</code> should have a better name like <code>printDuplicates()</code></li>\n</ul>\n\n<h2>Algorithm</h2>\n\n<p>The solution you have for this problem appears to work. The algorithm relies on passing a token around, and relies on first walking the right-edge of the tree to create a 'stop-gate'. These two items detract from the solution. There are 'simpler' ways to do this recursive problem without the overheads you have. Consider the functions:</p>\n\n<pre><code>public void printDuplicates() {\n printDuplicatesHelper(root, 0, 0);\n}\n\nprivate void printDuplicatesHelper(final TreeNode node, final int parentval, final int parentcount) {\n if ((node == null || node.item != parentval) && parentcount > 1) {\n System.out.printf(\"Item %d was duplicated %d times\\n\", parentval, parentcount);\n }\n if (node == null) {\n return;\n }\n // make sure the parentcount is 0 going left.\n printDuplicatesHelper(node.left, 0, 0);\n printDuplicatesHelper(node.right, node.item, node.item == parentval ? (parentcount + 1) : 1);\n}\n</code></pre>\n\n<p>The above functions also do an in-order scan of the data. The difference is that the recursion is designed to go <em>past</em> the leaf node, and to treat the <code>null</code> node as if it was the end of a duplicate streak. By doing it this way, and by pushing the duplicate-detecting values down with the recursion, you can detect the end-of-duplicates in a much easier pattern.</p>\n\n<p>I created a 'main method' that compares the above code with yours:</p>\n\n<pre><code> public static void main(String[] args) {\n TreeNode left = new TreeNode(null, 1, new TreeNode(null, 1, null));\n TreeNode right = new TreeNode(\n new TreeNode(null, 5, new TreeNode(null, 5, null)), 6, new TreeNode(null, 6, new TreeNode(null, 6, null)));\n TreeNode top = new TreeNode(left, 3, right);\n\n DuplicateCountInBST tree = new DuplicateCountInBST();\n tree.root = top;\n tree.print();\n tree.printDuplicates();\n}\n</code></pre>\n\n<p>And the results I get from running the two calls are:</p>\n\n<blockquote>\n<pre><code>1 : 2\n5 : 2\n6 : 3\nItem 1 was duplicated 2 times\nItem 5 was duplicated 2 times\nItem 6 was duplicated 3 times\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T01:21:25.720",
"Id": "42832",
"ParentId": "31960",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "42832",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:30:22.967",
"Id": "31960",
"Score": "5",
"Tags": [
"java",
"algorithm",
"tree",
"binary-search"
],
"Title": "Duplicate detection and reporting in a BST"
}
|
31960
|
<p>This is a Python script that I use on my Android tablet. It moves the files in the <code>Download</code> folder to a folder on the external SD card. The files are sorted based on their extensions and are moved to folders (for each different type of extension). If it encounters a new file type, it will create a new folder. If the file name already exists, the new file will be renamed by appending the first five hash digits to the end of the file name. The original file is deleted.</p>
<p>How can I improve my program? What changes should I make?</p>
<pre><code>import os
import hashlib
download_dir = "/sdcard/Download/"
save_dir = "/mnt/external_sd/Download/"
FileList = os.listdir(download_dir)
for File in FileList:
#print File
extension = ''.join(os.path.splitext(File)[1])
name = ''.join(os.path.splitext(File)[0])
ext = extension.strip('.')
if os.path.isdir(download_dir + File):
pass
else:
if os.path.exists(save_dir + ext + "/" + File):
Data = open(download_dir + File, "r").read()
m = hashlib.sha1()
m.update(Data)
h = (m.hexdigest())[0:5]
file(save_dir + ext + "/" +name+"-"+h+"."+ext, "w").write(Data)
print File, " ","-->"," ",name+"-"+h+"."+ext
os.remove(download_dir + File)
elif os.path.exists(save_dir + ext):
Data = open(download_dir + File, "r").read()
file(save_dir + ext + "/" + File, "w").write(Data)
print File #, " ","-->"," ",name+"."+ext
os.remove(download_dir + File)
if os.path.exists(save_dir + ext) != True:
os.makedirs(save_dir + ext)
Data = open(download_dir + File, "r").read()
file(save_dir + ext + "/" + File, "w").write(Data)
print File , " ","-->"," ","/"+ext+"/"+name+"."+ext
os.remove(download_dir + File)
</code></pre>
|
[] |
[
{
"body": "<p><code>File</code>, <code>FileList</code>, and <code>Data</code> are neither class names nor constants; variable names should be lower_case in Python. I'd call it <code>filename</code> instead of <code>file</code> to avoid clashing with Python's built-in <code>file()</code> constructor.</p>\n\n<p>Avoid calling <code>splitext()</code> twice with <code>name, extension = os.path.splitext(filename)</code>.</p>\n\n<p>For portability, clarity, and to avoid accidental omission of the path component separator, it would be better to use <code>os.path.join(dirname, filename)</code> instead of <code>dirname + filename</code>, even if you only plan to run it on Android.</p>\n\n<p>You open files for reading and writing but don't close them. In particular, it's important to make sure the destination file handle is successfully closed before removing the source, or you might lose data. Also, it's preferable to call <a href=\"http://docs.python.org/2/library/functions.html#open\" rel=\"nofollow\"><code>open()</code> instead of <code>file()</code></a>.</p>\n\n<p>The structure of your program can be simplified.</p>\n\n<pre><code>if a:\n ... # body a\nelse:\n if b:\n ... # body b\n elif c:\n ... # body c\n if c != True:\n ... # body d\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>if a:\n ... # body a\nelif b:\n ... # body b\nelif c:\n ... # body c\nelse:\n ... # body d\n</code></pre>\n\n<p>assuming that bodies b and c do not influence the <code>c != True</code> test. Also, I believe you intend for cases b, c, and d to be mutually exclusive, but I suspect it may be possible to execute both bodies b and d in your original program.</p>\n\n<p>Bodies b, c, and d are very similar to each other. You should try to reduce the redundancy in your code. One approach would be to copy the contents to a <a href=\"http://docs.python.org/2/library/tempfile.html\" rel=\"nofollow\"><code>tempfile</code></a> in the destination directory (computing the hash as you copy, in case you need it), then successively try to <code>os.rename()</code> the temporary file to various destination filenames.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T03:38:45.830",
"Id": "31970",
"ParentId": "31961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:52:25.453",
"Id": "31961",
"Score": "5",
"Tags": [
"python",
"android",
"linux",
"file-system"
],
"Title": "Moving and organizing files in download folder"
}
|
31961
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or simpler.</p>
<pre><code>public int heightHelper(TreeNode node) {
int height = -1;
if (node == null) return height;
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(node);
int currentLevelNodeCount = 1;
int nextLevelNodeCount = 0;
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
currentLevelNodeCount--;
if (current.left != null) { queue.add(current.left); nextLevelNodeCount++; }
if (current.right != null) { queue.add(current.right); nextLevelNodeCount++; }
// current level is done.
if (currentLevelNodeCount == 0) {
height++;
currentLevelNodeCount = nextLevelNodeCount;
nextLevelNodeCount = 0;
}
}
return height;
}
</code></pre>
|
[] |
[
{
"body": "<p>The code is basically sound.</p>\n\n<p>It's not a helper function, so don't name it as such. (Helper functions would usually be <code>private</code>.)</p>\n\n<p>Comments would be good. In particular, a JavaDoc explaining how to interpret the height of a degenerate tree would be helpful.</p>\n\n<p>Your <code>currentLevelNodeCount</code> and <code>nextLevelNodeCount</code> are basically segmenting the queue into two queues the hard way. Why not reduce the bookkeeping by using two queues? (I've named them <code>thisLevel</code> and <code>nextLevel</code> because variable names that have the same length make the code look pretty.)</p>\n\n<p>A few tweaks here and there make the code slightly more compact.</p>\n\n<pre><code>/**\n * Returns the maximum depth of a tree.\n *\n * @param node The root of the tree\n *\n * @return -1 if node is null, 0 if node has no children,\n * a positive number otherwise.\n */\npublic int height(TreeNode node) {\n int height = -1;\n if (node != null) {\n // Breadth-first traversal, keeping track of the number of levels\n Queue<TreeNode> thisLevel = new LinkedList<TreeNode>(),\n nextLevel = new LinkedList<TreeNode>();\n\n thisLevel.add(node);\n while (null != (node = thisLevel.poll())) {\n if (node.left != null) nextLevel.add(node.left);\n if (node.right != null) nextLevel.add(node.right);\n\n if (thisLevel.isEmpty()) {\n height++;\n\n Queue<TreeNode> swapTemp = thisLevel;\n thisLevel = nextLevel;\n // We could create a new nextLevel queue, but reusing the\n // newly emptied thisLevel queue is more efficient.\n nextLevel = swapTemp;\n }\n }\n }\n return height;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:45:10.863",
"Id": "51054",
"Score": "0",
"body": "perfectly agreed, i hope some crazy interviewer does not see `2 data structures used` as a disadvantage. It happens."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:46:57.433",
"Id": "51056",
"Score": "0",
"body": "i do accept your code as a better answer, but for `sake of interviews` stick with 2 counters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T02:20:19.263",
"Id": "51057",
"Score": "4",
"body": "In almost all circumstances, priorities should be 1) bug-free, 2) easy to understand and maintain, and 3) efficient. An interviewer who insists on prioritizing (3) over (1) and (2) should be a red flag. They may be interviewing you as a candidate, but remember, you're evaluating them too as a potential employer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T18:22:49.790",
"Id": "106217",
"Score": "0",
"body": "@200_success well done. This code is really easy to understand."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:42:06.150",
"Id": "31967",
"ParentId": "31963",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "31967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T00:41:28.120",
"Id": "31963",
"Score": "5",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Find height of a tree without using recursion"
}
|
31963
|
<p>This essentially checks if any of these <code>if</code> statements are true, then echos a statement.</p>
<p>Unfortunately, wrapping the error message with a <code>div</code> tag is impossible since I set error to 1 after I would have the div tag show up. I assume I could use a function for this but I don't understand how they work.</p>
<p>Is there a better way to check all these parameters then return a string that I can check if something exists in that string or not to post?</p>
<pre><code>if ($error == '1'){ echo '<div class="error_message">';}
if(strlen($display)<4)
{
echo "Display name is too short. <br>";
$error = '1';
}
if ($email == '')
{
echo "You did not put a valid email adress. We require this to verify your account. <br>";
$error = '1';
}
if(mysql_num_rows($check_display) != 0)
{
echo "Display name is already in use. <br>";
$error = '1';
}
if(mysql_num_rows($check_user) != 0)
{
echo "Username is already in use. <br>";
$error = '1';
}
if(mysql_num_rows($check_mail) != 0)
{
echo "Email is already in use. <br>";
$error = '1';
}
if ($pass != $pass2)
{
echo 'Passwords do not match. <br>' ;
$error = '1';
}
if ($error == '1'){ echo '</div>';}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:21:01.280",
"Id": "51052",
"Score": "0",
"body": "http://stackoverflow.com/questions/4731810/if-else-embedding-inside-html\r\n\r\nHere's a solution to problem here on stackflow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:21:20.223",
"Id": "51053",
"Score": "0",
"body": "I understand what functions are.. but I don't quite understand how to use them for this case. I'm working on something currently. Trying it out at least."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T16:47:58.000",
"Id": "51082",
"Score": "1",
"body": "[Don't use `mysql_*` functions in new code!](http://stackoverflow.com/a/14110189/1667018)"
}
] |
[
{
"body": "<p>Like so:\nHere you can see that is easier to have errors as an array, use alternative control statments to separate php from html:</p>\n\n<pre><code> <?php\n $messages = array();\n if(strlen($display)<4)\n {\n $messages[] = 'Display name is too short';\n }\n if (empty($email))\n {\n $messages[] ='You did not put a valid email address. We require this to verify your account.';\n } \n if(mysql_num_rows($check_display) != 0)\n {\n $messages[] = 'Display name is already in use';\n }\n\n if(mysql_num_rows($check_user) != 0)\n {\n $messages[] = 'Username is already in use.';\n }\n\n if(mysql_num_rows($check_mail) != 0)\n {\n $messages[] = 'Email is already in use.';\n }\n\n if ($pass != $pass2) \n { \n echo 'Passwords do not match.'; \n }\n ?>\n <div class=\"error_message\">\n <?php if(!empty($messages):?>\n <ol>\n <?php foreach($messages as $message):?>\n <li><?php echo $message;?></li>\n <?php endforeach;?>\n </ol>\n <?php endif;?>\n </div>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T02:00:08.013",
"Id": "31968",
"ParentId": "31965",
"Score": "2"
}
},
{
"body": "<p>The solution KA_lin gave is a good and clean one. I would however make a small change when displaying it. You should only display the error box when there are some errors to display otherwise you will have an empty error box in your page. It also uses less rendering time and bandwidth when no errors are to be displayed.</p>\n\n<p>Put everything inside the if statement.</p>\n\n<pre><code><?php if(!empty($messages):?>\n <div class=\"error_message\">\n <ol>\n <?php foreach($messages as $message):?>\n <li><?php echo $message;?></li>\n <?php endforeach;?>\n </ol>\n </div>\n<?php endif;?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-29T05:43:12.720",
"Id": "284584",
"Score": "0",
"body": "maybe ka_lin purposely put the box there with some styling.. but i got your point"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-13T11:07:00.413",
"Id": "83989",
"ParentId": "31965",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31968",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:08:08.417",
"Id": "31965",
"Score": "2",
"Tags": [
"php",
"html",
"validation",
"email"
],
"Title": "Redundant email checking in PHP"
}
|
31965
|
<p>Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple. Also its really hard to make this code work if <code>preorder array contains duplicate</code>. Any code/psuedocode is useful.</p>
<pre><code>public class PreOrderTraversalBST {
private TreeNode root;
private static class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode (TreeNode left, int item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
/**
* QQ: is there any alternative for this ?
*/
private static class Counter {
int counter;
Counter(int counter) {
this.counter = counter;
}
}
public void preOrderRecursive (int[] a) {
root = dpPreOrderRecursive (a, new Counter(0), Integer.MIN_VALUE, Integer.MAX_VALUE );
}
private TreeNode dpPreOrderRecursive (int[] arr, Counter counter, int min, int max) {
if (counter.counter < arr.length && arr[counter.counter] > min && arr[counter.counter] < max) {
int item = arr[counter.counter];
TreeNode treeNode = new TreeNode(null, item, null);
counter.counter++;
treeNode.left = dpPreOrderRecursive(arr, counter, min, item);
treeNode.right = dpPreOrderRecursive(arr, counter, item, max);
return treeNode;
}
return null;
}
public void preOrderWithStack (int[] arr) {
final Stack<TreeNode> stack = new Stack<TreeNode>();
root = new TreeNode(null, arr[0], null);
stack.push(root);
int i = 1;
while (arr[i] < root.item) {
TreeNode node = new TreeNode(null, arr[i], null);
if (arr[i] < stack.peek().item) {
stack.peek().left = node;
} else {
TreeNode temp = null;
while (!stack.isEmpty() && arr[i] >= stack.peek().item) {
temp = stack.pop();
}
temp.right = node;
stack.push(temp);
}
stack.push(node);
i++;
}
TreeNode rightNode = new TreeNode(null, arr[i], null);
root.right = rightNode;
stack.push(rightNode);
i++;
while (i < arr.length) {
TreeNode node = new TreeNode(null, arr[i], null);
if (arr[i] >= stack.peek().item) {
stack.peek().right = node;
stack.push(node);
} else {
TreeNode temp = null;
while (!stack.isEmpty() && arr[i] < stack.peek().item) {
temp = stack.pop();
}
temp.left = node;
stack.push(temp);
}
stack.push(node);
i++;
}
}
}
</code></pre>
<p>Complexity check. Does stack based solution account to O(nlogn) time comlexity or O(n2) ?</p>
|
[] |
[
{
"body": "<p>Your binary tree setup does not appear to be well balanced.... and no, the counter is unnecessary. I think you have perhaps over-thought the process...</p>\n\n<p>If the data is pre-sorted, you can simply bifurcate your data in a recursive process.</p>\n\n<p>Your method is very close to what I would do, so copy/paste:</p>\n\n<pre><code>private TreeNode dpPreOrderRecursive (int[] arr, /*Counter counter,*/ int min, int max) {\n\n int mid = (min + max) >> 1;\n TreeNode treeNode = new TreeNode(null, arr[mid], null);\n treeNode.left = mid > min ? dpPreOrderRecursive(arr, min, mid - 1) : null;\n treeNode.right = mid + 1 < max ? dpPreOrderRecursive(arr, mid + 1, max) : null;\n}\n</code></pre>\n\n<p>Then, you can get your tree with:</p>\n\n<pre><code>TreeNode root = dpPreOrderRecursive(arr, 0, arr.length);\n</code></pre>\n\n<p>(none of the Integer.MIN/MAX).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T20:26:46.357",
"Id": "36376",
"ParentId": "31972",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36376",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T06:54:18.970",
"Id": "31972",
"Score": "1",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Given preorder array construct a BST"
}
|
31972
|
<p>I've started my first application using backbone and have something basic up and running, backbone seems to give a lot of freedom to application design and I don't know what I'm doing right and wrong in that regard. I'm just after some tips and criticism.</p>
<p>The first view is for the details which should be visible when the page loads:</p>
<pre><code>var DetailsView = Backbone.View.extend({
el: $(".details"),
initialize: function(options) {
// nothing here yet
},
render: function() {
// nothing here yet
},
events: {
"click .btn": "setDetails"
},
setDetails: function(e) {
this.$el.hide();
// will do validation here...
this.options.dataEditorView.$el.show();
this.options.finalView.render();
}
});
</code></pre>
<p>Once a user has completed the details form for that view, the data edit view is displayed:</p>
<pre><code>var DataEditorView = Backbone.View.extend({
el: $(".data-editor"),
initialize: function(options) {
},
events: {
"keypress .point-x": "addSeriesPoint",
"keypress .point-y": "addSeriesPoint"
},
addSeriesPoint: function(e) {
if (e.keyCode != 13) return;
//if (!this.input.val()) return;
console.log('adding point');
var point = [];
point[0] = $("#input-point-x").val();
point[1] = $("#input-point-y").val();
Series.create({
x: $("#input-point-x").val(),
y: $("#input-point-y").val()
});
var points = this.options.seriesCollection.toJSON();
this.options.summaryView.addPoint(points);
$(".point-x").val("");
$(".point-x").focus();
}
});
</code></pre>
<p>And the summary view which is visible while the date editor view is visible:</p>
<pre><code>var SummaryView = Backbone.View.extend({
initialize: function() {
console.log('initialising...');
this.canvas = d3.select(this.el)
.append("svg")
.attr("width", 600)
.attr("height", 500);
},
className: "summary",
render: function() {
$("body").append(this.el);
},
addPoint: function(points) {
console.log(points);
this.canvas.selectAll("circle")
.data(points)
.enter()
.append("circle")
.attr("r", 42)
.attr("cx", function(d) { return d.x })
.attr("cy", function(d) { return d.y })
.transition().selectAll('circle')
.ease('bounce').duration(900)
.attr('r', function (d) {
console.log(d);
return 99; //ugh
});
}
});
</code></pre>
|
[] |
[
{
"body": "<h3>DetailsView</h3>\n\n<p>You should pass jquery selector to the <code>el</code> — <a href=\"http://backbonejs.org/docs/backbone.html#section-140\" rel=\"nofollow\">Backbone will handle it</a>. Also, note that you should pass DOM element to the <code>el</code> property.</p>\n\n<hr>\n\n<p>Injecting one view into another is often a bad practice (if relation is not like parent and subview): <code>is.options.dataEditorView.$el.show(); this.options.finalView.render();</code></p>\n\n<p>Consider triggering event like <code>validation-success</code> from <code>DetailsView</code>. Subscriber to this event should be in the route or other main object.</p>\n\n<h3>DataEditorView</h3>\n\n<pre class=\"lang-js prettyprint-override\"><code>var point = {\n x: $(\"#input-point-x\").val(),\n y: $(\"#input-point-y\").val()\n};\n\nSeries.create(point); \n// Probably you want to add new point to existing collection this.options.seriesCollection?\n</code></pre>\n\n<hr>\n\n<p>Another view injection: <code>this.options.summaryView.addPoint(points);</code></p>\n\n<p>Just add new point into collection and subscribe to <a href=\"http://backbonejs.org/#Collection-add\" rel=\"nofollow\">event</a> in the <code>summaryView</code> (see next block).</p>\n\n<hr>\n\n<pre><code>// Micro optimization\nvar pointX = $(\".point-x\");\npointX.val(\"\");\npointX.focus();\n</code></pre>\n\n<h2>SummaryView</h2>\n\n<p>Add <code>view.listenTo(seriesCollection, 'add', addPoint)</code> into <code>initialize</code> step. <code>addPoint</code> should <a href=\"http://backbonejs.org/#Events-catalog\" rel=\"nofollow\">accept parameters</a>: <code>model, collection, options</code>, where model is a new point which was added to the collection.</p>\n\n<p>In this function you should run <code>collection.toJSON()</code> to prepare points for <code>D3.data()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T19:02:24.897",
"Id": "46581",
"ParentId": "31974",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T09:35:46.427",
"Id": "31974",
"Score": "3",
"Tags": [
"javascript",
"backbone.js",
"d3.js"
],
"Title": "Basic Backbone application using d3"
}
|
31974
|
<p>I ask if the following code need some refactoring :</p>
<pre><code>public static int InsertBonus(DataTable dt, int month, int year)
{
int affectedRow = -1;
using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["xxx"].ToString()))
{
using (IfxTransaction tran = con.BeginTransaction())
{
try
{
StringBuilder cmdTxt = new StringBuilder();
cmdTxt.Append(" DELETE FROM rh7uiw WHERE bonus_mon = ? AND bonus_year = ? ");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
myIfxCmd.Parameters.Add("bonus_mon", IfxType.Integer);
myIfxCmd.Parameters.Add("bonus_year", IfxType.Integer);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters[0].Value = ((object)month) ?? DBNull.Value;
myIfxCmd.Parameters[1].Value = ((object)year) ?? DBNull.Value;
affectedRow = myIfxCmd.ExecuteNonQuery();
}
cmdTxt.Length = 0;
cmdTxt.Append(" INSERT INTO rh7uiw (emp_num,bonus_year,bonus_mon,bonus_value,bonus_no,rr_code) VALUES(?,?,?,?,?,?) ");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
myIfxCmd.Parameters.Add("emp_num", IfxType.Integer);
myIfxCmd.Parameters.Add("bonus_year", IfxType.Integer);
myIfxCmd.Parameters.Add("bonus_mon", IfxType.Integer);
myIfxCmd.Parameters.Add("bonus_value", IfxType.Integer);
myIfxCmd.Parameters.Add("bonus_no", IfxType.Integer);
myIfxCmd.Parameters.Add("rr_code", IfxType.Integer);
foreach (DataRow r in dt.Rows)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters[0].Value = (r["emp_num"]) ?? DBNull.Value;
myIfxCmd.Parameters[1].Value = (r["year"]) ?? DBNull.Value;
myIfxCmd.Parameters[2].Value = (r["month"]) ?? DBNull.Value;
myIfxCmd.Parameters[3].Value = (r["bonus_al"]) ?? DBNull.Value;
myIfxCmd.Parameters[4].Value = 1;
myIfxCmd.Parameters[5].Value = 1;
affectedRow = myIfxCmd.ExecuteNonQuery();
}
}
tran.Commit();
con.Close();
con.Dispose();
return affectedRow;
}
catch
{
tran.Rollback();
throw;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Yes:</p>\n\n<ul>\n<li>You don't need to use a <code>StringBuilder</code> when you are not building a string. Just use the string.</li>\n<li>Don't check the state of the connection for every query. Just open the connection before the first query, and it stays open.</li>\n<li>The check for null for <code>month</code> and <code>year</code> in the first query is not needed. An <code>int</code> can not be null.</li>\n<li>As you are creating the connection in a <code>using</code> block, you don't need to close and dispose it. The <code>using</code> block will do that for you.</li>\n<li>Returning <code>affectedRow</code> from the method seems pointless, as it only contains how many records the last query affected.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T23:39:34.937",
"Id": "32004",
"ParentId": "31975",
"Score": "1"
}
},
{
"body": "<p>I totally agree with Guffa, but I want to add some things: I don't like so long methods, because they are really hard to read, especially for other people which might maintain you code in the future. So I would create some private methods with meaningful names. So everything within the try block, I would change to something like this (pseudocode):</p>\n\n<pre><code>try{\n ExcecuteDelete(parameters, ...)\n ExcecuteInsert(parameters,...) \n}\n</code></pre>\n\n<p>So you have three short instead of one long method. \nThe query text (\"<code>DELETE FROM rh7uiw WHERE bon...</code>\") seems to be constant, so I would like to make it a private static constant class variable. </p>\n\n<p>Furthermore, don't use any prefix like my, our and so on, as far as they don't have a special meaning in the context they are used for variable names. Simply call them ifxCommand, command or better: deleteCommand and insertCommand.</p>\n\n<p>By the way, why don't you use a updateCommand? If the affected rows are 0 after a update, you know you have to insert new stuff. But in most cases you have only one database query, instead of always two.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T06:41:58.320",
"Id": "32016",
"ParentId": "31975",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T09:53:49.803",
"Id": "31975",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "simple transaction process"
}
|
31975
|
<p>Implement data structure overflow queue. Overflow queue is a normal queue with one extra property. It never throw Stack overflow exception. So whenever queue becomes full, it replaces the oldest element present in the queue and front pointer simply shifted one step ahead. Constraint:- it should have public void enQueue(int n) and public int deQueue() methods of time complexity O(1) The implementation should be optimum and clean. </p>
<p>Here is my version of implementation. You review is highly appreciated.</p>
<pre><code>public class OverflowQueue {
private int[] queue;
private int front = -1, rear = -1;
public OverflowQueue(int size) {
queue = new int[size];
}
public void enQueue(int n){
rear = getNextIndex(rear);
queue[rear] = n;
if (rear == front || front == -1){
front = getNextIndex(front);
}
}
private int getNextIndex(int index){
if (index == queue.length - 1 ){
index = 0;
} else {
index ++ ;
}
return index;
}
public int deQueue(){
if (front == -1 ){
throw new NullPointerException("deQueue operation is called on empty queue.");
}
int elem = queue[front];
if (front == rear ){
front = -1;
rear = -1;
} else {
front = getNextIndex(front);
}
return elem;
}
public static void main(String[] args) {
OverflowQueue q = new OverflowQueue(5);
q.enQueue(1);q.enQueue(2);q.enQueue(3);
q.enQueue(4);q.enQueue(5);q.enQueue(6);
System.out.println(q.deQueue());
System.out.println(q.deQueue());
System.out.println(q.deQueue());
System.out.println(q.deQueue());
System.out.println(q.deQueue());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T21:49:48.060",
"Id": "51107",
"Score": "2",
"body": "See [EvictingQueue](http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/EvictingQueue.java)."
}
] |
[
{
"body": "<p>With this implementation, it would not throw a stackoverflow exception but there could be an unusual behavior. Maybe there could be some better exception message to handle this case.</p>\n\n<pre><code>OverflowQueue q = new OverflowQueue(n);\n</code></pre>\n\n<p>Now, let's say I want to enqueue n+1 number of elements and then dequeue the same number of elements. Here it doesn't throw any error to enqueue n+1 elements. However <code>deQueue</code> method will throw NullPointerException as soon as the method is executed (n+1)th times.</p>\n\n<p>I would prefer to \"resize the array\" to avoid Stack overflow exception. There is a possibility of unused space in memory in case of resize array implementation if enqueue and dequeue are executed randomly. This can be handled by sinking the array if required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T17:49:03.300",
"Id": "51087",
"Score": "0",
"body": "well you can re size array if you want but at a time queue only can contain elements of the size passed in constructors. This is in the problem statement that u should be able to take n+1 element. However throwing exception on n+1 is something I did. What better you suggest then?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T17:29:53.383",
"Id": "31989",
"ParentId": "31978",
"Score": "3"
}
},
{
"body": "<p>Your <code>getNextIndex</code> method can be simplified using the <strong>ternary operator</strong></p>\n\n<pre><code>private int getNextIndex(int index){\n return index == queue.length - 1 ? 0 : index + 1;\n}\n</code></pre>\n\n<p>Besides this simplification, I agree with Kinjal's answer.</p>\n\n<p>As your <code>index</code> variable is local to only that method, there's no reason to use <code>index++</code> which will modify the index variable, that's why I'm using <code>index + 1</code> here instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T17:52:38.990",
"Id": "35611",
"ParentId": "31978",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T12:07:59.510",
"Id": "31978",
"Score": "5",
"Tags": [
"java",
"algorithm",
"queue"
],
"Title": "Implement data structure overflow queue"
}
|
31978
|
<p>Is there a more efficient algorithm to generate random numbers in C++?</p>
<p>(This code is working on Dev-C++, but I'm not sure if it works on a Borland compiler.)</p>
<pre><code>/*
Author: Arpit Agrawal
Email: arpitagrawal294@gmail.com
Description: Dice Roll Algorithm.
Project Name: e-Roll.
*/
#include<iostream.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#include <stdio.h>
#include <Windows.h>
void call();
void one();
void two();
void three();
void four();
void five();
void six();
void call();
int main()
{
//gotoxy(30,15);
cout<<"\n\n\n\n\t\tAuthor: Arpit Agrawal\n\t\tEmail: arpitagrawal294@gmail.com\n\t\tDescription: Dice Roll Algorithm.\n\t\tProject Name: e-Roll.\n\t\t" ;
cout<<"\n\n\t\tLoading. . . . . . . ";
Sleep(3000);
cout<<"\n\n\t\tPress r to roll or q to quit the game "<<endl;
char ch;
ch = getch();
xm:
if (ch=='r'){
system("cls");
call(); }
else
exit (0);
cout<<endl<<endl<<"Press r to roll again q to quit!";
ch = getch();
goto xm;
getch();
}
void call()
{
srand (time(NULL));
int n;
n= rand();
n = 1 + n % 6;
switch (n)
{
case 1:
one();
break;
case 2:
two();
break;
case 3:
three();
break;
case 4:
four();
break;
case 5:
five();
break;
case 6:
six();
break;
default:
cout<<"NONUM";
}
}
void one()
{
cout << " -----" << endl;
cout << "| |" << endl;
cout << "| O |" << endl;
cout << "| |" << endl;
cout << " -----" << endl;
}
void two()
{
cout << " -----" << endl;
cout << "| O|" << endl;
cout << "| |" << endl;
cout << "|O |" << endl;
cout << " -----" << endl;
}
void three()
{
cout << " -----" << endl;
cout << "| O|" << endl;
cout << "| O |" << endl;
cout << "|O |" << endl;
cout << " -----" << endl;
}
void four()
{
cout << " -----" << endl;
cout << "|O O|" << endl;
cout << "| |" << endl;
cout << "|O O|" << endl;
cout << " -----" << endl;
}
void five()
{
cout << " -----" << endl;
cout << "|O O|" << endl;
cout << "| O |" << endl;
cout << "|O O|" << endl;
cout << " -----" << endl;
}
void six()
{
cout << " -----" << endl;
cout << "|O O|" << endl;
cout << "|O O|" << endl;
cout << "|O O|" << endl;
cout << " -----" << endl;
}
</code></pre>
|
[] |
[
{
"body": "<p>Only call <code>srand()</code> once in an application:</p>\n\n<pre><code> srand (time(NULL));\n</code></pre>\n\n<p>Should be just after <code>main()</code> starts.</p>\n\n<p>This does not generate an evenly distributed the random numbers.</p>\n\n<pre><code> n= rand();\n n = 1 + n % 6;\n</code></pre>\n\n<p>This is because rand() returns a number from [0,RAND_MAX) or [0,32767) which is not exactly divisible by 6. So you get:</p>\n\n<pre><code> 1: 1/5462 Notice this is one more than the others.\n 2: 1/5461\n 3: 1/5461\n 4: 1/5461\n 5: 1/5461\n 6: 1/5461\n</code></pre>\n\n<p>Probably not an issue for a simple app but worth noting. The proper way to do this is:</p>\n\n<pre><code>int dieRoll() // 1-6 evenly distributed.\n{\n static int const max = RAND_MAX/6*6;\n\n int r = rand();\n while(r >= max) { r = rand();}\n\n return r%6+1;\n}\n</code></pre>\n\n<p>Probably best not to use goto:</p>\n\n<pre><code>xm:\nif (ch=='r'){\nsystem(\"cls\"); \ncall(); }\nelse\nexit (0);\ncout<<endl<<endl<<\"Press r to roll again q to quit!\";\nch = getch();\ngoto xm;\n</code></pre>\n\n<p>Prefer (a standard loop):</p>\n\n<pre><code>while (ch=='r') {\n system(\"cls\"); \n call();\n\n cout<<endl<<endl<<\"Press r to roll again q to quit!\";\n ch = getch();\n}\n</code></pre>\n\n<p>Lets also compress your switch statement:</p>\n\n<pre><code> switch (n) {\n case 1: one();break;\n case 2: two();break;\n case 3: three();break;\n case 4: four();break;\n case 5: five();break;\n case 6: six();break;\n // We know the number will never be anything else\n // so don't need the default.\n }\n</code></pre>\n\n<p>Don't need to use so many std::endl.</p>\n\n<pre><code> cout << \" ----- \\n\"\n << \"|O O|\\n\"\n << \"| |\\n\"\n << \"|O O|\\n\"\n << \" -----\" << endl;\n</code></pre>\n\n<p>std::endl is used to flush the output. If you just want a new line use \"\\n\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T19:57:24.913",
"Id": "31992",
"ParentId": "31980",
"Score": "14"
}
},
{
"body": "<p>There's no reason to use a case statement, replace it with:</p>\n\n<pre><code>void (* draw[])() = {one, two, three, four, five, six };\ndraw[n]();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T21:02:47.773",
"Id": "108205",
"Score": "3",
"body": "Careful with the zero-based _vs._ one-based arrays. Also, why not store six constant strings to be printed instead of six pointers to functions that print strings?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T21:58:19.887",
"Id": "32000",
"ParentId": "31980",
"Score": "4"
}
},
{
"body": "<p><strong>Function-naming</strong></p>\n\n<p>Your function names are <em>absolutely</em> useless. They should all be in verb form as they perform an action, making the function's purpose clear. You have already done this with <code>call()</code>, though the name itself is quite unhelpful since functions <em>are</em> called.</p>\n\n<p>Based on what they're doing, <code>call()</code> can be renamed to something like <code>runGame()</code>, and the rest of them can be renamed to something like <code>displayDiceX()</code> (replace <code>X</code> with the respective number).</p>\n\n<p><strong><code>main()</code> function</strong></p>\n\n<p>There is no separation between different lines of code (based on purpose), nor is there any indentation in the conditional statements. Not only that, but you use <code>goto</code>, which has a great potential of causing \"spaghetti code\" (not a good thing). Try to keep the control flow as easy to follow as possible.</p>\n\n<p>I can hardly follow the logic at a glance, but the one thing that makes sense are the outputs, and even some of those are weird. It's not technically \"loading\" if it's sleeping for a set period of time, although I can understand the aesthetic effect you're trying to achieve. Also, do you <em>really</em> need to output your email address? What does that have to do with anything in this program?</p>\n\n<p><strong>Function-indentation</strong></p>\n\n<p>I also have no idea why you've indented these entire functions towards the right. You do already have <code>main()</code> aligned correctly, so why not the rest? At a glance, I thought all of this was part of <code>main()</code>, making me think that you were missing the function definitions. You also haven't indented the code <em>inside</em> these \"number\" functions, though you have done it correctly elsewhere. Try to keep things consistent.</p>\n\n<p><strong>Overall</strong></p>\n\n<p>Overall, this looks like C code and not at all C++. It's okay to keep it simple for learning purposes, but this could use a lot of work to make it look like an ideal game implementation.</p>\n\n<p>If you want to take this a step further and <em>really</em> make it look more like C++, consider defining your own classes, such as a <code>Game</code> and a <code>Die</code> class. The <code>Game</code> class will define the game rules, while the <code>Die</code> class will represent one die <em>and</em> will allow you to create dice (<code>Die</code> objects). The <code>Game</code> class will handle most of the work, and <code>main()</code> will just need to have a <code>Game</code> object that can call a <code>public</code> interface function for running the game. Nothing else would need to be done in <code>main()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T18:02:15.203",
"Id": "59929",
"ParentId": "31980",
"Score": "11"
}
},
{
"body": "<p>Your <code>main()</code> is pretty messy and very hard to read... I won't comment on the <code>while</code> loop since someone else already did (and I agree with him), but stylistically to make your code more readable, you want to have proper indentation:</p>\n\n<pre><code>int main()\n{\n\n //gotoxy(30,15);\n cout<<\"\\n\\n\\n\\n\\t\\tAuthor: Arpit Agrawal\\n\\t\\tEmail: arpitagrawal294@gmail.com\\n\\t\\tDescription: Dice Roll Algorithm.\\n\\t\\tProject Name: e-Roll.\\n\\t\\t\" ; \n cout<<\"\\n\\n\\t\\tLoading. . . . . . . \";\n Sleep(3000);\n cout<<\"\\n\\n\\t\\tPress r to roll or q to quit the game \"<<endl;\n char ch;\n ch = getch();\n xm:\n if (ch=='r') {\n system(\"cls\"); \n call();\n }\n else\n exit (0);\n\n cout<<endl<<endl<<\"Press r to roll again q to quit!\";\n ch = getch();\n goto xm;\n getch();\n}\n</code></pre>\n\n<p>I'm not sure what your objectives are, but this is what your code is doing. The last <code>getch()</code> will never get executed ever because of the <code>goto xm</code> statement and it really is a mess. The 3 lines only get executed if <code>ch=='r'</code> so it would be more clear to have it in that block.</p>\n\n<p>Anyways, the best way to do what you want to do there is a loop - it is the clearest even though it effectively does the same thing as your <code>goto</code>. With a <code>goto</code>, you have to analyze the code to determine that you want looping behavior. When someone glances at a <code>while</code>, they automatically know it will loop based on the condition inside the <code>while</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T20:04:36.283",
"Id": "59943",
"ParentId": "31980",
"Score": "6"
}
},
{
"body": "<p>While <code>rand()</code> is fine, like Jamal said, this is very \"C\" code. So if you want a more C++ way of generating random numbers, use the C++ libraries for them.</p>\n\n<pre><code>#include <random>\nint getRandomInRange(int min, int max)\n{\n std::random_device rd; // obtain a random number from hardware\n std::mt19937 eng(rd()); // seed the generator\n std::uniform_int_distribution<> distr(min, max); // define the range\n return distr(eng);\n}\n</code></pre>\n\n<p>(Shamelessly 'borrowed' from <a href=\"https://stackoverflow.com/a/7560564/1924068\">this SO answer</a> every time I want a random number, as I always forget)</p>\n\n<p>I should probably note that you should put the seeding of the engine somewhere other than where you're getting the number to prevent the randomness being less than random. (Although I'm suddenly less confident about that being the case with <code>std::mt19937</code>, given that it's not based off time). The only reason I put it together here is so there could be a self-contained function explaining the point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-28T10:27:45.620",
"Id": "133278",
"ParentId": "31980",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "31992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T13:47:23.910",
"Id": "31980",
"Score": "11",
"Tags": [
"c++",
"beginner",
"game",
"random",
"dice"
],
"Title": "Simple Dice Roll game"
}
|
31980
|
<p>I have tested all the cases of how a line could be</p>
<ol>
<li>vertically</li>
<li>horizontally </li>
<li>has a slope that's positive or less than 1</li>
</ol>
<p>The function works, but I would like it reviewed, such as if there are overflows, etc.</p>
<pre><code>// Draw line using DDA Algorithm
void Graphics::DrawLine( int x1, int y1, int x2, int y2, Color&color )
{
float xdiff = x1-x2;
float ydiff = y1-y2;
int slope = 1;
if ( y1 == y2 )
{
slope = 0;
}
else if ( x1 == x2 )
{
slope = 2; // vertical lines have no slopes...
}
else
{
slope = (int)xdiff/ydiff;
}
if ( slope <= 1 )
{
int startx = 0;
int endx = 0;
if ( x1 > x2 )
{
startx = x2;
endx = x1;
}
else
{
startx = x1;
endx = x2;
}
float y = y1; // initial value
for(int x = startx; x <= endx; x++)
{
y += slope;
DrawPixel(x, (int)abs(y), color);
}
}
else if ( slope > 1 )
{
float x = x1; // initial value
for(int y = y1;y <= y2; y++)
{
x += 1/slope;
DrawPixel((int)x, y, color);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T15:15:03.177",
"Id": "102135",
"Score": "0",
"body": "https://en.wikipedia.org/wiki/Bresenham's_line_algorithm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T20:50:28.490",
"Id": "102231",
"Score": "2",
"body": "Question is almost year old. Working code for him (with flaws). I do **not** see any reason why we should close this question now as answer is also provided and accepted."
}
] |
[
{
"body": "<p>This makes no sense. The <code>slope</code> must be an <code>int</code> such as 0, 1, 2, 3, 4, … but a vertical line is treated as a line of slope 2? How is that accurate at all?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-13T10:04:44.933",
"Id": "52177",
"Score": "0",
"body": "How would I solve it ? Vertical lines have no slope at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-13T10:22:02.690",
"Id": "52182",
"Score": "0",
"body": "[DDA](http://en.wikipedia.org/wiki/Digital_differential_analyzer_\\(graphics_algorithm\\)). Make two cases. If `abs(ydiff) <= abs(xdiff)`, then proceed as usual with `slope = ydiff / xdiff` and iterate along the x-axis pixels, plotting y. Otherwise, reverse the roles of the x and y axes — compute an `inverseSlope = xdiff / ydiff` and iterate along the y-axis pixels, plotting x."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-13T10:49:42.940",
"Id": "52187",
"Score": "0",
"body": "I have the book Fundamental of computer graphics, by peter shirely, but it doesn't really explain the algorithms really well, can you suggest a better reference for software rasterizations ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-17T15:39:08.897",
"Id": "102378",
"Score": "0",
"body": "Go from a slope to a dx and a dy, with either the dx or dy being 1."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:54:54.740",
"Id": "32023",
"ParentId": "31982",
"Score": "1"
}
},
{
"body": "<p>Here are some flaws in the current algorithm.</p>\n\n<ul>\n<li><code>xdiff</code> will have a roundoff error if <code>x1-x2</code> is large in magnitude, likewise for the <code>y</code> variables.</li>\n<li><code>slope</code> is set to <code>1</code> for no reason, and then immediately reinitialized to something else.</li>\n<li><code>slope</code> is restricted to an integer, when most slopes will not be integral.</li>\n<li>It's impossible to justify setting the slope of a vertical line to <code>2</code>. There are slopes greater than <code>2</code> that are not vertical lines.</li>\n<li>In the line <code>slope = (int)xdiff/ydiff;</code>, casting is higher precedence than division, so this will first cast <code>xdiff</code> to an <code>int</code>, overflowing if <code>xdiff > MAXINT</code>, throwing away the fractional part if there is one, then dividing this <code>int</code> by <code>ydiff</code>. The odds of this being the actual slope are very small.</li>\n<li><code>startx</code> and <code>endx</code> are initialized to <code>0</code> for no reason, then immediately reinitialized to somethiing else.</li>\n<li>Roundoff errors will accumulate as you repeatedly add <code>slope</code> to <code>y</code> (or <code>1/slope</code> to x).</li>\n<li>What's the justification for the <code>abs(y)</code>? If <code>y</code> changes sign in the range, this will cause a kink in the line. Similarly for <code>x</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T15:24:46.717",
"Id": "57213",
"ParentId": "31982",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "57213",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T14:18:09.263",
"Id": "31982",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"graphics"
],
"Title": "Implementation of DDA Line Algorithm"
}
|
31982
|
<p>I'm changing an HTML datepicker value (<code>#date</code>) into 3 separate values in order to post them to a booking engine. I've managed to get it to work but there is a lot of repetition and the original <code>#date</code> value is also submitted unnecessarily.</p>
<p>The engine takes these parameters: </p>
<pre><code>date_day=27&date_month=9&date_year=2013&nights=3&people=2&ref=558&langClient=eng&expr=EUR`
</code></pre>
<p>HTML</p>
<pre><code> <form id="quick_res" action="#" method="post" name="availability">
<ul>
<li>
<label for="date" id="anchor">Date :</label><input type="date" name="date" id="date" placeholder="12/09/13">
</li>
<li>
<label for="numNights">Nights :</label><input type="number" name="nights" id="nights" placeholder="2">
</li>
<li>
<label for="numGuests">Guests :</label><input type="number" name="people" id="people" placeholder="2">
</li>
<input name="ref" type="hidden" id="ref" value="558" />
<input name="langClient" type="hidden" id="langClient" value="eng" />
<li class="select-container">
<label for="currency">Currency :</label>
<select name="expr" id="expr">
<option value="EUR" selected="selected">EURO</option>
<option value="USD">US Dollar</option>
<option value="ARS">Argentine Peso</option>
<option value="AUD">Australian Dollar</option>
</select>
</li>
</ul>
<input type="submit" name="submit" class="secondary button radius text-center" value="Click to Book">
</form>
</code></pre>
<p>jQuery</p>
<pre><code> $('#date').on('change', function() {
var new_val = $(this).val().split('-'),
dateYear = parseInt(new_val[0]),
dateMonth = parseInt(new_val[1]),
dateDay = parseInt(new_val[2]);
$('<input>', {
type: 'hidden',
name: 'date_day',
id: 'date_day',
value: dateDay
}).appendTo('#anchor');
$('<input>', {
type: 'hidden',
name: 'date_month',
id: 'date_month',
value: dateMonth
}).appendTo('#anchor');
$('<input>', {
type: 'hidden',
name: 'date_year',
id: 'date_year',
value: dateYear
}).appendTo('#anchor');
});
</code></pre>
|
[] |
[
{
"body": "<p>The tought process to make your code <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> is almost always the same:</p>\n\n<ol>\n<li>Find the commonalities between blocks of code.</li>\n<li>Extract these into an iterable structure.</li>\n<li>Loop.</li>\n</ol>\n\n<p>Here we can see that everything is the same except the <em>prefix</em> and the <em>value</em>.</p>\n\n<p>The code could be changed to:</p>\n\n<p><em>Please note that you should always specify the <code>radix</code> argument when using the <code>parseInt</code> function since 10 is not default in every browser.</em></p>\n\n<pre><code>$('#date').on('change', function() {\n var newVal = $(this).val().split('-'), //renamed new_val to newVal, always stick to one naming convention\n dateParts = {\n year: parseInt(newVal[0], 10),\n month: parseInt(newVal[1], 10),\n day: parseInt(newVal[2], 10)\n };\n\n $('#anchor').append($.map(dateParts, function (index, key) {\n var name = 'date_' + key;\n\n return $('<input>', {\n type: 'hidden',\n name: name,\n id: name,\n value: dateParts[key]\n });\n }));\n});\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Note that with the above logic, you will end up having duplicate inputs with different values if the user changes the value multiple times. You could solve this by removing the previously added inputs before adding the new ones, but you could also simply add the inputs just prior to form submission by listening to the <strong>submit</strong> event instead.</p>\n\n<p>Also, if you want to avoid sending <code>#date</code>'s value, you can disable that input before submitting; disabled inputs aren't sent to the server.</p>\n\n<p>Finally, you could choose to simply submit the form in <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow\">AJAX</a> using <a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"nofollow\">$.ajax</a> (or any of it's shortcut methods such as <a href=\"http://api.jquery.com/jQuery.post/\" rel=\"nofollow\">$.post</a>). That would have the advantage of making your site slighlty more dynamic and you would not have to append inputs to the form since you can use the <code>data</code> option.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:14:52.367",
"Id": "51134",
"Score": "0",
"body": "Thanks, much better. I made a few edits though. There was no need to add 1 to the month to make up for 0 base as the month is already provided in the date."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:08:59.903",
"Id": "51158",
"Score": "0",
"body": "@mantis, Thanks for fixing silly mistakes ;) I updated the answer with additionnal information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:55:59.603",
"Id": "51162",
"Score": "0",
"body": "Thanks for the edit comment. You're right, I do need to do it on submit as I put in some code to initialize the date and of course it won't work if the date isn't changed. I was going to submit in ajax but its a responsive site whereas the booking engine's is not and it would be a lot of extra work to restyle their content. It would make more sense though. Would I need some sort of endpoint page for that? I'm going to try to work it out on submit now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:15:20.797",
"Id": "51166",
"Score": "0",
"body": "http://jsfiddle.net/rHZwS/ :) Unfortunately, when I go back to the page after being sent to the booking form the date is, of course, gone. Is there a way to remove it from the data submitted but reset it after submission?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:31:54.937",
"Id": "51168",
"Score": "0",
"body": "@mantis You mean that the selected date value isin't persistent after the page reloads? You could use `localStorage` to make it persistent through requests. Did I misunderstood your problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T15:36:08.640",
"Id": "51172",
"Score": "0",
"body": "That sounds like a good way to do it. Could I use it to reset the form when the user leaves the page? I'll have to read up on it a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:37:52.870",
"Id": "51176",
"Score": "0",
"body": "@mantis Well you could, however it starts to get slightly more complicated. Perhaps what you could do is add something like `form.html?selectedDate=2013-01-01` when performing the redirection (if you have control over it). However, again using AJAX would solve all issues here, since the page wouldn't be reloaded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T18:09:20.800",
"Id": "51182",
"Score": "0",
"body": "@plaix, hmm, in that case I think I'll just leave the date as is and spend my efforts on creating some sort of ajax module for their booking form. Thanks so much for your help!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T04:50:22.267",
"Id": "32011",
"ParentId": "31990",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T18:28:58.800",
"Id": "31990",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"datetime",
"form"
],
"Title": "jQuery date split into day month year"
}
|
31990
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or simpler. Although, agree that generics should be used, instead of integers, let's punt on generics as a review for now.</p>
<pre><code>public class CreateBinarySearchTree {
private TreeNode root;
public CreateBinarySearchTree() {
}
/**
* Will create a BST imperative on order of elements in the array
*/
public CreateBinarySearchTree(int[] a) {
this();
for (int i : a) {
add(i);
}
}
private static class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode(TreeNode left, int item, TreeNode right) {
this.left = left;
this.right = right;
this.item = item;
}
}
public void add(int item) {
if (root == null) {
root = new TreeNode(null, item, null);
return;
}
TreeNode node = root;
while (true) {
if (item < node.item) {
if (node.left == null) {
node.left = new TreeNode(null, item, null);
break;
}
node = node.left;
} else {
if (node.right == null) {
node.right = new TreeNode(null, item, null);
break;
}
node = node.right;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:00:06.080",
"Id": "57817",
"Score": "0",
"body": "Have you tested this code properly to make sure that it works correctly? There's just something about your `right` and `left` fields in the `TreeNode` that doesn't feel right to me."
}
] |
[
{
"body": "<p><code>root</code> is created if and only if you add an element. From the BST I know, the <code>root</code> always exists, even if the tree contains no elements.</p>\n\n<p>Also, the name is confusing. Is it a 'BST creator'? \nThen the name is ok, but some 'BST' itself should be accessible.</p>\n\n<p>Is it just a BST? Then the name should be changed to 'BinarySearchTree' and you should provide more methods to acually be able to <em>use</em> the BST.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:35:54.090",
"Id": "32022",
"ParentId": "31994",
"Score": "6"
}
},
{
"body": "<h3>Correctness:</h3>\n<p>One thing many BST's need to define is the behavior when an item already exists and you attempt to add it again. Usually this means that you will locate the position of the existing item and then do nothing; I personally recommend replacing it (more useful with generics; doesn't make sense with integers). In your case, I <em>think</em> you add it again - this is probably not what is desired.</p>\n<h3>Performance:</h3>\n<p>Like most simple BSTs, your class ends up being a limited linked list if the input data is already sorted. Consider learning about AVL or Red-Black trees to find a way to auto-balance your BST.</p>\n<h3>Usefulness:</h3>\n<p>Currently you only have methods to add to the structure but it doesn't have helpful methods like <code>contains</code> or <code>traverse</code>/<code>visit</code>.</p>\n<p>Consider moving your constructor <code>CreateBinarySearchTree(int[] a)</code> to a more general <code>add(int[] a)</code>; this would allow you to add an array of values at some other point besides construction (such as adding two arrays to the tree to use it as a way to identify unique values). Some people would also argue that such methods are inherently useless. I suggest evaluating if adding an array is more helpful than just iterating across the array in the calling code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T15:16:19.820",
"Id": "33520",
"ParentId": "31994",
"Score": "6"
}
},
{
"body": "<p>This class is too basic to be useful. You can only add nodes to it, but you don't provide a way to access those nodes. As such this is something incomplete.</p>\n\n<h3>Make it testable</h3>\n\n<p>At the minimum, make it testable. For example by implementing a <code>toString</code> method:</p>\n\n<pre><code>@Override\npublic String toString() {\n return toString(root);\n}\n\nprivate String toString(TreeNode node) {\n if (node == null) {\n return null;\n }\n return \"[\" + toString(node.left) + \",\" + node.item + \",\" + toString(node.right) + \"]\";\n}\n</code></pre>\n\n<p>Now we can write some tests to verify it's actually working:</p>\n\n<pre><code>@Test\npublic void test345() {\n CreateBinarySearchTree tree = new CreateBinarySearchTree();\n tree.add(3);\n tree.add(4);\n tree.add(5);\n assertEquals(\"[null,3,[null,4,[null,5,null]]]\", tree.toString());\n}\n\n@Test\npublic void test453() {\n CreateBinarySearchTree tree = new CreateBinarySearchTree();\n tree.add(4);\n tree.add(5);\n tree.add(3);\n assertEquals(\"[[null,3,null],4,[null,5,null]]\", tree.toString());\n}\n</code></pre>\n\n<h3>NOT a Binary Search Tree</h3>\n\n<p>The implementation violates a requirement of a Binary Search Tree: it will add duplicate elements. Let's expose this bug by adding a unit test:</p>\n\n<pre><code>@Test\npublic void testNoDups() {\n CreateBinarySearchTree tree = new CreateBinarySearchTree();\n tree.add(4, 4);\n tree.add(4);\n assertEquals(\"[null,4,null]\", tree.toString());\n}\n</code></pre>\n\n<p>Easy enough to fix, by adding an <code>else</code> in the main loop:</p>\n\n<pre><code> while (true) {\n if (item < node.item) {\n if (node.left == null) {\n node.left = new TreeNode(null, item, null);\n break;\n }\n node = node.left;\n } else if (item > node.item) {\n if (node.right == null) {\n node.right = new TreeNode(null, item, null);\n break;\n }\n node = node.right;\n } else {\n break;\n }\n }\n</code></pre>\n\n<h3>Recursive add</h3>\n\n<p>Instead of a <code>while</code> loop, it would be more elegant to implement adding a node using recursion:</p>\n\n<pre><code>public void add(int item) {\n if (root == null) {\n root = new TreeNode(null, item, null);\n } else {\n add(root, item);\n }\n}\n\npublic void add(TreeNode node, int item) {\n if (item < node.item) {\n if (node.left == null) {\n node.left = new TreeNode(null, item, null);\n } else {\n add(node.left, item);\n }\n } else if (item > node.item) {\n if (node.right == null) {\n node.right = new TreeNode(null, item, null);\n } else {\n add(node.right, item);\n }\n }\n}\n</code></pre>\n\n<h3>Minor things</h3>\n\n<blockquote>\n<pre><code>public CreateBinarySearchTree() {}\n\npublic CreateBinarySearchTree(int[] a) {\n this();\n for (int i : a) {\n add(i);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The constructor that takes an array calls <code>this()</code>, but since that other constructor does nothing, this is pointless. The variable names <code>a</code> and <code>i</code> are poor, it would be better to rename them to <code>arr</code> or <code>items</code>, and <code>item</code>, respectively.</p>\n\n<p>As others have pointed out, it would make sense to move the adding logic outside of the constructor. In fact, how about removing all the constructors, and using this new method instead to add elements:</p>\n\n<pre><code>public void add(int... items) {\n for (int item : items) {\n add(item);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-23T16:57:42.040",
"Id": "60885",
"ParentId": "31994",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T20:07:21.430",
"Id": "31994",
"Score": "10",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Creating a binary search tree"
}
|
31994
|
<p>I have written a small wrapper class for using PHP Mcrypt for encrypting and decrypting text data. This class generates a salt for hashing the key and encrypts the given data with the generated key hash. The encrypted data get stored with the initialization vector and the key salt into a container class. The container class can be decrypted when the given key is valid.</p>
<pre><code>class Mcrypt
{
/**
* @var array
*/
protected static $validCiphers = [
MCRYPT_BLOWFISH,
MCRYPT_TWOFISH,
MCRYPT_RIJNDAEL_128,
MCRYPT_RIJNDAEL_192,
MCRYPT_RIJNDAEL_256,
MCRYPT_SERPENT
];
/**
* @var string
*/
protected $cipher = MCRYPT_TWOFISH;
/**
* @var string
*/
protected $mode = MCRYPT_MODE_CBC;
/**
* @var string
*/
protected $keyHashRounds = '11';
/**
* Encrypts the data with the given key.
*
* @param string $data
* @param string $key
* @return McryptContainer
*/
public function encrypt($data, $key)
{
$data = trim($data);
$container = new McryptContainer;
$container->setInitializationVector($this->getInitializationVector());
$container->setPasswordSalt($this->generateSalt());
$container->setCipher($this->cipher);
$container->setData(mcrypt_encrypt(
$this->cipher,
$this->getKeyHash($key, $container->getPasswordSalt()),
sha1($data) . $data,
$this->mode,
$container->getInitializationVector()
));
return $container;
}
/**
* Decrypts the container data with the given key
* or returns false if the key is not valid.
*
* @param McryptContainer $container
* @param string $key
* @return bool|string
*/
public function decrypt(McryptContainer $container, $key)
{
$data = trim(mcrypt_decrypt(
$container->getCipher(),
$this->getKeyHash($key, $container->getPasswordSalt()),
$container->getData(),
$this->mode,
$container->getInitializationVector()
));
$checkSum = substr($data, 0, 40);
$data = substr($data, 40);
if (sha1($data) != $checkSum) {
return false;
}
return $data;
}
/**
* Generates a hash for the given key.
*
* @param string $key
* @return string
*/
protected function getKeyHash($key, $salt)
{
$length = mcrypt_enc_get_key_size(mcrypt_module_open($this->cipher, '', $this->mode, ''));
$hash = crypt($key, sprintf('$2a$%s$%s$', $this->keyHashRounds, $salt));
return substr($hash, $length * -1);
}
/**
* Generates a random salt.
*
* @return string
*/
protected function generateSalt()
{
$length = mcrypt_enc_get_key_size(mcrypt_module_open($this->cipher, '', $this->mode, ''));
$validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt = '';
$count = strlen($validChars) - 1;
while ($length--) {
$salt .= $validChars[mt_rand(0, $count)];
}
return $salt;
}
/**
* Generates a new mcrypt initialization vector.
*
* @return string
*/
protected function getInitializationVector()
{
return mcrypt_create_iv(mcrypt_get_iv_size($this->cipher, $this->mode), MCRYPT_DEV_URANDOM);
}
/**
* Sets the cipher.
*
* @param string $cipher
*/
public function setCipher($cipher)
{
if (!in_array($cipher, static::$validCiphers)) {
$msg = 'Given cipher is not supported, supported ciphers are: ' . implode(', ', static::$validCiphers);
throw new \InvalidArgumentException($msg);
}
$this->cipher = $cipher;
}
/**
* Sets the rounds used for hashing the key.
*
* @param string $keyHashRounds
*/
public function setKeyHashRounds($keyHashRounds)
{
$this->keyHashRounds = $keyHashRounds;
}
}
</code></pre>
<p>Are there any security issues with my usage of Mcrypt?</p>
<p>Here is a <a href="https://gist.github.com/Cacodaimon/6743696">Gist</a> containing both classes.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T14:59:52.767",
"Id": "51234",
"Score": "1",
"body": "If you `trim` the data prior to encrypting it, don't trim the decrypted data. It should be excactly the same, and require no additional processing. If that's not the case, the data is invalid"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T21:26:07.867",
"Id": "51245",
"Score": "0",
"body": "The `trim` during decryption, which could be a `rtrim` indeed, is used to remove the padding, a leftover of the CBC mode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-27T10:21:49.820",
"Id": "111054",
"Score": "0",
"body": "what i do to encrypted data is base64 encode it. back again when decrypting base64 decode. this will make the encrypted data string smaller."
}
] |
[
{
"body": "<p>I have been wanting to answer this for a while now, and I think I can give an answer today! So...</p>\n\n<blockquote>\n <p>Am I using PHP Mcrypt the right way?</p>\n</blockquote>\n\n<p>Well, what is <em>right</em>? Hows about, <em>what is wrong</em>? There's a blog I know of, which is written by <a href=\"https://stackoverflow.com/users/338665/ircmaxell\">a pretty well respected man on StackOverflow</a>, and he published <a href=\"http://blog.ircmaxell.com/2012/12/seven-ways-to-screw-up-bcrypt.html\" rel=\"nofollow noreferrer\">a post back in late 2012</a>. It covers the basics of the most common mistakes when using Bcrypt. Let's move through each one and see how you did.</p>\n\n<p><strong>Using A Non-Random Salt</strong></p>\n\n<p><em>I'm looking at you <code>generateSalt()</code>!</em> Unfortunately, your salt generation does a poor job. But why? Well the biggest mistake I see is your use of <code>mt_rand()</code>.</p>\n\n<p>As noted by <a href=\"https://crypto.stackexchange.com/questions/2231/cryptographic-security-of-php-mt-rand-function-using-mersenne-twister-algo\">this question regarding the state of PHP's Mersenne Twister function</a>, it's not such a secure generator:</p>\n\n<blockquote>\n <p>the chief vulnerability is that if an attacker is given a large enough sample of Mersenne Twister output, he can then predict future (and past) outputs. This is a gross violation of the properties that a cryptographically secure random number generator is supposed to have (where you're supposed to not even be able to tell if the random bit string could have been produced by the RNG in question).</p>\n</blockquote>\n\n<p>So, we need to stop using <code>mt_rand()</code> (and don't roll back to plain ol' <code>rand()</code>!). What should we use instead? For now, <a href=\"https://security.stackexchange.com/a/26212/38125\"><code>openssl_random_pseudo_bytes()</code></a> is your best bet.</p>\n\n<p>From the ircmaxell's post though, it is noted that:</p>\n\n<blockquote>\n <p>you should use strong randomness while not using [Cryptographically Secure randomness for salts (Such as /dev/random)]. A perfect source would be /dev/urandom. Other sources would be mcrypt_create_iv when paired with MCRYPT_DEV_URANDOM.</p>\n</blockquote>\n\n<p>Talking about the source of your randomness also knocks out his topic of <strong>Using An Incorrect Random Source for Salt Generation</strong>.</p>\n\n<p>How's about his third point: <strong>Using Too Weak Of A Cost Parameter</strong>? This one highly depends on your hardware. You seem to have chosen 11, which if it works for you, is fine. There's <a href=\"https://wildlyinaccurate.com/bcrypt-choosing-a-work-factor\" rel=\"nofollow noreferrer\">a lot to be said about choosing the right cost</a>, and just like many things security related, it's a security vs. UX trade-off.</p>\n\n<p>So onto his fourth point: <strong>Using The Wrong PHP Version</strong>. The only things you really need to know is: keep your PHP updated. Updates are meant to help you, and who doesn't like help?</p>\n\n<p>The fifth point bring sup an interesting debate: <strong>Using The Wrong Prefix</strong>. First off, <a href=\"https://security.stackexchange.com/questions/20541/insecure-versions-of-crypt-hashes\">scratch <code>$2a</code> and use <code>$2y</code></a>. <a href=\"http://php.net/manual/en/function.crypt.php\" rel=\"nofollow noreferrer\">From the PHP docs</a>:</p>\n\n<blockquote>\n <p>developers targeting only PHP 5.3.7 and later should use \"$2y$\" in preference to \"$2a$\"</p>\n</blockquote>\n\n<p>His seventh point could possibly be a game changer here: <strong>Not Using A Library</strong>. You're rolling out your own system. For what benefit? I know, I know, it's always nice to build something and know exactly how things work and you just get a sense of pride! But some things are better left for the experts. Sure it's just wrapper, it's best to just rely on someone else's trusted code.</p>\n\n<p>His eighth point: <strong>Not Using A Timing Safe Comparison</strong>. This one is interesting. Basically, an attacker can determine patterns based on the time it takes to execute an algorithm. These are called <a href=\"https://en.wikipedia.org/wiki/Timing_attack\" rel=\"nofollow noreferrer\">timing attacks</a>. I'm not an expert though, and I don't feel i have the knowledge to critique this aspect of your code.</p>\n\n<p>And then I suggest you take a look at his ninth point, as it is pretty valuable. After you get rid of your salt generation code, this will come in handy <em>before</em> you add that dangerous <code>substr</code> function!</p>\n\n<p>On top of all of hsi points, there are a few things I'd like to mention.</p>\n\n<ol>\n<li><p>I would avoid limiting the user to only a specific list of ciphers. This little snippet may inspire you:</p>\n\n<pre><code>if (!in_array($cipher, mcrypt_list_algorithms())) {\n throw new InvalidArgumentException('Algorithm not supported.');\n}\n</code></pre></li>\n<li><p>The same principle could be applied to the mode. Just use <code>in_array($mode, mcrypt_list_modes())</code>.</p></li>\n<li>Having the default as <code>MCRYPT_TWOFISH</code> really isn't the best default. I would suggest <code>MCRYPT_RIJNDAEL_256</code>.</li>\n<li>I see no benefit from <code>sha1($data) . $data</code>. It seems weak to <code>sha</code> the data like that.</li>\n<li>You may want a way to store the ciphertext as a string or such.</li>\n</ol>\n\n<p>My attempt was made at doing something similar based off your question. Only for learning purposes though. I received <a href=\"https://codereview.stackexchange.com/a/58526/35559\">a well written response regarding the security</a>. I highly you read it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-14T19:48:39.697",
"Id": "62900",
"ParentId": "31996",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T20:30:14.877",
"Id": "31996",
"Score": "7",
"Tags": [
"php",
"security",
"php5",
"cryptography"
],
"Title": "Am I using PHP Mcrypt the right way?"
}
|
31996
|
<p>I am writing PHP code to update a database, but this code is extremely repetitive and thus error prone. I am effectively typing the variable names six times each! Can this be improved without loosing functionality? I am certain there must be better way!</p>
<p>First, the definition of the demandArrayValue function:</p>
<pre><code>function demandArrayValue($array, $key) {
$value = isset($array[$key]) ? $array[$key] : null;
if (is_null($value)) {
throw new Exception("Failed to get value for '".$key."'.");
}
return $value;
}
</code></pre>
<p>Next an example of my extremely repetitive code:</p>
<pre><code>try{
if ($_POST) {
$var1 = demandArrayValue($_POST, "Var1");
$var2 = demandArrayValue($_POST, "Var2");
$var3 = demandArrayValue($_POST, "Var3");
[ ... and so on. ]
$query = "UPDATE Table SET Var1 = :var1, Var2 = :var2, Var3 = :var3, [...] WHERE VarX = :varX";
$stmt = $db->prepare($query);
$stmt->bindParam(':var1', $Var1);
$stmt->bindParam(':var2', $Var2);
$stmt->bindParam(':var3', $Var3);
[ ... and so on. ]
$stmt->execute();
}
}
catch [ ... ]
</code></pre>
<p>Can a better PHP programmer than I am help me out please? Many many thanks in advance!</p>
<p>Disclaimer: I asked this same question on stackoverflow and was pointed to this site as a potentially better location. I have no idea how you move a question from one site to another, so I am sorry to duplicate this.</p>
|
[] |
[
{
"body": "<p>If I were you, I'd create a function that looked like this:</p>\n\n<pre><code>function getArrayValues( array $array, array $keys)\n{\n $result = array();\n foreach($keys as $key)\n {\n if (!isset($array[$key]))\n {\n throw new RuntimeException($key.' is not set');\n }\n $result[$key] = $array[$key];\n }\n return $result;\n}\n</code></pre>\n\n<p>This function will return an array, containing just those keys you were actually looking for. Then, in your try-catch block, I'd write this:</p>\n\n<pre><code>$values = getArrayValues($_POST, array('var1','var2','var3'));\n$stmt = $db->prepare('your query here');\n$stmt->execute($values);\n</code></pre>\n\n<p>And that's it.<br/>\nNow I do have some worries/thoughts/suggestions about your code, but I'll add them in a future edit.</p>\n\n<p><em>Edit:</em><Br/>\nYou're throwing exceptions when an array-key does not exist. In <em>this</em> particular case, that might be desirable. You can't insert a row in your db, lest all data is at hand. I get that. But how often might you end up writing <em>either</em>:</p>\n\n<pre><code>try\n{\n $var = demandArrayValue($someArray, 'isNotSet');\n}\ncatch(Exception $e)\n{\n $var = 'default value';\n}\n</code></pre>\n\n<p>Or, to avoid having to write the <code>try-catch</code> too many times: </p>\n\n<pre><code>$var = isset($someArray['notSet'] ? $someArray['notSet'] : 'default value';\n</code></pre>\n\n<p>You could write 2 distinct functions: one throwing exceptions, one that doesn't, but that's just silly. getting array-keys shouldn't throw an exception. your code should be able to handle a missing parameter.<Br/>\nWhat's more, you place the <code>demandArrayValue</code> in the same try-catch block as all of your DB operations. If you're using <code>PDO</code>, and you've set the <code>PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION</code>, then you're actually handling 2 distinct exceptions in the same catch block:</p>\n\n<pre><code>catch(Exception $e)\n{//you have to catch Exception, since that's what demandArrayValue throws\n if ($e instanceof PDOException)\n {\n $db->rollBack();\n echo $e->getMessage();//handle DB exception\n }\n else\n {\n echo $e->getMessage();//handle other Exception\n }\n}\n</code></pre>\n\n<p>Now, that's not nice. Besides, like I said before: dealing with the request parameters is something that is, actually, quite a complex task, but most, if not all frameworks, implement a (series of) request objects. <a href=\"https://codereview.stackexchange.com/questions/29469/critique-request-php-request-method-class/29485#29485\">You can write your own, too</a>. <Br/>\nOnce you've done that, you can actually use the <code>getKey</code> or <code>get</code> or <code>getAll</code> methods you might implement:</p>\n\n<pre><code>class PostRequest\n{\n private $raw = null;\n private $data = null;\n public function __construct(array $data = null)\n {\n $data = $data ?: $_POST;\n $this->raw = $data;\n $this->setData();\n }\n public function get($name, $default = null)\n {\n if (isset($this->data[$name]))\n {\n return $this->data[$name];\n }\n return $default;\n }\n private function setData()\n {\n $this->data = array();\n foreach ($this->raw as $k => $v)\n {//validate, sanitize, decode... do whatever\n $this->data[$k] = trim($v);\n }\n return $this;\n }\n}\n</code></pre>\n\n<p>You could expand on this basic template, with custom email validation, or number formatting and what have you, but you could just as well implement some form of constant-system, to set the <code>get</code> method's behaviour:</p>\n\n<pre><code>const POST_EXCEPTION = 1;\nconst POST_DEFAULT = 0;\nprivate $exceptionMode = false;\n\npublic function setExceptionMode($exceptionMode = self::POST_DEFAULT)\n{\n $this->exceptionMode = !!$exceptionMode;\n return $this;\n}\npublic function get($name, $default = null)\n{\n if (!isset($this->data[$name]))\n {\n if ($this->exceptionMode === true)\n {\n throw new Exception($name. ' key is not set');\n }\n return $default;\n }\n return $this->data[$name];\n}\n</code></pre>\n\n<p>This <code>get</code> method does everything yours does, and more... but please, do look into the linked answer, and look into how other frameworks deal with the request. It's all been done before, and you're free to <em>copy with pride</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:32:07.717",
"Id": "51128",
"Score": "0",
"body": "That has to be one of the most amazingly thoughtful replies I've ever read. I feel tragically poor being able to do nothing more than accept and upvote your answer. Your considered reply has made my day a whole lot better. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:40:20.543",
"Id": "51129",
"Score": "0",
"body": "\"You could write 2 distinct functions: one throwing exceptions, one that doesn't, but that's just silly.\" Would you like to go into your comment with some more detail? It is indeed what I'd done. My rationale was that there were cases where I **demanded** a value be supplied (`demandArrayValue`), and one where I **got** a value, and if that didn't exist, I provided a default when calling `getArrayValue`... But perhaps, as you'd say I'd be best off not re-inventing the wheel, I promise to look into those references!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:54:57.403",
"Id": "51132",
"Score": "0",
"body": "You talk about frameworks twice in your answer. Do you have any specific examples that you recommend I look into?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:18:03.693",
"Id": "51135",
"Score": "0",
"body": "@MatthewWalker: Well, 2 distinct methods, one throwing an exception and the other _not_ throwing is made redundant when using a class, like I showed. You set the instance's behaviour to throwing an exception if that's what's required. But really: get all keys from the post array, and pass `array_filter($resultingArray)` to the execute call. If the resulting array doesn't return all required keys, `PDO` will throw an exception anyway, so why bother writing a function that throws, when the exception would've been thrown by PDO anyway?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:19:33.077",
"Id": "51136",
"Score": "0",
"body": "On frameworks: Well, I've been using Symfony2 a lot lately, and I've grown to like it. I also used ZendFW (1 and 2, though not so much 2). Both are worth a peek"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:38:09.787",
"Id": "51144",
"Score": "0",
"body": "@MatthewWalker: Oh, and don't feel bad about up-voting and accepting. It's more than enough for me to know I've helped you understand some things, and gain a bit of rep in doing so. Besides, I take it you also upvoted the linked answer of mine, which has earned me the _\"Good answer\"_ badge now, too... thanks :P happy coding"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T07:38:28.203",
"Id": "32018",
"ParentId": "31997",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T20:57:46.273",
"Id": "31997",
"Score": "1",
"Tags": [
"php"
],
"Title": "Modifying database using POSTed variables in PHP"
}
|
31997
|
<p>Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple. ( Generics would be added a bit later). </p>
<pre><code>public class CreateABinaryTree {
private TreeNode root;
public CreateABinaryTree() {
}
/**
* Constructs a binary tree in order of elements in an array.
* After the number of nodes in the level have maxed, the next
* element in the array would be a child of leftmost node.
*
* http://codereview.stackexchange.com/questions/31334/least-common-ancestor-for-binary-search-tree/31394?noredirect=1#comment51044_31394
*/
public CreateABinaryTree(List<Integer> items) {
this();
create(items);
}
private static class TreeNode {
TreeNode left;
int element;
TreeNode right;
TreeNode(TreeNode left, int element, TreeNode right) {
this.left = left;
this.element = element;
this.right = right;
}
}
private void create (List<Integer> items) {
root = new TreeNode(null, items.get(0), null);
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I only see one really questionable thing in your code. Why do you call <code>this()</code> in your constructor? Your parameter-less constructor does absolutely nothing, so this line is irrelevant. If anything, I would actually even remove that constructor entirely so that your API can only be used with your meaningful and useful one.</p>\n\n<p>Also, as a side note, the following line opens you up to a <code>NullPointerException</code> since you never check to see if <code>items</code> is <code>null</code> or if it has any elements.</p>\n\n<pre><code>root = new TreeNode(null, items.get(0), null);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T01:13:50.510",
"Id": "51111",
"Score": "0",
"body": "I agree with your point, in this code i should take off the parameterless constructor. But to answer both your concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T01:14:18.933",
"Id": "51112",
"Score": "0",
"body": "http://stackoverflow.com/questions/19082841/to-null-check-or-not-to-do-a-null-check/19082905?noredirect=1#19082905 - should answer why null ptr check was not done. Plz correct me if i am still wrong"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T01:14:51.450",
"Id": "51113",
"Score": "0",
"body": "http://stackoverflow.com/questions/19081965/whats-the-use-of-this-in-linkedlist-java/19082264?noredirect=1#19082264 - should answer why this() is included."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T01:16:20.383",
"Id": "51114",
"Score": "1",
"body": "@JavaDeveloper I don't get what you mean by the answer you linked. It seems to *support* performing a null check of the parameter before using it. \"What I would do in this case, would either check at the beginning if the param is null, and then return false (so it doesn't break the runtime flow - Objective-C style), OR assertIsNotNull at the beginning of the method, and specify it in the javadoc (e.g. \"the thing must not be null, yo\").\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T01:17:06.480",
"Id": "51116",
"Score": "0",
"body": "@JavaDeveloper Yeah, I get why you would have `this()` if the parameter-less constructor actually *did* anything. :) It just doesn't, and so it's pointless. That's all."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T00:58:28.313",
"Id": "32005",
"ParentId": "31998",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32005",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T21:04:42.237",
"Id": "31998",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Create a binary tree, code review request"
}
|
31998
|
<p>I'm reading <em>TDD By Example</em> by Kent Beck (which I highly recommend, if you haven't read it!) In <em>The xUnit Example</em>, he discusses how to collect the results of multiple tests in a single <code>TestResult</code>. His code looks like this:</p>
<pre><code># in TestCase
def run(self, result):
result.testStarted()
self.setUp()
try:
method = getattr(self, self.name)
method()
except:
result.testFailed()
# in TestSuite
def run(self, result):
for test in self.tests:
test.run(result)
</code></pre>
<p>In short, Beck <em>passes in</em> the currently running <code>TestResult</code> and asks the tests to add their results to it; the <code>TestSuite</code> acts in much the same way. (Beck says the <code>TestSuite</code> is a <em>Composite</em>, and the pattern of passing in the <code>TestResult</code> is called <em>Collecting Parameter</em>.) In other words, somewhere at the top of the call stack, something is creating a single <code>TestResult</code> which gets passed all the way down to the <code>TestCase</code>.</p>
<p>I find the single <code>TestResult</code> object aesthetically distasteful - I generally don't like sharing state between different components. It smacks of C#'s <code>out</code> keyword (which is not a compliment).</p>
<p>My approach would be to <em>return</em> a <code>TestResult</code> from every <code>TestCase</code>, and allow <code>TestResult</code>s to be added to one another:</p>
<pre><code># in TestResult
def __init__(self, runCount=0, errorCount=0):
self.runCount = runCount
self.errorCount = errorCount
def __add__(self, other):
runCount = self.runCount + other.runCount
errorCount = self.errorCount + other.errorCount
return TestResult(runCount, errorCount)
# in TestCase
def run(self):
result = TestResult()
result.testStarted()
self.setUp()
try:
method = getattr(self, self.name)
method()
except:
result.testFailed()
return result
# in TestSuite
def run(self):
result = TestResult()
for test in self.tests:
result += test.run()
return result
</code></pre>
<p>How would you weigh up these two approaches? The state of any given instance of <code>TestResult</code> is now local to the methods. On the other hand, there's more duplication in mine - every method now creates and returns a new <code>TestResult</code>, which might make writing a new implementation of <code>run</code> harder work.</p>
|
[] |
[
{
"body": "<p>One benefit of a collecting parameter is writers can add multiple items to the list. The collecting parameter can descend deeper into the stack and each method is free to add as many items to the list as necessary.</p>\n\n<p>If what was added to the list was restricted to the return value of the method, then it becomes the sender's responsibility to know how to add the receiver's return values to the list, and the receiver cannot return another value other than what would have been added to it.</p>\n\n<p>The collecting parameter seems more flexible because any number of receivers may write to it and still be able to return values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-16T12:51:44.563",
"Id": "52360",
"Score": "0",
"body": "Python makes it easy to return multiple values from a function (`return x, y`), but your point about the caller needing to know how to add the return values to the list is a very good one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-15T18:52:37.337",
"Id": "32721",
"ParentId": "32002",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T22:52:02.670",
"Id": "32002",
"Score": "2",
"Tags": [
"python",
"design-patterns"
],
"Title": "Collecting Parameter vs overloading addition"
}
|
32002
|
<p>I am trying to clean up and make the following code more efficient -</p>
<p><a href="https://gist.github.com/eWizardII/6757364" rel="nofollow">https://gist.github.com/eWizardII/6757364</a></p>
<pre><code>from PIL import Image
import numpy as np
from PIL import ImageChops
import subprocess
import math
import datetime
from PIL import ImageFont
from PIL import ImageDraw
from collections import deque
def image_entropy(prev, curr, smasumm, values):
im1 = Image.open(prev)
im2 = Image.open(curr)
img = ImageChops.difference(im1, im2)
w, h = img.size
a = np.array(img.convert('RGB')).reshape((w * h, 3))
h, e = np.histogramdd(a, bins=(16,) * 3, range=((0, 256),) * 3)
prob = h / np.sum(h) # normalize
prob = prob[prob > 0] # remove zeros
comp = -np.sum(prob * np.log2(prob))
framsd = SD(values, smasumm)
information = 'ENT: ' + str('{0:.2f}'.format(comp)) + ' SMA: ' + str('{0:.2f}'.format(smasumm)) + ' LB: ' + str(
'{0:.2f}'.format(smasumm - framsd)) + ' UB: ' + str('{0:.2f}'.format(smasumm + framsd))
cimg = Image.open(curr)
draw = ImageDraw.Draw(cimg)
font = ImageFont.truetype("arial.ttf", 24)
draw.text((0, 0), information, (0, 255, 0), font=font)
cimg.save(curr)
return comp
def SD(values, mean):
size = len(values)
sumsd = 0.0
for n in range(0, size):
sumsd += math.sqrt((values[n] - mean) ** 2)
return math.sqrt((1.0 / (size - 1)) * (sumsd / size))
try:
print "Initial Image ..."
time = datetime.datetime.now()
filename = "image_"
subprocess.call(
"raspistill -t 1000 -ex night -awb auto -w 720 -h 480 -o %s" % filename + '1.jpg',
shell=True)
prev = filename + '1.jpg'
i = 1
summ = smasumm = 0.0
period = n = 10
values = deque([0.0] * period)
while True:
time = datetime.datetime.now()
filename = "image_" + str(i) + ".jpg"
subprocess.call(
"raspistill -t 1000 -ex night -awb auto -w 720 -h 480 -o %s" % filename,
shell=True)
i += 1
curr = filename
sma = image_entropy(prev, curr, smasumm, values)
values.append(sma)
summ += sma - values.popleft()
smasumm = summ / n
prev = curr
print(datetime.datetime.now() - time)
except KeyboardInterrupt:
print " Quit"
</code></pre>
<p>I believe my biggest bottleneck is in using the <code>subprocess.call</code> in Python but I don't know of any way to improve up such a call - in the long run when I know the program works properly I'll try and transition to Java/C; but this is easier for my immediate application and debugging. Any help or advice would be appreciated thanks in addition to any improvements in the other aspects of the code.</p>
|
[] |
[
{
"body": "<p>I don't know about \"more efficient\", but here are some hints and tips that will help you clean up the code and make it more readable:</p>\n\n<h2>Style remarks</h2>\n\n<ul>\n<li>My style checker asks for at least 2 spaces before an inline comment (lines 20-21). I don't think it's a bad idea.</li>\n<li>According to PEP8, you should keep your lines shorter than 80 characters (lines 24, 25 and 49).</li>\n<li><p>This line is not very clear.</p>\n\n<pre><code>information = 'ENT: ' + str('{0:.2f}'.format(comp)) + ' SMA: ' + str('{0:.2f}'.format(smasumm)) + ' LB: ' + str(\n '{0:.2f}'.format(smasumm - framsd)) + ' UB: ' + str('{0:.2f}'.format(smasumm + framsd))\n</code></pre></li>\n</ul>\n\n<p>It would be a lot clearer to rewrite it like this:</p>\n\n<pre><code>'ENT: {0:.2f} SMA: {0:.2f} LB: {0:.2f} UB: {0:.2f}'.format(\n comp, smasumm, smasumm - framsd, smasumm + framsd)\n</code></pre>\n\n<ul>\n<li>Avoid one letter variable names (and other cryptic names like <em>smasumm</em>, because they're not descriptive and it's not immediately obvious what they represent.</li>\n<li>The lack of comments makes it difficult to follow what you're trying to do. You should use docstrings to write a small paragraph that provides an explanation of what you're trying to do.</li>\n<li>Again according to PEP8:</li>\n</ul>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n \n <ul>\n <li><p>standard library imports</p></li>\n <li><p>related third party imports</p></li>\n <li><p>local application/library specific imports</p></li>\n </ul>\n</blockquote>\n\n<p>So you want to replace your imports with this:</p>\n\n<pre><code>from collections import deque\nimport datetime\nimport math\nimport subprocess\n\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageChops\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n</code></pre>\n\n<ul>\n<li>Why do you alias <code>numpy</code> as <code>np</code>? It's not very readable. I'd rather read <code>numpy</code> in full letters each time.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T20:49:46.347",
"Id": "51192",
"Score": "1",
"body": "Re: aliasing `numpy` as `np`: this is the standard alias, and is used throughout the `numpy` source itself. It's also used by `scipy`, `matplotlib`, `pandas`, etc., pretty much everything on the stack."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:35:46.137",
"Id": "32021",
"ParentId": "32003",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T23:06:21.127",
"Id": "32003",
"Score": "2",
"Tags": [
"python",
"optimization"
],
"Title": "Python Code Cleanup/Optimization"
}
|
32003
|
<p>The following script is being used to generate the status line in <a href="https://code.google.com/p/wmii/" rel="nofollow">wmii</a>. I'm curious if there are faster/more efficient ways to find the various info I'm grabbing. I'm also a relative newbie when it comes to zsh (and shell scripting in general) so I'd also suspect that there are better ways to process some of the data.</p>
<pre><code>#!/bin/zsh
cpu_freq=$(grep "cpu MHz" /proc/cpuinfo | sed 's/[\t ]*//g; s/cpuMHz://g')
cpu0=$(echo "scale=2;" `echo $cpu_freq | head -n 1 | tail -n 1` / 1000 | bc)
cpu1=$(echo "scale=2;" `echo $cpu_freq | head -n 2 | tail -n 1` / 1000 | bc)
cpu2=$(echo "scale=2;" `echo $cpu_freq | head -n 3 | tail -n 1` / 1000 | bc)
cpu3=$(echo "scale=2;" `echo $cpu_freq | head -n 4 | tail -n 1` / 1000 | bc)
stat=$(mpstat | tail -n 1 | tr -s ' ')
usr=$(echo $stat | cut -d ' ' -f 4)
nice=$(echo $stat | cut -d ' ' -f 5)
sys=$(echo $stat | cut -d ' ' -f 6)
cpu=$(echo $usr + $nice + $sys | bc)
memline=$(free | head -n 2 | tail -n 1 | tr -s ' ')
cached=$(echo $memline | cut -d ' ' -f 7)
free=$(echo $memline | cut -d ' ' -f 4)
cachedfree=$(echo $cached + $free | bc)
mem=$(echo "scale=3;" $cachedfree / 1000000 | bc)
network=$(nmcli nm | sed 's/ */\;/g' | cut -d \; -f 2 | tail -n 1)
tun0=$(ifconfig tun0 2>/dev/null)
vpn=$(if [[ -n $tun0 ]]; then; echo "(vpn:" $(cat /tmp/current-vpn)")"; else; echo ""; fi)
battery=$(acpi -b | sed 's/Battery 0: //; s/ until charged//; s/ remaining//; s/Charging/C/; s/Discharging/D/; s/Full, //; s/Unknown, //')
load=$(uptime | sed 's/.*://; s/,//g')
date=$(date +%a\ %b\ %d\ %H:%M)
echo -n $vpn $network '||' $mem GB '||' $cpu% '('$cpu0 $cpu1 $cpu2 $cpu3') ||' $load '||' $date '||' $battery
</code></pre>
|
[] |
[
{
"body": "<h3>Extracting a column</h3>\n\n<p>It's a lot easier to extract columns from text using awk.\nInstead of this:</p>\n\n<blockquote>\n<pre><code>grep \"cpu MHz\" /proc/cpuinfo | sed 's/[\\t ]*//g; s/cpuMHz://g'\n</code></pre>\n</blockquote>\n\n<p>This is shorter, and uses a single awk process instead of <code>grep</code> + <code>sed</code>:</p>\n\n<pre><code>awk '/cpu MHz/ {print $4}' /proc/cpuinfo\n</code></pre>\n\n<h3>Extracting a line</h3>\n\n<p>This is a really awkward method to extract the 4th line:</p>\n\n<blockquote>\n<pre><code>echo $cpu_freq | head -n 4 | tail -n 1\n</code></pre>\n</blockquote>\n\n<p>This is simpler and better:</p>\n\n<pre><code>sed -ne 4p <<< \"$cpu_freq\"\n</code></pre>\n\n<h3>Using arrays</h3>\n\n<p>Instead of getting the values of <code>cpu0..cpu3</code> one by one by running separate command(s) for each, you can get it in one go:</p>\n\n<pre><code>cpus=($({ echo scale=2; awk '/cpu MHz/ {print $4 \" / 1000\"}' /proc/cpuinfo; } | bc))\n</code></pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li>The <code>awk</code> command appends the <code>\" / 1000\"</code> to the CPU frequency, so it's ready for piping to <code>bc</code></li>\n<li>Pipe all lines (commands) to <code>bc</code> at once, and get all the output at once</li>\n<li>Group the <code>echo scale=2</code> and the <code>awk</code> for <code>bc</code> by enclosing in <code>{ ...; }</code></li>\n<li>Store the output of <code>bc</code> in an array</li>\n</ul>\n\n<p>From this array, you can extract the individual CPU values</p>\n\n<pre><code>cpu0=${cpus[0]}\ncpu1=${cpus[1]}\ncpu2=${cpus[2]}\ncpu3=${cpus[3]}\n</code></pre>\n\n<h3>Next steps</h3>\n\n<p>I don't want to spoil all the fun for you :-)\nFollowing the techniques above,\nyou should be able to extract the other values more efficiently (using fewer processes) in a similar fashion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-28T09:32:46.817",
"Id": "115256",
"ParentId": "32008",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "115256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T02:02:16.003",
"Id": "32008",
"Score": "3",
"Tags": [
"beginner",
"linux",
"shell",
"zsh"
],
"Title": "zsh system status script"
}
|
32008
|
<p>Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.</p>
<pre><code>public class Trie {
private static final int ASCII = 256;
private TrieNode root;
public Trie () {
root = new TrieNode();
}
private static class TrieNode {
TrieNode[] alphabets;
char ch;
String word;
String meaning;
public TrieNode() {
this.alphabets = new TrieNode[ASCII];
}
public TrieNode (char ch) {
this.alphabets = new TrieNode[ASCII];
this.ch = ch;
}
}
public void add (String word, String meaning) {
TrieNode node = root;
char[] ch = word.toCharArray();
for (char c : ch) {
if (node.alphabets[c] == null) {
node.alphabets[c] = new TrieNode(c);
}
node = node.alphabets[c];
}
node.word = word;
node.meaning = meaning;
}
public String getMeaning (String word) {
TrieNode node = root;
char[] ch = word.toCharArray();
for (char c : ch) {
node = node.alphabets[c];
if (node == null) {
return null;
}
}
return node.meaning;
}
/**
* Deletes all its children, but does not delete itself.
*/
public void prune (String string) {
TrieNode node = root;
char[] ch = string.toCharArray();
for (char c : ch) {
node = node.alphabets[c];
if (node == null) {
return;
}
}
node.alphabets = new TrieNode[ASCII];
return;
}
public void print() {
printWhole(root);
}
private void printWhole(TrieNode node) {
if (node == null) {
return;
}
if (node.word != null) {
System.out.println("Word: " + node.word + " Meaning: " + node.meaning);
}
for (int i = 0; i < ASCII; i++) {
printWhole(node.alphabets[i]);
}
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.add("mouse", "rat");
trie.add("cop", "police");
trie.add("cope", "endure");
System.out.println("Expected rat, Actual: " + trie.getMeaning("mouse"));
System.out.println("Expected police, Actual: " + trie.getMeaning("cop"));
System.out.println("Expected endure, Actual: " + trie.getMeaning("cope"));
System.out.println("Expected null, Actual: " + trie.getMeaning("co"));
trie.print();
trie.prune("cop");
System.out.println("Expected police, Actual: " +trie.getMeaning("cop"));
System.out.println("Expected null, Actual: " +trie.getMeaning("cope"));
trie.print();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T05:32:18.773",
"Id": "51117",
"Score": "0",
"body": "What is the code doing??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T07:06:48.157",
"Id": "51126",
"Score": "3",
"body": "It is hopefully being a Trie. One thing I would say right away is that using arrays is not common in modern java. Replace your arrays with more powerful data structures like lists or maps, or include comments on why you don't do that -- Maybe in this case it doesn't make sense, but explain so. Just noting that arrays are much less common now that java has generics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-11T13:18:06.810",
"Id": "150753",
"Score": "1",
"body": "I know that this post is old, but thought the feedback would still be useful. You should not be storing the word itself in the node, This goes against the structure of the Trie itself. The idea is that each node should hold a specific letter, and together the nodes chain to make a word."
}
] |
[
{
"body": "<p>The <code>TrieNode[] alphabets</code> can probably be changed to a <code>Map<Character, TrieNode></code>.</p>\n\n<p>This would have some important advantages: </p>\n\n<ul>\n<li>First, you would not consume all characters domain space (256 in your sample code) unless you actually have nodes defined for all of them. </li>\n<li>Second, if you use a HashMap or LinkedHashMap as implementation, the search algorithm is pretty fast, you won't have to iterate over the entire collection to find an element since the search is based on hashes. </li>\n<li>Third, it will make it simpler to improve your code when you want to support other languages out there using more than just 256 characters.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:47:07.460",
"Id": "32030",
"ParentId": "32010",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32030",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T04:08:30.757",
"Id": "32010",
"Score": "0",
"Tags": [
"java",
"algorithm",
"tree",
"trie"
],
"Title": "Trie - code review request for improvement"
}
|
32010
|
<p>I'm wondering what would be the best way to calculate the hashcode when the order of a sequence doesn't matter. Here's the custom <code>IEqualityComparer<T></code> i've implemented for an <a href="https://stackoverflow.com/a/19089162/284240">answer</a> on Stackoverflow.</p>
<pre><code>public class AccDocumentItemComparer : IEqualityComparer<AccDocumentItem>
{
public bool Equals(AccDocumentItem x, AccDocumentItem y)
{
if (x == null || y == null)
return false;
if (object.ReferenceEquals(x, y))
return true;
if (x.AccountId != y.AccountId)
return false;
return x.DocumentItemDetails.Select(d => d.DetailAccountId).OrderBy(i => i)
.SequenceEqual(y.DocumentItemDetails.Select(d => d.DetailAccountId).OrderBy(i => i));
}
public int GetHashCode(AccDocumentItem obj)
{
if (obj == null) return int.MinValue;
int hash = obj.AccountId.GetHashCode();
if (obj.DocumentItemDetails == null)
return hash;
int detailHash = 0;
unchecked
{
var orderedDetailIds = obj.DocumentItemDetails
.Select(d => d.DetailAccountId).OrderBy(i => i);
foreach (int detID in orderedDetailIds)
detailHash = 17 * detailHash + detID;
}
return hash + detailHash;
}
}
</code></pre>
<p>As you can see the <code>foreach</code> in <code>GetHashCode</code> needs to order the (nested) sequence before it starts calculating the hashcode. If the sequence is large this seems to be inefficient. Is there a better way to calculate the hashcode if the order of a sequence can be ignored? </p>
<p>Here are the simple classes involved:</p>
<pre><code>public class AccDocumentItem
{
public string AccountId { get; set; }
public List<AccDocumentItemDetail> DocumentItemDetails { get; set; }
}
public class AccDocumentItemDetail
{
public int LevelId { get; set; }
public int DetailAccountId { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:25:47.683",
"Id": "51141",
"Score": "0",
"body": "Why don't you simply assign a unique ID upon creation of an object and redefine 'equality' of two objects instead? Using the ID when the `GetHashCode` is called is efficient and in case you have to compare two objects for equal content, you can use your redefined 'Equals' method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:54:07.880",
"Id": "51147",
"Score": "0",
"body": "@alzaimar I think that most of the time, when you want some kind of value equality, you can't just use reference equality instead. For example, this could be used to detect changes in the object, but your solution wouldn't work for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T15:50:07.530",
"Id": "51173",
"Score": "0",
"body": "Correct, but if I want to detect changes, I would maintain a 'Modified' property instead of trying to find changes. If I want to compare two instances whether they contain the same data, I would write a method doing that etc. But I would *never* use 'GetHashCode' to detect changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:08:54.607",
"Id": "51174",
"Score": "0",
"body": "@alzaimar: I'm not sure if i've understood your suggestion. Of course using an `ID` is efficient. But the whole point of creating a custom `IEqualityComparer<T>` is to use it for the linq extension methods like `GroupBy`. And the requirement was to differentiate `ParentClass` objets with the `AccountId` **and** the nested `List<DetailClass>` and their `DetailAccountId`. So if the `AccountId` is equal **and all** of the `DetailAccountId`s(independent of the order), then both objects are equal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T17:31:46.243",
"Id": "51181",
"Score": "0",
"body": "Got it. Use any hash you like (addition, xor) and don't forget to fully compare if the hashes match, as they always is a chance for collisions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-01T22:24:01.030",
"Id": "302338",
"Score": "0",
"body": "The simplest solution is to get hashes of individual items and order them. You can then use any operation to calculate the resulting hash and the item order won't matter."
}
] |
[
{
"body": "<p>If the order does not matter, use an kommutative operator to combine the hashCodes of the elements.</p>\n\n<p>Possible candidates are:<br>\n<code>^</code> binary <code>xor</code> // <em>THIS WOULD BE MY CHOICE</em><br>\n<code>+</code> addition // problem may be the overflow<br>\n<code>*</code> multiplication // problem may be the overflow<br>\n<code>|</code> binary <code>or</code> // not recommended, because after some of this operations it is likely that all bits are set, so the same hashCode would appear for quite different instances) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:53:05.413",
"Id": "51137",
"Score": "1",
"body": "Thanks. However, Mr Skeet himself advise againt using `xor`: http://stackoverflow.com/a/263416/284240 The `sum` approach is problematic since `1 + 1` would be the same as `2`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:26:27.360",
"Id": "51142",
"Score": "0",
"body": "@Tim Schmelter: You will never be able to avoid the possibility of collisions. And it is also not necessary to try to. Only try to avoid too many collisions because it would decrease performance of e.g. HashHmap. But feel free to multiply the hashCode of each element by the same constant before applying the kommutative operator It will change nothing `17*1 + 17*1 == 17*2`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:35:05.587",
"Id": "51143",
"Score": "1",
"body": "@Tim Schmelter: If you want the `order of a sequence doesn't matter` feature, I cannot imagen an implementation not using an `kommutative operator`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:46:06.563",
"Id": "51145",
"Score": "0",
"body": "I don't want to avoid the possibility of collision entirely, but as good as (so it's fine to overflow with the possibility of collisions). The resulting distribution of the additive and multiplicative hashes and even the `xor` are just not good enough. But that's probably better than ordering the sequence first (so +1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:50:42.250",
"Id": "51146",
"Score": "2",
"body": "@TimSchmelter And half of the reason Skeet advises against XOR is because it's commutative. Normally, you don't want hash(x,y)==hash(y,x), but that's exactly what you're asking for. (The other half of his point still stands, though.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:58:48.910",
"Id": "51148",
"Score": "0",
"body": "@svick: You can avoid the other one `hashCode(x,x) == 0 == hash(y,y)` by using `+` or `*`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T11:07:55.283",
"Id": "51150",
"Score": "2",
"body": "@MrSmith42 `*` has a different (and possibly even worse) flaw: 0 * anything == 0. That's not hard to work around, but I think it's worth mentioning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T12:00:28.067",
"Id": "51153",
"Score": "0",
"body": "@svick: You could use `(x+4)*(y+4)*...` to avoid the `0` problem. Or simply add a condition and replace every `0` by any other constant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T12:51:20.103",
"Id": "51157",
"Score": "0",
"body": "@MrSmith42 I think the first solution wouldn't work: what if `x` was -4? But yeah, something like `x == 0 ? 1 : x` would work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:27:51.397",
"Id": "51160",
"Score": "0",
"body": "@svick: All the attemps would work, a `0` in the product would only result in a very likely collision and therefore in bad HashSet performance, but it would still work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T15:01:10.727",
"Id": "51170",
"Score": "0",
"body": "@MrSmith42: My question was not about _working_ approaches ( have already one) but to find the most efficient that produces as less as possible collisions. However, i assume that this is a case where collisions are unavoidable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T15:08:06.670",
"Id": "51171",
"Score": "0",
"body": "@Tim Schmelter: There is no solution with 'as less as possible collisions'. There will always be collisions and if you know nothing about the hashCodes of the elements you cannot avoid the possibility that there are only collisions. If you know something about the distribution of the hashCodes of the single elements or come characteristics they have, you might be able to use this knowledge to reduce collisions. You may implement some variations and profile how many collisions you get for your test data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-15T20:56:40.950",
"Id": "482192",
"Score": "0",
"body": "@MrSmith42, could you please update the answer so it suggests \"combine the results from multiple commutative hash functions\"?\nFor instance: compute xor (a), compute sum (b), compute product (c) of the input elements, then use (a*17+b)*17+c as the overall hash function for the unordered list. It is easy to implement, and it would avoid pitfalls of individual xor/sum/product hashes."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:44:00.413",
"Id": "32025",
"ParentId": "32024",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "32025",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T09:12:20.233",
"Id": "32024",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "Calculating GetHashCode efficiently with unordered list"
}
|
32024
|
<p>Here I want to lock when populating a particular cache object, without blocking other calls to the same method requesting <code>Foo</code>s for other <code>barId</code>s. I realise the <code>MemoryCache</code> will be thread safe, but if two or more concurrent calls come in it seems like it would be better if only one of them populates the cache and locks the others out while this is done.</p>
<pre><code>using System.Runtime.Caching;
using Microsoft.Practices.Unity;
public class FooCacheService : IFooService
{
private static readonly ConcurrentDictionary<string, object> FooServiceCacheLocks = new ConcurrentDictionary<string, object>();
[Dependency("Explicit")]
public IFooService ExplicitService { get; set; }
public IEnumerable<Foo> GetFoosForBar(int barId)
{
string key = barId.ToString();
object lockObject = FooServiceCacheLocks.GetOrAdd(key, new object());
object cached = MemoryCache.Default[key];
if (cached == null)
{
lock (lockObject)
{
cached = MemoryCache.Default[key];
if (cached == null)
{
IEnumerable<Foo> foosForBar = this.ExplicitService.GetFoosForBar(barId);
MemoryCache.Default.Add(key, foosForBar, DateTime.Now.AddMinutes(5));
return foosForBar;
}
}
}
return (IEnumerable<Foo>)cached;
}
}
</code></pre>
<p>Assume <code>GetFoosForBar</code> is a CPU/IO intensive process and takes a short while to complete. Does this seem like a reasonable way to achieve this? I'm surprised that <code>System.Runtime.Caching</code> does not provide any support for this as default - or have I overlooked something?</p>
|
[] |
[
{
"body": "<p>What I don't like about your approach is that the lock objects are never removed from <code>FooServiceCacheLocks</code>, even when the object is removed from the cache.</p>\n\n<p>One way to simplify your code would be to combine <code>MemoryCache</code> with <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\"><code>Lazy</code></a>: instances of <code>Lazy</code> are cheap (as long as you don't access its <code>Value</code>) so you can create more of them than needed. With that your code would look something like this:</p>\n\n<pre><code>public IEnumerable<Foo> GetFoosForBar(int barId)\n{\n var newLazy = new Lazy<IEnumerable<Foo>>(\n () => this.ExplicitService.GetFoosForBar(barId));\n\n var lazyFromCache = (Lazy<IEnumerable<Foo>>)MemoryCache.Default.AddOrGetExisting(\n barId.ToString(), newLazy, DateTime.Now.AddMinutes(5));\n\n return (lazyFromCache ?? newLazy).Value;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:38:52.417",
"Id": "51251",
"Score": "0",
"body": "Is the OP's locking approach (two null checks with a lock in the middle) poor or just out of favour? I am currently using that approach in my projects. I am aware of the Lazy class but do not know enough of it to use it in my work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T00:54:39.207",
"Id": "51270",
"Score": "0",
"body": "@pwee167 Like I said, the locking approach here means lock objects are never removed, which is basically a memory leak. And it's unnecessarily complicated. And I think that if you don't know enough about something interesting, that's a great opportunity to learn. You should probably start with the documentation, `Lazy` is actually not that complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T01:13:40.937",
"Id": "51272",
"Score": "0",
"body": "I am reading about the Lazy class as I am typing this! I understand your point regarding storing the locks in the ConcurrentDictionary FooServiceCacheLocks and then not removing them once the corresponding cache item being removed. What my question was in reference to the locking strategy there after, and whether that was sound in design. I.e. If I only had one lock to control access to a piece of code, would the double null check with a lock in between be still good?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T01:35:00.077",
"Id": "51273",
"Score": "0",
"body": "@pwee167 This is called double-checked locking and it can be tricky to get it right. If possible, just lock and then check; that's somewhat less efficient, but easier to get right. But I *think* the way it's used here is correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T10:04:44.727",
"Id": "51310",
"Score": "0",
"body": "Thanks, that's what I was missing: I wondered why you could pass a lambda expression to `ConcurrentDictionary`'s `GetOrAdd` method, but there was no equivalent for the `MemoryCache` object - didn't realise you could combine it with `Lazy`. There is one small amendment though to your code to make it work - from the MS docco: _Return value: If a cache entry with the same key exists, the existing cache entry; otherwise, null._ so you need `if (lazyFromCache == null) { return newLazy.value; }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T11:56:47.777",
"Id": "51316",
"Score": "0",
"body": "@SilverlightFox Really? That seems like bad design to me (especially since `ConcurrentDictionary.GetOrAdd()` behaves the “right” way. I fixed that more succinctly by using `??`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-15T23:55:53.083",
"Id": "52338",
"Score": "0",
"body": "@svick: The double checked lock is not correct. `cached` needs to be volatile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-16T01:00:51.403",
"Id": "52340",
"Score": "0",
"body": "@ChrisWue It can't be `volatile`, it's a local variable, not a field. I believe the reason for `volatile` does not apply here, because `MemoryCache` is already thread-safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-16T18:28:38.337",
"Id": "52409",
"Score": "0",
"body": "@svick: Hm true, I missed the second call to MemoryCache"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:01:49.573",
"Id": "32091",
"ParentId": "32026",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "32091",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:04:09.050",
"Id": "32026",
"Score": "7",
"Tags": [
"c#",
"locking",
"cache"
],
"Title": "Locking during cache population"
}
|
32026
|
<p>I have a data structure composed of several <code>std::lists</code>, each sorted by a specific criterion. When a new item is inserted into this data structure, there is a need for a reference item already in this data structure. Also all the items between the reference and insertee need to be collected into sets.</p>
<p>According to the profiler, this insertion is the bottleneck of the entire program. Here I present a simplified version of my insertion method.</p>
<p><img src="https://i.stack.imgur.com/Y6WLq.png" alt="enter image description here"></p>
<pre><code>upperReferenceSet_.clear();
lowerReferenceSet_.clear();
for (int objective = 0; objective < nObjectives_; ++objective)
{
const Real referenceValue = reference_->value(objective);
const Real inserteeValue = insertee_->value(objective);
const bool lower = referenceValue >= inserteeValue;
const int directionTowardsInsertee = lower ? -1 : 1;
Iterator it = referencePositions_[objective];
ReferenceSet& referenceSet = lower ? lowerReferenceSet_:
upperReferenceSet_;
const auto comparison = lower ? [](Real a, Real b){return a >= b;}:
[](Real a, Real b){return a <= b;};
while (comparison(it->value(), inserteeValue))
{
referenceSet.insert(it->individual());
std::advance(it, directionTowardsInsertee);
}
lists_[objective].insert(it, Node(insertee_, inserteeValue));
}
</code></pre>
<p>Each list is of type <code>std::list<Node></code> where the Node is defined by:</p>
<pre><code>class Node
{
public:
Node(Individual* ind, Real val) :individual_(ind),value_(val){}
const Individual* individual() const {return individual_;}
Real value() const {return value_;}
private:
Individual* const individual_;
const Real value_;
};
</code></pre>
<p>The <code>Individual</code> is an entity which has <code>n</code> values (objectives), where each value can be accessed by an <code>Individual::value(int index)</code> member function. There are <code>n</code> lists, each containing the same set of <code>Individuals</code>, each sorted by one objective (value). Also the objective pertaining to that list is cached in the node and can be accessed by the <code>Node::value()</code> member function.</p>
<p>I would like to ask how can I make this method faster. I suspect that there are three sources of slowness:</p>
<ol>
<li>The access to reference sets indirectly using a C++ reference.</li>
<li>The use of lambda functions which produce another indirection.</li>
<li>The use of <code>std::advance</code> just to perform one step.</li>
</ol>
<p>I am thinking of refactoring the function to pass the data structure <strong>in two passes</strong>, first for the upper reference sets and then for the lower ones. This would solve all three problems.</p>
<p>I am hesitating since it would result in some code duplicity. Also I am curious about any opinions on my theories and my code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:45:56.710",
"Id": "51177",
"Score": "0",
"body": "Ending your identifiers with `_` makes very unreadable `->` expressions..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T17:03:40.157",
"Id": "51178",
"Score": "0",
"body": "I am trying to follow a convention of ending the names of private members with an underscore. This is actually a Google coding guideline http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Variable_Names#Variable_Names and although it is arguably ugly and needs some getting used to, for me it actually improved readability. I should have mentioned that the function is a member."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T17:08:48.167",
"Id": "51179",
"Score": "0",
"body": "I see. Also, you should probably elaborate on what you're trying to accomplish, what `objectives` are, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:12:23.880",
"Id": "51186",
"Score": "0",
"body": "If you want to maintain sorted lists, consider using a skip list, heap, or tree instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T22:57:06.703",
"Id": "51198",
"Score": "1",
"body": "@MartinDrozdik: The google style guide for c++ is a know terrible style guide. Find a better one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T02:07:45.573",
"Id": "51203",
"Score": "0",
"body": "@LokiAstari This is interesting. I actually never questioned that guide. Could you provide some alternative? Do you use some predefined style guide?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T02:17:06.863",
"Id": "51205",
"Score": "0",
"body": "@200_success I think the linked list is the fastest solution in this case, since you know exactly the position where to insert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T04:06:10.073",
"Id": "51208",
"Score": "2",
"body": "@MartinDrozdik: [C++ Coding Standards: 101 Rules, Guidelines, and Best Practices](http://www.amazon.com/dp/B004ISL6I0/?tag=stackoverfl08-20) Every company you go to will have its own style guide and you must learn to adapt to the style of the company. Getting a change in a guide once is established is an uphill battle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:16:57.267",
"Id": "61508",
"Score": "0",
"body": "Lambdas are particularly good at being inlined by the compiler when they are not capturing any variables. I would be surprised if there were actually any indirection occurring where your lambdas are called at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:20:53.493",
"Id": "61509",
"Score": "1",
"body": "Consider passing the parameters to the lambdas by const & to avoid making copies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:24:57.483",
"Id": "61513",
"Score": "2",
"body": "Maybe consider using std::generate to build your reference set instead of your while loop. With full optimizations turned on in your compiler you might be able to get the loop unrolled a bit by using std::generate, and who knows, maybe that will give you a performance boost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:43:38.010",
"Id": "77815",
"Score": "1",
"body": "Your can replace `lists_[objective].insert(it, Node(insertee_, inserteeValue));` by `lists_[objective].emplace(it, insertee_, inserteeValue);`, but I doubt that you will have any relevant performance gain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T12:04:42.773",
"Id": "78514",
"Score": "0",
"body": "Replace your sorted lists by sorted arrays. Have those arrays actually bigger sized to avoid resizing them on each change. Your performances will skyrocket, not a single doubt."
}
] |
[
{
"body": "<p>I haven't tested this solution, but I believe that your code could be simplified by using a <code>reverse_iterator</code>.</p>\n\n<pre><code>upperReferenceSet_.clear();\nlowerReferenceSet_.clear();\nfor (int objective = 0; objective < nObjectives_; ++objective)\n{\n const Real referenceValue = reference_->value(objective);\n const Real inserteeValue = insertee_->value(objective);\n const bool lower = referenceValue >= inserteeValue;\n Iterator it = referencePositions_[objective];\n if (!lower)\n {\n it = std::reverse_iterator<Iterator>(it);\n }\n ReferenceSet& referenceSet = lower ? lowerReferenceSet_:\n upperReferenceSet_;\n\n do\n {\n referenceSet.insert(it->individual());\n } while (it++->value() != inserteeValue);\n\n lists_[objective].insert(--it, Node(insertee_, inserteeValue));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T08:49:30.957",
"Id": "45071",
"ParentId": "32027",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T11:16:10.607",
"Id": "32027",
"Score": "8",
"Tags": [
"c++",
"performance",
"c++11",
"linked-list",
"iteration"
],
"Title": "Optimizing iteration through linked lists"
}
|
32027
|
<p>I am a beginner in Digital Signal Processing and I was trying to compute and plot an autocorrelation.</p>
<p>I've wrote this piece of code:</p>
<pre><code>r = [zeros(2,1); y(1:98,1)];
r = r.*y;
</code></pre>
<p>and I wished to know if this is a valid way of computing an autocorrelation.</p>
|
[] |
[
{
"body": "<p>How about <code>xcorr(y)</code>? The <a href=\"http://www.mathworks.com/help/signal/ref/xcorr.html\" rel=\"nofollow\"><code>xcorr()</code></a> function is part of the Signal Processing Toolbox.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T13:48:42.947",
"Id": "51230",
"Score": "0",
"body": "I was trying to calculate by hand, actually."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T05:23:14.667",
"Id": "32053",
"ParentId": "32031",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Your code contains <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow\">magic numbers</a>, avoid them</li>\n<li>To calculate the autocorrelation, you do not add zeros. <code>y(1+lag:end).*y(1:end-lag)</code> would match the definition.</li>\n<li>Multiplying requires your data to be binary -1 or 1, not 0 or 1. I would use a version which processes logic arrays.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T22:03:12.160",
"Id": "36539",
"ParentId": "32031",
"Score": "2"
}
},
{
"body": "<p>Are you trying to calculate the correlation factor or the cross correlation function?<br>\nThe correlation factor is basically a normalized dot product of two vectors.<br>\nThe cross correlation could be calculated using the <code>conv</code> function (By flipping one of the vectors).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:04:08.213",
"Id": "47172",
"ParentId": "32031",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "36539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:57:53.333",
"Id": "32031",
"Score": "2",
"Tags": [
"matlab"
],
"Title": "Is this a valid way of computing autocorrelation?"
}
|
32031
|
<p>This is my simple Fibonacci implementation in CoffeeScript. What do you think? Using cache (<code>fibResults</code>), it's very very fast. </p>
<pre><code>fibResults = []
defaultMax = 1000
nrMax = defaultMax
fibonacci = (n) ->
return fibResults[n] if fibResults[n]
if n < 2
fibResults[n] = n
else
fibResults[n] = fibonacci(n - 1) + fibonacci(n - 2)
nrMax = process.argv[2] if process.argv[2]
console.log("#{i}: #{fibonacci(i)}") for i in [0..nrMax]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:29:53.913",
"Id": "51175",
"Score": "0",
"body": "what is the max number that you are wanting to go to? i remember when we did this in C# and it got pretty intense, but i think we were just doing it in VIsual Studio Debug. and it was simple and quick for the low numbers."
}
] |
[
{
"body": "<p>Something I noticed in your algorithm is that despite using memoization, you are still reassigning the Fibonnacci number into the array every time you calculate it. </p>\n\n<p>You could avoid reassigning by having a function like <code>computeIfAbsent</code> that determines if the Fibonacci for a given <code>n</code> has already been calculated, and if not, use the Fibonacci function to calculate it and put it into the array, but only this time.</p>\n\n<p>Also, we could avoid having to calculate the first two Fibonaccis by having them memoized from the start, and make the code fail for any index <code>n</code> smaller than 0.</p>\n\n<pre><code>memo = [0,1]\n\ncomputeIfAbsent = (n, f) ->\n fib = memo[n]\n if typeof fib is 'undefined'\n fib = f(n)\n memo[n] = fib\n fib\n\nfibonacci = (x) ->\n if x < 0 \n throw Error(\"Invalid index: \" + x)\n computeIfAbsent(x, (n) -> fibonacci(n-1) + fibonacci(n-2))\n\nconsole.log(\"#{i}: #{fibonacci(i)}\") for i in [0..79]\n</code></pre>\n\n<p>Still, you must be aware that this code will not detect arithmetic overflows. It might look like it is calculating it right, but in fact, the calculations could be wrong due to overflow. I think your version and mine start to produce invalid results around 79.</p>\n\n<p>You can check using a <a href=\"http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibCalcX.html\" rel=\"nofollow\">Fibonacci Calculator</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T06:56:27.763",
"Id": "51211",
"Score": "0",
"body": "I'm returning the value if it's already in array here `return fibResults[n] if fibResults[n]`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:51:07.903",
"Id": "32034",
"ParentId": "32032",
"Score": "1"
}
},
{
"body": "<p>Or you could do the golden ration hack ^_~ (in Javascript)</p>\n\n<pre><code>var M = Math\n , pow = M.pow\n , round = M.round\n , phi = (M.sqrt(5)+1)/2\n , phiAnd2 = phi +2\n ;\nfunction fib(n){\n return round(pow(phi,n)/phiAnd2)\n}\n</code></pre>\n\n<p>Though this is only value up to n=75 when fib(75) === 2111485077978050</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:22:12.820",
"Id": "32148",
"ParentId": "32032",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:54:39.310",
"Id": "32032",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"coffeescript",
"fibonacci-sequence"
],
"Title": "Fibonacci using cache"
}
|
32032
|
<p>By having two model classes <code>Conversation</code> and <code>Message</code>, what are the best practices to handle the next situation: A conversation listening for its messages <code>PropertyChanged</code> events and so being able to update itself.</p>
<ol>
<li>What are the best practices? </li>
<li>How can I improve this model design?</li>
<li>Is it going to generate memory leaks?</li>
</ol>
<p>code </p>
<pre><code>using SoftConsept.Collections;
public class Conversation
{
readonly SortedObservableCollection<Message> messages;
public Conversation ()
{
messages = new SortedObservableCollection<Message> ();
}
public void Add (Message message)
{
messages.Add (message);
message.PropertyChanged += HandleMessagePropertyChanged;
}
public void Remove (Message message)
{
message.PropertyChanged -= HandleMessagePropertyChanged;
messages.Remove (message);
}
public IList<Message> Messages ()
{
return messages.ToList ();
}
void HandleMessagePropertyChanged (object sender, PropertyChangedEventArgs e)
{
// Uptade omitted conversations properties using data from the updated message.
}
}
public class Message : INotifyPropertyChanged
{
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T06:58:59.743",
"Id": "51212",
"Score": "0",
"body": "Looks fine to me"
}
] |
[
{
"body": "<p>First of all, the Conversation class does not provide any events for chances, so nobody has a chance to get to know if something changes. This is already be implemented within an (Sorted)Observable collection, but unfortunately you publish this private field as <code>IList<Message></code> by the Message method. So the notification abilities of this collection can not be used. Furthermore methods should always be connected with a action, so <code>GetMessages()</code> would be a more suitable name. But the best way is to make it a property. </p>\n\n<pre><code>using SoftConsept.Collections;\n\npublic class Conversation : INotifyPropertyChanged\n{\n readonly SortedObservableCollection<Message> messages;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public Conversation ()\n {\n messages = new SortedObservableCollection<Message> ();\n }\n\n private DateTime _updateTime = DateTime.Now;\n public DateTime UpdateTime{\n get{ return _updateTime;}\n private set{\n UpdateTime = value;\n OnPropertyChanged(\"UpdateTime\");\n }\n }\n\n private void OnPropertyChanged(string propertyName){\n var handler = PropertyChanged;\n if(handler==null) return;\n handler(this, new PropertyChangedEventArgs(propertyName));\n }\n\n public void Add (Message message)\n {\n messages.Add (message);\n UpdateTime = DateTime.Now;\n message.PropertyChanged += OnMessagePropertyChanged;\n }\n\n private void OnMessagePropertyChanged(object sender, PropertyChangedEventArgs args)\n {\n UpdateTime = DateTime.Now;\n }\n\n public void Remove (Message message)\n {\n messages.Remove (message);\n UpdateTime = DateTime.Now;\n message.PropertyChanged -= OnMessagePropertyChanged;\n }\n\n public ObservableCollection<Message> Messages \n {\n get{ \n //I assume that SortedObservableCollection is subtype of ObservableCollection\n return messages;\n }\n }\n}\n\npublic class Message : INotifyPropertyChanged {}\n</code></pre>\n\n<p>So now some observer might register for changes in Messages (add, delete) and also for changes in the single Message instances. </p>\n\n<p>For more info, look at <a href=\"http://msdn.microsoft.com/en-us/library/ms743695.aspx\" rel=\"nofollow\">Microsoft documentation</a>:</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T12:19:42.990",
"Id": "51390",
"Score": "0",
"body": "I really appreciated your answer. But just another question. Supposing that the `Conversation` class implements `INotifyPropertyChanged` as well and have the `UpdatedDate` property. How would you update its `UpdatedDate` value whenever a new message was added/updated inside the `Messages` collection? Would your `Conversation` listen for `Messages` changes or would you create another controller object to sync a `Conversation` properties with its current `Messages` collection state?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T07:50:21.003",
"Id": "51666",
"Score": "0",
"body": "I recently changed the implementation to fulfill your requirements. Its basically the same, you already started with, but with the addition of setting the UpdateTime property manually, to invoke PropertyChangedEvent while adding and removing a message and also when something within the messages changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T12:02:28.003",
"Id": "51676",
"Score": "0",
"body": "Ok, thank @hichaeretaqua for your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T10:01:23.900",
"Id": "32059",
"ParentId": "32035",
"Score": "2"
}
},
{
"body": "<p>There are two possible memory leaks likely to occur. </p>\n\n<ul>\n<li>You should implement the <code>IDisposable</code> interface or provide an alternative way of deattaching an object from events subscribed to referenced dependencies and/or event listeners.</li>\n<li>You should let the container objects dealing with <code>Converstation</code> and <code>Message</code> instances handle the lifetime of these objects correctly.</li>\n</ul>\n\n<p><code>Conversation</code> could keep <code>Message</code> instances alive and vice versa.</p>\n\n<pre><code>public void Clear() \n{\n foreach (var message in messages) \n {\n message.PropertyChanged -= OnMessagePropertyChanged;\n }\n messages.Clear();\n}\n\npublic void Dispose()\n{\n // .. dispose pattern impl\n Clear();\n}\n</code></pre>\n\n<p><code>Message</code> could keep any listener alive and vice versa.</p>\n\n<pre><code>public void Reset() \n{\n PropertyChanged = null;\n}\n\npublic void Dispose()\n{\n // .. dispose pattern impl\n Reset();\n}\n</code></pre>\n\n<p>Consider using <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/weak-event-patterns\" rel=\"nofollow noreferrer\">Weak Event Pattern</a> if you don't want a strong reference between an object and its event listeners.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T03:34:28.823",
"Id": "222789",
"ParentId": "32035",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32059",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-09-30T17:50:47.850",
"Id": "32035",
"Score": "3",
"Tags": [
"c#",
"event-handling",
"collections"
],
"Title": "How to observe nested objects"
}
|
32035
|
<p>I'm a C++ programmer using <a href="http://www.spoj.com/" rel="nofollow">SPOJ</a> problems to learn C(99). This is my solution to the problem <a href="http://www.spoj.com/problems/CMEXPR/" rel="nofollow">CMEXPR</a>, where the goal is to read a valid expression (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> only) from input and write it on output with superfluous parentheses removed.</p>
<p>The code yields correct answer according to the online judge (got an <code>AC</code>). My question is whether there are any C++-isms in the code and if so, what would be a more idiomatic C way of expressing them. Basically, I don't want to write C++ code in C (just like I don't like C code written in C++).</p>
<pre><code>#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
//#define TESTING
#ifdef TESTING
#define TEST_ASSERT(maCond) do { if (!(maCond)) { printf("%d: %s\n", __LINE__, #maCond); exit(1); } } while (0)
#define TEST_ASSERT_MSG(maCond, maFormat, maMsg) \
do { \
if (!(maCond)) { printf("%d: %s: '" maFormat "'\n", __LINE__, #maCond, (maMsg)); exit(1); } \
} while (0)
#define IF_TESTING(...) __VA_ARGS__
#else
#define TEST_ASSERT(maCond) do {} while (0)
#define TEST_ASSERT_MSG(maCond, maFormat, maMsg) do {} while(0)
#define IF_TESTING(...)
#endif
enum ParsingContext
{
CONTEXT_FIRST_TERM
, CONTEXT_ADDITIVE_EXPRESSION
, CONTEXT_NONFIRST_TERM
};
struct ExprNode
{
char type;
struct ExprNode *child[2];
};
struct NodeMemory
{
struct ExprNode data[MAX_NODE_COUNT];
struct ExprNode *end;
};
struct ExprNode* createNode(struct NodeMemory *mem, char type)
{
struct ExprNode *node = mem->end++;
TEST_ASSERT(mem->end - mem->data <= MAX_NODE_COUNT);
node->type = type;
IF_TESTING(
node->child[0] = node->child[1] = NULL;
)
return node;
}
struct ExprNode* moveToChild(
struct NodeMemory * restrict mem
, struct ExprNode * restrict node
, size_t idxChild
, char newParentType
)
{
struct ExprNode * result = createNode(mem, newParentType);
result->child[idxChild] = node;
return result;
}
char readChar(const char * restrict * restrict in)
{
char c = **in;
++*in;
return c;
}
void writeChar(char * restrict * restrict out, char c)
{
**out = c;
++*out;
}
struct ExprNode* parse(
struct NodeMemory * restrict mem
, const char * restrict * restrict in
, struct ExprNode * restrict root
, enum ParsingContext context
)
{
TEST_ASSERT(root != NULL);
bool skipStart = (context == CONTEXT_NONFIRST_TERM);
// Left operand
if (!skipStart) {
switch (**in) {
case '(':
++*in;
root = parse(mem, in, root, CONTEXT_FIRST_TERM);
TEST_ASSERT_MSG(**in == ')', "%c", **in);
++*in;
break;
default:
TEST_ASSERT_MSG(
**in != ')'
&& **in != '+'
&& **in != '-'
&& **in != '*'
&& **in != '/'
&& **in != '\n'
, "%c", **in
);
root->type = readChar(in);
break;
}
}
for (;;) {
// Operator
if (!skipStart) {
switch (**in) {
case '\n':
case ')':
TEST_ASSERT(root != NULL);
TEST_ASSERT(root->type != '.');
return root;
case '+':
case '-':
if (context == CONTEXT_NONFIRST_TERM) {
TEST_ASSERT(root != NULL);
TEST_ASSERT(root->type != '.');
return root;
}
TEST_ASSERT(
(context == CONTEXT_ADDITIVE_EXPRESSION)
==
(root->type == '+' || root->type == '-')
);
context = CONTEXT_ADDITIVE_EXPRESSION;
root = moveToChild(mem, root, 0, readChar(in));
break;
case '*':
case '/':
if (context == CONTEXT_ADDITIVE_EXPRESSION) {
TEST_ASSERT(root->child[1]->type != '.');
root->child[1] = moveToChild(mem, root->child[1], 0, readChar(in));
root->child[1] = parse(mem, in, root->child[1], CONTEXT_NONFIRST_TERM);
continue; // Parsed up to next operator or teminator
}
root = moveToChild(mem, root, 0, readChar(in));
break;
default:
TEST_ASSERT(false);
break;
}
}
skipStart = false;
// Right operand
switch (**in) {
case '(':
++*in;
root->child[1] = parse(mem, in, createNode(mem, '.'), CONTEXT_FIRST_TERM);
TEST_ASSERT_MSG(**in == ')', "%c", **in);
++*in;
break;
default:
TEST_ASSERT_MSG(
**in != ')'
&& **in != '+'
&& **in != '-'
&& **in != '*'
&& **in != '/'
&& **in != '\n'
, "%c", **in
);
root->child[1] = createNode(mem, readChar(in));
break;
}
}
}
void serialiseTree(const struct ExprNode * restrict node, char * restrict * restrict out, char parentType, bool isLeftChild)
{
IF_TESTING(
if (!node) {
writeChar(out, 'N');
return;
}
)
TEST_ASSERT(
parentType == '+'
|| parentType == '-'
|| parentType == '*'
|| parentType == '/'
);
bool paren = false;
switch (node->type) {
case '+':
case '-':
paren = (
parentType == '*'
|| parentType == '/'
|| (parentType == '-' && !isLeftChild)
);
break;
case '*':
case '/':
paren = (parentType == '/' && !isLeftChild);
break;
default:
writeChar(out, node->type);
return;
}
if (paren) {
writeChar(out, '(');
}
serialiseTree(node->child[0], out, node->type, true);
writeChar(out, node->type);
serialiseTree(node->child[1], out, node->type, false);
if (paren) {
writeChar(out, ')');
}
}
void createTree(struct NodeMemory *mem)
{
char expr[MAX_INPUT_SIZE + 2];
fgets(expr, sizeof(expr), stdin);
const char *in = expr;
if (*in == '\n') {
fputs(expr, stdout);
return;
}
struct ExprNode *root = parse(mem, &in, createNode(mem, '.'), CONTEXT_FIRST_TERM);
TEST_ASSERT(*in == '\n');
TEST_ASSERT(root != NULL);
char *out = expr;
serialiseTree(root, &out, '+', true);
*out++ = '\n';
*out = 0;
TEST_ASSERT(out - expr < sizeof(expr));
fputs(expr, stdout);
}
void runCase(void)
{
struct NodeMemory mem;
mem.end = mem.data;
createTree(&mem);
}
int main(void) {
int caseCount;
fscanf(stdin, "%d\n", &caseCount);
for (int idxCase = 0; idxCase < caseCount; ++idxCase) {
runCase();
}
return 0;
}
</code></pre>
<p>Notes:</p>
<ul>
<li><p>I use <a href="http://ideone.com/grzWm1" rel="nofollow">ideone</a> for developing this code, so that's why I'm using my own assertions instead of built-in <code>assert()</code>; an "unusual termination" wouldn't be too helpful.</p></li>
<li><p>There's no error checking on input because in the context of the online judge, input correctness is guaranteed.</p></li>
<li><p><code>NodeMemory</code> is used to avoid overhead of dynamic allocation in presence of a known maximum problem size.</p></li>
</ul>
|
[] |
[
{
"body": "<p>These comments are not really related to writing \"idiomatic C\", merely things I noticed in your code.</p>\n\n<ul>\n<li><p>Your handling of commas in lists is odd:</p>\n\n<pre><code>enum ParsingContext {\n CONTEXT_FIRST_TERM\n , CONTEXT_ADDITIVE_EXPRESSION\n , CONTEXT_NONFIRST_TERM\n};\n\nstruct ExprNode* moveToChild(\n struct NodeMemory * restrict mem\n , struct ExprNode * restrict node\n , size_t idxChild\n , char newParentType\n )\n</code></pre>\n\n<p>I have never seen things written like that and don't see any advantage\nover the normal use:</p>\n\n<pre><code>enum ParsingContext {\n CONTEXT_FIRST_TERM,\n CONTEXT_ADDITIVE_EXPRESSION,\n CONTEXT_NONFIRST_TERM\n};\n\nstruct ExprNode* moveToChild(struct NodeMemory * restrict mem,\n struct ExprNode * restrict node,\n size_t idxChild,\n char newParentType)\n</code></pre></li>\n<li><p>Your macros and their invocation should allow a semicolon to be placed where\nexpected. Otherwise, syntax-aware editors can get confused and mess up the\nindentation: </p>\n\n<pre><code> IF_TESTING(\n node->child[0] = node->child[1] = NULL;\n )\n return node;\n</code></pre>\n\n<p>Better to move the ; out of the bracket:</p>\n\n<pre><code> IF_TESTING((node->child[0] = node->child[1] = NULL));\n return node;\n</code></pre></li>\n<li><p>Your asserts that check against a list of chars could be simpler with\n<code>strchr</code> (also I find the placement of the && here to be distracting, but I\nknow some people like it that way):</p>\n\n<pre><code>TEST_ASSERT_MSG(\n **in != ')'\n && **in != '+'\n && **in != '-'\n && **in != '*'\n && **in != '/'\n && **in != '\\n'\n , \"%c\", **in\n );\n</code></pre>\n\n<p>Neater (?):</p>\n\n<pre><code>TEST_ASSERT_MSG(!strchr(\")+-*/\\n\", **in), \"%c\", **in);\n</code></pre></li>\n<li><p>I always find passing double pointers to be awkward and confusing, so I\navoid it if possible. In this case it seems that you could read and write\nthe input/output string directly to/from stdin/out as you go, replace\n<code>readChar</code> and <code>writeChar</code> with <code>fgetc</code> and <code>fputc</code> and pass\n<code>stdin</code>/<code>stdout</code> around in instead of <code>in</code> and <code>out</code> (or just use the\n<code>stdin</code>/<code>stdout</code> globals).</p></li>\n<li><p>Note that using an <code>assert</code> to check for exceeding the available memory is\nincorrect. This should be an explicit <code>if</code> and <code>exit</code>.</p>\n\n<pre><code>TEST_ASSERT(mem->end - mem->data <= MAX_NODE_COUNT);\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:53:14.867",
"Id": "51363",
"Score": "0",
"body": "+1, thanks. Nice use of `strchr()`, wouldn't have thought about that. The out-of-memory assert is due to the SPOJ specifics - I know the maximum input size, so running out of space can only be a bug in the algorithm. As for the `,` and `&&`, I find list modifications usually happen at the end more than at the beginning, and this placement makes the last line syntax non-special."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:53:47.330",
"Id": "51364",
"Score": "0",
"body": "About per-character input; wouldn't that be noticably slower than reading the string at once and then parsing it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T22:26:10.367",
"Id": "51370",
"Score": "0",
"body": "With your `,` and `&&` isn't the first line syntax now \"special\" (ie. it doesn't have a `,` etc)? Per-char reading speed noticeable to whom? Unless you are operating on really huge input strings I doubt the speed difference will be noticeable to a user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T07:01:34.567",
"Id": "51380",
"Score": "0",
"body": "Yes, the first line is special. But as I said, experience tells me one modifies a list's end more often than its beginning (adding params etc.). Per-char: it's true that on 250-char strings (even if there are tens of thousands of them), I was probably overly cautious. Thanks again."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T16:03:36.207",
"Id": "32075",
"ParentId": "32040",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:10:40.957",
"Id": "32040",
"Score": "4",
"Tags": [
"c",
"parsing"
],
"Title": "Parsing expressions using idiomatic C"
}
|
32040
|
<p>This is pretty much an OOP version of <a href="https://codereview.stackexchange.com/questions/31817/python-game-of-life">this question</a>, with the improvements:</p>
<pre><code>import copy
import shelve
class GameOfLife(object):
def __init__(self, board, generations = 10):
self.__board = board
for i in range(generations):
print(self)
self.__nextGeneration()
def __str__(self):
string = ""
for row in self.__board:
for cell in row:
if cell:
string += "#"
else:
string += "."
string += "\n"
return string
def __isInRange(self, row, cell):
return 0 <= row < len(self.__board) and \
0 <= cell < len(self.__board[0])
def __countSurrounding(self, row, cell):
SURROUNDING = ((row - 1, cell - 1),
(row - 1, cell ),
(row - 1, cell + 1),
(row , cell - 1),
(row , cell + 1),
(row + 1, cell - 1),
(row + 1, cell ),
(row + 1, cell + 1))
count = 0
for surrRow, surrCell in SURROUNDING:
if self.__isInRange(surrRow, surrCell) and \
self.__board[surrRow][surrCell]:
count += 1
return count
def __nextGeneration(self):
nextBoard = copy.deepcopy(self.__board)
for row in range(len(self.__board)):
for cell in range(len(self.__board[0])):
if self.__board[row][cell] and \
self.__countSurrounding(row, cell) not in (2, 3):
nextBoard[row][cell] = 0
elif not self.__board[row][cell] and \
self.__countSurrounding(row, cell) == 3:
nextBoard[row][cell] = 1
self.__board = nextBoard
def main():
boardFile = shelve.open("boardFile.dat")
board = boardFile["board"]
game = GameOfLife(board)
if __name__ == "__main__":
main()
</code></pre>
<p>Where <code>boardFile.dat</code> is just a shelved file containing a boolean array.</p>
<p>Can anyone provide an honest code review?
Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:57:10.390",
"Id": "51193",
"Score": "0",
"body": "To create a board… `import shelve; b = [[False] * 15] * 15 ; b[7][7] = True ; shelve.open('boardfile.dat')['board'] = b`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T22:03:49.963",
"Id": "51195",
"Score": "0",
"body": "Sections 2 to 5 of [my answer to your previous question](http://codereview.stackexchange.com/a/31952/11728) apply to this question too."
}
] |
[
{
"body": "<p>This looks good. Here are a few (untested) comments.</p>\n\n<ul>\n<li>Your <code>__str__</code> method could take advantage of ternary operator, list comprehension and the join method :</li>\n</ul>\n\n<p>This :</p>\n\n<pre><code>def __str__(self):\n string = \"\"\n for row in self.__board:\n for cell in row:\n if cell:\n string += \"#\"\n else:\n string += \".\"\n string += \"\\n\"\n return string\n</code></pre>\n\n<p>becomes this, </p>\n\n<pre><code>def __str__(self):\n string = \"\"\n for row in self.__board:\n for cell in row:\n string += \"#\" if cell else \".\"\n string += \"\\n\"\n return string\n</code></pre>\n\n<p>this :</p>\n\n<pre><code>def __str__(self):\n string = \"\"\n for row in self.__board:\n string += \"\".join([\"#\" if cell else \".\" for cell in row])\n string += \"\\n\"\n return string\n</code></pre>\n\n<p>and ultimately this :</p>\n\n<pre><code>def __str__(self):\n return \"\\n\".join([\"\".join([\"#\" if cell else \".\" for cell in row]) for row in self.__board])\n</code></pre>\n\n<ul>\n<li>Don't iterate using <code>range(len(list))</code>, use <code>enumerate</code>.</li>\n</ul>\n\n<p>For example :</p>\n\n<pre><code>for i,row in enumerate(self.__board):\n for j,cell in enumerate(row):\n if cell:\n if self.__countSurrounding(i, j) not in (2, 3):\n nextBoard[i][j] = 0\n else:\n if self.__countSurrounding(i, j) == 3:\n nextBoard[i][j] = 1\n</code></pre>\n\n<ul>\n<li>You could define <code>SURROUNDING</code> as a constant expression.</li>\n</ul>\n\n<p>You just need to a bit of the code using it.</p>\n\n<pre><code> SURROUNDING = ((-1, -1),\n (-1, 0),\n (-1, +1),\n ( 0, -1),\n ( 0, +1),\n (+1, -1),\n (+1, 0),\n (+1, +1))\n count = 0\n for x,y in SURROUNDING:\n i,j = row+x, cell+y\n if self.__isInRange(i,j) and \\\n self.__board[i][j]:\n count += 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:49:55.190",
"Id": "32045",
"ParentId": "32044",
"Score": "1"
}
},
{
"body": "<h1>Object-Orientedness</h1>\n\n<p>I find your object-oriented design deficient. Basically, it's a bunch of procedural code that has been thrown into a class. But what can you do with the <code>GameOfLife</code> object that you instantiate? Nothing!</p>\n\n<p>I would split the functionality into a <code>Board</code> class and a <code>GameOfLife</code> class. The <code>Board</code> should be able to provide its own string representation, report the contents of a cell, set the contents of a cell, check if a coordinate exists, clone itself, and perhaps load from or save to a file. The <code>GameOfLife</code> class would be a <a href=\"http://docs.python.org/2/library/stdtypes.html#generator-types\" rel=\"nofollow noreferrer\">generator</a>; each time you call <code>life.next()</code> it would produce a new board.</p>\n\n<p>Your <code>main()</code> function should look like this:</p>\n\n<pre><code>board = Board.load('boardFile.dat')\ngame = GameOfLifeGenerator(board)\nfor _ in range(11):\n print(board)\n board = game.next()\n</code></pre>\n\n<p>Alternatively,</p>\n\n<pre><code>from itertools import islice\n\nboard = Board(15)\nboard.fill(row=7, col=7)\nfor state in islice(GameOfLifeGenerator(board), 11):\n print(state)\n</code></pre>\n\n<h1>Naming</h1>\n\n<p>You shouldn't be using <a href=\"https://stackoverflow.com/q/1301346\">double-underscore</a> variables. If you want to suggest that an instance variable is private, use a name with a single underscore.</p>\n\n<p>You use <code>cell</code> to mean column number, which is confusing terminology. A \"cell\" should refer to one of the points on the grid; a cell has <code>row</code> and <code>column</code> coordinates. (In contrast, I don't object as much to using <code>row</code> as shorthand for the coordinate of a row. English is just weird that way.)</p>\n\n<p>In <code>__countSurrounding()</code>, the <code>SURROUNDING</code> list shouldn't be all caps. I'd consider that to be a variable rather than a constant. (You <em>could</em> define it as <code>SURROUNDING_OFFSETS = ((-1, -1), (-1, 0), ...)</code> instead, which <em>would</em> be a constant.) Also consider laying out the code this way for quick visualization:</p>\n\n<pre><code>surrounding = ((row - 1, col - 1), (row - 1, col), (row - 1, col + 1),\n (row , col - 1), (row , col + 1),\n (row + 1, col - 1), (row + 1, col), (row + 1, col + 1))\n</code></pre>\n\n<h1>Miscellaneous</h1>\n\n<p>In <code>__isInRange()</code> and <code>__nextGeneration()</code>, you use <code>len(__board[0])</code> as the width. I would prefer that you use <code>len(__board(row))</code> instead.</p>\n\n<p>The <code>__str__()</code> function could be implemented more succinctly as</p>\n\n<pre><code>def __str__(self):\n return \"\\n\".join(\n [''.join(\n ['#' if cell else '.' for cell in row]\n ) for row in self._board]\n ) + \"\\n\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>def __str__(self):\n return \"\\n\".join(\n map(lambda row: ''.join(\n map(lambda cell: '#' if cell else '.', row)\n ), self._board)\n ) + \"\\n\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T12:20:11.647",
"Id": "51224",
"Score": "1",
"body": "Shouldn't it be `'#' if col else '.'` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T22:50:35.143",
"Id": "32046",
"ParentId": "32044",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:24:24.487",
"Id": "32044",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"game-of-life"
],
"Title": "Game Of Life OOP Python"
}
|
32044
|
<p>I have a <code>ByteArray</code> value as <code>avroBinaryValue</code> , <code>Schema Id</code> value as <code>short</code> <code>schemaId</code> and <code>Last Modified Date</code> value as <code>lastModifiedDate</code> in <code>long</code>.</p>
<pre><code>short schemaId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] avroBinaryValue = os.toByteArray();
</code></pre>
<p>Now, I will write <code>schemaId</code> , <code>lastModifiedDate</code> and <code>avroBinaryValue</code> together into a single <code>ByteArray</code> and then deserialize that final <code>ByteArray</code> value to extract <code>schemaId</code> , <code>lastModifiedDate</code> and <code>avroBinaryValue</code> from it.</p>
<p>Below is the code, I have got so far...</p>
<pre><code>public static void main(String[] args) throws Exception {
String os = "whatever os is";
byte[] avroBinaryValue = os.getBytes();
long lastModifiedDate = 1379811105109L;
short schemaId = 32767;
ByteArrayOutputStream byteOsTest = new ByteArrayOutputStream();
DataOutputStream outTest = new DataOutputStream(byteOsTest);
outTest.writeShort(schemaId); // first write schemaId
outTest.writeLong(lastModifiedDate); // second lastModifiedDate
outTest.writeInt(avroBinaryValue.length); // then attributeLength
outTest.write(avroBinaryValue); // then its value
byte[] allWrittenBytesTest = byteOsTest.toByteArray();
DataInputStream inTest = new DataInputStream(new ByteArrayInputStream(allWrittenBytesTest));
short schemaIdTest = inTest.readShort();
long lastModifiedDateTest = inTest.readLong();
int sizeAvroTest = inTest.readInt();
byte[] avroBinaryValue1 = new byte[sizeAvroTest];
inTest.read(avroBinaryValue1, 0, sizeAvroTest);
System.out.println(schemaIdTest);
System.out.println(lastModifiedDateTest);
System.out.println(new String(avroBinaryValue1));
writeFile(allWrittenBytesTest);
}
</code></pre>
<p>I am trying to see whether there is any efficient way of doing this in Java or this is the only correct way of doing it in Java?</p>
<p>The way I am serializing all the three ByteArrays into one ByteArray and the way I am deserializing the resulting ByteArrays to extract the <code>schemaId</code>, <code>lastModifiedDate</code>, <code>avroBinaryValue</code> looks correct or not?</p>
|
[] |
[
{
"body": "<p>The way you are doing it is fine, however it seems like a better idea to just put all of the data you want to serialize into a <code>Serializable</code> object and then just serialize that automatically. For example you could do something like : </p>\n\n<pre><code>public static void main(String[] args) throws IOException,\n ClassNotFoundException {\n String os = \"whatever os is\";\n long lastModifiedDate = 1379811105109L;\n short schemaId = 32767;\n Thing myData = new Thing(os, lastModifiedDate, schemaId);\n\n ByteArrayOutputStream byteOsTest = new ByteArrayOutputStream();\n ObjectOutputStream outTest = new ObjectOutputStream(byteOsTest);\n outTest.writeObject(myData);\n\n byte[] allWrittenBytesTest = byteOsTest.toByteArray();\n\n ObjectInputStream inTest = new ObjectInputStream(new ByteArrayInputStream(\n allWrittenBytesTest));\n Thing myDataTest = (Thing) inTest.readObject();\n\n short schemaIdTest = myDataTest.getSchemaId();\n long lastModifiedDateTest = myDataTest.getLastModifiedDate();\n String avro = myDataTest.getAvro();\n\n System.out.println(schemaIdTest);\n System.out.println(lastModifiedDateTest);\n System.out.println(avro);\n\n writeFile(allWrittenBytesTest);\n}\n\n// in its own java file\npublic final class Thing implements Serializable {\n\n private final String avro;\n\n private final long lastModifiedDate;\n\n private final short schemaId;\n\n public Thing(String avro, long lastModifiedDate, short schemaId) {\n this.avro = avro;\n this.lastModifiedDate = lastModifiedDate;\n this.schemaId = schemaId;\n }\n\n public String getAvro() {\n return avro;\n }\n\n public long getLastModifiedDate() {\n return lastModifiedDate;\n }\n\n public short getSchemaId() {\n return schemaId;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T03:12:59.380",
"Id": "51274",
"Score": "0",
"body": "The only problem with using Java serialization is that it wouldn't contain a \"pure\" representation - it would also contain the class, field, and serial version information. But I agree it's a good method if you just want to transport that data from Java-Java.You could implement `Externalizable`, though and achieve a pure data representation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T15:48:02.210",
"Id": "32074",
"ParentId": "32048",
"Score": "1"
}
},
{
"body": "<p>Instead of writing them to a byte array first, why not just write them directly to the file?</p>\n\n<pre><code>public void writeInfo(final OutputStream fileStream) throws IOException {\n final DataOutputStream data = new DataOutputStream(fileStream);\n data.writeShort(schemaId);\n data.writeLong(lastModifiedDate);\n data.writeInt(avroBinary.length);\n data.write(avroBinaryValue);\n data.flush();\n // if it's okay to close the underlying stream:\n data.close();\n}\n</code></pre>\n\n<p>Of course, the method <em>names</em> the stream a <code>fileStream</code>, but really it's just an untyped <code>OutputStream</code> (to write directly to a file pass in a <code>FileOutputStream</code>). This is also testable since you can still pass in a <code>ByteArrayOutputStream</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T03:24:08.237",
"Id": "32105",
"ParentId": "32048",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "32074",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T01:06:42.437",
"Id": "32048",
"Score": "1",
"Tags": [
"java"
],
"Title": "Merge three ByteArrays together and then split resulting ByteArrays"
}
|
32048
|
<p>I have been working a number pyramid program. This is a question from Y. Daniel Laing's <em>Introduction to programming using Python</em> (which is based on Python 3.2). The question is from chapter 5, and it is number 5.19 in programming exercises portion of the chapter. The question is stated as follows:</p>
<blockquote>
<p>Write a program that prompts the user to enter an integer from 1 to 15
and displays it as the following sample run:</p>
</blockquote>
<p>I don't have the image, but it is something like this:</p>
<blockquote>
<p>Enter the number of lines: 3</p>
<pre><code> 1
2 1 2
3 2 1 2 3
</code></pre>
</blockquote>
<p>The solution I have come up with is this:</p>
<pre><code>p = eval(input("Enter the number of lines: "))
num = 0
y = 1
while num < p:
y = num
line = str(y+1) + " "
while y >= 1:
y -= 1
line += str(y+1) + " "
while y < num:
line += str(y + 2) + " "
y +=1
print(format(line, "^80s"))
num +=1
</code></pre>
<p>If anyone has a better solution that would be simpler, please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T06:44:58.160",
"Id": "51210",
"Score": "2",
"body": "But that's not a working code at all. It will just get infinitely stuck at the first loop."
}
] |
[
{
"body": "<p>This feels like a C program. Python can be a lot more compact, and more importantly, expressive. The key is to think at a higher level than a few characters at a time. List comprehensions help a lot.</p>\n\n<p>Each row consists of a countdown, a \"1\" in the middle, then an ascending count. Let's work on the right half first. We can generate the ascending count using <code>range()</code>. We have to format them all into a fixed width column. Then we concatenate the mirror-image of the right half, the middle \"1\", and the right half.</p>\n\n<pre><code>def pyramid(height):\n FMT = '%3s'\n def row(r):\n right_half = [FMT % num for num in range(2, 2 + r)] + \\\n [FMT % ' ' for spc in range(2 + r, 1 + height)]\n return ''.join(list(reversed(right_half)) + # Mirrored right half\n [FMT % 1] + # Center\n right_half) # Right half\n return \"\\n\".join([row(r) for r in range(height)])\n\nprint(pyramid(p))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T13:54:53.433",
"Id": "51393",
"Score": "0",
"body": "Wow Half of what you guys just wrote we haven't even touched on, I really think they should reconstruct this book because I am finding that a lot of the higher functions can be used in these exercises and yet they haven't even mentioned them, as for the formatting yeah this book only gives about 5 options."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T04:04:46.037",
"Id": "32052",
"ParentId": "32050",
"Score": "1"
}
},
{
"body": "<p>Like <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">200_success</a> said, the key is in thinking at the higher level. But I think his approach can be simplified.</p>\n\n<p>Lets first define a <code>row</code> function, which simply calculates a list of numbers in an <em>n</em>'th row of our output:</p>\n\n<pre><code># When n=3, returns [3, 2, 1, 2, 3]\ndef row(n):\n return list(reversed(range(2, n+1))) + list(range(1, n+1))\n</code></pre>\n\n<p>And now we can use this to print out the lines:</p>\n\n<pre><code>for n in range(1, 5):\n print(row(n))\n</code></pre>\n\n<p>Giving us the following output:</p>\n\n<pre><code>[1]\n[2, 1, 2]\n[3, 2, 1, 2, 3]\n[4, 3, 2, 1, 2, 3, 4]\n</code></pre>\n\n<p>The core of the problem is now solved. The only thing left is formatting. For this we can write another function, which formats each number in list into a three-character box (with <code>\"%3s\"</code>), and also appends a certain amount of padding to make sure lines are aligned like a pyramid:</p>\n\n<pre><code>def formatted_row(n, num_rows):\n padding = ' ' * (num_rows-n)\n return padding + ''.join([\"%3s\" % x for x in row(n)])\n</code></pre>\n\n<p>Now we're almost there. Just need to tie it all together:</p>\n\n<pre><code># When n=3, returns [3, 2, 1, 2, 3]\ndef row(n):\n return list(reversed(range(2, n+1))) + list(range(1, n+1))\n\ndef formatted_row(n, num_rows):\n padding = ' ' * (num_rows-n)\n return padding + ''.join([\"%3s\" % x for x in row(n)])\n\nnum_lines = eval(input(\"Enter the number of lines: \"))\nfor n in range(1, num_lines+1):\n print(formatted_row(n, num_lines))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T07:36:41.400",
"Id": "32055",
"ParentId": "32050",
"Score": "4"
}
},
{
"body": "<p>Another high-level of thinking about pyramid is as of matrix:</p>\n\n<pre><code>f(1, -n) f(1, -n+1) ... f(1, -1) f(1, 0) f(1, 1) ... f(1, n)\nf(2, -n) ... f(2, -1) f(2, 0) f(2, 1) ... f(2, n)\n... ... ...\nf(n, -n) ... f(n, 0) ... f(n, n)\n</code></pre>\n\n<p>Where some of <code>f(x, y)</code> is numbers and some are just spaces. Note, how I chose to index columns from <code>-n</code> to <code>n</code> instead of from <code>0</code>, this will make our code simpler. Given all that, it's trivial to write <code>f()</code>:</p>\n\n<pre><code>def f(line, place):\n # number is just an offset from center + 1\n number = abs(place) + 1\n # don't display numbers greater than line number\n return str(number) if number <= line else ' '\n</code></pre>\n\n<p>Now we only need to go for all lines from 1 to pyramid height and display a row of <code>f()</code> values joined with <code>' '</code>:</p>\n\n<pre><code>def pyramid(height):\n # same indexes for each line, so we'll reuse them\n places = range(-height+1, height)\n for line in range(1, height+1):\n print ' '.join(f(line, place) for place in places)\n</code></pre>\n\n<p>As an added bonus we can trivially prevent pyramid from skewing for numbers > 9 by changing last line in <code>f()</code> to:</p>\n\n<pre><code> return str(number) if number <= line else ' ' * len(str(number))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-16T05:52:57.433",
"Id": "80649",
"ParentId": "32050",
"Score": "2"
}
},
{
"body": "<p>Agree, the first block definitely puts you in an infinite loop. Also the three while loops don't make it clear what you are doing - better to break up the padding from the pyramid construction.</p>\n\n<p>I'm also working from Yang's book. This challenge in Ch.5 assumes no knowledge of functions but the above got me close to a solution with this:</p>\n\n<pre><code>lines = input(\"enter the number of lines\")\n\nlines = int(lines)\n\ncount = 1\n\n\n\nwhile count < lines+1:\n\n padding = ' '*(lines-count)\n\n digits = list(range(1,count+1))\n\n\n output = padding + str(digits[::-1]) + str(digits[1:])\n print(output)\n count+=1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T07:40:21.287",
"Id": "324339",
"Score": "0",
"body": "Welcome to Code Review! A good answer should be about the code in the question. Please explain what you did differently and why it is better than the posted code. See also [answer]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T12:02:18.003",
"Id": "324386",
"Score": "0",
"body": "We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T06:46:20.680",
"Id": "171183",
"ParentId": "32050",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T01:30:08.340",
"Id": "32050",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"ascii-art"
],
"Title": "Building a number pyramid"
}
|
32050
|
<p>I am working on a bigger project and want to separate game updates from rendering and not end up with a super complicated game loop. So I came up with the idea of isolating the problem and writing a controller for this. My game loop looks like:</p>
<pre><code>public class Game {
public bool Running;
public void Loop()
{
var update = new FrameController(10, 30, true, Update);
var render = new FrameController(1, 1000, false, Render);
while (Running)
{
update.TryFrame();
render.TryFrame();
}
}
public void Update(double delta_time)
{
[...]
}
public void Render(double delta_time)
{
[...]
}
}
</code></pre>
<p>And my tick/frame controller looks like:</p>
<pre><code>public class FrameController
{
protected double DeltaTime;
protected readonly double MaxDeltaTime;
protected readonly double MinDeltaTime;
protected readonly bool SlowCatchUp;
protected readonly Action<double> Action;
protected readonly Stopwatch Watch;
public FrameController(int min_fps, int max_fps, bool slow_catch_up, Action<double> action)
: this(slow_catch_up, action)
{
MaxDeltaTime = 1.0 / min_fps;
MinDeltaTime = 1.0 / max_fps;
}
public FrameController(double min_delta_time, double max_delta_time, bool slow_catch_up, Action<double> action)
: this(slow_catch_up, action)
{
MaxDeltaTime = min_delta_time;
MinDeltaTime = max_delta_time;
}
protected FrameController(bool slow_catch_up, Action<double> action)
{
SlowCatchUp = slow_catch_up;
Action = action;
Watch = new Stopwatch();
Watch.Start();
}
public void TryFrame()
{
var delta_time = Watch.Elapsed.TotalSeconds;
Watch.Restart();
DeltaTime += delta_time;
if (DeltaTime <= MinDeltaTime)
// Skip
return;
else if (DeltaTime >= MaxDeltaTime)
DoFrame(SlowCatchUp ? MaxDeltaTime : DeltaTime);
else
DoFrame(DeltaTime);
}
protected void DoFrame(double delta_time)
{
Action(delta_time);
DeltaTime -= delta_time;
}
}
</code></pre>
<p>The updates will fire 10 to 30 times per second and if the game hangs they will slowly catch up to the current state. Apart from this the rendering will fire 1 to 1000 times per second (just for testing) and if the game hangs they will catch up immediately. If the game is running to fast frame will be skipped.</p>
<p>Any input and critique is welcome!</p>
|
[] |
[
{
"body": "<p>I think sourcing the game-loop out is basically a good idea to improve separation of concerns. But I would go farther: I would implement a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a> which makes the behavior of the game loop exchangeable. Futhermore I would source out the loop itself, too.</p>\n\n<pre><code>public interface IGameLoop{\n void Start();\n void Stop();\n}\npublic interface IUpdateBahvior\n{\n bool TryUpdate();\n}\npublic interface IRenderBehavior\n{\n bool TryRender();\n}\n</code></pre>\n\n<p>Example implementation: </p>\n\n<pre><code>class SynchronGameLoop : IGameLoop\n{\n private bool _isRunning;\n private readonly IUpdateBehavior _updateBehavior;\n private readonly IRenderBehavior _renderBehavior;\n\n public SynchronGameLoop(IUpdateBehavior updateBehavior, IRenderBehavior renderBehavior){\n _updateBehavior = updateBehavior;\n _renderBehavior = IRenderBehavior ;\n }\n\n public void Start(){\n if(_isRunning) return;\n while(_isRunning){\n _updateBehavior.TryUpdate();\n _renderBehavior.TryRender();\n }\n }\n public void Stop()\n {\n _running = false;\n }\n}\n\nclass AsyncGameLoop : IGameLoop ...\n\nclass StatisticProvidingGameLoop: IGameLopp ...\n</code></pre>\n\n<p>This system offers you the possibility to exchange the game loop behavior at run-time. So If you decide to implement a game loop that offers statistic information(update count, update time, render count) for debugging purpose, you free to exchange this, without altering your code. </p>\n\n<p>The separation into two *behavior interface provide the possibility to implement completely independent strategies, for this two functionality. But if you wish to, one class can implement both interfaces and can make the functionality dependent on each other. So while implementing your engine, you don't define what kind of game loop and update/render behavior is finally used. For example in XNA, you can switch between fixed time steps and variable one. All this is easily possible with the strategy pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T09:43:35.433",
"Id": "51217",
"Score": "0",
"body": "Thank you for the feedback. I already have an even more complex system in place. I use a game state object that has a start up/shutdown logic and provides update and render methods. It can easily be swapped during runtime and will shutdown the old state and start up the new state. I am more interested in feedback on the FrameController then on the Game. Sorry if this is not clear enough."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T09:38:01.573",
"Id": "32058",
"ParentId": "32054",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T07:04:56.660",
"Id": "32054",
"Score": "3",
"Tags": [
"c#",
"game"
],
"Title": "Control game ticks/frames of updates and rendering separately"
}
|
32054
|
<p>Can someone please find out why this store procedure is timing out?</p>
<pre><code>ALTER PROCEDURE [dbo].[Insertorupdatedevicecatalog]
(@OS NVARCHAR(50)
,@UniqueID VARCHAR(500)
,@Longitude FLOAT
,@Latitude FLOAT
,@Culture VARCHAR(10)
,@Other NVARCHAR(200)
,@IPAddress VARCHAR(50)
,@NativeDeviceID VARCHAR(50))
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TranCount INT;
SET @TranCount = @@TRANCOUNT;
DECLARE @OldUniqueID VARCHAR(500) = ''-1'';
SELECT @OldUniqueID = [UniqueID] FROM DeviceCatalog WHERE (@NativeDeviceID != '''' AND [NativeDeviceID] = @NativeDeviceID);
BEGIN TRY
IF @TranCount = 0
BEGIN TRANSACTION
ELSE
SAVE TRANSACTION Insertorupdatedevicecatalog;
DECLARE @Geo GEOGRAPHY = geography::STGeomFromText(''POINT('' + CONVERT(VARCHAR(100), @Longitude) + '' '' + CONVERT(VARCHAR(100), @Latitude) + '')'', 4326);
IF EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @UniqueID)
BEGIN
DECLARE @OldGeo GEOGRAPHY
,@OldCity NVARCHAR(100)
,@OldCountry NVARCHAR(100)
,@OldAddress NVARCHAR(100);
SELECT @OldGeo = [LastUpdatedLocationFromJob]
,@OldCity = [City]
,@OldCountry = [Country]
,@OldAddress = [Address]
FROM DeviceCatalog
WHERE [UniqueID] = @UniqueID;
UPDATE DeviceCatalog
SET [OS] = @OS
,[Location] = @Geo
,[Culture] = @Culture
,[Other] = @Other
,[IPAddress] = @IPAddress
WHERE [UniqueID] = @UniqueID;
IF (@OldGeo IS NULL OR @OldAddress IS NULL OR @OldCity IS NULL OR @OldCountry IS NULL OR ISNULL(@Geo.STDistance(@OldGeo) / 1000,0) > 50)
BEGIN
UPDATE DeviceCatalog
SET [Lastmodifieddate] = Getdate()
WHERE [UniqueID] = @UniqueID;
END
END
ELSE
BEGIN
INSERT INTO DeviceCatalog
([OS]
,[UniqueID]
,[Location]
,[Culture]
,[Other]
,[IPAddress]
,[NativeDeviceID])
VALUES (@OS
,@UniqueID
,@Geo
,@Culture
,@Other
,@IPAddress
,@NativeDeviceID);
IF(@OldUniqueID != ''-1'' AND @OldUniqueID != @UniqueID)
BEGIN
EXEC DeleteOldAndroidDeviceID @OldUniqueID, @UniqueID;
END
END
LBEXIT:
IF @TranCount = 0
COMMIT;
END TRY
BEGIN CATCH
DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
SELECT @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();
IF @XState = -1
ROLLBACK;
IF @XState = 1 AND @TranCount = 0
rollback
IF @XState = 1 AND @TranCount > 0
ROLLBACK TRANSACTION Insertorupdatedevicecatalog;
RAISERROR (''Insertorupdatedevicecatalog: %d: %s'', 16, 1, @error, @message) ;
END CATCH
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T14:42:40.253",
"Id": "57144",
"Score": "1",
"body": "why do you use double `'` around things?"
}
] |
[
{
"body": "<p>It's impossible to say what the problem is without knowing how the data is structured, how many rows are in each table, what the indexes are, and other information. Even then, the problem may not even be with this query but with some other query that causes problems for the database as a whole. Basically, your question is far too narrow. </p>\n\n<p>That said, you could try a few things:</p>\n\n<ol>\n<li>Try running this with Explain Plan turned on. That should tell you what part of the query is taking the longest.</li>\n<li>Run <code>SET STATISTICS IO ON;</code> and then your query. That will give you an idea if the I/O usage is high. </li>\n<li>If the above don't suggest improvement, check the overall DB for problems. <a href=\"http://sqlserverperformance.wordpress.com/2013/09/24/sql-server-diagnostic-information-queries-for-september-2013/\" rel=\"nofollow\">Glenn Berry's SQL diagnostics queries</a> are a good place to start. </li>\n<li>If you still can't figure it out, hire someone like Glenn to help you. Or start reading a lot of books on SQL Server optimization.</li>\n</ol>\n\n<p>(disclaimer: Glenn's a friend and former colleague of mine, but he is really good at this stuff. I don't get kickbacks. Maybe a beer, but probably not.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T19:59:45.107",
"Id": "32200",
"ParentId": "32060",
"Score": "3"
}
},
{
"body": "<p>What if <code>@TranCount < 1</code>, would that cause a weird looping condition?</p>\n\n<pre><code> IF @TranCount = 0\n BEGIN TRANSACTION\n ELSE\n SAVE TRANSACTION Insertorupdatedevicecatalog;\n</code></pre>\n\n<p>In the example on <a href=\"http://technet.microsoft.com/en-us/library/ms188378.aspx\" rel=\"nofollow\">Microsoft's SAVE TRANSACTION (Transact-SQL)</a> it gives an example like this:</p>\n\n<pre><code>IF @TranCounter > 0\n SAVE TRANSACTION ProcedureSave;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T15:00:39.967",
"Id": "57147",
"Score": "0",
"body": "http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T15:04:28.583",
"Id": "57148",
"Score": "0",
"body": "ok, that is someone's blog from 2009, and I posted a link to Microsoft. I would take a look at what Microsoft has to say on this and see if you can make it look like theirs, the code you presented is timing out, maybe this is why."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T14:49:30.117",
"Id": "35296",
"ParentId": "32060",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "32200",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T10:12:12.053",
"Id": "32060",
"Score": "1",
"Tags": [
"sql",
"sql-server",
"t-sql",
"time-limit-exceeded",
"geospatial"
],
"Title": "Store procedure timing out sometimes"
}
|
32060
|
<p>I was trying to solve the final puzzle at the end of the classes chapter (Chapter 8) in "Python Programming for the Absolute Beginner" which is stated as:</p>
<blockquote>
<p>Create a Critter Farm program by instantiating several <code>Critter</code> objects and keeping track of them through a list. Mimic the <code>Critter Caretaker</code> program, but instead of requiring the user to look after a single critter, require them to care for an entire farm. Each menu choice should allow the user to perform some action for all the critters (feed all the critters, play with all of the critters, or listen to all of the critters). To make the program interesting, give each critter random starting hunger and boredom levels.</p>
</blockquote>
<p>Here is my solution:</p>
<pre><code>from random import randrange
class Critter(object):
def __init__(self, name):
self.__name = name
self.__hunger = randrange(7)
self.__boredom = randrange(7)
def __str__(self):
return "Hi, I'm " + self.__name + " and I feel " + self.mood + "."
def talk(self):
print(self)
self.__passTime()
def eat(self):
self.__hunger -= 3
if self.__hunger < 0:
self.__hunger = 0
self.__passTime()
def play(self):
self.__boredom -= 3
if self.__boredom < 0:
self.__boredom = 0
self.__passTime()
def __passTime(self):
self.__hunger += 1
self.__boredom += 1
@property
def mood(self):
happiness = self.__hunger + self.__boredom
if happiness < 5:
return "happy"
elif happiness < 10:
return "ok"
else:
return "sad"
class CritterFarm(object):
def __init__(self):
self.__critters = []
def talk(self):
for critter in self.__critters:
critter.talk()
def add(self, name):
self.__critters.append(Critter(name))
def eat(self):
for critter in self.__critters:
critter.eat()
def play(self):
for critter in self.__critters:
critter.play()
def main():
farm = CritterFarm()
option = ""
while option != "0":
choice = input("""
0 - Quit
1 - Add a Critter to your Farm
2 - Listen to your Critters
3 - Feed your Critters
4 - Play with your Critters
Choice: """)
if choice == "0":
print("Exiting...")
elif choice == "1":
name = input("Enter your new Critter's name: ")
farm.add(name)
elif choice == "2":
farm.talk()
elif choice == "3":
farm.eat()
elif choice == "4":
farm.play()
if __name__ == "__main__":
main()
</code></pre>
<p>Can anyone offer a code review? Thanks.</p>
|
[] |
[
{
"body": "<p>Not much to say:</p>\n\n<p><strong>Variable naming</strong></p>\n\n<p>I find that <code>happiness</code> is not very well chosen; <code>sadness</code> would probably be a better name.</p>\n\n<p><strong>Conciseness</strong></p>\n\n<p><code>self.__hunger = max(self.__hunger - 3, 0)</code> is a bit shorter. Same applies to <code>boredom</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T12:39:16.047",
"Id": "32069",
"ParentId": "32063",
"Score": "2"
}
},
{
"body": "<p>Why are you using <code>__double_underscore_prefixes</code> for your member variable names?</p>\n\n<p>Double-underscores get name-mangled by Python for the purpose of 'class-local references'. They're for when your class's implementation relies on something that you don't want subclasses to customise. This is a very rare situation, and typically happens quite late in a library's lifetime.</p>\n\n<p>What double-underscore names are <em>not</em> for is access control. This is one of the biggest pieces of mis-information given to Python beginners.\nPython doesn't have a concept of 'public' and 'private', and you shouldn't try to hack one together out of a language feature designed for something else. All your member variables should just be public by default; if you need to change an implementation detail, you can maintain your contract using <a href=\"http://docs.python.org/3.3/library/functions.html#property\" rel=\"nofollow\">properties</a>.</p>\n\n<p>If you really insist on declaring something as private, the conventional way to do that in Python is using a <code>_single_leading_underscore</code>. It's still not <em>actually</em> private, it's just a clear signal to your consumers that they shouldn't mess around with that stuff because it might change.</p>\n\n<hr>\n\n<p>I also don't really like the way you're using <code>__str__</code>. <code>__str__</code> is designed to return a meaningful description of the object, generally for the purposes of debugging (or when you wish to emulate string-like behaviour). You're using <code>__str__</code> as part of the behaviour of your class (returning a formatted string in plain English).</p>\n\n<p>I'd put the body of <code>__str__</code> inside the <code>talk</code> method, and either delete <code>__str__</code> altogether, or use it for something more meaningful to a person working with the code - something like this:</p>\n\n<pre><code>def __str__(self):\n return \"Critter named {} with hunger {} and boredom {}\".format(self.__name, self.__hunger, self.__boredom)\n\ndef talk(self):\n print(\"Hi, I'm \" + self.__name + \" and I feel \" + self.mood + \".\")\n self.__passTime()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T14:01:35.730",
"Id": "32072",
"ParentId": "32063",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T11:21:31.650",
"Id": "32063",
"Score": "1",
"Tags": [
"python",
"object-oriented"
],
"Title": "OOP Challenge in Python"
}
|
32063
|
<p>I'm messing around with JavaScript and am trying out objects, functions & arrays. I'd like to know if someone has tips about making it better, shorter, or has a better solution for what I have thought about for now. What I've tried to do is just do simple math (+ and -) using arrays as input for numbers. It all works, but I'm just wondering if it could be even better and/or cleaner.</p>
<pre><code>//Write the result
function ap(n) {
$(".value").append(n);
}
// Make sure the input is a number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function doMath(options) {
var defaults = {
method: 'add'
};
var options = $.extend({}, defaults, options);
// Add
if(options.method == 'add') {
var n = 0;
for(var i=0; i<options.numbers.length; i++) {
if(isNumber(options.numbers[i])) {
n = n + options.numbers[i];
}
if(i===options.numbers.length-1) {
ap(n);
}
}
}
// Subtract
if(options.method == 'subtract' ) {
for (var i=0; i<options.numbers.length; i++) {
if(i===0) {
n = options.numbers[0];
} else {
if(isNumber(options.numbers[i])) {
n = n - options.numbers[i];
}
}
if(i===options.numbers.length-1) {
ap(n);
}
}
}
}
//Print the result
doMath({'numbers': [10,5,2,2], 'method':'subtract'});
</code></pre>
|
[] |
[
{
"body": "<pre><code>function doMath(options) {\n var defaults = {\n method: 'add'\n };\n var options = $.extend({}, defaults, options);\n\n var n = 0;\n\n for(var i=0; i<options.numbers.length; i++) {\n if(isNumber(options.numbers[i])) {\n if(options.method == 'add' || i == 0) {\n n += options.numbers[i];\n }\n else if(options.method == \"subtract\"){\n n -= options.numbers[i];\n }\n }\n }\n ap(n);\n}\n</code></pre>\n\n<p>This code is making many assumptions, for example that <code>options.numbers</code> is defined, but for the lack of the exact definition of the problem you are trying to solve this looks at least shorter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T12:05:12.493",
"Id": "32065",
"ParentId": "32064",
"Score": "1"
}
},
{
"body": "<p>You should avoid mixing calculations with input/output. It would be better if your <code>doMath()</code> would not call the output function <code>ap()</code> directly, but instead would just return the result of its calculations:</p>\n\n<pre><code>ap(doMath({'numbers': [10,5,2,2], 'method':'subtract'}));\n</code></pre>\n\n<p>Of course the <code>ap</code> itself is a lousy name for a function, but it's more of a helper in here I guess.</p>\n\n<p>I see no reason why you would use and options object instead of passing in just two parameters, but even when you use an options object, it would be simpler to extract its values into local variables and work with these. One can also easily drop the use of <code>$.extend</code> in favor of simple <code>||</code> operator, which is the canonical way of implementing default values for parameters:</p>\n\n<pre><code> var method = options.method || \"add\";\n var numbers = options.numbers;\n</code></pre>\n\n<p>Another step to simplify code is to filter out the invalid numbers before doing any calculations on them. <code>Array.filter</code> helps us here:</p>\n\n<pre><code>var validNumbers = numbers.filter(isNumber);\n</code></pre>\n\n<p>The actual calculation can be easily implemented with <code>Array.reduce</code>. First we can define functions <code>add</code> and <code>subtract</code></p>\n\n<pre><code>var methods = {\n add: function(a, b) { return a + b; },\n subtract: function(a, b) { return a - b; }\n};\n</code></pre>\n\n<p>And then using <code>Array.reduce</code> we can apply them for the whole array:</p>\n\n<pre><code>validNumbers.reduce(methods.add);\n// or\nvalidNumbers.reduce(methods.subtract);\n</code></pre>\n\n<p>Pulling it all together:</p>\n\n<pre><code>function doMath(options) {\n var method = options.method || \"add\";\n var numbers = options.numbers;\n\n var validNumbers = numbers.filter(isNumber);\n\n var methods = {\n add: function(a, b) { return a + b; },\n subtract: function(a, b) { return a - b; }\n };\n\n return validNumbers.reduce(methods[method]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T13:33:22.253",
"Id": "32070",
"ParentId": "32064",
"Score": "3"
}
},
{
"body": "<p>Another solution (e.g. if you cannot use the Array-Methods):</p>\n\n<pre><code>function doMath(options){\n var result;\n var operations={\n add: function(){\n var result=0;\n return function(o){\n return result+=o;\n }\n }(),\n substract: function(){\n var result=0;\n return function(o){\n return result-=o;\n }\n }()\n };\n\n var fn=operations[options.method]||operations.add;\n\n while(number=options.numbers.pop()){\n result=fn(number);\n }\n return result;\n}\n</code></pre>\n\n<p>Here is the <a href=\"http://jsfiddle.net/bAbGR/\" rel=\"nofollow\">Fiddle</a>.</p>\n\n<p>Not quite as elegant as <code>Array.reduce()</code> but does its job.\n(Validation for numbers omitted)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T19:20:43.810",
"Id": "32080",
"ParentId": "32064",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "32070",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T11:35:42.943",
"Id": "32064",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Simple math using arrays"
}
|
32064
|
<p>Using a combination provided from <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="nofollow noreferrer">this example</a> and <a href="https://codereview.stackexchange.com/questions/11785/ef-code-first-with-repository-unitofwork-and-dbcontextfactory">this implementation</a>, I'm creating a solution that decouples the <code>UnitOfWork</code> class from the individual repositories, as they violate the Open-Closed Principle: every time you added a new repository you would have to modify the <code>UnitOfWork</code> class. I am using <strong>Unity 3.0</strong> as the IoC container to wire up dependencies, together with <strong>Unity Bootstrapper for ASP.NET MVC</strong> and its <a href="http://msdn.microsoft.com/en-us/library/dn178463%28v=pandp.30%29.aspx#sec38" rel="nofollow noreferrer">PerRequestLifetimeManager</a> to handle automatically disposing the <code>UnitOfWork</code> and <code>DbContextFactory</code> classes.</p>
<p>Here's my proposed demo solution:</p>
<p><strong>Repositories</strong></p>
<pre><code>public interface IRepository<TEntity> where TEntity : class
{
TEntity Create();
// omitted for brevity
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly DbContext _context;
public Repository(IUnitOfWork uow)
{
_context = uow.Context;
}
public virtual TEntity Create(TEntity entity)
{
return _context.Set<TEntity>().Add(entity);
}
// omitted for brevity
}
public interface IEmployeeRepository : IRepository<Employee>
{
}
public interface ICustomerRepository : IRepository<Customer>
{
}
public class EmployeeRepository : Repository<Employee>
{
public EmployeeRepository(IUnitOfWork uow)
: base(uow)
{
}
}
public class CustomerRepository : Repository<Customer>
{
public CustomerRepository(IUnitOfWork uow)
: base(uow)
{
}
}
</code></pre>
<p><strong>DbContext Factory</strong></p>
<pre><code>public interface IDbContextFactory
{
DbContext GetContext();
}
public class DbContextFactory : IDbContextFactory
{
private readonly DbContext _context;
public DbContextFactory()
{
_context = new MyDbContext("ConnectionStringName");
}
public DbContext GetContext()
{
return _context;
}
}
</code></pre>
<p><strong>Unit Of Work</strong></p>
<pre><code>public interface IUnitOfWork
{
void SaveChanges();
DbContext Context { get; }
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DbContext _context;
private bool disposed = false;
public UnitOfWork(IDbContextFactory contextFactory)
{
_context = contextFactory.GetContext();
}
public void SaveChanges()
{
if (_context != null)
{
_context.SaveChanges();
}
}
public DbContext Context
{
get { return _context; }
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
_context.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
</code></pre>
<p><strong>Service</strong></p>
<pre><code>public class CompanyService
{
private readonly IUnitOfWork _uow;
private readonly IEmployeeRepository _employeeRepository;
private readonly ICustomerRepository _customerRepository;
public CompanyService(IUnitOfWork uow, IEmployeeRepository employeeRepository, ICustomerRepository customerRepository)
{
_uow = uow;
_employeeRepository = employeeRepository;
_customerRepository = customerRepository;
}
// over-simplified example method of using 2 separate repositories
public void AddEmployeeAndCustomer()
{
_employeeRepository.Create(new Employee {Id = 1, Name = "Test Employee"});
_customerRepository.Create(new Customer { Id = 2, Name = "Test Customer" });
_uow.SaveChanges();
}
// over-simplified example method of getting all employees
public List<Employee> GetEmployess()
{
return _employeeRepository.Create(new Employee {Id = 1, Name = "Test Employee"});
}
}
</code></pre>
<p>Does anyone have any input with regards to this solution - perhaps a "better" way? The benefit by injecting the <code>IUnitOfWork</code>, <code>IEmployeeRepository</code> and <code>ICustomerRepository</code> dependancies into the service layers is being able to access the repositories directly, without having to go through the <code>UnitOfWork</code> class to access a repository (.e.g., <code>_uow.EmployeeRepository.FindAll()</code>), but also being able to call the <code>UnitOfWork.SaveChanges()</code> method for insert/updates/deletes when needed.</p>
<p>One concern with using the <a href="http://msdn.microsoft.com/en-us/library/dn178463%28v=pandp.30%29.aspx#sec38" rel="nofollow noreferrer">PerRequestLifetimeManager</a>: "<em>Although the PerRequestLifetimeManager class works correctly and can help you to work with stateful or thread-unsafe dependencies within the scope of an HTTP request, it is generally not a good idea to use it if you can avoid it. Using this lifetime manager can lead to bad practices or hard to find bugs in the end user’s application code when used incorrectly.</em>" </p>
<p>An alternative solution could be to store the <code>DbContext</code> within the <code>System.Web.HttpContext.Items</code> collection.</p>
|
[] |
[
{
"body": "<p>While I'm not sure of the safety of <code>PerRequestLifetimeManager</code>, one thing I'd recommend changing in your repository is to avoid inheritance from <code>Repository<T></code>.</p>\n\n<p>Instead of </p>\n\n<pre><code>public class EmployeeRepository : Repository<Employee>\n{\n ...\n}\n</code></pre>\n\n<p>do</p>\n\n<pre><code>public class EmployeeRepository : IEmployeeRepository\n{\n private Repository<Employee> _genericRepo;\n ...\n}\n</code></pre>\n\n<p>When you don't want to implement all methods of <code>Repository<T></code> in your <code>EmployeeRepository</code> (like say, you don't want to delete Employees), it leads to cleaner code. You avoid exposing the unwanted interface, you avoid throwing exceptions if the Delete method is called. And instead of calling <code>base.SomeMethod()</code>, you call <code>_genericRepo.SomeMethod()</code>, thus getting the same advantage of code re-use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:54:45.313",
"Id": "67802",
"Score": "0",
"body": "Another way to phrase this answer is to [prefer composition over inheritance](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T14:24:59.000",
"Id": "38633",
"ParentId": "32071",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T13:59:57.187",
"Id": "32071",
"Score": "6",
"Tags": [
"c#",
"design-patterns",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Entity Framework using Repository Pattern, Unit of Work and Unity - viable approach?"
}
|
32071
|
<p>I need to provide a service (either a Windows Service or an Azure Worker Role) which will handle the parallel execution of jobs. These jobs could be anything from importing data to compiling of reports, or to sending out mass notifications, etc. </p>
<p><strong>Database Design:</strong></p>
<p>The whole process of running these jobs is persistent. </p>
<p><img src="https://i.stack.imgur.com/cKlex.png" alt="enter image description here"></p>
<ul>
<li><code>JobDefinition</code> stores varchar reference to the <code>IJob</code> concrete type class.</li>
<li><code>JobInstance</code> is an instance of <code>JobDefinition</code> which needs to be executed as a job.</li>
<li><code>JobInstanceEvent</code> stores the process of executing an instance (the change of states).</li>
</ul>
<p><strong>Class Structure:</strong></p>
<p><img src="https://i.stack.imgur.com/yGRgq.png" alt="enter image description here"></p>
<p>In order to create new jobs the simple <code>IJob</code> interface needs to be implemented:</p>
<pre><code>public interface IJob
{
bool Execute();
}
</code></pre>
<p><code>JobHandler</code> is responsible for deserializing the serialized varchar in the database and also saving state changes:</p>
<pre><code>public class JobHandler
{
public string State
{
get
{
return jobInstance.State;
}
set
{
using (MyEntities context = new MyEntities())
{
context.JobInstances.Attach(jobInstance);
jobInstance.State = value;
context.SaveChanges();
}
SaveJobEvent(String.Empty);
}
}
private JobInstance jobInstance;
public JobHandler(JobInstance job)
{
jobInstance = job;
}
public IJob CreateJobObject()
{
Type type = Type.GetType(jobInstance.JobDefinition.FullAssemblyType);
XmlSerializer serializer = new XmlSerializer(type);
using (StringReader reader = new StringReader(jobInstance.SerialisedObject))
{
return serializer.Deserialize(reader) as IJob;
}
}
public void SaveJobEvent(string jobEventMessage)
{
using (MyEntities context = new MyEntities())
{
context.JobInstances.Attach(jobInstance);
jobInstance.JobInstanceEvents.Add(
new JobInstanceEvent()
{
State = jobInstance.State,
Date = DateTime.UtcNow,
Message = jobEventMessage
}
);
context.SaveChanges();
}
}
}
</code></pre>
<p>The <code>JobConsumer</code> is what will run in the service. It performs two primary parallel tasks:</p>
<ul>
<li>Adding items to the blocking queue (through polling)</li>
<li>Executing items from the blocking queue (through thread blocking)</li>
</ul>
<p>It is able to run multiple jobs concurrently (<code>ParallelExecutionSlots</code>).</p>
<pre><code>public class JobConsumer
{
public IJobSource JobSource { get; private set; }
public BlockingCollection<JobHandler> JobQueue { get; private set; }
public int ParallelExecutionSlots { get; private set; }
private bool isPopulating;
private CancellationTokenSource consumerCancellationTokenSource;
public JobConsumer(IJobSource jobSource, int parallelExecutionSlots)
{
JobQueue = new BlockingCollection<JobHandler>();
JobSource = jobSource;
ParallelExecutionSlots = parallelExecutionSlots;
consumerCancellationTokenSource = new CancellationTokenSource();
StartPopulatingQueue();
}
public void StartPopulatingQueue()
{
StartPopulatingQueue(500);
}
public void StartPopulatingQueue(int pollingDelay)
{
if (!isPopulating)
{
isPopulating = true;
var task = Task.Factory.StartNew(() =>
{
while (isPopulating)
{
foreach (var job in JobSource.ReadNewJobs())
{
job.State = "Queued";
JobQueue.Add(job);
}
Tasks.Task.Delay(pollingDelay).Wait();
}
})
.ContinueWith(t =>
{
isPopulating = false;
JobConsumerLog.LogException("JobConsumer populating process failed", t.Exception);
},
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.Current
);
}
}
public void StopPopulatingQueue()
{
isPopulating = false;
}
public void StartConsumer()
{
Task.Factory.StartNew(() =>
{
SemaphoreSlim slotsSemaphore = new SemaphoreSlim(ParallelExecutionSlots);
foreach (var job in JobQueue.GetConsumingEnumerable(consumerCancellationTokenSource.Token))
{
slotsSemaphore.Wait();
JobHandler jobHandler = job;
Task.Factory.StartNew(() =>
{
try
{
ExecuteJob(jobHandler);
}
finally
{
slotsSemaphore.Release();
}
},
TaskCreationOptions.LongRunning
);
}
consumerCancellationTokenSource.Token.ThrowIfCancellationRequested();
}, consumerCancellationTokenSource.Token)
.ContinueWith(t =>
{
JobConsumerLog.LogException("JobConsumer execution process failed", t.Exception);
},
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.Current
)
.ContinueWith(t =>
{
JobConsumerLog.LogException("JobConsumer execution process stopped", t.Exception);
},
CancellationToken.None,
TaskContinuationOptions.OnlyOnCanceled,
TaskScheduler.Current
);
}
public void StopConsumer()
{
consumerCancellationTokenSource.Cancel();
}
private void ExecuteJob(JobHandler job)
{
job.State = "Executing";
try
{
if (job.CreateJobObject().Execute())
{
job.State = "Successful";
}
else
{
job.State = "Failed";
}
}
catch (Exception ex)
{
job.State = "FailedOnException";
}
}
}
</code></pre>
<p>Feedback on the overall design would be much appreciated. I'm looking for a <strong>maintainable and extensible solution</strong>.</p>
<p>I am using .NET 4.5</p>
<p>(Note: this is a second iteration of the <a href="https://codereview.stackexchange.com/questions/31903/parallel-job-consumer">following post</a>)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:45:47.613",
"Id": "51266",
"Score": "0",
"body": "I think you don't have ReSharper installed and screaming at your private field naming convention! Prefixing them with an underscore really helps readability I find - I was WTF-looking for a local variable when I came across `jobInstance`. Declaring them at the top of the class also helps, especially if you're not prefixing them and you're using them before they're declared. Call that a \"readability review\" :) Is `JobConsumerLog` a static class? I'd just replace that with a constructor-injected `ILogger`, otherwise you've got *ambient context* here, not obvious the thing is logging anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T05:51:36.007",
"Id": "51377",
"Score": "1",
"body": "Have you considered Quartz.NET, it contains a lot of job running logic out of the box and also retry policies etc. It is more of an scheduling framework but in your case you could it set it to run jobs as fast as possible (fire now)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-07T00:00:10.913",
"Id": "126219",
"Score": "0",
"body": "You might want to look into using something like Microsoft HPC if you aren't set on rolling your own solution, as that seems to be what you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T17:55:14.607",
"Id": "136292",
"Score": "0",
"body": "Have you consider using Windows Workflow Foundation (WFF) for this?"
}
] |
[
{
"body": "<p>Only some few minor things:</p>\n\n<ol>\n<li>In <code>StartPopulatingQueue</code> to me as the reader it's unclear in what unit <code>pollingDelay</code> is in. Two classic solutions:\n\n<ul>\n<li>Change it to be a <code>TimeSpan</code> - I usually prefer this since it provides the most flexibility.</li>\n<li>Add the unit suffix to the parameter name. like <code>Ms</code> for milliseconds or <code>Sec</code> for seconds etc.</li>\n</ul></li>\n<li><code>CreateJobObject</code> can potentially return <code>null</code> if the deserialized object cannot be cast to <code>IJob</code> in which case <code>ExecuteJob</code> will throw a <code>NullReferenceException</code> which is typically not very meaningful. You should throw a more meaningful exception on deserialization (as mentioned in the comment by Roman you could use a direct cast instead of <code>as</code> which would throw an <code>InvalidCastException</code>)</li>\n<li>It feels wrong to me that the consumer defines the job execution states. The consumer seems largely responsible for managing the job queue and it should stick to that single responsibility. Hence I think <code>Execute</code> should be moved into <code>JobHandler</code>.</li>\n<li>I'd also consider moving <code>CreateJobObject</code> to <code>JobInstance</code> so <code>JobInstance</code> is responsible to provide the actual object instance. Then <code>JobHandler</code> is just concerned with the state changes of the job.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-05T19:12:53.720",
"Id": "202474",
"Score": "0",
"body": "Adding to your second point: This should be a direct cast rather than \"as\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-05T19:02:50.767",
"Id": "109919",
"ParentId": "32073",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "109919",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T14:36:16.253",
"Id": "32073",
"Score": "6",
"Tags": [
"c#",
"design-patterns",
"serialization"
],
"Title": "Parallel Job Consumer using TPL"
}
|
32073
|
<p>This is my very first Bash script that does something real. I'm here to learn, so please tell me if and how this can be done better.</p>
<pre><code>#!/bin/sh
# Daniele Brugnara
# October - 2013
if [ -k $1 ]; then
echo "Error! You must pass a repository name!"
exit 1
fi
SVN_PATH="/var/lib/svn"
currPath=$(pwd)
cd $SVN_PATH
svnadmin create $1
chown -R www-data:www-data $1
cd $currPath
echo "Done! Remember to set valid user permission in authz file."
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>If the first argument to your script contains a space, then you get an error message:</p>\n\n<pre><code>$ ./cr32076.sh \"my repository\"\n./cr32076.sh: line 6: [: my: binary operator expected\n</code></pre>\n\n<p>To avoid this, put quotes around the variable <code>$1</code>, like this:</p>\n\n<pre><code>if [ -k \"$1\" ]; then\n</code></pre></li>\n<li><p>The <a href=\"http://www.unix.com/man-page/FreeBSD/1/test/\" rel=\"nofollow\">man page for <code>[</code></a> says:</p>\n\n<pre><code>-k file True if file exists and its sticky bit is set.\n</code></pre>\n\n<p>is this really what you mean? It seems more likely that you want the <code>-z</code> option:</p>\n\n<pre><code>-z string True if the length of string is zero.\n</code></pre></li>\n<li><p>You remember the current directory in a variable:</p>\n\n<pre><code>currPath=$(pwd)\n</code></pre>\n\n<p>and then later change to it:</p>\n\n<pre><code>cd $currPath\n</code></pre>\n\n<p>but this will go wrong if the current directory has a space in its name:</p>\n\n<pre><code>$ pwd\n/Users/gdr/some directory\n$ currPath=$(pwd)\n$ cd $currPath\nbash: cd: /Users/gdr/some: No such file or directory\n</code></pre>\n\n<p>To avoid this, put quotes around the variable, like this:</p>\n\n<pre><code>cd \"$currPath\"\n</code></pre></li>\n<li><p>If you want to change directory temporarily and change back again, then instead of writing</p>\n\n<pre><code>currPath=$(pwd) # remember old directory\ncd \"$SVN_PATH\" # change to new directory\n# do some stuff\ncd \"$currPath\" # go back to old directory\n</code></pre>\n\n<p>you can use a <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping\" rel=\"nofollow\"><em>subshell</em></a>:</p>\n\n<pre><code>(\n cd \"$SVN_PATH\" # change to new directory\n # do some stuff \n) # old directory is automatically restored when subshell exits\n</code></pre>\n\n<p>But in this script, there's no need to change directory back again, because after you go back all you do is <code>echo \"Done! ...\"</code> and it doesn't matter what directory you do that in.</p></li>\n<li><p>In fact, there's no need to change directory at all, because instead of</p>\n\n<pre><code>SVN_PATH=\"/var/lib/svn\"\ncurrPath=$(pwd)\n\ncd \"$SVN_PATH\"\nsvnadmin create \"$1\"\nchown -R www-data:www-data \"$1\"\ncd \"$currPath\"\n</code></pre>\n\n<p>you could write</p>\n\n<pre><code>SVN_PATH=\"/var/lib/svn/$1\"\nsvnadmin create \"$SVN_PATH\"\nchown -R www-data:www-data \"$SVN_PATH\"\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:17:16.073",
"Id": "51283",
"Score": "0",
"body": "**Thanks**. This is a very useful answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T20:26:57.927",
"Id": "32084",
"ParentId": "32076",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T16:06:42.553",
"Id": "32076",
"Score": "4",
"Tags": [
"bash"
],
"Title": "New svn repository script"
}
|
32076
|
<p>I'm trying to create a custom div scroller. I got it working, but it's still a little rough around the edges. Please take a look..</p>
<p><a href="http://jsfiddle.net/5t3Ju/134/" rel="nofollow">DEMO</a></p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
#content {
margin-top: 100px;
height: 500px;
width: 500px;
overflow: hidden;
border: solid 1px red;
}
#scr {
height: 100px;
width: 100px;
border: solid 1px black;
background-color: #26a0eb;
z-index: 3;
opacity: 0;
filter: alpha(opacity = 0);
}
#content:hover #scr {
opacity: 0.1;
filter: alpha(opacity = 10);
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="content">
<div id="scr">
</div>
<div id="container">
<script type="text/javascript">
var strContent = '';
for (var i = 1; i < 101; i++) {
document.writeln(i + '<br />');
}
</script>
</div>
</div>
</form>
<script type="text/javascript">
window.onload = function () {
draggable('scr');
};
var scr = null;
function draggable(id) {
var obj = document.getElementById(id);
obj.style.position = "absolute";
obj.onmousedown = function () {
scr = obj;
}
}
document.onmouseup = function (e) {
scr = null;
};
document.onmousemove = function (e) {
if (!e) e = window.event;
var y = (e.pageY) ? e.pageY : e.clientY;
if (scr == null)
return;
var c = document.getElementById('content');
if ((y >= c.offsetTop + 50) && (y < c.clientHeight + 50)) {
var pct = (scr.offsetTop - c.offsetTop) / (c.clientHeight - 50);
c.scrollTop = Math.floor(c.scrollHeight * pct);
scr.style.top = y - 50 + 'px';
}
};
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Just focusing on the Javascript:</p>\n\n<ul>\n<li><p>I feel a urge to to reference a <a href=\"http://thecodelesscode.com/case/34?topic=naming\" rel=\"nofollow\">story about a monk</a>. Instead I'll just say that descriptive names will help when you come back to your code or when others try to read it.<br>\nfor example:</p>\n\n<pre><code>var obj = document.getElementById(id);\nobj.style.position = \"absolute\";\nobj.onmousedown = function () {\n scr = obj;\n}\n</code></pre>\n\n<p>Here it would be better to name <code>obj</code> something like <code>draggableElement</code> or some such. this was I know instantly what we are referring to. </p></li>\n<li><p>You are testing <code>e</code> and <code>pageY</code> and assigning a variable in two different way. Pick one way and be consistent about it. It really matters not what you choose so much as sticking to it.</p>\n\n<p>Here are a couple of different ways you could do it.</p>\n\n<ol>\n<li><p>if</p>\n\n<pre><code>if (!e) e = window.event;\nvar y = e.pageY;\nif(!y) y = e.clientY;\n</code></pre></li>\n<li><p>ternary</p>\n\n<pre><code>e = e ? e : window.event;\nvar y = e.pageY ? e.pageY : e.clientY;\n</code></pre></li>\n<li><p>or </p>\n\n<pre><code>e = e || window.event;\nvar y = e.pageY || e.clientY;\n</code></pre></li>\n</ol>\n\n<p>I personally favour this last way.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T01:02:05.647",
"Id": "35736",
"ParentId": "32077",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T16:55:15.113",
"Id": "32077",
"Score": "5",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Custom scrollable div"
}
|
32077
|
<p>Is there a more efficient way of achieving the same result besides setting up a database?</p>
<pre><code># In reality, contains 4 million tuples.
stuff_tuple = (
('hello', 241, 1),
('hi', 243, 3),
('hey', 242, 2)
)
# Convert tuple to set for faster searching?
stuff_set = set(stuff_tuple)
# Only first two values are known ("hello", 241), ('hi', 243), etc.
for item in stuff_set:
if item[0] == 'hello' and item[1] == 241:
print item[2]
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"https://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table\">This question</a> suggests that dictionaries and sets - which are both based on hashtables internally -- are the fastest for random retrieval of hashable data (which your sample seems to b). It's always a good idea to try the base data structures in Python, they're usually pretty high quality :)</p>\n\n<p>If that's not fast enough, you have a couple of options.</p>\n\n<p>If you can come up with a single sortable key value for your list, you could use the <a href=\"http://docs.python.org/2/library/bisect.html\" rel=\"nofollow noreferrer\">bisect module</a> to speed up searches. For example, if you had a deterministic way of turning the first two keys into a number, and then sort on that number, bisect should make it easy to find items quickly. The big drawback here is that you're on the hook for coming up with the method for creating that numberic key, which can be dicey depending on your data set.</p>\n\n<p>The less ambitious (but maybe less risky) is to subdivide the data yourself so you don't search 4 million items every time. If you have to use data like the data in your example, you should look at patterns in your sample for characteristics that group it into similarly sized subsets and store the data that way first -- for example, if your whole table of four million entries included a roughly flat distribution of the second (integer) key you could bust the whole up into buckets in a pre-pass, producing a few hundred or few thousand lists with self-similar second keys:</p>\n\n<pre><code> list_241 = [('hello', 241, 1), ('goodbye', 241, 2), ('yo!', 241, 3)....]\n list_242 = [('hi', 242, 3), ('hola', 242, 4)...]\n</code></pre>\n\n<p>then you store the lists in a dictionary and grab them as a first pass, then do the brute force search in the sub-list of thousands instead of the master list of millions. Of course some data won't lend itself to this either, but if it looks anything like your sample it should not be too hard. THe binning doesn't have to be super logical - you could bin on the length of the string in item[0] or the first letter as easily as you could on item <a href=\"https://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table\">1</a> -- but to be useful it will need to produces bins of similar size. The nice thing is that with really big lists it's easy to rack up big gains: even going from 1 list of 4million to 10 lists of 400000 will probably make things faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T20:23:19.477",
"Id": "32083",
"ParentId": "32078",
"Score": "-1"
}
},
{
"body": "<p>If all your queries are similar to the example, you would obviously benefit from storing the data in a <code>dict</code> where a tuple of two values is the key, and the value is a list of ints -- all of the third items that share the same key.</p>\n\n<pre><code>from collections import defaultdict\n\nstuff_dict = defaultdict(list)\nfor t in stuff_tuple:\n stuff_dict[t[:2]].append(t[2])\n\nfor item in stuff_dict['hello', 241]:\n print item\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T05:33:56.137",
"Id": "32111",
"ParentId": "32078",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32111",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T17:19:24.890",
"Id": "32078",
"Score": "1",
"Tags": [
"python"
],
"Title": "Search set, return item"
}
|
32078
|
<p>I wrote some code using meteor, which is working, but I don't know if I did it the best way. I'm asking for opinions on other ways to perform this task.</p>
<p>It's just a list of places. You can fill the textfield with a place and it'll appear on the list. You have an option to remove the place by clicking on the "x".</p>
<p>Very simple, but I'm new to meteor.</p>
<h2>place_list.js</h2>
<pre><code> Places = new Meteor.Collection('placesNew');
if(Meteor.isClient){
Template.places_list.places = function(){
return Places.find({},{sort:{name: 1}});
console.log(Template.place_list.place);
}
Template.places_list.events({
'blur .place': function (obj) {
Places.insert({name: obj.target.value});
},
'click .plc_remove': function(obj){
Places.remove( obj.toElement.attributes['data-ref'].value);
}
});
}
</code></pre>
<h2>place_list.html</h2>
<pre><code><head>
<title>Place List</title>
</head>
<body>
<h1>Place List :</h1>
{{> places_list}}
</body>
<template name="places_list">
<input type="text" placeholder="Insert a place here" class="place" />
<ul>
{{#each places}}
<li> {{ name}} | <a class="plc_remove" data-ref="{{_id}}" href="#">x</a> | </li>
{{/each}}
</ul>
</template>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T21:46:35.700",
"Id": "51248",
"Score": "1",
"body": "Would you prefer a new tag for meteor.js?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T22:01:17.573",
"Id": "51249",
"Score": "0",
"body": "Yep! it's sounds greate... or just a meteor tag, like stackoverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:20:58.540",
"Id": "58128",
"Score": "0",
"body": "I think that you are missing a `{` somewhere or you have an extra floating at the end of your .js"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:24:12.687",
"Id": "58529",
"Score": "0",
"body": "It looks good to me. No obvious errors or gotchas."
}
] |
[
{
"body": "<p>Great start! You're very close. I changed things around a little bit, and added an extra template and a separate event map for that template. This should make it easier to understand, and it means you don't have to store the place's id in a data attribute. Check it out:</p>\n\n<pre><code>Places = new Meteor.Collection('places');\n\nif(Meteor.isClient) {\n Template.places_list.places = function () {\n return Places.find({}, { sort: { name: 1 } });\n }\n\n Template.places_list.events({\n 'keypress #place': function (evt) {\n if (evt.which === 13) {\n // The user pressed enter\n Places.insert({ name: evt.currentTarget.value });\n place.currentTarget.value = ''; // Reset the text input\n }\n }\n });\n\n Template.place_item.events({\n 'click .plc_remove': function () {\n Places.remove(this._id); // Access the document fields with this.foo\n }\n });\n}\n</code></pre>\n\n<p>And the HTML:</p>\n\n<pre><code><head>\n <title>Place List</title>\n</head>\n<body>\n <h1>Place List :</h1> \n {{> places_list}}\n</body>\n\n<template name=\"places_list\">\n <input type=\"text\" placeholder=\"Insert a place here\" id=\"place\" />\n\n <ul>\n {{#each places}}\n {{> place_item}}\n {{/each}}\n </ul>\n</template>\n\n<template name=\"place_item\">\n <li> {{ name}} | <a class=\"plc_remove\" href=\"#\">x</a> | </li>\n</template>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T18:00:41.693",
"Id": "32300",
"ParentId": "32086",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T21:26:49.900",
"Id": "32086",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"meteor"
],
"Title": "Better way to write list of places program"
}
|
32086
|
<p>Meteor is an Open-Source JavaScript web framework that provides a modular platform for developing client/server applications in pure JavaScript.<br>
Meteor's core consists of the DDP (Distributed Data Protocol), which is merely a client-server protocol for querying/updating a server-side database, as well as for synchronizing such updates among clients. Meteor's DDP utilizes the publish-subscribe (pubsub) messaging pattern.</p>
<p><a href="https://www.meteor.com/" rel="nofollow">Meteor.com</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T22:07:02.137",
"Id": "32087",
"Score": "0",
"Tags": null,
"Title": null
}
|
32087
|
This tag is for questions written using the Meteor open-source web framework. These questions should also be tagged with [javascript].
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T22:07:02.137",
"Id": "32088",
"Score": "0",
"Tags": null,
"Title": null
}
|
32088
|
<p>Originally my wireframe was </p>
<p><img src="https://i.stack.imgur.com/c5sIz.png" alt="original wireframe"></p>
<p>But I ended up going with this in testing. The image is the result of my new code. </p>
<p><img src="https://i.stack.imgur.com/3mrlJ.png" alt="prototype 1"></p>
<p>Keep in mind that the actual content is just filler content and will be dynamic. I just wanted to get the styling in place. </p>
<p>I created each article with the following code</p>
<p><strong>HTML</strong></p>
<pre><code><div class="discusBox">
<img src="http://placekitten.com/120/120"> <!-- just for testing -->
<div class="discusTitle">
<h3>[test] Title of the Discussion</h3> <!-- just for testing -->
</div>
<div class="discusBrief">
<p>Here we are talking about something. and this is the short brief about it.</p>
<!-- just for testing -->
</div><!-- end of discusBrief -->
<div class="discusMeta">
<div class="discusMetaPostedOn">
<span>Posted on</span>
<span class="discusMetaPostedOnDate">
4/4/1984 <!-- just for testing -->
</span>
</div>
<div class="discusBy">
<span>by</span>
<span>
Firstname Surname <!-- just for testing -->
</span>
</div>
<div class="discusLink">
<a href="#">View &rarr;</a> <!-- just for testing -->
</div>
</div><!-- end of discusMeta -->
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.discusBox {
border: #333 solid 1px;
height: 120px;
width: 720px;
position: relative;
background-color: #fff;
}
.discusTitle {
line-height: 40px;
padding-left: 6px;
position: absolute;
top: 0;
left: 120px;
width: 600px;
vertical-align: middle;
}
.discusTitle h3 {
font-size: 18px;
font-weight: bold;
}
.discusBrief {
height: 60px;
width: 600px;
position: absolute;
top: 40px;
left: 120px;
overflow: hidden;
}
.discusBrief p { padding-left: 6px; }
.discusMeta {
height: 20px;
width: 600px;
position: absolute;
top: 100px;
left: 120px;
font-size: 11px;
line-height: 20px;
vertical-align: middle;
}
.discusMetaPostedOn, .discusBy {
display: inline;
float: left;
}
.discusMetaPostedOn {
padding-left: 6px;
margin-right: 24px;
}
.discusMetaPostedOn p { margin-bottom: 0;}
.discusBy { }
.discusLink {
float: right;
background-color: #2fb7e0;
width: 120px;
text-align: center;
}
.discusLink a{
color: #fff;
text-decoration: none;
display: block;
}
</code></pre>
|
[] |
[
{
"body": "<p>this looks really good so far, </p>\n\n<p>I don't see anything that I would change about this. you are using <code>span</code> tags correctly and efficiently for what you are doing with them, your <code>div</code> tags are also used to the best of their abilities.</p>\n\n<p>your CSS also looks good, I don't think I would change anything there either.</p>\n\n<p>I guess the only thing that I might change, and this depends on how you intend to use it, is probably the grouping of the <code>discusBy</code> and the <code>discusMetaPostedOn</code>, I might group those together because they look like they are going to be the same formatting aside from the things that you have given specific classes to. </p>\n\n<p>you might want to give each <code><div class=\"discusBox\"></code> it's own unique ID especially if you are going to work some Javascript magic or server-side magic on it. </p>\n\n<p>otherwise it looks really good, you probably won't make any of the changes I mentioned because of the way you want to go forward with the code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T22:25:13.613",
"Id": "53860",
"Score": "1",
"body": "While I appreciate the time you took to write your response. Telling me to check with various browsers is something that all of us web developers do by default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T22:31:09.103",
"Id": "53862",
"Score": "0",
"body": "yeah, I hear that......"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T18:00:28.867",
"Id": "33610",
"ParentId": "32092",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:13:55.677",
"Id": "32092",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "Review of HTML and CSS for a newsfeed of posts"
}
|
32092
|
<p>I am pretty new to Python but I'm learning from classes.</p>
<p>I am working on a project for class and this is my code. Anyone got a better idea of a way to organize the code or put it differently so there aren't so many conditional statements?</p>
<pre><code>def cm(centimeter):
"""Centimeter to Meters Converter!"""
if centimeter == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = round(centimeter / 100)
print ("%d centimeters is the same as %d meters." % (centimeter, result))
def meter(meter):
"""Meter to Centimeters Converter!"""
if meter == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = round(meter * 100)
print ("%d meters is the same as %d centimeters." % (meter, result))
def cent2(centin):
"""Centimeter to Inches Converter!"""
if meter == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = centin * 0.39
print ("%d centimeters is the same as %d inches." % (centin, result))
def inchcm(inches):
"""Feet to Meters Converter!"""
if inches == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = inches / 0.39
print ("%d inches is the same as %d centimeters." % (inches, result))
def kmmiles(km):
"""Meters to Inches Converter!"""
if km == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = km * 0.62137
print ("%d km is the same as %d miles." % (km, result))
def mileskm(miles):
"""Miles to KM Converter!"""
if miles == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = miles / 0.62137
print ("%d miles is the same as %d kilometers." % (miles, result))
def fer(fc):
"""Farenheight to Celcius Converter!"""
if fc == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = (fc - 32) * 5/9
print ("%d farenheit is the same as %d celcius." % (fc, result))
def cel(cf):
"""Farenheight to Celcius Converter!"""
if cf == ("false"):
print ("It looks like you input a value that wasn't a number! Try again!")
else:
result = cf * 9/5 + 32
print ("%d celcius is the same as %d farenheit." % (cf, result))
print ("Kevin's Sexy Converter!")
print("")
print("A. Length")
print("B. Temperature")
print("C. Mass")
print("")
type=input("Please choose an option: ")
if type == ("a") or type ==("A"):
print("")
print("1. CM to Meters")
print("2. Meters to CM")
print("3. CM to Inches")
print("4. Inches to CM")
print("5. KM to Miles")
print("6. Miles to KM")
print("")
test=input("Please choose an option: ")
if test == ("1"):
cent=input("Centimeters: ")
if cent.isdigit():
cm(int(cent))
else:
cm("false")
elif test == ("2"):
meters=input("Meters: ")
if meters.isdigit():
meter(int(meters))
else:
meter("false")
elif test == ("3"):
centin=input("Centimeters: ")
if centin.isdigit():
cent2(int(centin))
else:
centin("false")
elif test == ("4"):
inches=input("Inches: ")
if inches.isdigit():
inchcm(int(inches))
else:
feeet("false")
elif test == ("5"):
km=input("KM: ")
if km.isdigit():
kmmiles(int(km))
else:
metersin("false")
elif test == ("6"):
miles=input("Miles: ")
if miles.isdigit():
mileskm(int(miles))
else:
metersin("false")
else:
print("You did not choose a valid option!")
elif type == ("b") or type == ("B"):
print("")
print("1. Farenheit to Celcius")
print("2. Celcius to Farenheit")
print("")
temp=input("Please choose an option: ")
if temp == ("1"):
fc=input("Fahrenheit: ")
if fc.isdigit():
fer(int(fc))
else:
fc("false")
if temp == ("2"):
cf=input("Celsius: ")
if cf.isdigit():
cel(int(cf))
else:
cf("false")
else:
print("You did not choose a valid option!")
</code></pre>
|
[] |
[
{
"body": "<p>Instead of trying to determine if the input is a number and then looking for a special value (<code>\"false\"</code>), let Python determine if the input is a number:</p>\n\n<pre><code>def cm(centimeter):\n \"\"\"Centimeter to Meters Converter!\"\"\"\n result = round(centimeter / 100)\n print (\"%d centimeters is the same as %d meters.\" % (centimeter, result))\n...\n try:\n if test == (\"1\"):\n cent=input(\"Centimeters: \")\n cm(int(cent))\n if ....\n except ValueError:\n print (\"It looks like you input a value that wasn't a number! Try again!\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:48:33.230",
"Id": "51267",
"Score": "0",
"body": "Thanks! I did that and it works but for some reason if I put a number that isn't defined under the try statement than it won't say what its supposed to say after the except statement. Any idea?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:40:17.350",
"Id": "32094",
"ParentId": "32093",
"Score": "-2"
}
},
{
"body": "<p>First of all i would return the data and print them\nand second i would create a new function for the testing</p>\n\n<pre><code>def check_if_is_digit(data_input):\n try:\n int(data_input) #or float(data_input) for int, long, float\n except ValueError:\n return False\n return True\n\ndef cm(centimeter):\n \"\"\"Centimeter to Meters Converter!\"\"\"\n if check_if_is_digit(centimeter):\n result = round(centimeter / 100)\n return(\"%d centimeters is the same as %d meters.\" % (centimeter, result))\n\n return(\"It looks like you input a value that wasn't a number! Try again!\")\n\n# example\nprint(cm(100))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T00:54:55.267",
"Id": "64668",
"Score": "0",
"body": "The check_if_is_digit function seems redundant - the `isdigit` method does more or less the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T07:58:09.480",
"Id": "64683",
"Score": "0",
"body": "`>>> \"-1\".isdigit()\nFalse`\nThats the reason i didn't used the isdigit()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T00:29:52.837",
"Id": "64811",
"Score": "0",
"body": "Okay but it may not have been the OP's intention to allow negative values. It would make sense for temperatures but not for other units. Also, it might be easier just to build the try...except into the conversion function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T13:29:26.100",
"Id": "38693",
"ParentId": "32093",
"Score": "0"
}
},
{
"body": "<p><strong>To remove repetition</strong></p>\n\n<p>If you set up a list of the possible conversions:</p>\n\n<pre><code>conversions = [\n ('cm', 'meters'), \n ('meters', 'cm'), \n ('cm', 'inches'), \n ('inches', 'cm'), \n ('km', 'miles'), \n ('miles', 'km')\n]\n</code></pre>\n\n<p>And a dictionary of the factors required to convert each unit into metres:</p>\n\n<pre><code>meters = {\n 'meters': 1.0,\n 'cm': 0.01,\n 'inches': 0.0254,\n 'km': 1000\n}\n</code></pre>\n\n<p>Then (e.g.) if the user asks for conversion type 3 - cm to inches - look up the conversion from the list of conversions:</p>\n\n<pre><code>convert_from, convert_to = conversions[int(user_choice) - 1]\n</code></pre>\n\n<p>Then to convert cm to inches, you multiply by 0.01 to get a number of metres then divide by 0.0254 to get a number of inches, which will look like this in your code:</p>\n\n<pre><code>result = original_amount * meters[convert_from] / meters[convert_to]\n</code></pre>\n\n<p>This will allow you to combine all of the length conversions into a single short function and remove all of the if...then... elif... repetition. You will still need a separate function for temperature.</p>\n\n<p><strong>Taking user input</strong></p>\n\n<p>In some places you tell the user to 'try again' but at this point the programme terminates. Usually you would want a <code>while</code> loop that repeats until the user enters a valid response:</p>\n\n<pre><code>while True:\n amount = input(convert_from + ': ')\n if amount.isdigit():\n result = float(amount) * meters[convert_from] / meters[convert_to]\n print('%s %s is the same as %d %s' % (amount, convert_from, result, convert_to))\n break\n else:\n print(\"It looks like you input a value that wasn't a number! Try again!\")\n</code></pre>\n\n<p>Alternatively, it is often useful to use <code>try</code>...<code>except</code>: attempt to process the user's input, and if that causes an error, ask them to respond again:</p>\n\n<pre><code>while True:\n amount = input(convert_from + ': ')\n try:\n result = float(amount) * meters[convert_from] / meters[convert_to]\n print('%s %s is the same as %d %s' % (amount, convert_from, result, convert_to))\n break\n except ValueError:\n print(\"It looks like you input a value that wasn't a number! Try again!\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:19:08.303",
"Id": "38719",
"ParentId": "32093",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:31:07.203",
"Id": "32093",
"Score": "5",
"Tags": [
"python",
"beginner",
"converting"
],
"Title": "Organization of measurements converter"
}
|
32093
|
<p>I am currently writing an app that converts musical keys. In a nutshell the conversion part of the script, is one giant if / then statement (if the user selected A then display B, etc etc.).</p>
<p>While this works perfectly fine, I definitely feel like this is fairly crude, and extremely lengthy, with all of the keys that need to be converted.</p>
<p>The following is an excerpt of the conversion function. It should be fairly readable, but basically the function first checks to make sure they've selected two keys (in this example C and B♭) and then checks the note (and whether or not it's sharp or flat), and then puts the correct answer in a couple of divs I have on the page (<code>.noteName</code> and <code>.supNote</code>).</p>
<pre><code>//C to Bb Conversion
if (firstInstSelected == "C" && secondInstSelected == "Bb") {
if (firstNote == "A" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("B");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "A" && secondNote == "sharp" || firstNote == "B" && secondNote == "flat") {
$('#' + btnLabelSelected).find('.noteName').text("C");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "B" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("C");
$('#' + btnLabelSelected).find('.supNote').text("#");
return false;
}
if (firstNote == "C" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("D");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "C" && secondNote == "sharp" || firstNote == "D" && secondNote == "flat") {
$('#' + btnLabelSelected).find('.noteName').text("E");
$('#' + btnLabelSelected).find('.supNote').text("b");
return false;
}
if (firstNote == "D" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("E");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "D" && secondNote == "sharp" || firstNote == "E" && secondNote == "flat") {
$('#' + btnLabelSelected).find('.noteName').text("F");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "E" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("F");
$('#' + btnLabelSelected).find('.supNote').text("#");
return false;
}
if (firstNote == "F" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("G");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "F" && secondNote == "sharp" || firstNote == "G" && secondNote == "flat") {
$('#' + btnLabelSelected).find('.noteName').text("A");
$('#' + btnLabelSelected).find('.supNote').text("b");
return false;
}
if (firstNote == "G" && secondNote == undefined) {
$('#' + btnLabelSelected).find('.noteName').text("A");
$('#' + btnLabelSelected).find('.supNote').text("");
return false;
}
if (firstNote == "G" && secondNote == "sharp" || firstNote == "A" && secondNote == "flat") {
$('#' + btnLabelSelected).find('.noteName').text("B");
$('#' + btnLabelSelected).find('.supNote').text("b");
return false;
} else {
$('#' + btnLabelSelected).find('.noteName, .supNote').text("");
$('#' + btnLabelSelected).find('.noteFont').removeClass('hide');
}
}
</code></pre>
<p>As you can see, this is really lengthy, and the app needs to have a bunch of these, so as you might imagine, that's a seriously long / redundant function.</p>
<p>I thought about perhaps maybe putting the correct answers into an array, and trying to grab the right answer from the array, but I'm sure if that would really save me any code length? (because I still would need a bunch of conditions, if the person selected keys C and B♭ and then the note A, etc etc.)</p>
<p>I'm hoping some of you JavaScript / jQuery wizards out there might have an alternative solution for me to shorten this up and make it more compact.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:35:39.707",
"Id": "51252",
"Score": "0",
"body": "you could use a switch statement instead. http://www.w3schools.com/js/js_switch.asp That way your script stops when it finds a match and doesn't have to check the other conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T19:17:38.967",
"Id": "51253",
"Score": "0",
"body": "I want to thank everyone for the very creative answers. There really is some great stuff here, which is why this is an awesome community, so thanks for everyone's suggestions. :)"
}
] |
[
{
"body": "<p>This is just a nebulous thought, but you could make each key an array ie Cmaj=(c,d,e,...), Dmaj=(d,e,f#,...) then take the position in the original key's array of the note to be transposed and find the note at that position in the target key's array. So for example if the keys were Cmaj and Dmaj as before and the note to be transposed was 'e' you find its position in the first array (2) and check the target array at position 2 and you get 'f#'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T20:46:10.823",
"Id": "51254",
"Score": "0",
"body": "That's a very interesting idea. It's definitely worth further exploration, although it *might* be a bit above my jquery / javascript abilities."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:42:27.307",
"Id": "32096",
"ParentId": "32095",
"Score": "0"
}
},
{
"body": "<p>yeah I'd use a data structure that encodes the \"business logic\" and then a simple lookup to update the UI:</p>\n\n<pre><code>var notes = {\n CBb: {\n A: { noteName: \"B\", supNote: \"\" },\n Asharp: { noteName: \"C\", supNote: \"\" },\n Bflat: { noteName: \"C\", supNote: \"\" },\n ...\n },\n CF: {\n A: { noteName: \"B\", supNote: \"\" },\n Asharp: { noteName: \"C\", supNote: \"\" },\n Bflat: { noteName: \"C\", supNote: \"\" },\n ...\n }\n};\n\nvar findNote = function (firstInstSelected, secondInstSelected, firstNote, secondNote) {\n var outer = notes[firstInstSelected + (secondInstSelected || \"\")];\n return outer && outer[firstNote + (secondNote || \"\")];\n};\n\n\n//...your event handler...\nvar note = findNote(firstInstSelected, secondInstSelected, firstNote, secondNote);\nif (note) {\n $(\"#\" + btnLabelSelected).find(\".noteName\").text(note.noteName);\n $(\"#\" + btnLabelSelected).find(\".supNote\").text(note.supNote);\n return false;\n}\n\n$('#' + btnLabelSelected).find('.noteName, .supNote').text(\"\");\n$('#' + btnLabelSelected).find('.noteFont').removeClass('hide');\n</code></pre>\n\n<p>This keeps your logic nice and tidy and easy to understand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:03:12.873",
"Id": "51255",
"Score": "0",
"body": "Love this solution. Almost easy to wrap my brain around, I think this will be the first one I attempt to impliment. Only thing I'm a bit confused on is this looks awesome for one set only, but if I need multiple versions of this, (CBb:, CF:, CEb, etc etc) I would just use a different var name (not notes) for each grouping, right? Or would I combine all the possible groupings into the one notes var (At the top of the answer) and then somehow in the event handler select the right array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:46:48.217",
"Id": "51256",
"Score": "0",
"body": "Based only on your example, all would be done within the same `notes` variable. Notice it is a nested structure. The outer-level would be the groupings `CBb`, `CF`, `CEb`, ... and then the inner-level are the values for that grouping. I added a `CF` to my example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:57:10.923",
"Id": "51257",
"Score": "0",
"body": "This solution would require an object for each combination of keys, or 12 choose 2 = 66 objects (or more if you construct objects separately for identical sharps and flats). Instead, it would be easier to recognize that keys are related mathematically and just store the offsets between keys in an object, then index into an array with these offsets. See my answer below with an implementation of such a function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:43:08.150",
"Id": "32097",
"ParentId": "32095",
"Score": "6"
}
},
{
"body": "<p>First of all, is there a good reason you are separating the sharps/flats from their owning note? Why wouldn't the firstNote be \"F#\" for example.. Not only would that immediately flatten and simplify some of the conditionals, it would more accurately represent the actual real world data (namely.. the first note IS an \"F#\" not an \"F\" followed by a \"#\" note. That doesn't make real world sense).</p>\n\n<p>How you could do this is create an object with keys (haha) being your \"from\" musical key and values being your \"to\" musical key. Then you simply look up notes from that object.</p>\n\n<p>Since musical keys are offset mathematically, though, you could also have an array of notes with an object that keeps track of keys' offsets from other keys. You'd then index into this array with the appropriate offset in the conversion function. This is slightly more complicated that the object approach, but means you wouldn't have to build an object for each conversion, which is actually a huge win, since 12 choose 2 is 66. So you'd have to hard code 66 objects rather than just 66 offsets from each key to each other key.</p>\n\n<p>Edit2: Here's a fiddle: <a href=\"http://jsfiddle.net/FX5CU/3/\" rel=\"nofollow\">http://jsfiddle.net/FX5CU/3/</a></p>\n\n<p>Edit: added array implementation.</p>\n\n<pre><code>var notes = ['A', 'A#/Bb', 'B', 'C', 'C#/Db', 'D', 'D#/Eb', 'E', 'F', 'F#/Gb', 'G', 'G#/Ab']\n , positions = { 'A': 0\n , 'A#':1\n , 'Bb':1\n , 'B': 2\n , 'C': 3\n , 'C#':4\n , 'Db':4 //This encodes the positions in the array for each note.\n , 'D': 5\n , 'D#':6\n , 'Eb':6\n , 'E': 7\n , 'F': 8\n , 'F#':9\n , 'Gb':9\n , 'G':10\n , 'G#':11\n , 'Ab':11\n }\n , keyOffsets={'AA#':1\n ,'ABb':1\n ,'AB':2\n ,'AC':3\n /**etc**/ // Every pair of offsets here. You could get tricky and only\n ,'FC': -5 // store one direction if you wanted\n ,'FC#':-4 \n /**etc**/\n }\n ;\nfunction transpose( key1, key2, note){\n return notes[positions[note] + keyOffsets[key1 + key2]]\n}\n</code></pre>\n\n<p>Pretty neat, eh? The function finds the array position of your starting note in your <code>positions</code> object and gets the offset between the two keys by looking in your <code>keyOffsets</code> object. Adding these together yields the position in your <code>notes</code> array of the note in the new key. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T20:45:06.987",
"Id": "51258",
"Score": "0",
"body": "Well, yes, I suppose it would have helped for you to see how people are selecting the notes, so envision if you a will a telephone keypad, it's very similar. \n\nThe redundancy is so that if a user presses the sharp or flat key and doesn't press an actual note first, the program can deal with this scenario adequately. Am I thinking about this improperly? Possibly, as it's easy for me to get \"lost in the logic\" of the thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T21:22:13.077",
"Id": "51259",
"Score": "0",
"body": "Hmm.. UX-wise I wonder if the keypad would be better implemented as a one button for each possible note (shared buttons for A#/Bb etc). Seems like it'd lower amount of clicks by a decent amount for just two additional buttons (8 notes + # and b for 10 vs. 12 notes). This would help simplify the logic as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T23:47:43.140",
"Id": "51260",
"Score": "0",
"body": "Because..err..umm.. yeah, um. I guess I didn't consider making a few extra buttons to integrate #'s /b's. At first the extra button press didn't seen like much of a big deal, however, that's actually a pretty good idea.. duh, I should have thought of that. \n\nYour offset'd array idea is very cool. I'm going to have to study it for a while to really grasp what your doing, at first glance I'm not entirely sure how to get it up and running, but I'm sure with a bit of study of study and possibly another question or two, this one really might be the way to go. Thanks for this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T19:16:58.493",
"Id": "51261",
"Score": "0",
"body": "Wyatt, I'm pretty sure this is definitely going to be the accepted answer, would you be opposed to me asking you a question or two via email to implement this? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T19:49:19.273",
"Id": "51262",
"Score": "0",
"body": "Not at all. Talk to you soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T22:01:14.077",
"Id": "51263",
"Score": "0",
"body": "Or I don't suppose you could toss this up in a jfiddle, so I could check it out that way? Also, as I'm new here, I don't know if it's ok to post my email addy for you here, but it's on my profile, so please drop me a line at your earliest convenience. Thanks Wyatt!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:39:51.323",
"Id": "51264",
"Score": "0",
"body": "@Nick Check out http://jsfiddle.net/FX5CU/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T23:50:56.110",
"Id": "51268",
"Score": "0",
"body": "@Nick Edited http://jsfiddle.net/FX5CU/1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:28:26.920",
"Id": "51355",
"Score": "0",
"body": "Hi Wyatt,\n\nI checked out the fiddle, and the first thing that didn't work out of the gate, was the C to Bb conversion (try any note and you get an undefined error). So while I'm still muddling through your solution, I don't know how to fix this. My guess is perhaps it's an problem with the math in calculating the offset? Could you possibly take a look at the fiddle again and see if something jumps out at you? Thanks Wyatt, I owe you a beer or three for your help. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:36:46.510",
"Id": "51361",
"Score": "0",
"body": "@Nick Oh, woops. It is the `toUpperCase()` call. I wanted to allow lower case inputs, but I stored all flats as lowercase b in the offsets objects. Silly mistake, fixed in http://jsfiddle.net/FX5CU/2/ by checking explicitly for flats in the input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:58:09.073",
"Id": "51365",
"Score": "0",
"body": "Hi Wyatt, that's cool, that was my second guess, and your correction got rid of the undefined error, which is fantastic, yet the calculation is incorrect (in my test example, converting from C to Bb and choosing the letter A should produce an answer of B, not G.) So that we can take this offline, here's my email addy: leftygtrplayer at gmail and perhaps you can give me a pointer on how to correct this. Thanks! :)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:48:40.840",
"Id": "32098",
"ParentId": "32095",
"Score": "3"
}
},
{
"body": "<p>Convert the keys (start and end) and the note into numbers that represent semitones (a value from 0 to 11) do the calculation and then go back from semitone number to standard notation.</p>\n\n<p>A ---> 0</p>\n\n<p>A# ---> 1</p>\n\n<p>B ---> 2</p>\n\n<p>C ---> 3</p>\n\n<p>...</p>\n\n<p>G# ---> 11</p>\n\n<p>Do this with a <strong>switch</strong> statement</p>\n\n<p>Once you have <strong>startNote</strong>, <strong>startKey</strong>, <strong>endKey</strong></p>\n\n<p>You get <strong>endNote</strong> this way:</p>\n\n<pre><code>endNote = (endKey - startKey) + startNote;\nendNote = (endNote<0?endNote+12:endNote%12);\n</code></pre>\n\n<p>Hope it's clear enought </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:53:51.897",
"Id": "32099",
"ParentId": "32095",
"Score": "1"
}
},
{
"body": "<p>Interesting question. Being notes within a musical scale, presumably theres some way of automatically generating the array. I'm too tired now to even consider such a proposition. However, here's roughly how I'd go throwing into an array: (each of the 3 very basic tests pass)</p>\n\n<p><strong>The output is:</strong></p>\n\n<pre><code>$('#' + btnLabelSelected).find('.noteName').text('E');\n$('#' + btnLabelSelected).find('.supNote').text('b');\n\n$('#' + btnLabelSelected).find('.noteName').text('E');\n$('#' + btnLabelSelected).find('.supNote').text('_flat_');\n\n$('#' + btnLabelSelected).find('.noteName, .supNote').text('');\n$('#' + btnLabelSelected).find('.noteFont').removeClass('hide'); \n</code></pre>\n\n<p><strong>Code:</strong></p>\n\n<pre><code><!DOCTYPE html>\n<html>\n<head>\n<script>\nfunction mInit()\n{\n // expecting to see this data ---> noteName: \"E\", supNote: \"b\"},\n emitCode(\"C\", \"Bb\", \"D\", \"flat\");\n\n // expecting to see this data ---> noteName: \"E\", supNote: \"_flat_\"},\n emitCode(\"C#\", \"Bb\", \"D\", \"flat\");\n\n // expecting to see calls to set supNote text to '' and to remove the hide class from noteFont\n emitCode(\"C\", \"Bb\", \"D\", \"garbage\");\n}\n\n\nwindow.addEventListener('load', mInit, false);\n\nvar dataArray =\n[\n {\n firstInst: \"C\", \n secondInst: \"Bb\", \n conditions: \n [\n { firstNote: \"A\", secondNote: undefined, noteName: \"B\", supNote: \"\"},\n { firstNote: \"A\", secondNote: \"sharp\", noteName: \"C\", supNote: \"\"},\n { firstNote: \"B\", secondNote: \"flat\", noteName: \"C\", supNote: \"\"},\n { firstNote: \"B\", secondNote: undefined, noteName: \"C\", supNote: \"#\"},\n { firstNote: \"C\", secondNote: undefined, noteName: \"D\", supNote: \"\"},\n { firstNote: \"C\", secondNote: \"sharp\", noteName: \"E\", supNote: \"b\"},\n { firstNote: \"D\", secondNote: \"flat\", noteName: \"E\", supNote: \"b\"},\n { firstNote: \"D\", secondNote: undefined, noteName: \"E\", supNote: \"\"},\n { firstNote: \"D\", secondNote: \"sharp\", noteName: \"F\", supNote: \"\"},\n { firstNote: \"E\", secondNote: \"flat\", noteName: \"F\", supNote: \"\"},\n { firstNote: \"E\", secondNote: undefined, noteName: \"F\", supNote: \"#\"},\n { firstNote: \"F\", secondNote: undefined, noteName: \"G\", supNote: \"\"},\n { firstNote: \"F\", secondNote: \"sharp\", noteName: \"A\", supNote: \"b\"},\n { firstNote: \"G\", secondNote: \"flat\", noteName: \"A\", supNote: \"b\"},\n { firstNote: \"G\", secondNote: undefined, noteName: \"A\", supNote: \"\"},\n { firstNote: \"G\", secondNote: \"sharp\", noteName: \"B\", supNote: \"b\"},\n { firstNote: \"A\", secondNote: \"flat\", noteName: \"B\", supNote: \"b\"}\n ]\n },\n {\n firstInst: \"C#\", \n secondInst: \"Bb\", \n conditions: \n [\n { firstNote: \"A\", secondNote: undefined, noteName: \"B\", supNote: \"\"},\n { firstNote: \"A\", secondNote: \"sharp\", noteName: \"C\", supNote: \"\"},\n { firstNote: \"B\", secondNote: \"flat\", noteName: \"C\", supNote: \"\"},\n { firstNote: \"B\", secondNote: undefined, noteName: \"C\", supNote: \"#\"},\n { firstNote: \"C\", secondNote: undefined, noteName: \"D\", supNote: \"\"},\n { firstNote: \"C\", secondNote: \"sharp\", noteName: \"E\", supNote: \"b\"},\n { firstNote: \"D\", secondNote: \"flat\", noteName: \"E\", supNote: \"_flat_\"}, // **\n { firstNote: \"D\", secondNote: undefined, noteName: \"E\", supNote: \"\"},\n { firstNote: \"D\", secondNote: \"sharp\", noteName: \"F\", supNote: \"\"},\n { firstNote: \"E\", secondNote: \"flat\", noteName: \"F\", supNote: \"\"},\n { firstNote: \"E\", secondNote: undefined, noteName: \"F\", supNote: \"#\"},\n { firstNote: \"F\", secondNote: undefined, noteName: \"G\", supNote: \"\"},\n { firstNote: \"F\", secondNote: \"sharp\", noteName: \"A\", supNote: \"b\"},\n { firstNote: \"G\", secondNote: \"flat\", noteName: \"A\", supNote: \"b\"},\n { firstNote: \"G\", secondNote: undefined, noteName: \"A\", supNote: \"\"},\n { firstNote: \"G\", secondNote: \"sharp\", noteName: \"B\", supNote: \"b\"},\n { firstNote: \"A\", secondNote: \"flat\", noteName: \"B\", supNote: \"b\"}\n ]\n },\n];\n\nfunction emitCode(firstInst, secondInst, firstNote, secondNote)\n{\n var i, n;\n\n n = dataArray.length;\n for (i=0; i<n; i++)\n {\n if ((dataArray[i].firstInst == firstInst) && (dataArray[i].secondInst == secondInst))\n {\n var j, m = dataArray[i].conditions.length;\n for (j=0; j<m; j++)\n {\n if (firstNote == dataArray[i].conditions[j].firstNote && secondNote == dataArray[i].conditions[j].secondNote)\n {\n console.log(\"$('#' + btnLabelSelected).find('.noteName').text('\" + dataArray[i].conditions[j].noteName + \"');\");\n console.log(\"$('#' + btnLabelSelected).find('.supNote').text('\" + dataArray[i].conditions[j].supNote + \"');\");\n return;\n }\n }\n console.log(\"$('#' + btnLabelSelected).find('.noteName, .supNote').text('');\");\n console.log(\"$('#' + btnLabelSelected).find('.noteFont').removeClass('hide');\");\n return;\n }\n }\n}\n\n</script>\n<style>\n</style>\n</head>\n<body>\n</body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T20:48:07.240",
"Id": "51265",
"Score": "0",
"body": "Your solution \"looks\" very elegant, and it will take me some time to muddle through the understanding of it. It appears fairly complex in nature. If this is you coding when you're \"wiped out\" I'm scared to see what you'd come up with when you're firing on all cylinders. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T17:19:45.813",
"Id": "32100",
"ParentId": "32095",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "32098",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:29:46.023",
"Id": "32095",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"music"
],
"Title": "Transposing notes by one whole step"
}
|
32095
|
<p>I have the following, quite ugly statement - is there a better way to write something of this nature?</p>
<pre><code>if (!item["Created By"].ToString().Contains("System Account") &&
!item.Url.Contains("_catalogs") &&
!item.Url.Contains("Style Library") &&
!item.Url.Contains("Cache Profiles") &&
!item.ContentType.ToString().Contains("Theme Gallery") &&
!item.ContentType.ToString().Contains("Converted Forms") &&
!item.ContentType.ToString().Contains("Page Output Cache") &&
!item.ContentType.ToString().Contains("Master Page"))
{
query.RecordItems(item.ID.ToString(), item.ContentType.Name,
item.DisplayName, item.Name,
"", item.Url, item["Created By"].ToString(),
"",
Convert.ToDateTime(item["Modified"]),
item["Modified By"].ToString(),
Convert.ToDateTime(item["Created"]),
item["Created By"].ToString());
}
</code></pre>
<p>For a frame of reference, here's the proceeding code:</p>
<pre><code>using (var web = activeSiteCollection.OpenWeb())
{
foreach (SPList list in web.Lists)
{
query.RecordLists(list.ID.ToString(), list.Author.ToString(), list.Title,
list.DefaultViewUrl,
list.ParentWeb.Title, list.ParentWebUrl, list.ItemCount,
list.LastItemModifiedDate, list.LastItemDeletedDate);
// check if files exist in the document library, if they don't break out to next level
if (list.ItemCount <= 0) continue;
for (int i = 0; i < list.Items.Count; i++)
{
try
{
SPListItem item = list.Items[i];
if (!item["Created By"].ToString().Contains("System Account") &&
!item.Url.Contains("_catalogs") &&
!item.Url.Contains("Style Library") &&
!item.Url.Contains("Cache Profiles") &&
!item.ContentType.ToString().Contains("Theme Gallery") &&
!item.ContentType.ToString().Contains("Converted Forms") &&
!item.ContentType.ToString().Contains("Page Output Cache") &&
!item.ContentType.ToString().Contains("Master Page"))
{
query.RecordItems(item.ID.ToString(), item.ContentType.Name,
item.DisplayName, item.Name,
"", item.Url, item["Created By"].ToString(),
"",
Convert.ToDateTime(item["Modified"]),
item["Modified By"].ToString(),
Convert.ToDateTime(item["Created"]),
item["Created By"].ToString());
}
}
catch (NullReferenceException)
{
SPListItem item = list.Items[i];
Logger.Error(
"[{0}] Filed moving on file {1} as not all content was present",
item.Name);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>As well as some standard indenting, a quick thought could be reversing the item being compared and using some temporary variables for readability. </p>\n\n<p><strong>EDIT</strong>:<br>\nOk, so svick pointed out that the original code was fundamentally flawed. So how about creating an extension method on <code>string</code> to do the Contains for us. Something like:</p>\n\n<pre><code>// Method would do well with some unit tests ....\npublic static bool ContainsAny(this string source, string[] findStr)\n{\n return findStr.Any(p => source.Contains(p));\n}\n</code></pre>\n\n<p>Then used like</p>\n\n<pre><code>var contentTypes = new [] { \"Theme Gallery\", \"Converted Forms\", \"Page Output Cache\", \"Master Page\" };\nvar urls = new[] { \"_catalogs\", \"Style Library\", \"Cache Profiles\" };\nvar accounts = new [] { \"System Account\" };\n\nvar contentType = item.ContentType.ToString();\nvar createdBy = item[\"Created By\"].ToString();\n\nif (!createdBy.ContainsAny(accounts) &&\n !item.Url.ContainsAny(urls) &&\n !contentType.ContainsAny(contentTypes))\n{\n query.RecordItems(\n item.ID.ToString(), \n item.ContentType.Name,\n item.DisplayName, \n item.Name,\n \"\", \n item.Url, \n createdBy,\n \"\",\n Convert.ToDateTime(item[\"Modified\"]),\n item[\"Modified By\"].ToString(),\n Convert.ToDateTime(item[\"Created\"]),\n createdBy);\n}\n</code></pre>\n\n<p>Also, do you need to catch the exception in this method? Could you not just handle that situation in an if statement as it looks like you are letting the exception handle the case where one of the values is null when a simple null check would suffice??</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T03:52:49.327",
"Id": "51275",
"Score": "0",
"body": "+1 I don't think the exception has been tested. The `Logger.Error` has a `{0}` and a `{1}` with only one argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T04:02:34.843",
"Id": "51276",
"Score": "0",
"body": "Very nice solution. I was actually midway through changing the logging into events when I posted this, which is why there was an argument missing at the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T06:27:16.590",
"Id": "51282",
"Score": "0",
"body": "@ElvisLikeBear A small suggestion. If you let the question be unaccepted for a few days you are more likely to get other alternative or better suggestions, or even improvements on what I've done. Just a suggestion..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:49:26.853",
"Id": "51291",
"Score": "0",
"body": "But this doesn't work the same as the original code. That tests for example for URLs that *contain* `\"_catalogs\"` as a substring, but you're checking only for URLs that are exactly `\"_catalogs\"`. Also, saving `ContentType` to `url` is extremely confusing (and I think that because of that bad naming, you're comparing the wrong values)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:49:52.880",
"Id": "51300",
"Score": "0",
"body": "@svick yep, appears you might be onto something. I knew there was a reason I didn't want it accepted :) Back to the drawing board me thinks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T11:51:42.310",
"Id": "51315",
"Score": "0",
"body": "That `ToList()` in `ContainsAny()` is completely unnecessary, LINQ works on arrays too."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T03:35:31.457",
"Id": "32107",
"ParentId": "32103",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "32107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T01:44:51.113",
"Id": "32103",
"Score": "2",
"Tags": [
"c#",
"optimization",
"sharepoint"
],
"Title": "Surely there's a better way to write this statement?"
}
|
32103
|
<p>I am trying not to pick up any bad habits while improving the way I write programs. Any suggestions on the following lines of code?</p>
<pre><code>package guessGame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
// Main Class
public class GuessGame extends JFrame {
// Declare class variables
private static final long serialVersionUID = 1L;
public static Object prompt1;
private JTextField userInput;
private JLabel comment = new JLabel(" ");
private JLabel comment2 = new JLabel(" ");
private int randomNumber;
private int counter = 0;
// Constructor
public GuessGame() {
super("Guessing Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Content pane
setLayout(new FlowLayout());
Container c = getContentPane();
// Create components
JButton guessButton = new JButton("Try the number");
JButton newGameButton = new JButton("New Game");
JButton quitButton = new JButton("Quit");
JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
JLabel prompt2 = new JLabel("Can you guess the number?");
JLabel prompt3 = new JLabel("Please enter your guess: ");
comment = new JLabel(" ");
comment2 = new JLabel(" ");
userInput = new JTextField(5);
// Adding components to the pane
c.add(prompt1);
c.add(prompt2);
c.add(prompt3);
c.add(userInput);
c.add(guessButton);
c.add(newGameButton);
c.add(quitButton);
c.add(comment);
c.add(comment2);
// Set the mnemonic
guessButton.setMnemonic('T');
newGameButton.setMnemonic('N');
quitButton.setMnemonic('Q');
// Format pane
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
initializeNumber();
// Create the button handlers
GuessButtonHandler ghandler = new GuessButtonHandler(); // instantiate
// new object
guessButton.addActionListener(ghandler); // add event listener
NewButtonHandler nhandler = new NewButtonHandler();
newGameButton.addActionListener(nhandler);
QuitButtonHandler qhandler = new QuitButtonHandler();
quitButton.addActionListener(qhandler);
} // End constructor
//
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
}
// GuessButton inner class
private class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Declare class variables
int getUserInput;
int diff;
int Difference;
// Validate input and if statements for user input
try {
getUserInput = Integer.parseInt(userInput.getText().trim());
counter++;
if (getUserInput == randomNumber) {
JOptionPane.showMessageDialog(null, "Correct! It took you "
+ counter + " guesses", "Random Number: "
+ randomNumber, JOptionPane.INFORMATION_MESSAGE);
initializeNumber();
return;
}
if (getUserInput > randomNumber) {
comment2
.setText("The guess was too HIGH. Try a lower number.");
comment2.setForeground(Color.WHITE);
diff = getUserInput - randomNumber;
Difference = Math.abs(diff);
} else {
comment2
.setText("The guess was too LOW. Try a higher number.");
comment2.setForeground(Color.WHITE);
diff = randomNumber - getUserInput;
Difference = Math.abs(diff);
}
if (Difference >= 30) {
comment.setText("Your Cold. ");
comment.setForeground(Color.WHITE);
GuessGame.this.setBackgroundColor(Color.BLUE);
}
if (Difference <= 15) {
comment.setText("Your getting Warm");
comment.setForeground(Color.WHITE);
GuessGame.this.setBackgroundColor(Color.RED);
}
} catch (NumberFormatException ex) {
comment.setText("Enter a VALID number!");
}
}
} // End GuessButtonHandler
// NewButton inner class
private class NewButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
GuessGame app = new GuessGame();
}
} // End NewButtonHandler
// QuitButton inner class
private class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
} // End QuitButtonHandler
// Setting background color
private void setBackgroundColor(Color RED) {
getContentPane().setBackground(RED);
}
// Main method
public static void main(String args[]) {
// instantiate GuessGame object
GuessGame app = new GuessGame();
}// End main method
}// End main class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T04:07:51.103",
"Id": "51277",
"Score": "0",
"body": "you can minimize that long if-else block by having a separate method"
}
] |
[
{
"body": "<p>Problems I see:</p>\n\n<ol>\n<li><p><code>comment</code> and <code>comment2</code> are initialised twice, once in the class definition and again in the constructor.</p></li>\n<li><p>If you click the <code>New Game</code> button, you'll get a new window but the old one will still be there. (see also the last point below)</p>\n\n<p>You may want to provide a <code>reset()</code> method that will both initialise a random number and also reset the comment labels to their default values. Then you can call <code>reset()</code> both from your constructor and also when a game is done. Or even when a new game is asked for.</p></li>\n<li><p><code>prompt1</code> is declared as a class member, but never used. You can get rid of it at the class level.</p></li>\n</ol>\n\n<p>Try to find repeated parts of code, and think about how you can pull those out to a reusable method. Keep your code <strong><a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a></strong>.</p>\n\n<p>Some pro-level tips and style-oriented things:</p>\n\n<ol>\n<li><p>I usually like to make Swing components as self-contained as possible (see examples below). Therefore, for any UI-specific logic (such as internal event listening) I have the component (your <code>JFrame</code>) implement the listener interface (e.g., <code>ActionListener</code> for button clicks). If that triggers some type of application event, I'd fire off that type of event from within the <code>actionPerformed()</code> method of the UI component. The only time I extract an explicit separate class for Swing listeners is when they're generally useful across several UI components, which isn't real often.</p>\n\n<p>This helps to isolate the UI as being Swing-based; the rest of your application receives an application-level event and it doesn't need to know if it was from a Swing button, a web button, a service invocation, or whatever. (You shouldn't be importing Swing interfaces into non-UI classes).</p>\n\n<p>For trivial Swing applications like this, using inner classes to implement listeners is fine, and indeed it's a common practice. It just seems more clean (to me at least) to make a self-contained component out of it. For large Swing applications, however, all those extra classes can eat up your PermGen memory.</p></li>\n<li><p>For convenience, the <code>JFrame.add()</code> method targets the content pane, so it's not strictly necessary to reference it directly. But it's good to remember that you need to deal with the content pane.</p></li>\n<li><p>I also typically localise (small-L) the configuration of my internal components instead of spreading them out:</p>\n\n<pre><code>JButton button = new JButton(\"Try the number\");\nbutton.setMnemonic('T');\nbutton.addActionListener(this);\nadd(button);\n</code></pre>\n\n<p>Now I can reuse the <code>button</code> variable name for the next one. Same with labels. After you create a couple of panels or frames, you'll start to notice some common coding patterns you use. Those can be extracted into static methods in a utility class. For instance, you could have a static method that creates and returns a new button given some text, a mnemonic, a command, and a listener.</p>\n\n<p>Doing some of that, it might look like:</p>\n\n<pre><code>public static JButton mkButton(String text, Character mnemonic, String command, ActionListener listener) {\n final JButton button = new JButton(text);\n if (mnemonic != null) button.setMnemonic(mnemonic);\n if (command != null) button.setActionCommand(command);\n if (listener != null) button.addActionListener(listener);\n return button;\n}\n</code></pre>\n\n<p>These utility methods really start to shine when you start using more advanced layout managers. Next, create constants for your commands in your class:</p>\n\n<pre><code>private static final String ACTION_GUESS = \"guess\";\nprivate static final String ACTION_NEW = \"new\";\nprivate static final String ACTION_QUIT = \"quit\";\n</code></pre>\n\n<p>then, in the constructor it's just: </p>\n\n<pre><code>add(mkButton(\"Try the number\", 'T', ACTION_GUESS, this));\n</code></pre>\n\n<p>finally, you can <code>switch</code> on the action command of your button to either do trivial work in the switch or dispatch to a method for more complex operations:</p>\n\n<pre><code>@Override\npublic void actionPerformed(ActionEvent e) {\n switch(e.getActionCommand()) {\n case ACTION_GUESS:\n guess();\n break;\n\n case ACTION_QUIT:\n System.exit(0);\n break;\n\n case ACTION_NEW:\n reset();\n break;\n }\n}\n</code></pre></li>\n<li><p>Having said all of the above concerning buttons, if you're building a large complex Swing app, you'll want to define <code>javax.swing.Action</code>s and reuse them in buttons and menus.</p></li>\n<li><p>After you add all of your components, call <code>pack()</code>. That will set up dimensions if you want to tweak them (as opposed to setting absolute dimensions as you have).</p></li>\n<li><p>You definitely don't want to <code>setVisible(true)</code> (or other side-effects) in a constructor. Let calling code determine when to display UI components.</p></li>\n<li><p>Unless you know absolutely that your frame will only ever be used from <code>main()</code>, don't set the default close operation in the constructor; let the calling code set that (in this case, <code>main()</code>).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T05:19:31.337",
"Id": "32110",
"ParentId": "32104",
"Score": "3"
}
},
{
"body": "<p>Name your variables properly </p>\n\n<pre><code>// Declare class variables\n int getUserInput;\n int diff;\n int Difference;\n</code></pre>\n\n<p>They are not class variables, they are declared within a method.\nBut my point is to \n<strong>Stick to conventions</strong> - diff and Difference does not adhere same naming convention and also its hard to tell what is the purpose of each one, because whats the difference between diff (abbreviation of difference) and actual Difference? </p>\n\n<p>This code fragment</p>\n\n<pre><code>public void actionPerformed(ActionEvent e) {\n GuessGame app = new GuessGame();\n\n }\n</code></pre>\n\n<p>does nothing. It just create new object which is lost after method is executed because is stored in local variable.</p>\n\n<p>And do not put much code into constructors. Use construcotrs only for instance initialization. Not for actual logic. So you main method then would look like. </p>\n\n<pre><code>GuessGame app = new GuessGame();\napp.start();\n</code></pre>\n\n<p>Also i see a lot of duplication in GuessButtonHandler#actionPerformed in body of your if and else branches. Extract it to methods and re-use it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T05:35:03.547",
"Id": "32112",
"ParentId": "32104",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32110",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T01:58:44.320",
"Id": "32104",
"Score": "3",
"Tags": [
"java",
"game",
"swing",
"number-guessing-game"
],
"Title": "Number-guessing game in Java with Swing UI"
}
|
32104
|
<p>I am writing a byte array value into a file, consisting of up to three of these arrays, using Java with big Endian byte order format. Now I need to read that file from a C++ program.</p>
<pre><code>short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();
</code></pre>
<p>I am writing <code>employeeId</code>, <code>lastModifiedDate</code> and <code>attributeValue</code> together into a single byte array. I am writing that resulting byte array into a file and then I will have my C++ program retrieve that byte array data from the file and then deserialize it to extract <code>employeeId</code>, <code>lastModifiedDate</code> and <code>attributeValue</code> from it.</p>
<p>This writes the byte array value into a file with big Endian format:</p>
<pre><code>public class ByteBufferTest {
public static void main(String[] args) {
String text = "Byte Array Test For Big Endian";
byte[] attributeValue = text.getBytes();
long lastModifiedDate = 1289811105109L;
short employeeId = 32767;
int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4
ByteBuffer bbuf = ByteBuffer.allocate(size);
bbuf.order(ByteOrder.BIG_ENDIAN);
bbuf.putShort(employeeId);
bbuf.putLong(lastModifiedDate);
bbuf.putInt(attributeValue.length);
bbuf.put(attributeValue);
bbuf.rewind();
// best approach is copy the internal buffer
byte[] bytesToStore = new byte[size];
bbuf.get(bytesToStore);
writeFile(bytesToStore);
}
/**
* Write the file in Java
* @param byteArray
*/
public static void writeFile(byte[] byteArray) {
try{
File file = new File("bytebuffertest");
FileOutputStream output = new FileOutputStream(file);
IOUtils.write(byteArray, output);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
</code></pre>
<p>Now I need to retrieve the byte array from that same file using this C++ program and deserialize it to extract <code>employeeId</code>, <code>lastModifiedDate</code> and <code>attributeValue</code> from it. I am not sure what the best way is on the C++ side.</p>
<pre><code>int main() {
string line;
std::ifstream myfile("bytebuffertest", std::ios::binary);
if (myfile.is_open()) {
uint16_t employeeId;
uint64_t lastModifiedDate;
uint32_t attributeLength;
char buffer[8]; // sized for the biggest read we want to do
// read two bytes (will be in the wrong order)
myfile.read(buffer, 2);
// swap the bytes
std::swap(buffer[0], buffer[1]);
// only now convert bytes to an integer
employeeId = *reinterpret_cast<uint16_t*>(buffer);
cout<< employeeId <<endl;
// read eight bytes (will be in the wrong order)
myfile.read(buffer, 8);
// swap the bytes
std::swap(buffer[0], buffer[7]);
std::swap(buffer[1], buffer[6]);
std::swap(buffer[2], buffer[5]);
std::swap(buffer[3], buffer[4]);
// only now convert bytes to an integer
lastModifiedDate = *reinterpret_cast<uint64_t*>(buffer);
cout<< lastModifiedDate <<endl;
// read 4 bytes (will be in the wrong order)
myfile.read(buffer, 4);
// swap the bytes
std::swap(buffer[0], buffer[3]);
std::swap(buffer[1], buffer[2]);
// only now convert bytes to an integer
attributeLength = *reinterpret_cast<uint32_t*>(buffer);
cout<< attributeLength <<endl;
myfile.read(buffer, attributeLength);
// now I am not sure how should I get the actual attribute value here?
//close the stream:
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
</code></pre>
<p>Can anybody take a look on C++ code and see what I can do to improve it, as I don't think it is looking much efficient? Any better way to deserialize the byte array and extract relevant information on the C++ side?</p>
|
[] |
[
{
"body": "<p>Obviously the code isn't portable to big-endian machines. I'll use C syntax, since I'm more familiar with that than C++.</p>\n\n<p>If you have <code>endian.h</code>, you can use the functions in there; if not, you should have <code>arpa/inet.h</code> which defines functions for swapping network byte order (big-endian) to host byte order, but lacks a function for 64-bit values. Look for either <code>be16toh</code> (from <code>endian.h</code>) or <code>ntohs</code> (from <code>arpa/inet.h</code>) and friends.</p>\n\n<p>Why not read directly into the values:</p>\n\n<pre><code>fread((void *)&employeeId, sizeof(employeeId), 1, file);\nemployeeId = be16toh(employeeId);\n</code></pre>\n\n<p>Since you can manipulate pointers in C, you just need to provide a universal pointer (<code>void *</code>) to the read function where it should place the results. The <code>&</code> operator takes the address of a value. Once that is done, you can manipulate the value directly, as above.</p>\n\n<p>Using this Java test code:</p>\n\n<pre><code>import java.io.*;\n\npublic class write {\n public static void main(String... args) throws Exception {\n final FileOutputStream file = new FileOutputStream(\"java.dat\");\n final DataOutputStream data = new DataOutputStream(file);\n\n final long time = System.currentTimeMillis();\n final short value = 32219;\n\n // fill a table with a..z0..9\n final byte[] table = new byte[36];\n int index = 0;\n for (int i = 0; i < 26; i++) {\n table[index++] = (byte)(i + 'a');\n }\n for (int i = 0 ; i < 10; i++) {\n table[index++] = (byte)(i + '0');\n }\n\n data.writeLong(time);\n data.writeShort(value);\n data.writeInt(table.length);\n data.write(table);\n data.close();\n\n System.out.format(\"wrote time: %d%n value: %d%n length: %d%n table:%n\", time, value, table.length);\n for (int i = 0; i < table.length; i++) {\n System.out.format(\"%c \", (char)table[i]);\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>The output from this code is:</p>\n\n<pre><code>wrote time: 1380743479723\n value: 32219\n length: 36\n table:\na b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 \n</code></pre>\n\n<p>You can read the values in with this C code:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <endian.h>\n#include <sys/types.h>\n\nint main(int argc, char **argv) {\n int64_t time;\n int16_t value;\n int32_t length;\n u_int8_t *array;\n\n FILE *in = fopen(\"java.dat\", \"rb\");\n\n fread(&time, sizeof(time), 1, in);\n time = (int64_t)be64toh( (u_int64_t)time);\n\n fread(&value, sizeof(value), 1, in);\n value = (int16_t)be16toh( (u_int16_t)value );\n\n fread(&length, sizeof(length), 1, in);\n length = (int32_t)be32toh( (u_int32_t)length );\n\n array = (u_int8_t *)malloc(length);\n fread(array, sizeof(array[0]), length, in);\n\n fclose(in);\n\n printf(\"time: %ld\\nvalue: %d\\narray length: %d\\narray:\\n\", time, value, length);\n for (int i = 0; i < length; i++) {\n printf(\"%c \", array[i]);\n }\n printf(\"\\n\");\n\n free(array);\n return 0;\n}\n</code></pre>\n\n<p>I compiled this on Ubuntu x64 with clang. Its output was:</p>\n\n<pre><code>./a.out\ntime: 1380743479723\nvalue: 32219\narray length: 36\narray:\na b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 \n</code></pre>\n\n<p>Keep in mind that the only unsigned types in Java are <code>byte</code> (8 bits) and <code>char</code> (16-32 bits).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T06:25:41.237",
"Id": "51281",
"Score": "0",
"body": "Thanks for suggestion.. The big problems is, I am not C++ developer, I am mainly a Java developer so that's why I am facing lot of problem.. By reading lot of stuff I was able to write that bunch of code in C++... Can you help me on this with a simple example basis on my code how can I deserialize on C++ side?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T21:24:29.263",
"Id": "51366",
"Score": "0",
"body": "Thanks for edit.. One quick question I have is- Does this c++ code work with my Java example in the way how it is writing into a file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T21:34:56.087",
"Id": "51367",
"Score": "0",
"body": "You are writing a short, long, and int; I'm writing a long, short, int. So it's out of order. I just noticed you're specifying BIG_ENDIAN for your ByteBuffer. Can you not just use LITTLE_ENDIAN on output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T21:41:48.163",
"Id": "51368",
"Score": "0",
"body": "I guess BIG ENDIAN is the preferred format for BYTE ORDER when we are dealing with cross platform issues? RIght? That's why I was following this.. Is there any way to use my c++ code to deserialize it properly? I am able to extract the attribute length but not sure how to read it back in my c++ code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T00:38:52.950",
"Id": "51373",
"Score": "0",
"body": "To use C++, I think you have to use `#include <new>`, and allocate a big enough buffer with `char *attribute = new char[length];`. Then you can read the attribute array into `attribute` using `read`. Since it's allocated on the heap, when you're done with it you'll need to `delete[] attribute;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T00:46:00.427",
"Id": "51374",
"Score": "0",
"body": "Re: BIG ENDIAN; that's also called network byte order, so it's common for network traffic. However, if it's just between your own systems, I'd use LITTLE ENDIAN since most platforms are now that way (x86/x64)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T06:23:46.133",
"Id": "32115",
"ParentId": "32106",
"Score": "4"
}
},
{
"body": "<p>I'm assuming that the reason for needing this is for some form of interoperability between a Java process/routine and a C++ process/routine. For the sake of having a more robust solution, have you considered using some form of serialization library to handle the byte array format for you?</p>\n\n<p>For instance, Google's <a href=\"https://developers.google.com/protocol-buffers/docs/reference/other?hl=en\" rel=\"nofollow\">Protocol Buffer</a> project is perfect for creating a single definition of your data model, and then creating bindings for different languages (Java and C++ supported) so that you can serialize/deserialize that object from any source.</p>\n\n<p>Essentially you'd create an definition of the data you want to represent in a <code>.proto</code> file (like so):</p>\n\n<pre><code>message TouchInfo {\n required sint32 employee_number = 1;\n required int64 last_modified_date = 2;\n repeated sint32 attribute_value = 3 [packed=true];\n}\n</code></pre>\n\n<p>The <code>sint32</code> is signed variable length encoding integer and maps to <code>int32</code> scalar in C++ and <code>int</code> primitive in Java. The <code>int64</code> is a plain and simple <code>int64</code> in C++ and <code>long</code> in Java. The last field accepts some slight overhead to simplify the code by encoding the field as an array. The option on the end configures the library to pack in the values as tightly as it can. This is for simplicity's sake, and if you require anything more granular than that, there is always the <code>bytes</code> type, which maps to <code>string</code> in C++ and <code>ByteString</code> in Java.</p>\n\n<p>Finally, you'd use the <code>protoc</code> command to create C++ and Java libraries that will handle the serialization for you. <code>protoc</code> will generate the <code>.h</code> and <code>.cpp</code> files for the C++ bindings and a <code>.java</code> class with a special <code>Builder</code> object for Java. </p>\n\n<p>The best part of this is that protobufs support plenty of helpful features to let you add or remove fields while maintaining a degree of backwards compatibility. Need to add a new field? Just recompile the bindings. The older versions of bindings will gracefully ignore any data fields they don't care about. Extensibility can be a big deal if the data has any chance of being modified in the future.</p>\n\n<p>Google uses this as their \"lingua franca\" of data serialization tools, both for storing data and encoding RPC requests.</p>\n\n<p>(My examples use protobuf v2, but they now have a v3)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-10T01:57:26.057",
"Id": "209997",
"Score": "0",
"body": "Worth pointing out that `uint32` isn't the same as `int` -- `int32` is the same as `int`; `uint32` is unsigned. At least, unless I missed something in the doc you linked, which is entirely possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-10T02:06:14.020",
"Id": "209998",
"Score": "0",
"body": "@QPaysTaxes - nice catch. I was just going off of the following bindings located at this link : https://developers.google.com/protocol-buffers/docs/proto#scalar. Answer is updated to use the `sint32` bindings."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-10T01:32:21.743",
"Id": "113453",
"ParentId": "32106",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T03:34:42.043",
"Id": "32106",
"Score": "3",
"Tags": [
"java",
"c++",
"serialization"
],
"Title": "Deserializing a byte array from Java in C++"
}
|
32106
|
<p>I am writing a simple event handling class in C++, to avoid having delegate registration and calls cluttering the rest of the code. I have a design that seems to do the job, but it has a couple of drawbacks.</p>
<p>So far it looks like this:</p>
<pre><code>template<typename T>
struct IDelegate { virtual void operator ()(const T & args) const = 0; };
template<typename T>
class EventHandler
{
public:
void Trigger(const T & args) const;
void AddListener(const IDelegate<T> & delegate);
void RemoveListener(const IDelegate<T> & delegate);
};
</code></pre>
<p>Which in practice would look like this (some code elided for clarity):</p>
<pre><code>class Foo
{
public:
struct CustomEventArgs { int i; };
EventHandler<CustomEventArgs> * SomeHandler() const { return m_handler; }
void SomeMethod()
{
// Some code
CustomEventArgs someArgs = { 42 };
SomeHandler()->Trigger(someArgs);
}
private:
EventHandler<CustomEventArgs> * m_handler;
};
class Bar : public IDelegate<Foo::CustomEventArgs>
{
public:
void operator ()(const Foo::CustomEventArgs & args) const
{
std::cout << args.i << " bottles of beer" << std::endl;
}
void StartListening(const Foo & foo)
{
foo.SomeHandler()->AddListener(*this);
}
};
</code></pre>
<p>This code would basically do what I want, but there are still several things I don't quite like.</p>
<p><strong>EventHandler::Trigger() is public</strong></p>
<p>Anyone can call it, which is a serious flaw. Only the owner should be able to call that method. I can see two ways of ensuring this, but I am not happy with any of them:</p>
<ul>
<li>Making the <code>EventHandler</code>(s) hidden from outside <code>Foo</code>. This defeats the purpose though, since it would then require to add as many <code>AddListener</code>/<code>RemoveListener</code> methods.</li>
<li>Making <code>Trigger()</code> protected, deriving from <code>EventHandler</code>, then declaring <code>Foo</code> as a <code>friend</code>. This would require to declare a specific class for every single pair of event-handler/class-using-that-event-handler, which is less than ideal.</li>
</ul>
<p><strong>SomeHandler() returns a pointer</strong></p>
<p>If possible, I think it'd be better to make <code>m_handler</code> an actual member instead of having it somewhere (else) on the heap, and return a reference to it. But I don;t see how to do that without getting plagued with non-const-ness: I want <code>StartListening()</code> to take a const reference.</p>
<p><strong>The question[s]</strong></p>
<ol>
<li>What would you recommend regarding these two issues?</li>
<li>Do you see other flaws in this design?</li>
</ol>
|
[] |
[
{
"body": "<p>Been a while since I've done much in the way of heavy C++ & I'm sure others will weigh in with their own suggestions, but my two cents:</p>\n\n<ol>\n<li><p>I think the best solution is the first one you rejected: add Foo::{Add,Remove}Listener. Yep, it's more code but (a) it solves both the issues you observe with the code & (b) the implementation of these methods will be trivial. It's a compromise: better encapsulation in exchange for a little more code.</p>\n\n<p>If you're really set on your approach, I'm pretty sure you could work around issue #1 by separating EventHandler into two classes (e.g. EventHandler & EventTrigger) & using friends to expose the dirty details, but IMO that's comparatively ugly. This stuff doesn't deserve that kind of hack.</p>\n\n<p>Along that line of thinking but maybe a little cleaner: have EventTrigger derive from EventHandler (the former providing ::Trigger, the latter ::{Add,Remove}Listener), making m_handler an EventTrigger & having Foo::SomeHandler return a pointer to an EventListener -- effectively \"hiding\" the Trigger method from the outside world. You're still \"leaking\" here because you'll need to expose a protected instance variable or method (the list of listeners), but this stuff is simple enough that it shouldn't be completely abhorrent.</p>\n</li>\n\n<li>Depends what you consider a \"flaw\" :) Implementors of IDelegate might find the fact the method is const to be annoying (but then you might be making assumptions about implementations of IDelegate that I'm not aware of). Other than that & the issues you observed, things look fine to me.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:22:04.380",
"Id": "51284",
"Score": "0",
"body": "Thank you, I'll reconsider the `Foo::{Add,Remove}Listener` solution with regards to alternatives. What I'm worried about is to see lots of \"empty\" code clutter in case there are many kinds of events."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:23:47.733",
"Id": "51285",
"Score": "0",
"body": "I like your suggestion of splitting `EventTrigger`/`EventHandler`. Sure you can always cast, but at least now the intent is clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T07:41:26.703",
"Id": "51288",
"Score": "0",
"body": "I wondered too about whether the `IDelegate` method should be const or not, I don't know which is wiser."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T06:57:07.887",
"Id": "32116",
"ParentId": "32108",
"Score": "1"
}
},
{
"body": "<p>What Tom Lee said was great (and I'd upvote if I could), but I'd like to add a few misc remarks.</p>\n\n<p>On the constness of the <code>IDelegate</code> method: without more knowledge of what you're trying to implement, I'd vote against it. The reason here is that your delegate reacts to an event, without returning any new computed value (as indicated by the <code>void</code> return type); this would tend to indicate that the only way the delegate could do anything useful would be either by modifying itself or by having \"external\" side effects. The const restriction forces your delegates to only actively react to an event with external side effects. Of course, removing the const qualifier won't magically forbid you to make side effects, but it might remove the need for them. (Hope that's clear enough.)</p>\n\n<p>On the same topic, I don't see why you intend to pass <code>Foo</code> as a const ref to <code>StartListening</code>? The method modifies the Foo instance, maybe not programatically, but at least semantically: it'd be way more correct IMHO to have a non-const ref given to the <code>StartListening</code> method.</p>\n\n<p>As for trigger / add / remove, it seems to me you wouldn't need a friend declaration if <code>Foo</code> publicly inherited from <code>EventHandler</code> and <code>Trigger</code> were protected: it would publicly expose <code>AddListener</code> and <code>RemoveListener</code>, and you'd be able to call <code>Trigger</code> only from Foo methods, which is what you aim to do if I'm not mistaken? Did I miss something?</p>\n\n<p>Some design remarks concerning <code>Bar::StartListening</code> method. Is there a need for it to have a <code>Foo</code> parameter? Wouldn't it be better to just give it a <code>EventHandler<Foo::CustomEventArgs></code>? Another thing that bothers me is why you chose to put a registration method in the delegate object at all: you already have a registration method, which is <code>AddListener</code>. By adding StartListening, you make Bar \"aware\" of <code>Foo</code> (or at least of <code>EventHandler</code>), which it doesn't need: theoretically, <code>Bar</code> should and could work with any <code>EventHandler<CustomEventArgs></code>, not just with <code>Foo</code> (just like <code>Foo</code> works with any delegate, not just <code>Bar</code>, which it doesn't know). That's why I'd move the registration call out of Bar and make the \"link\" at an upper level.</p>\n\n<p>My tuppence worth, hope that helps!</p>\n\n<p><br />\n<strong>EDIT</strong>: so, if you want Bar to be aware of Foo, but are reluctant to have Bar hold to a non-const pointer or ref to a Foo instance, I see two imperfect solutions.</p>\n\n<p>The first is to move EventHandler \"outside\" of Foo: either Foo holds a non-const pointer member (as in your code), or the EventHandler is stored and accessed outside of Foo. Foo is const, Bar can happily register / unregister at will, but this doesn't solve the original \"Trigger is public\" issue.</p>\n\n<p>Another solution is for Bar to hold a non-const reference to something that is a <em>subset</em> of Foo (interface segregation). For instance, consider this:</p>\n\n<pre><code>class IFoo\n{\n public:\n virtual int MyConstMethod1() const = 0;\n virtual float MyConstMethod2(int, int) const = 0;\n\n virtual void AddListener(const IDelegate<CustomEventArgs> & delegate) = 0;\n virtual void RemoveListener(const IDelegate<CustomEventArgs> & delegate) = 0;\n};\n\nclass Foo : public IFoo { /* ... */ };\n</code></pre>\n\n<p>Now Bar may hold a non-const pointer or ref to an IFoo without having access to any of the non-const API of Foo excepted AddListener / RemoveListener, as it only has access to what it's supposed to use. The only issue is that it's a <em>bit</em> verbose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:39:04.850",
"Id": "51297",
"Score": "0",
"body": "I like your point on IDelegate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:47:18.553",
"Id": "51299",
"Score": "0",
"body": "Foo and Bar are only examples. `StartListening` is just emphasizing the consequence of having or not a const event handler. For a more realistic example: imagine a Viewer object that reacts to events of a UIControl, which is exposed by a UIControlsContainer. You probably want to have a `Register`/`Unregister` pair of functions to call depending on focus for example. I think UIControlsContainer shouldn't have to expose a non const UIControl just because of some event listener somewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:52:09.387",
"Id": "51302",
"Score": "0",
"body": "Yep, OK, I see your point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:01:02.880",
"Id": "51304",
"Score": "0",
"body": "(continued) If you want to be able to register to and from an object without it exposing a mutable interface, then the only \"non-tricky\" way to do it is to move the delegate list outside of the object (which then requires `trigger` to be public, which you wanted to avoid). Another solution would be for your delegate to know only about a \"subset\" of Foo, via an interface that only exposes what Bar needs: non-const registration methods and const methods: it'd hold a non-const pointer, but not to the whole Foo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:06:28.333",
"Id": "51305",
"Score": "0",
"body": "I am not sure to understand what you mean. How about you add an example to your answer?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:25:57.030",
"Id": "32122",
"ParentId": "32108",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T04:04:28.150",
"Id": "32108",
"Score": "2",
"Tags": [
"c++",
"delegates",
"event-handling"
],
"Title": "Designing an EventHandler in C++"
}
|
32108
|
<p>Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple. </p>
<pre><code>public final class StringValueOf {
private StringValueOf () {}
// note that int max value is 10 digits
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
private final static char[] DigitOne = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
};
private final static char[] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
};
private static int stringSize(int x) {
for (int i = 0; ; i++) {
if (x <= sizeTable[i]) {
return i + 1;
}
}
}
private static void getChars (char[] buf, int size, int i) {
int charPos = size - 1;
if (i < 0) {
i = -i;
}
while (i >= 10) {
int r = i % 100;
i = i / 100;
buf[charPos--] = DigitOne[r];
buf[charPos--] = DigitTens[r];
}
if (i > 0) {
buf[charPos--] = DigitOne[i];
}
if (charPos == 0) {
buf[charPos] = '-';
}
}
public static String valueOf(int i) {
if (i == Integer.MAX_VALUE) {
return "-2147483648";
}
int size = (i < 0) ? stringSize(-i ) + 1 : stringSize(i);
char[] buf = new char[size];
buf.toString();
getChars(buf, size, i);
/**
* There are 2 ways to convert a char into string.
* 1. buf.toString()
* 2. String(buf)
*
* but we should use String(buf) because:
* 1. Mostly buf.toString would internally call String(buf)
* 2. Integer class uses new String.
*/
return new String(buf);
}
public static void main(String[] args) {
System.out.println(valueOf(101));
System.out.println(valueOf(-2010));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:08:02.210",
"Id": "51353",
"Score": "0",
"body": "The `buf.toString()` doesn't do anything. Also, don't you mean to test for `Integer.MIN_VALUE` and return `-2147483648`?"
}
] |
[
{
"body": "<p>Since it's easy to convert integer digits to their character values ('0' = 0x30..'9' = 0x39), why not:</p>\n\n<pre><code>public static String stringValueOf(int value) {\n if (value == 0) return \"0\";\n if (value == Integer.MIN_VALUE) return \"-2147483648\";\n\n final boolean negative = value < 0;\n if (negative) value = -value;\n\n final StringBuilder buf = new StringBuilder();\n while (value != 0) {\n int digit = value % 10;\n buf.append( (char)(0x30 + digit) );\n value = value / 10;\n }\n if (negative) buf.append('-');\n\n return buf.reverse().toString();\n}\n</code></pre>\n\n<p>It's easy to test this for correctness over the int range; but to do so, I'd extract the <code>StringBuilder</code> construction from the method into a static class variable and just call <code>buf.setLength(0)</code> each time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:56:27.370",
"Id": "51303",
"Score": "0",
"body": "I have some reservations in terms of efficiency. 1. Stringbuilder is less efficient then char array of fized capacity. 2. Your while loop takes twice more iterations. Rest I do admit your code is cleaner and concise"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:31:28.850",
"Id": "51307",
"Score": "0",
"body": "You can change the implementation of this answer to use `char[]` instead of `StringBuilder` if you prefer it. And the more iterations should not be as bad as you may think"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:24:44.203",
"Id": "51330",
"Score": "0",
"body": "Minor nitpick, you could directly return `Integer.MIN_VALUE.ToString()` instead of a hardcoded string. Would mostly improve readability. ... Or you could pull those two ifs together and return `Integer.toString(value)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:54:59.087",
"Id": "51350",
"Score": "2",
"body": "@Bobby The only reason I took the convenience of hard-coding the MIN_VALUE as a special case is because of two's complement format and negation; `-MIN_VALUE == MIN_VALUE` in 2's complement. I thought the whole point of this exercise was to re-implement `Integer.toString()`, so you wouldn't be allowed to call what you're re-implementing (otherwise what's the point?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:00:24.597",
"Id": "51352",
"Score": "0",
"body": "Was the point of this to maximize speed? That wasn't stated in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-20T16:26:13.420",
"Id": "158056",
"Score": "0",
"body": "@JavaDeveloper `StringBuilder` *is* a char array of fixed size with a nice API over it (unless it needs to reallocate, which it won't in this case because by default it allocates 16 chars and the maximum length of `Int` bounds is 12 digits plus negation)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T05:44:48.770",
"Id": "32113",
"ParentId": "32109",
"Score": "5"
}
},
{
"body": "<p>I would replace (just to reduce size of the source-code</p>\n\n<pre><code>private final static char[] DigitOne = {\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', \n};\n\n\nprivate final static char[] DigitTens = {\n '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',\n '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',\n '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',\n '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',\n '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',\n '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',\n '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',\n '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',\n '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',\n};\n</code></pre>\n\n<p>by </p>\n\n<pre><code>private final static char[] DigitOne = \n (\"0123456789\"+\"0123456789\"+\"0123456789\"+\"0123456789\"+\"0123456789\" //\n +\"0123456789\"+\"0123456789\"+\"0123456789\"+\"0123456789\"+\"0123456789\")\n .toCharArray();\n};\n\n\nprivate final static char[] DigitTens = {\n (\"0000000000\"+ \"1111111111\"+\"2222222222\"+\"3333333333\"+\"4444444444\" //\n +\"5555555555\"+\"6666666666\"+\"7777777777\"+\"8888888888\"+\"9999999999\")\n .toCharArray(); \n};\n</code></pre>\n\n<p>Or even generate the constants with a static method using loops.</p>\n\n<p>If you want to avoid speed loss by the loop, unroll it completely.\nThere are only 10 possible cases for the length. With a binary-decision you can determine the length with 4 if-statements and than convert the value without any loop at all. Code would get a bit long, but also very fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:23:17.863",
"Id": "51329",
"Score": "0",
"body": "Is there a `+` missing in your initialization of DigitOne? Also shouldn't `static final`s be UPPER_SNAKE_CASE?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:52:35.180",
"Id": "51334",
"Score": "0",
"body": "@Bobby: Thanks for the missing `+` hint, I fixed it. And I have not changed the names of the variables, because that is pure convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:04:05.470",
"Id": "51346",
"Score": "0",
"body": "@MrSmith42 String concat is a very expensive operation, check that section of effective java encouraging string builders instead of string concay"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:27:55.610",
"Id": "51354",
"Score": "2",
"body": "@JavaDeveloper Static string concatenation is now resolved at compile time. But it didn't used to be; so it's no longer expensive at runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:12:07.430",
"Id": "51450",
"Score": "0",
"body": "@JavaDeveloper: String concat is only performed once while initialization of the constants, if not already at compile time. Therefore this should be no performance issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T20:58:39.323",
"Id": "51545",
"Score": "0",
"body": "While I do thank everyone involved - but still not completely convinced, .toCharArray() is run not at compile time, making this approach marginally inefficient"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T15:57:14.767",
"Id": "51617",
"Score": "1",
"body": "@JavaDeveloper: That ok, because the `.toCharArray()` method call is done only once while loading the class."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:41:37.707",
"Id": "32125",
"ParentId": "32109",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32125",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T04:24:04.060",
"Id": "32109",
"Score": "3",
"Tags": [
"java"
],
"Title": "Implement String's valueOf function, code review request"
}
|
32109
|
<p>I am currently working on an app and have some issues with the date handling.
Found a simple solution, and want your opinion.
First thing, that I want to achieve:</p>
<ol>
<li>I have 2 date format inputs, one is like 2013-09-30 14:20:00 and the other is 30/09/2013 1420</li>
<li>Time stamp is given with no day light saving time.</li>
</ol>
<p>So, I have to store my date/time in DB with the same format in order to compare one with each other, and also I need to adjust the time stamp +1 hour if it is in the DST period.
For this, I made the following function:</p>
<pre><code>function format_date($date_string, $date_format)
{
$unix = mktime( substr($date_string, strpos($date_format, 'HH'), 2),
(strpos($date_format, 'ii'))? substr($date_string, strpos($date_format, 'ii'), 2) : '00',
(strpos($date_format, 'ss'))? substr($date_string, strpos($date_format, 'ss'), 2) : '00',
substr($date_string, strpos($date_format, 'MM'), 2),
substr($date_string, strpos($date_format, 'DD'), 2),
substr($date_string, strpos($date_format, 'YYYY'), 4)
) ;
$human = date('Y-m-d H:i:s', $unix);
$dst = date('I', $unix);
return (object)array(
'unix' => $unix,
'human' => $human,
'dst' => $dst
);
}
//Usage:
$date1 = format_date('2013-09-30 14:20','YYYY-MM-DD HH:ii');
$date2 = format_date('30/09/2013 1420','DD/MM/YYYY HHii');
echo $date1->human ;
echo '<br />';
echo $date2->human ;
echo '<br />';
// $date1->human is the same with $date1->human, also ->unix
</code></pre>
<p>Maybe this will help others, but if you find something not right in this function please let me know before I put it in production.</p>
<p>Update: (thank you Glavić)</p>
<pre><code>function format_date1($date_string, $date_format)
{
$date_build = DateTime::createFromFormat ( $date_format , $date_string );
return (object)array(
'unix' => $date_build->format('U'),
'human' => $date_build->format('Y-m-d H:i:s'),
'dst' => $date_build->format('I')
);
}
$make_date = format_date1('30/09/2013 1420', 'd/m/Y Hi');
print_r($make_date);
//returns stdClass Object ( [unix] => 1380540000 [human] => 2013-09-30 14:20:00 [dst] => 1 )
//Use: $make_date->unix | $make_date->human | $make_date->dst
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:15:54.350",
"Id": "51295",
"Score": "1",
"body": "You should take a look at [`DateTime::createFromFormat`](http://www.php.net/manual/en/datetime.createfromformat.php) and [`DateTime::format`](http://www.php.net/manual/en/datetime.format.php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:43:38.287",
"Id": "51298",
"Score": "0",
"body": "Aha! good point."
}
] |
[
{
"body": "<p>Use <a href=\"http://www.php.net/manual/en/datetime.createfromformat.php\" rel=\"nofollow\">DateTime::createFromFormat</a> method to convert datetime strings to DateTime object:</p>\n\n<pre><code>$date1 = DateTime::createFromFormat('Y-m-d H:i', '2013-09-30 14:20');\n$date2 = DateTime::createFromFormat('d/m/Y Hi', '30/09/2013 1420');\n</code></pre>\n\n<p>Now you can just format your output:</p>\n\n<pre><code>echo 'unix : ' . $date1->format('U') . \"\\n\";\necho 'human : ' . $date1->format('Y-m-d H:i:s') . \"\\n\";\necho 'dst : ' . $date1->format('I') . \"\\n\";\n</code></pre>\n\n<p>And you don't need to adjust timestamp for <code>+1 hour</code> if in DST, DateTime can handle leap years and DST correctly. Set timezone when you create DateTime object, or <a href=\"http://www.php.net/manual/en/datetime.settimezone.php\" rel=\"nofollow\">change timezone after</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:31:14.270",
"Id": "51306",
"Score": "0",
"body": "I can not make the correction DST work as desired...\nMy input date is in let`s say GMT+2 (which means no DST) when in DST it is +1 hour, the output should be +1h"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T09:48:16.260",
"Id": "51308",
"Score": "0",
"body": "DateTime objects work with timezones. [Every timezone](http://php.net/manual/en/timezones.php) chooses to follow DST or not. [How to find out if timezone observes DST or not?](http://stackoverflow.com/a/1586628/67332) [Here](http://stackoverflow.com/questions/2532729/daylight-saving-time-and-time-zone-best-practices) is also a good read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T10:00:58.333",
"Id": "51309",
"Score": "0",
"body": "[Example of DST change](https://eval.in/51923) for `UTC` (no DST) and `Europe/Berlin` (with DST)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:46:58.713",
"Id": "32124",
"ParentId": "32120",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32124",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:12:19.037",
"Id": "32120",
"Score": "1",
"Tags": [
"php"
],
"Title": "PHP date reformat function"
}
|
32120
|
<p>I have written the following Executor:</p>
<pre><code>/**
* <p>This executor guarantees that there is never more than one element waiting to be executed. If an element is
* submitted for execution and another element is still in queue, the newly submitted element replaces the previously
* queued element in the queue</p>
*
* <p>Additionally this executor sleeps a constructor specified number of milliseconds before executing tasks to give queued
* items a chance to be canceled</p>
*
* <p>This class is intended to be used when runnables are created in rapid succession and newer runnables supersede
* ones that have been created previously. This is e.g. the case if a user interface reacts to user inputs, possibly
* on every keystroke and the reaction causes slow tasks (e.g. server calls for validation).</p>
*/
public class SingleQueuedElementExecutor implements Executor {
private final Sleeper sleeper;
private final ExecutorService delegate;
private Future<?> queuedSleeper;
private Future<?> queuedElement;
public SingleQueuedElementExecutor(final ExecutorService delegate, final long sleepBeforeExecutionMilliseconds) {
this.delegate = delegate;
sleeper = new Sleeper(sleepBeforeExecutionMilliseconds);
}
public void execute(final Runnable runnable) {
if (queuedElement != null) {
queuedElement.cancel(false);
queuedSleeper.cancel(true);
}
queuedSleeper = delegate.submit(sleeper);
queuedElement = delegate.submit(runnable);
}
private static class Sleeper implements Runnable {
private final long duration;
private Sleeper(final long duration) {
this.duration = duration;
}
public void run() {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
// Simply abort sleeping
}
}
}
}
</code></pre>
<p>I believe that the JavaDoc describes accurately what I expect the class to do.</p>
<p>Now the interesting part which I ask a review about is the test for this class I came up with:</p>
<pre><code>public class SingleQueuedElementExecutorTest {
private SingleQueuedElementExecutor executor;
private ExecutorService delegateExecutor;
private static final long SLEEP_BETWEEN_TASKS_MS = 10;
private static final long NANO_TIME_ACCURACY_MS = 2;
@BeforeMethod
public void setUp() throws Exception {
delegateExecutor = Executors.newSingleThreadExecutor();
executor = new SingleQueuedElementExecutor(delegateExecutor, SLEEP_BETWEEN_TASKS_MS);
}
@Test
public void execute_sleepsBeforeExecuting() throws Exception {
// setup
final InvocationCounter invocationCounter = new InvocationCounter();
// execution
final long startTime = System.nanoTime();
executor.execute(invocationCounter);
waitForTasksToComplete();
final long endTime = System.nanoTime();
// evaluation
assertThat(endTime - startTime)
.describedAs("number of ns execution took")
.isGreaterThanOrEqualTo((SLEEP_BETWEEN_TASKS_MS - NANO_TIME_ACCURACY_MS) * 1000);
}
private void waitForTasksToComplete() throws InterruptedException {
delegateExecutor.shutdown();
if (!delegateExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
// There is nothing that takes even near 1 second in this test. So if the executor does not terminate within
// 30s, than there is surely an error.
throw new Error("executor did not terminate within 30s.");
}
}
@Test
public void execute_executesTask() throws Exception {
// setup
final InvocationCounter invocationCounter = new InvocationCounter();
// execution
executor.execute(invocationCounter);
waitForTasksToComplete();
// evaluation
assertThat(invocationCounter.invocations)
.isEqualTo(1);
}
@Test
public void execute_abortsPreviouslyAddedTasks() throws Exception {
// setup
final InvocationCounter invocationCounterA = new InvocationCounter();
final InvocationCounter invocationCounterB = new InvocationCounter();
// execution
executor.execute(invocationCounterA);
executor.execute(invocationCounterB);
waitForTasksToComplete();
// evaluation
assertThat(invocationCounterA.invocations)
.describedAs("invocations of counter A")
.isEqualTo(0);
assertThat(invocationCounterB.invocations)
.describedAs("invocations of counter B")
.isEqualTo(1);
}
private static class InvocationCounter implements Runnable {
private int invocations = 0;
public synchronized void run() {
++invocations;
}
}
}
</code></pre>
<p>While the test seems to work fine on my machine I don't like the timing parts of the test. The call to <code>delegateExecutor.awaitTermination(30, TimeUnit.SECONDS)</code> but maybe acceptable. However I strongly dislike my <code>execute_sleepsBeforeExecuting</code> method which relies on <code>System.nanoTime()</code>.</p>
<p>What do you think about it? Any suggestions for improvement?</p>
|
[] |
[
{
"body": "<p>Here is an alternative that you could use that works single threaded and thus completely without timing issues. However it assumes knowledge of internal logic (Name of the class \"Sleeper\", the way that the executor performs sleeping (by adding a sleeper into the queue) etc.). So neither pretty, but maybe worth a glance:</p>\n\n<pre><code>public class SingleQueuedElementExecutorTest {\n private MockExecutor delegateExecutor;\n private SingleQueuedElementExecutor executor;\n private static final long SLEEP_BETWEEN_TASKS_MS = 10;\n\n @BeforeMethod\n public void setUp() throws Exception {\n delegateExecutor = new MockExecutor();\n executor = new SingleQueuedElementExecutor(delegateExecutor, SLEEP_BETWEEN_TASKS_MS);\n }\n\n @Test\n public void execute_sleepsThanExecutes() throws Exception {\n // setup\n final EmptyRunnable emptyRunnable = new EmptyRunnable();\n\n // execution\n executor.execute(emptyRunnable);\n\n // evaluation\n assertThat(delegateExecutor.queue)\n .describedAs(\"queue size\")\n .hasSize(2);\n assertThatQueueElementIsSleeper(0, false);\n assertThatQueueElementIsRunnable(1, emptyRunnable, false);\n }\n\n @Test\n public void execute_abortsPreviouslyAddedTasksAndSleepers() throws Exception {\n // setup\n final EmptyRunnable emptyRunnableA = new EmptyRunnable();\n final EmptyRunnable emptyRunnableB = new EmptyRunnable();\n\n // execution\n executor.execute(emptyRunnableA);\n executor.execute(emptyRunnableB);\n\n // evaluation\n assertThat(delegateExecutor.queue)\n .describedAs(\"queue size\")\n .hasSize(4);\n assertThatQueueElementIsSleeper(0, true);\n assertThatQueueElementIsRunnable(1, emptyRunnableA, true);\n assertThatQueueElementIsSleeper(2, false);\n assertThatQueueElementIsRunnable(3, emptyRunnableB, false);\n }\n\n private void assertThatQueueElementIsSleeper(final int index, final boolean canceled) {\n assertThat(delegateExecutor.queue.get(index).runnable.getClass().getSimpleName())\n .describedAs(\"queue[\" + index + \"].runnable.class.name\")\n .isEqualTo(\"Sleeper\");\n assertThat(Deencapsulation.getField(delegateExecutor.queue.get(index).runnable, \"duration\"))\n .describedAs(\"sleep duration\")\n .isEqualTo(SLEEP_BETWEEN_TASKS_MS);\n assertThat(delegateExecutor.queue.get(index).canceled)\n .describedAs(\"queue[\" + index + \"].canceled\")\n .isEqualTo(canceled);\n if (canceled) {\n assertThat(delegateExecutor.queue.get(index).cancelWithInterrupt)\n .describedAs(\"queue[\" + index + \"].cancelWithInterrupt\")\n .isTrue();\n }\n }\n\n private void assertThatQueueElementIsRunnable(final int index, final Runnable runnable, final boolean canceled) {\n assertThat(delegateExecutor.queue.get(index).canceled)\n .describedAs(\"queue[\" + index + \"].canceled\")\n .isEqualTo(canceled);\n if (canceled) {\n assertThat(delegateExecutor.queue.get(index).cancelWithInterrupt)\n .describedAs(\"queue[\" + index + \"].cancelWithInterrupt\")\n .isFalse();\n }\n assertThat(delegateExecutor.queue.get(index).runnable)\n .describedAs(\"queue[\" + index + \"].runnable\")\n .isSameAs(runnable);\n }\n\n private static class EmptyRunnable implements Runnable {\n public void run() {\n\n }\n }\n\n private static class MockExecutor implements ExecutorService {\n private final List<MockFuture<?>> queue = new ArrayList<MockFuture<?>>();\n\n public void shutdown() {\n throw new UnsupportedOperationException();\n }\n\n public List<Runnable> shutdownNow() {\n throw new UnsupportedOperationException();\n }\n\n public boolean isShutdown() {\n throw new UnsupportedOperationException();\n }\n\n public boolean isTerminated() {\n throw new UnsupportedOperationException();\n }\n\n public boolean awaitTermination(final long l, final TimeUnit timeUnit) throws InterruptedException {\n throw new UnsupportedOperationException();\n }\n\n public <T> Future<T> submit(final Callable<T> tCallable) {\n throw new UnsupportedOperationException();\n }\n\n public <T> Future<T> submit(final Runnable runnable, final T t) {\n throw new UnsupportedOperationException();\n }\n\n public Future<?> submit(final Runnable runnable) {\n final MockFuture<?> result = new MockFuture<Object>(runnable);\n queue.add(result);\n return result;\n }\n\n public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> callables) throws InterruptedException {\n throw new UnsupportedOperationException();\n }\n\n public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> callables, final long l, final TimeUnit timeUnit) throws InterruptedException {\n throw new UnsupportedOperationException();\n }\n\n public <T> T invokeAny(final Collection<? extends Callable<T>> callables) throws InterruptedException, ExecutionException {\n throw new UnsupportedOperationException();\n }\n\n public <T> T invokeAny(final Collection<? extends Callable<T>> callables, final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {\n throw new UnsupportedOperationException();\n }\n\n public void execute(final Runnable runnable) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class MockFuture<T> implements Future<T> {\n private boolean canceled;\n private boolean cancelWithInterrupt;\n private final Runnable runnable;\n\n private MockFuture(final Runnable runnable) {\n this.runnable = runnable;\n }\n\n public boolean cancel(final boolean b) {\n canceled = true;\n cancelWithInterrupt = b;\n return false;\n }\n\n public boolean isCancelled() {\n return canceled;\n }\n\n public boolean isDone() {\n return false;\n }\n\n public T get() throws InterruptedException, ExecutionException {\n return null;\n }\n\n public T get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {\n return null;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T11:49:09.763",
"Id": "32130",
"ParentId": "32127",
"Score": "0"
}
},
{
"body": "<p>Currently your test is biased to help the unit under test to pass. The delegateExecutor is chosen to be a <code>Executors.newSingleThreadExecutor()</code>, which actually forces the SingleQueuedElementExecutor to finish with the <code>Sleeper</code> task before being able to start the actual task. Replace the delegateExecutor with <code>Executors.newCachedThreadPool()</code> and things get hairier.</p>\n\n<p>Yet the class is helped in another way too : the timing times completion of all tasks, which incidently will include the <code>Sleeper</code> task. If you change the test to time until the start of <code>SingleQueuedElementExecutorTest.InvocationCounter#run</code>, the test will fail consistently.</p>\n\n<p>Also you should note that one millisecond is 1000000 nanoseconds.</p>\n\n<p>Since your unit under test uses <code>Thread.sleep()</code> it's hard to test without doing some stopwatch timing. That being said, it's not so hard to test the behavior you desire. What you basically want is that when the executorService is bombarded in short succession with new tasks that only the most recent one executes. That is actually not so hard to set up, and does not require awkard sleeping in the tests.\nAnother test could check that once a task has begun, a subsequently submitted task will also get executed (if not immediately followed by a slew of tasks itself). This test can simply make use of custom Runnables that force some timing using <code>CountDownLatch</code> instances.</p>\n\n<p>Here's a sample :</p>\n\n<pre><code>public class SingleQueuedElementExecutorTest {\n\n private SingleQueuedElementExecutor executor;\n\n private ExecutorService delegateExecutor;\n private static final long SLEEP_BETWEEN_TASKS_MS = 10;\n private static final long NANO_TIME_ACCURACY_MS = 2;\n\n @Before\n public void setUp() throws Exception {\n delegateExecutor = Executors.newCachedThreadPool();\n executor = new SingleQueuedElementExecutor(delegateExecutor, SLEEP_BETWEEN_TASKS_MS);\n }\n\n @Test(timeout = 1000)\n public void testOnlyExecuteLastWhenTasksAreSubmittedInQuickSuccession() throws InterruptedException {\n final CountDownLatch lastExecuted = new CountDownLatch(1);\n final AtomicInteger executedCount = new AtomicInteger(0);\n for (int i = 0; i < 1000; i++) {\n executor.execute(new Runnable() {\n @Override\n public void run() {\n executedCount.incrementAndGet();\n }\n });\n }\n executor.execute(new Runnable() {\n @Override\n public void run() {\n lastExecuted.countDown();\n }\n });\n lastExecuted.await();\n assertThat(executedCount.get()).isEqualTo(0); // all tasks preceding the last should have been cancelled\n }\n\n @Test(timeout = 1000)\n public void testSubmissionWhileExecutingPreviousDoesNotCancelPrevious() throws InterruptedException {\n final CountDownLatch startFirst = new CountDownLatch(1);\n final CountDownLatch secondSubmitted = new CountDownLatch(1);\n final CountDownLatch secondDone = new CountDownLatch(1);\n final AtomicBoolean firstExecuted = new AtomicBoolean(false);\n executor.execute(new Runnable() {\n @Override\n public void run() {\n startFirst.countDown();\n try {\n secondSubmitted.await();\n firstExecuted.set(true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n });\n startFirst.await();\n executor.execute(new Runnable() {\n @Override\n public void run() {\n secondDone.countDown();\n }\n });\n secondDone.await();\n assertThat(firstExecuted.get()).isTrue();\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:11:34.303",
"Id": "32136",
"ParentId": "32127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T10:48:45.647",
"Id": "32127",
"Score": "4",
"Tags": [
"java",
"unit-testing",
"concurrency"
],
"Title": "Testing an Executor"
}
|
32127
|
<p>The processing is the same, but the response type differs based on whether it's an AJAX request or not.</p>
<p>One way I can think of is to store all the response calls inside closure functions, and return once at the end (twice in the function overall because of the first return). That would only make it look a teensy bit better, in my subjective opinion. Not much of an improvement...</p>
<pre class="lang-php prettyprint-override"><code>public function post_update()
{
$submission = Input::all();
$rules = array(
'password' => 'required',
'password_repeat' => 'required|same:password',
'terms_accepted' => 'required'
);
$validator = Validator::make($submission, $rules);
if (! $validator->passes()) {
if (Request::ajax()) {
return Response::json($validator->errors, 400);
} else {
return Redirect::to('signup/manual_password')->with_errors($validator);
}
}
$user = Auth::user();
$user->password = $submission['password'];
$user->set_repeated_password($submission['password_repeat']);
$user->password_set_manually = 1;
try {
$user->save_or_ex();
if (Request::ajax()) {
return Response::json(Session::get('_next_uri'));
} else {
return Redirect::to(Session::get('_next_uri'));
}
} catch (ValidationException $e) {
if (Request::ajax()) {
return Response::json($e->getErrors(), 500);
} else {
return Response::error(500);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T12:12:45.330",
"Id": "51317",
"Score": "0",
"body": "looks to me like your controller method is actually being used for 3 distinct requests... consider creating an ajax-only controller, a form controller, and a regular controller, that way, your methods will be a lot shorter..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T12:21:13.930",
"Id": "51318",
"Score": "0",
"body": "Yes! That sounds very good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T03:52:29.067",
"Id": "59182",
"Score": "1",
"body": "@EliasVanOotegem I know it is short, but your comment is an answer. Having it as an answer rather than a comment benefits the site metrics for questions per answer and answered questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T07:16:13.707",
"Id": "59202",
"Score": "1",
"body": "@Paul: I've added my comment as an answer, including a basic example of how the OP can refactor the original code, and my reasoning behind it"
}
] |
[
{
"body": "<p><em>Seeing I was asked to post my comment as an answer, I've set about typing this little thing up. It's, essentially, a slightly more verbose version of my initial comment.</em></p>\n\n<p>Well, all in all, a controller action is a method, so the same <em>\"rules\"</em> should apply: 1 type of request goes to 1 distinct action method. Your method seems to be dealing with 3 distinct types of requests:</p>\n\n<ul>\n<li>Client requests form page</li>\n<li>Client submits form</li>\n<li>Ajax submission of form-data</li>\n</ul>\n\n<p>So I'd create 3 distinct actions. That way you can get rid of all those <code>if (Request::ajax())</code> branches. You should still check if the request is an ajax request, but unless you're in the ajax controller, you can just redirect or return an error.<br/>\nSince in 2/3 cases, you're validating the same form, you are, of course, free to stash that logic in a private helper method, or in some helper method in the model layer.</p>\n\n<p>Something along these lines (I haven't got much experience with laravel, mind you):</p>\n\n<pre><code>class YourController extends BaseController\n{\n public function updateForm()\n {\n //create the form, pass it to the view\n }\n\n public function ajaxUpdate()\n {\n if (!Request::ajax())\n {\n Response::json(\n array(\n 'message' => 'Invalid request',\n 'redirect' => 'some url'\n )\n );\n }\n $validator = $this->validateInput(Input::all());\n //process resulst\n }\n\n public function postUpdate()\n {\n if (Request::ajax())\n {\n Response::json(\n array(\n 'message' => 'Invalid request',\n 'redirect' => 'some url'\n )\n );\n }\n $validator = $this->validateInput(Input::all());\n //process resulst\n }\n\n private function validateInput($submission)\n {//No type-hint, because I'm not sure what type Input::all() returns\n $rules = array(\n 'password' => 'required',\n 'password_repeat' => 'required|same:password',\n 'terms_accepted' => 'required'\n );\n $validator = Validator::make($submission, $rules);\n }\n}\n</code></pre>\n\n<p>Now this may range anywhere from pretty-darn copy-paste ready to bizarre, but it's just to serve as an example of how <em>I</em> would set about this. To my eye, this is pretty clean code, easy to maintain, and, most important of all: Each action method deals with 1 specific request. In order not to repeat myself, I've created a private <code>validateInput</code> method, too, but I take it that's pretty self-evident ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T07:15:27.673",
"Id": "36181",
"ParentId": "32128",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36181",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T11:08:06.703",
"Id": "32128",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"laravel"
],
"Title": "How do I reduce the if..else soup in this Controller function?"
}
|
32128
|
<p>I'm using Pygame to create a small game with few rectangle shapes. However, I want to learn more about classes, and I'm trying to use them. I'm very new to classes and inheritance, but I want to learn the best habits possible. I'm using Python 3.3.2.</p>
<pre><code>import pygame
class Screen(object):
''' Creates main window and handles surface object. '''
def __init__(self, width, height):
self.WIDTH = width
self.HEIGHT = height
self.SURFACE = pygame.display.set_mode((self.WIDTH, self.HEIGHT), 0, 32)
class GameManager(object):
''' Handles game state datas and updates. '''
def __init__(self, screen):
self.screen = screen
pygame.init()
Window = Screen(800, 500)
Game = GameManager(Window)
</code></pre>
<p>I skipped a few functions to make it simpler. The thing that bothers me is that I've been told that I don't need <code>GameManager</code> to be subclasses of <code>Screen</code>. I was advised to use this implementation, but I find it very strange to use 'Window' as a parameter to <code>GameManager</code>.</p>
<p>Do I need to use inheritance? Should I use <code>super()</code>? Later on, I will have class <code>Player</code> and I will need some of the attributes from the <code>Screen</code> class. From the viewpoint of designing OO for a GUI game using Pygame.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T06:39:08.417",
"Id": "51379",
"Score": "1",
"body": "See [Prefer composition over inheritance?](http://stackoverflow.com/q/49002/222914)"
}
] |
[
{
"body": "<p>First off, you don't need to explicitly inherit from <code>object</code> when creating classes. In Python 3.x, you can just type <code>class MyClass:</code>, and leave it as that if you aren't inheriting from any other classes.</p>\n\n<p>Secondly, I think your current design is fine, as long as the <code>Screen</code> class implements more methods, and the <code>GameManager</code> as well.</p>\n\n<p>Finally, just a little nitpicky tip, your variables <code>Window</code>, and <code>Game</code> should be renamed to <code>window</code> and <code>game</code>.\nLikewise, in <code>Screen</code>, the attributes <code>WIDTH</code>, <code>HEIGHT</code>, <code>SURFACE</code> should be renamed to <code>width</code>, <code>height</code>, <code>surface</code>, respectively.\nActually more than being nitpicky,\nthese recommendations come from <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>, the Python style guide.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-03T02:47:52.143",
"Id": "95636",
"ParentId": "32129",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T11:33:31.857",
"Id": "32129",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"game",
"inheritance"
],
"Title": "Creating a game with rectangular shapes"
}
|
32129
|
<p>I just wrote this tiny library called <a href="https://github.com/dhilipsiva/isRTL.coffee" rel="nofollow">isRTL.coffee</a> to determine the direction of the text. Is there any better way of doing this?</p>
<pre><code>rtlChars = '\u0600-\u06FF' # Arabic - Range
rtlChars += '\u0750-\u077F' # Arabic Supplement - Range
rtlChars += '\uFB50-\uFDFF' # Arabic Presentation Forms-A - Range
rtlChars += '\uFE70-\uFEFF' # Arabic Presentation Forms-B - Range
reRTL = new RegExp "^[#{rtlChars}]"
window.isRTL = (value) ->
if value.match reRTL
true
else
false
</code></pre>
|
[] |
[
{
"body": "<p>Yep, it's possible to improve. You can simply do:</p>\n\n<pre><code>window.isRTL = (value) ->\n reRTL.test value\n</code></pre>\n\n<p>Another way to improve is the way you declare your special characters. Right now, it's confusing between the <code>=</code> and <code>+=</code>. Here is another way:</p>\n\n<pre><code>rtlChars = [\n '\\u0600-\\u06FF' # Arabic - Range\n '\\u0750-\\u077F' # Arabic Supplement - Range\n '\\uFB50-\\uFDFF' # Arabic Presentation Forms-A - Range\n '\\uFE70-\\uFEFF' # Arabic Presentation Forms-B - Range\n].join(\"\")\n\nreRTL = new RegExp \"^[#{rtlChars}]\"\n</code></pre>\n\n<p>This way, adding a new character is simply adding a line in an array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T06:38:51.960",
"Id": "52067",
"Score": "1",
"body": "@FlorianMargaine, using `match` is not appropriate, not only you are discarding the match but the function will not return a boolean value, so `isRTL(...) === true` will never evaluates to `true`. It would be best to use `reRTL.test value` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T12:02:30.597",
"Id": "59439",
"Score": "0",
"body": "@plalx : Correction a string does not have a \"test\" method. match seems to be the way to go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T13:31:54.120",
"Id": "59449",
"Score": "0",
"body": "@dhilipsiva No, just call `test` on the regular `RegExp` instance rather than the string like I demonstrated in my previous comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T12:31:24.047",
"Id": "59562",
"Score": "0",
"body": "@plalx I just feel so stupid sometimes :P Thanks. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T12:44:25.217",
"Id": "32132",
"ParentId": "32131",
"Score": "5"
}
},
{
"body": "<p>The real usefulness of such a library can only come from completeness. You should try to support all other RTL languages as well. Anybody can come up with a simple function to detect Arabic chars.</p>\n\n<p>Also, what if the text contains a mix of languages, some RTL while others LTR. Your library would report any text containing at least one arabic character as RTL.</p>\n\n<ul>\n<li>One approach would be to report number of RTL chars v/s LTR chars.</li>\n<li>Another take would be to parse the text into sections, each labeled as RTL or LTR.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:00:40.270",
"Id": "51324",
"Score": "0",
"body": "Removed the code samples, concentrating of the general talk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:02:18.667",
"Id": "51325",
"Score": "0",
"body": "Yes, I agree. Just scratching my own itch for now. Will make it better eventually. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T12:55:37.947",
"Id": "32133",
"ParentId": "32131",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32132",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T12:28:09.447",
"Id": "32131",
"Score": "5",
"Tags": [
"javascript",
"performance",
"coffeescript",
"i18n",
"unicode"
],
"Title": "isRTL.coffee library to determine if a text is of right-to-left direction"
}
|
32131
|
<p><strong>HTML</strong></p>
<pre><code><!Doctype html>
<html>
<head>
<title>Welcome To DPS Raipur</title>
<link rel="icon" type="image/png" href="logo.gif" />
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="wrapper" id="wrapper">
<div class="title" id="title"><img class="dps_logo" id="dps_logo" src="dps_logo.jpg" alt="DPS Logo" title="DPS Logo" /></div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>div.wrapper
{
background-color: #D0D0D0;
width: 1200px;
height: 1000px;
margin: 0 auto;
}
div.title
{
background-color: #06472F;
width: 1200px;
height: 20px;
}
</code></pre>
<p>This is a website I am creating and I am completely a beginner, so I don't know whether this code will adjust its alignments automatically with respect to the user's screen. What should I do to make it like that? How can it be improved?</p>
<p>Also, I've been asked to create this site and I don't know how to put a site online. So, will it be OK if I keep all the web pages on my computer by in various folders?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:50:23.340",
"Id": "51333",
"Score": "0",
"body": "have you done any searching for what you are asking here? this Question smells of \"Off-Topic\" for Code Review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:57:27.497",
"Id": "51335",
"Score": "0",
"body": "I asked whether the code I have written will adjust itself according to the user's screen's resolution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:01:55.773",
"Id": "51336",
"Score": "0",
"body": "Why don't you simply say: sorry. I can't make that ;) I think it is best you read some tutorials on html and start from there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:07:10.187",
"Id": "51337",
"Score": "0",
"body": "Just an FYI: I **have** read some tutorials. And that's the only thing I am struggling with. :/"
}
] |
[
{
"body": "<p>Yes </p>\n\n<p>the code will auto align to the user's browser window, as long as the browser window is greater than <code>1200px</code></p>\n\n<p><strong>Second Question</strong></p>\n\n<p>if you keep the files on your computer they will not be online, you have to host the pages on a web server and obtain a Domain name and all sorts of other stuff pertaining to attaching that site to the Domain Name and DNS Servers and such.</p>\n\n<p>most of the time they will give you a root directory and as long as you keep the file structure the same you shouldn't have to change the links, you should look into <code>absolute pathing</code> and because I could be wrong, I usually have to check to make sure that I set my links right, but I am pretty sure that your graphics should show up if they are in the root folder of the site with out having to change the links.</p>\n\n<p>personally I would recommend that you create a folder called <code>images</code> or <code>pictures</code> or <code>graphics</code> something to that effect, and change the links to <code>images/logo.gif</code> same with your StyleSheets those should as well be in their own folder, I usally name my CSS folder <code>CSS</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:22:16.363",
"Id": "51338",
"Score": "0",
"body": "Thanks a lot! Though, I know that they won't go online just by keeping them on my computer. I wanted to know whether it'll be OK if I keep all the web pages on my computer and link the images and hyperlinks to a folder in my computer. Then when we upload the home page with all the folders, will it accept the directory or I need to put **all** the pages online and change the links like this:\n\nwebsite.com/path?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:26:21.943",
"Id": "51339",
"Score": "0",
"body": "P.S. By \"align itself\" do you mean that if the website is viewed in a larger resolution, say 2048 X 1152, will it be displayed as same as it would in a resolution of 1024px or will the user need to zoom-in in order fit it with respect to its screen?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:30:41.313",
"Id": "51340",
"Score": "0",
"body": "your content will only take up `1200px` and the left and right margins are set to auto, so any extra space on the sides will be margin, it will automatically center the content in the middle of the screen (horizontally)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T15:14:11.367",
"Id": "51343",
"Score": "0",
"body": "OK, again, thanks a lot. Also, I am thinking about creating folders with names like: \"about us\" \"our things\" which will be accessed through the home page and the all the stylesheets used will be inside these folders."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T15:21:30.030",
"Id": "51345",
"Score": "0",
"body": "just make sure that you check out file paths. if you have a a page that is in a folder and you want to link to something else in that folder I don't think you need to preface it with the folder that the page is in. does that make sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:57:46.023",
"Id": "51351",
"Score": "0",
"body": "I think so. LOL. But I know what I have to do now, so, thanks. :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:13:43.473",
"Id": "32137",
"ParentId": "32135",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32137",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T13:25:14.893",
"Id": "32135",
"Score": "3",
"Tags": [
"html",
"beginner",
"css"
],
"Title": "Will this code adjust its alignments automatically with respect to the user's screen?"
}
|
32135
|
<p>I wrote <a href="https://github.com/dhilipsiva/dssudokusolver">DSSudokuSolver</a> - a sudoku solving algorithm a while back. Is there any possibility that this algorithm can be improved?</p>
<p><strong>Original Algorithm:</strong></p>
<pre><code>CleanElements = function(comp_ary, Qsudoku){
for(i=0; i<9; i++){
for(j=0; j<9; j++){
/*if(Qsudoku[i][j] != ""){
comp_ary[i][j]=[];
}*/
for(k=0; k<9; k++){
i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);
if(i_index != -1){
comp_ary[i][k].splice(i_index, 1);
}
j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);
if(j_index != -1){
comp_ary[k][j].splice(j_index, 1);
}
}
if(i < 3){
i_min = 0;
i_max = 2;
}
else if(i < 6){
i_min = 3;
i_max = 5;
}
else{
i_min = 6;
i_max = 8;
}
if(j < 3){
j_min = 0;
j_max = 2;
}
else if(j < 6){
j_min = 3;
j_max = 5;
}
else{
j_min = 6;
j_max = 8;
}
for(i_box=i_min; i_box<=i_max; i_box++){
for(j_box=j_min; j_box<=j_max; j_box++){
index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);
if(index != -1){
comp_ary[i_box][j_box].splice(index, 1);
}
}
}
}
}
return comp_ary;
}
FindElements = function(comp_ary, Qsudoku){
for(i=0; i<9; i++){
for(j=0; j<9; j++){
if(comp_ary[i][j].length == 1){
if (Qsudoku[i][j] == ""){
Qsudoku[i][j] = comp_ary[i][j][0];
comp_ary[i][j] = [];
}
}
}
}
return Qsudoku;
}
IsThereNullElement = function(Qsudoku){
for(i=0; i<9; i++){
for(j=0; j<9; j++){
if(Qsudoku[i][j] == ""){
return false;
}
}
}
return true;
}
InitEmptyArray = function(){
empty_ary = Array();
for(i=0; i<9; i++){
empty_ary[i] = Array();
for(j=0; j<9; j++){
empty_ary[i][j] = Array();
for(k=0; k<9; k++){
empty_ary[i][j][k] = (k+1).toString();
}
}
}
return empty_ary;
}
DSSolve = function(Qsudoku){
comp_ary = InitEmptyArray(); //Complementary Array
window.comp_ary_old = comp_ary;
IterationMax = 5000;
while(true){
IterationMax -= 1;
comp_ary = CleanElements(comp_ary, Qsudoku);
console.log(comp_ary);
if(window.comp_ary_old == comp_ary){
//implement this.
}
else{
window.comp_ary_old = comp_ary;
}
Qsudoku = FindElements(comp_ary, Qsudoku);
//console.log(Qsudoku);
if(IsThereNullElement(Qsudoku)){
return Qsudoku;
}
if(IterationMax == 0){
return null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T15:20:38.540",
"Id": "51344",
"Score": "0",
"body": "You should generally avoid adding properties to `window`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:45:59.327",
"Id": "63730",
"Score": "0",
"body": "It seems you are using the brute force approach ( http://en.wikipedia.org/wiki/Sudoku_solving_algorithms ), any other approach will be much faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T16:09:07.540",
"Id": "64019",
"Score": "0",
"body": "Why did you declare all functions anonymously?"
}
] |
[
{
"body": "<p>It's not a huge improvement, just taking a stab at a few slight tweaks:</p>\n\n<pre><code>var sudoku = {\n CleanElements:function(comp_ary, Qsudoku){\n var i_factor,\n j_factor,\n i_min,\n i_max,\n i_index,\n j_index,\n index;\n\n for(var i=9; i--;){\n i_factor = (3*Math.floor(i/3));\n i_min = 6 - i_factor;\n i_max = 8 - i_factor;\n\n for(var j=9; j--;){\n j_factor = (3*Math.floor(j/3));\n j_min = 6 - j_factor;\n j_max = 8 - j_factor;\n\n for(var k=9; k--;){\n i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);\n j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);\n\n if(i_index !== -1){\n comp_ary[i][k].splice(i_index,1);\n }\n\n if(j_index !== -1){\n comp_ary[k][j].splice(j_index,1);\n }\n }\n\n for(var i_box=i_max; i_box>=i_min; i_box--){\n for(var j_box=j_max; j_box>=j_min; j_box--){\n index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);\n if(index !== -1){\n comp_ary[i_box][j_box].splice(index, 1);\n }\n }\n }\n }\n }\n return comp_ary;\n },\n FindElements:function(comp_ary, Qsudoku){\n for(var i=9; i--;){\n for(var j=9; j--;){\n if(comp_ary[i][j].length === 1){\n // in case you were specifically checking that it was an empty string and not a null / undefined / etc, change to Qsudoku[i][j] === ''\n if (Qsudoku[i][j].length === 0){\n Qsudoku[i][j] = comp_ary[i][j][0];\n comp_ary[i][j] = [];\n }\n }\n }\n }\n return Qsudoku;\n },\n IsThereNullElement:function(Qsudoku){\n for(var i=9; i--;){\n for(var j=9; j--;){\n // same here, change to === '' if specifically needed\n if(Qsudoku[i][j].length === 0){\n return false;\n }\n }\n }\n return true;\n },\n InitEmptyArray:function(){\n var empty_ary = Array();\n\n for(var i=9; i--;){\n empty_ary[i] = Array();\n\n for(var j=9; j--;){\n empty_ary[i][j] = Array();\n\n for(var k=9; k--;){\n empty_ary[i][j][k] = (k+1)+'';\n }\n }\n }\n return empty_ary;\n },\n DSSolve:function(Qsudoku){\n var self = this,\n comp_ary = self.InitEmptyArray(),\n Qsudoku;\n\n this.comp_ary_old = comp_ary;\n\n for(var i=5000; i--;){\n comp_ary = self.CleanElements(comp_ary, Qsudoku);\n // console.log(comp_ary);\n\n if(sudoku.comp_ary_old === comp_ary){\n // implement this.\n } else {\n sudoku.comp_ary_old = comp_ary;\n }\n\n Qsudoku = self.FindElements(comp_ary, Qsudoku);\n // console.log(Qsudoku);\n\n if(self.IsThereNullElement(Qsudoku)){\n return Qsudoku;\n }\n\n if(i === 0){\n return null;\n }\n }\n }\n};\n</code></pre>\n\n<p>And then you call it with this (Qsudoku being the value you want to pass in):</p>\n\n<pre><code>sudoku.DSSolve(Qsudoku);\n</code></pre>\n\n<p>Quick breakdown of changes:</p>\n\n<ul>\n<li>changed all for loops and final while loop to decrement (faster in all browsers)</li>\n<li>changed <code>== ''</code> to <code>.length === 0</code> (faster in all browsers)</li>\n<li>applied strict comparison <code>===</code> rather than implicit <code>==</code> (faster on certain browsers)</li>\n<li>changed multiple if/else if/else statements to applying <code>Math.floor</code> to compute reduction factor</li>\n<li>encapsulated all functions within object to allow for use of object <code>comp_ary_old</code> (instead of using <code>window</code>)</li>\n<li>added explicit <code>var</code> statement for variable declaration (prevents bubbling up to <code>window</code>)</li>\n<li>moved variables to top of respective function and assigned value at point where the fewest loops occur while retaining value integrity</li>\n<li>changed the <code>.toString()</code> function to the <code>+''</code> trick (its a miniscule improvement, more of a \"squeeze every byte\" thing, so if you would rather stick with code clarity switch it back to <code>.toString()</code>)</li>\n</ul>\n\n<p>I haven't tested this at all, so no benchmarks to show if it actually improves performance, but theoretically it should maintain your code operations while executing faster. Figured it was worth a shot, since no one else answered. Hope it helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:30:06.673",
"Id": "63700",
"Score": "0",
"body": "Great input. I'm not going to award the bounty for a while yet as there may be other answers coming. Feel free to improve on your answer if you feel there are other things to add."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:08:34.443",
"Id": "63711",
"Score": "0",
"body": "Oh no worries, the bounty is whatever to me anyway, it just seemed weird that a question like this would go unanswered for so long without someone at least giving it a shot. A faster web is a better web, :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:06:46.783",
"Id": "82353",
"Score": "0",
"body": "Wow, thanks for the great answer. A really fantastic one."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T15:12:38.487",
"Id": "38273",
"ParentId": "32138",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38273",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:49:02.187",
"Id": "32138",
"Score": "7",
"Tags": [
"javascript",
"optimization",
"algorithm",
"sudoku"
],
"Title": "DSSudokuSolver - A JavaScript Sudoku solving algorithm"
}
|
32138
|
<p>After recently getting a bulk of work done on my WebAPI service layer, I thought I'd post some of my working on here for you guys to tear apart, generally, most of it 'feels' mostly okay, but I know there are areas for improvement. Hopefully no screaming issues with it:</p>
<p>Someone is going to quote me Ayende, note that my queries are separated and passed in, I'm not creating countless methods. </p>
<p>Hopefully you will see that there is some use in the abstraction I've put in place, since some of the objects don't map nicely to EF objects and there is some pretty complex logic that needs to executed in different conditions, so duplication would be an issue without it I believe.</p>
<p>My routing:</p>
<pre><code> config.Routes.MapHttpRoute(
name: ControllerOnly,
routeTemplate: "{controller}"
);
//For filtering and lookups we will overload the get method to pass in more parameters.
config.Routes.MapHttpRoute(
name: ControllerAndAction,
routeTemplate: "{controller}/act/{action}/",
defaults: null//, //defaults: new { id = RouteParameter.Optional } //,
//constraints: new { id = @"^\d+$" } // id must be all digits
);
config.Routes.MapHttpRoute(
name: ControllerAndActionId,
routeTemplate: "{controller}/act/{action}/{id}",
defaults: null//, //defaults: new { id = RouteParameter.Optional } //,
//constraints: new { id = @"^\d+$" } // id must be all digits
);
//For filtering and lookups we will overload the get method to pass in more parameters.
config.Routes.MapHttpRoute(
name: ControllerAndId,
routeTemplate: "{controller}/{id}",
defaults: null//, //defaults: new { id = RouteParameter.Optional } //,
//constraints: new { id = @"^\d+$" } // id must be all digits
);
</code></pre>
<p>This routing is a bit crusty, since I have to use /act/ to call an action, since the <code>id</code> could be a string and the routing was matching the action name to <code>id</code>. Any alternatives welcomed.</p>
<pre><code>public class FaqController : ControllerBase
{
private readonly IFaqRepository _repo;
public FaqController(IFaqRepository repo, IUnitOfWork uow, ITokenRepository tokens)
{
_uow = uow;
_repo = repo;
_tokens = tokens;
}
// [Authorize]
[UnitOfWorkCommit]
public void Post(FaqContent content)
{
if (content.FaqId != 0)
{
_repo.Update(content, content.FaqId);
}
else
{
_repo.Insert(content);
}
}
[UnitOfWorkCommit]
[HttpDelete]
public void Delete(int id) {
_repo.Delete(id);
}
[Authorize]
public IEnumerable<FaqContent> Get()
{
return _repo.Get(orderBy: o => o.OrderBy(i => i.FaqId));
}
[Authorize]
public IEnumerable<FaqContent> Get(int id)
{
return _repo.Get(filter: j => j.FaqId == id, orderBy: o => o.OrderBy(i => i.FaqId));
}
}
</code></pre>
<p>A few basic CRUD operations above, using proper HTTP verbs and delegating down to repository. Note the authorize attribute.</p>
<pre><code>public class AuthHandler : DelegatingHandler
{
private IUserRepository _userRepository;
private ITokenRepository _tokenRepo;
public AuthHandler()
{
}
protected Guid? GetTokenValue(HttpRequestMessage request)
{
Guid tokenValue;
var accessToken = request.Headers.GetCookies("token"); //See if the token is in the cookies
if (accessToken.Count == 0) //Nothing in the cookie... Check the querystring
{
var qs = request.GetQueryNameValuePairs();
var accessTokenQs = qs.Where(o => o.Key == "token").ToList();
if (accessTokenQs.Count == 0)
{
return null;
}
else
{
if (Guid.TryParse(accessTokenQs[0].Value, out tokenValue))
return tokenValue;
return null;
}
}
else
{
if (Guid.TryParse(accessToken[0]["token"].Value, out tokenValue))
return tokenValue;
return null;
}
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_userRepository = request.GetDependencyScope().GetService(typeof(IUserRepository)) as IUserRepository;
_tokenRepo = request.GetDependencyScope().GetService(typeof(ITokenRepository)) as ITokenRepository;
var tokenValue = GetTokenValue(request);
if (tokenValue == null)
{
return base.SendAsync(request, cancellationToken); //Still no token, carry on
}
var token = _tokenRepo.CheckToken(tokenValue.Value, true);
if (token == null)
return base.SendAsync(request, cancellationToken);
var user = _userRepository.GetByUserName(token.AssignedToUser);
var identity = new GenericIdentity(user.UserName, "Basic");
var principal = new GenericPrincipal(identity, user.Roles.Select(o => o.RoleName).ToArray());
Thread.CurrentPrincipal = principal;
return base.SendAsync(request, cancellationToken);
}
}
</code></pre>
<p>This is what handles the authorization, I am using cached repositories at the moment for stuff like that, so I don't hit the DB every time, these use the MemoryCache to store result sets, currently they have a sliding timer but I'll need to rework that at the moment as other applications will change the data, so I need to build in some contingency.</p>
<pre><code> public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
internal IUnitOfWork context;
internal DbSet<TEntity> dbSet;
private List<IAction<TEntity>> _actionsOnSave = new List<IAction<TEntity>>();
public ObservableCollection<TEntity> GetLocalEntities()
{
return dbSet.Local;
}
public void FireActions()
{
foreach (var act in _actionsOnSave)
{
act.Execute(this);
}
//Execute each action
}
public void AddAction(IAction<TEntity> action)
{
_actionsOnSave.Add(action);
}
public GenericRepository(IUnitOfWork uow)
{
this.context = uow;
this.dbSet = context.GetContext().Set<TEntity>();
}
public virtual IQueryable<TEntity> GetLazy(
Expression<Func<TEntity, bool>> filter = null, DynamicFilter dynamicFilters = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (dynamicFilters != null)
{
query = dynamicFilters.FilterObjectSet(query);
}
return query;
}
public object GetPagedData(int pageNo, int rows, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy, DynamicFilter f)
{
//Add back in order by to optimize perforamnce on large DS
var startAt = (pageNo * rows) - rows;
var retrieved = GetLazy(dynamicFilters: f); //Get an instance of IQueryable to use for the class
var totalRows = retrieved.Count(); //Count before paging occurs
int totalPages = (int)Math.Ceiling((double)totalRows / (double)rows);
if (pageNo > totalPages) pageNo = totalPages;
var filteredResults = ApplyPaging(retrieved, orderBy, startAt, rows);
var ret = new
{
page = pageNo,
total = totalPages,
records = totalRows,
repeatitems = true,
cell = "cell",
userdata = "userdata",
rows = filteredResults
};
return ret;
}
public virtual IQueryable<TEntity> ApplyPaging(IQueryable<TEntity> query, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, int skip = 0, int take = 0)
{
if (orderBy != null)
{
if (take != 0)
{
return orderBy(query).Skip(skip).Take(take);
}
else
{
return orderBy(query).Skip(skip);
}
}
return query;
}
public virtual IEnumerable<TEntity> Get(
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
IQueryable<TEntity> query = dbSet;
if (orderBy != null)
{
return orderBy(query).ToList();
}
throw new Exception("You must specify an OrderBy");
//return null;
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
int skip = 0, int take = 0,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
if (take != 0)
{
return orderBy(query).Skip(skip).Take(take).ToList();
}
else
{
return orderBy(query).Skip(skip).ToList();
}
}
throw new Exception("You must specify an OrderBy");
//return null;
}
public virtual int GetCount(
Expression<Func<TEntity, bool>> filter = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
return query.Count();
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
if (entityToDelete == null)
{
throw new Exception(string.Format("Entity with ID ({0}) not found in dbSet", id));
}
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.GetContext().Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate, object id)
{
if (entityToUpdate == null)
{
throw new ArgumentException("Cannot add a null entity.");
}
var entry = context.GetContext().Entry(entityToUpdate);
if (entry.State == EntityState.Detached)
{
var ent = dbSet.Find(id);
if (ent != null)
{
var attachedEntry = context.GetContext().Entry(ent);
attachedEntry.CurrentValues.SetValues(entityToUpdate);
}
else
{
entry.State = EntityState.Modified;
}
}
}
}
</code></pre>
<p>My generic repo, I have concrete implementations as well, where I might need to return a more complex object.</p>
<p>Finally, my unit of work filter:</p>
<pre><code> public class UnitOfWorkCommitAttribute :ActionFilterAttribute
{
public IUnitOfWork uow { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
uow = actionExecutedContext.Request.GetDependencyScope().GetService(typeof(IUnitOfWork)) as IUnitOfWork;
if (actionExecutedContext.Exception == null)
uow.Commit();
}
}
</code></pre>
<p>There is a lot more to the project but these are some of the core parts I wouldn't mind having an experienced eye look over.</p>
|
[] |
[
{
"body": "<p>I do mostly Windows development so I might not be the experienced eye you're looking for in terms of ASP.NET MVC, but I'll share a couple thoughts anyway:</p>\n\n<ul>\n<li><strong>Your default/parameterless constructor for the <code>AuthHandler</code> class is redundant</strong> and can be removed - unless there's a parameterized constructor you've excluded from the posted code, the compiler generates the default constructor for you so putting it in is just clutter.</li>\n<li>I'll have to look again at that specific chapter (the one specifically aimed at DI with ASP.NET MVC) in Mark Seeman's excellent <a href=\"http://www.manning.com/seemann/\" rel=\"nofollow\">Dependency Injection in .NET</a>, but one thing I know for sure is that Mark Seeman wouldn't have gone with this <code>IUnitOfWork</code> stuff and I agree with the DI Guru - EF already implements <em>Unit of Work</em> and <em>Repostory</em> patterns, wrapping EF around your own is overkill.\n<ul>\n<li><strong>Your generic repository is tied to EF anyway</strong>, since it's using <code>DbSet<T></code>.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T17:36:55.113",
"Id": "114701",
"Score": "0",
"body": "I'm not sure that you're correct with the last bit of your second bullet-point. Yes EF does coordinate changes, but it's about ensuring that all of your repositories all use a SINGLE EF DbContext. I can use EF, but if I have two instances of an EF DbContext then the changes won't be coordinated as intended with Unit Of Work"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T17:56:11.630",
"Id": "114708",
"Score": "0",
"body": "@Coulton All DbSets under a DbContext will use the same context. If you have more than a single context alive during a single transaction, I'd question the architecture. DbContext instances should be short-lived; the IoC container (here Ninject) should be configured to inject an *instance per request* into the controller or service that depends on it. Everything that happens during a request will use the same DbContext."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T18:06:42.420",
"Id": "114709",
"Score": "0",
"body": "I think you probably know more about this that I do :). I agree that Ninject should be configured to create a single instance per request, but I thought that was the whole point in the unit of work if you choose to use it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T18:14:26.520",
"Id": "114710",
"Score": "0",
"body": "UoW is really about encapsulating a transaction; I find it useful when working with raw ADO.NET (heck, I even implemented one in VBA with ADODB).. but EF's DbContext does that all by itself. Managing object lifetime, in a DI setup, is the job of the IoC container ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T20:44:52.697",
"Id": "114728",
"Score": "0",
"body": "Mat, I'd really appreciate it if you could take a look at this question of mine regarding this: http://stackoverflow.com/questions/25827376/owin-dbcontext-and-a-single-dbcontext-for-all-of-my-repositories I don't know how I'm supposed to use a single DbContext for use by all of my repositories, which I assume I'm supposed to do?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T01:25:26.360",
"Id": "35996",
"ParentId": "32139",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T14:51:08.590",
"Id": "32139",
"Score": "6",
"Tags": [
"c#",
"design-patterns",
"asp.net-mvc-4"
],
"Title": "Unit of work, Ninject, Repository and WebAPI implementation"
}
|
32139
|
<p>This is a simple script that I use for wrapping a selected word in a textarea field. I'm looking to:</p>
<ol>
<li><p>make sure my logic is valid/see what others have done in a relative context.</p></li>
<li><p>request improvements to the OO approach I'm going for.</p></li>
</ol>
<pre><code>Formatter = {};
Formatter.getSelection = function(event) {
var text = document.getElementById("mass_message");
var sPos = text.selectionStart;
var ePos = text.selectionEnd;
var front = (text.value).substring(0, sPos);
var sel = (text.value).substring(sPos, ePos);
var back = (text.value).substring(ePos, text.value.length);
format = event.data.format;
var print = Formatter.setString(text, format, front, back, sel);
}
Formatter.setString = function(text, format, front, back, sel) {
text.value = front + "<" + format + ">" + sel + "</" + format + ">" + back;
}
$(document).ready(function(){
$( '#bolden' ).on('click', { format: "b" }, Formatter.getSelection);
$( '#italicize' ).on('click', { format: "i" }, Formatter.getSelection);
});
</code></pre>
<p>I'm appreciative of any suggestions and am happy to answer questions about the code.</p>
|
[] |
[
{
"body": "<p>One comment I might suggest is your hard reference to mass_message, consider passing that in as part of your event data, as it makes the code more re-usable (Several instances of your editor on a page?)</p>\n\n<p>A thought to consider is to swap your hard b and i tags to instead define css classes to be used? This will give you code re-use, if you had bold and italic defined in a css, you could use the above code you have to simply change the class on click instead, allowing you to do more jazzy stuff, borders and such, or be very clever and have specific things you define, maybe floats and margins/padding etc. You could use span as a first try and set the class of the span equal to the specified format :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:52:29.403",
"Id": "51358",
"Score": "2",
"body": "The bummer is i'm using textarea, which won't interpret CSS. The alternative here is to instead use an editable div, then send the div with the styles to the mailer. Provoking enough of a comment to make me think of it in a different way, thanks much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:37:14.253",
"Id": "32151",
"ParentId": "32140",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T15:26:49.193",
"Id": "32140",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"object-oriented"
],
"Title": "Object Oriented JavaScript optimization"
}
|
32140
|
<p>I'm learning DB design. How would you change the following schema which tries to replicate Stack Overflow's functionality:</p>
<pre><code>create_table "questions", :force => true do |t|
t.text "question", :null => false
t.text "description", :null => false
t.integer "up_votes", :null => false, :default => 0
t.integer "down_votes", :null => false, :default => 0
t.timestamps
end
create_table "answers", :force => true do |t|
t.integer "question_id", :null => false
t.text "answer", :null => false
t.integer "up_votes", :null => false, :default => 0
t.integer "down_votes", :null => false, :default => 0
t.timestamps
end
create_table "question_comments", :force => true do |t|
t.integer "question_id", :null => false
t.text "comment", :null => false
t.timestamps
end
create_table "answer_comments", :force => true do |t|
t.integer "answer_id", :null => false
t.text "comment", :null => false
t.timestamps
end
create_table "tags", :force => true do |t|
t.string "tag", :null => false, :limit => 100
t.timestamps
end
add_index "tags", ["tag"], :name => "tag_UNIQUE", :unique => true
create_table "question_tags", :force => true do |t|
t.integer "question_id", :null => false
t.integer "tag_id", :null => false
t.timestamps
end
create_table "users", :force => true do |t|
t.string "first_name", :limit => 45, :null => false
t.string "last_name", :limit => 45, :null => false
t.string "email", :limit => 100, :null => false
t.string "password", :null => false
t.string "salt", :null => false
t.timestamps
end
create_table "user_votes", :force => true do |t|
t.integer "user_id", :null => false
t.integer "question_id"
t.integer "answer_id"
t.boolean "is_positive_vote"
t.timestamps
end
create_table "user_favorites", :force => true do |t|
t.integer "user_id", :null => false
t.integer "question_id"
t.integer "answer_id"
t.timestamps
end
create_table "question_flags", :force => true do |t|
t.integer "user_id", :null => false
t.integer "question_id"
t.timestamps
end
create_table "answer_flags", :force => true do |t|
t.integer "user_id", :null => false
t.integer "question_id"
t.timestamps
end
create_table "related_questions", :force => true do |t|
t.integer "question_id", :null => false
t.integer "related_question_id", :null => false
t.timestamps
end
</code></pre>
|
[] |
[
{
"body": "<p>Your answers table doesn't actually have an answerID, which is later referenced in your answer comments.</p>\n\n<p>Your link tables for comments, I would have a primary key assigned that is separate from the answerid, since you don't want a composite key between answerID and comment (Think about updating/removing post logic). Apply the same to question comments.</p>\n\n<p>Consider storing users against questions/answer submissions, otherwise, how will you know who posted it? Think about edit functionality too, do you want to audit changes?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T16:26:20.240",
"Id": "32149",
"ParentId": "32141",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T15:28:16.340",
"Id": "32141",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Critique my Stack Overflow schema"
}
|
32141
|
<p>I've asked <a href="https://codeclimate.com/" rel="nofollow noreferrer">Code Climate</a> to <a href="https://codeclimate.com/github/wconrad/ftpd" rel="nofollow noreferrer">generate metrics</a> for the <a href="https://github.com/wconrad/ftpd/tree/94beb23d544e8d8d5a6e1c0d6731ae7f5fa3a62f" rel="nofollow noreferrer">ftpd Ruby gem</a>. It correctly identified the God class; I know what to do about that. But one of the smaller classes has me stumped. This is <em>telnet.rb</em>:</p>
<pre><code># -*- ruby encoding: us-ascii -*-
module Ftpd
# Handle the limited processing of Telnet sequences required by the
# FTP RFCs.
#
# Telnet option processing is quite complex, but we need do only a
# simple subset of it, since we can disagree with any request by the
# client to turn on an option (RFC-1123 4.1.2.12). Adhering to
# RFC-1143 ("The Q Method of Implementing TELNET Option Negiation"),
# and supporting only what's needed to keep all options turned off:
#
# * Reply to WILL sequence with DONT sequence
# * Reply to DO sequence with WONT sequence
# * Ignore WONT sequence
# * Ignore DONT sequence
#
# We also handle the "interrupt process" and "data mark" sequences,
# which the client sends before the ABORT command, by ignoring them.
#
# All Telnet sequence start with an IAC, followed by at least one
# character. Here are the sequences we care about:
#
# SEQUENCE CODES
# ----------------- --------------------
# WILL IAC WILL option-code
# WONT IAC WONT option-code
# DO IAC DO option-code
# DONT IAC DONT option-code
# escaped 255 IAC IAC
# interrupt process IAC IP
# data mark IAC DM
#
# Any pathalogical sequence (e.g. IAC + \x01), or any sequence we
# don't recognize, we pass through.
class Telnet
# The command with recognized Telnet sequences removed
attr_reader :plain
# Any Telnet sequences to send
attr_reader :reply
# Create a new instance with a command that may contain Telnet
# sequences.
# @param command [String]
def initialize(command)
telnet_state_machine command
end
private
module Codes
IAC = 255.chr # 0xff
DONT = 254.chr # 0xfe
DO = 253.chr # 0xfd
WONT = 252.chr # 0xfc
WILL = 251.chr # 0xfb
IP = 244.chr # 0xf4
DM = 242.chr # 0xf2
end
include Codes
def telnet_state_machine (command)
@plain = ''
@reply = ''
state = :idle
command.each_char do |c|
case state
when :idle
if c == IAC
state = :iac
else
@plain << c
end
when :iac
case c
when IAC
@plain << c
state = :idle
when WILL
state = :will
when WONT
state = :wont
when DO
state = :do
when DONT
state = :dont
when IP
state = :idle
when DM
state = :idle
else
@plain << IAC + c
state = :idle
end
when :will
@reply << IAC + DONT + c
state = :idle
when :wont
state = :idle
when :do
@reply << IAC + WONT + c
state = :idle
when :dont
state = :idle
else
raise "Unknown state #{state.inspect}"
end
end
end
end
end
</code></pre>
<p><em>Code Climate</em> does not like the complexity of <code>#telnet_state_machine</code>. I agree, but I don't know how to reduce the complexity without also making the state machine harder to follow. State machines never seem to be all that readable as it is. What would you suggest?</p>
<p>Note: If you want to try some refactoring, this class has rspec test coverage. Just do "git clone" of the <a href="https://github.com/wconrad/ftpd/tree/94beb23d544e8d8d5a6e1c0d6731ae7f5fa3a62f" rel="nofollow noreferrer">ftpd</a> project.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T19:33:20.523",
"Id": "51360",
"Score": "1",
"body": "what about using a \"real\" state machine instead of a switch implementation ? If you don't want to use a gem like [state_machine](https://github.com/pluginaweek/state_machine) you can always try to use composition - i'll try to come up with something if i have time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:20:12.667",
"Id": "51496",
"Score": "0",
"body": "@m_x I like the idea of trying the state_machine gem. I'll try it and post the result here, if nobody else has."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T20:42:50.523",
"Id": "51904",
"Score": "0",
"body": "In any case, are you looking for contributors on your gem ? I never contributed to any open-source project and i'd like to give it a try. I'm willing to do anything you throw at me, even if it's only doc improvement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T21:18:32.467",
"Id": "51912",
"Score": "0",
"body": "@m_x, Sure! The project is on github (see link in question). My email address is in the README."
}
] |
[
{
"body": "<h3>EDIT</h3>\n\n<p>the more I think about it, the more it seems obvious that a parser would be more adapted to this problem than a state machine. Unfortunately, I don't know much about writing parsers...</p>\n\n<h3>ORIGINAL ANSWER</h3>\n\n<p>Maybe you could try to create one class per state :</p>\n\n<pre><code>class TelnetState\n\n include Telnet::Codes\n attr_reader :plain, :reply\n\n def initialize( plain = '', reply ='' )\n @plain = plain\n @reply = reply\n end\n\n def accept_char( char )\n raise \"Abstract Method - not implemented\"\n end\n\nend\n\nclass TelnetIDLEState < TelnetState\n\n def accept_char( char )\n if char == IAC \n TelnetIACState.new( plain, reply )\n else\n @plain << char\n self \n end\n end\n\nend\n\nclass TelnetIACState < TelnetState\n\n def accept_char( char )\n update_plain!( char )\n next_state( char )\n end\n\n private\n\n def update_plain!( char )\n return if [WILL, WONT, DO, DONT, IP,DM].include? char\n @plain << char == IAC ? char : IAC + char\n end\n\n def next_state( char ) \n next = case char\n when WILL then TelnetWILLState\n when WONT then TelnetWONTState\n when DO then TelnetDOState\n when WONT then TelnetDONTState\n end\n next ? next.new( plain, reply ) : self\n end\n\n end\n</code></pre>\n\n<p>... and so on, then : </p>\n\n<pre><code>class Telnet\n\n def telnet_state_machine( command )\n state = command.each_char.inject( TelnetIDLEState.new ) do |state, char|\n state.accept_char( char )\n end\n @plain, @reply = state.plain, state.reply\n end\n\nend\n</code></pre>\n\n<p>Of course, there is certainly a way to improve that... just an idea. (I'm not really familiar with telnet protocol, either - so I did this a bit blindfolded)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:17:57.877",
"Id": "51495",
"Score": "0",
"body": "Thank you for the answer. I'm not keen on the class-per-state idea because it spreads the state machine out over multiple pages. State machines in code are difficult to read, being a 1D representation of a 2D structure; when the representation no longer fits on a screen, they get _much_ harder to understand. The idea of using a parser is interesting! I suspect a general purpose parser such as parslet is too heavy a tool to apply to this problem, but I'll keep the idea in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:09:23.697",
"Id": "51514",
"Score": "0",
"body": "Agreed, a state machine can become very hard to understand - when the pattern does not naturally adhere to its subject, as it is the case here. In some other cases it feels logic and natural. As i said, I don't really know how to build a parser; however the problem just calls it pretty clearly. Think of it : you have a string that is just a sequence of symbols that express commands to perform in a certain order..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:20:43.757",
"Id": "51515",
"Score": "0",
"body": "just out of curiosity, I just checked the source of core's `Telnet` class... just to find out it's [far more complex (to say the least)](http://rxr.whitequark.org/mri/source/lib/net/telnet.rb) than your implementation. Do you have reasons not to use core ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:24:17.307",
"Id": "51517",
"Score": "0",
"body": "also, if it's a server you need, you might want to take a look at [this](https://www.ruby-forum.com/topic/75391)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:32:02.700",
"Id": "51518",
"Score": "0",
"body": "btw, thanks for pointing out parslet, seems pretty neat !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:08:33.397",
"Id": "51525",
"Score": "0",
"body": "You're welcome; parslet is the bee's knees. The Telnet class won't work for me because it's a client class for connecting to a Telnet server. FTPD is neither a telnet server nor client; it's an FTP server. FTP uses telnet for the control connection (ugh). Mr. Gray's implementation using gsub is simple, but possibly flawed (responding to WONT or DONT). Beyond that, I think that any approach using gsub will need careful thought to handle properly all possible sequences (imagine a sequence where the option code is 255 (IAC))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:44:10.710",
"Id": "51533",
"Score": "0",
"body": "I forgot to say: Thank you for thinking this an interesting enough problem to devote so much of your energy to!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T03:18:04.653",
"Id": "51557",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10900/discussion-between-wayne-conrad-and-m-x)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:17:10.703",
"Id": "32157",
"ParentId": "32144",
"Score": "3"
}
},
{
"body": "<p>As suggested, I tried using a gem like <a href=\"https://github.com/pluginaweek/state_machine\" rel=\"nofollow noreferrer\">state_machine</a>. Well, not a gem <em>like</em> state_machine, but that particular gem. The state machine defintion is:</p>\n\n<pre><code> state_machine :state, :initial => :idle do\n\n event :iac do\n transition :idle => :iac\n transition :iac => :idle\n transition [:will, :wont, :do, :dont] => :idle\n end\n\n event :will do\n transition :iac => :will\n transition :will => :idle\n end\n\n event :dm do\n transition :iac => :idle\n end\n\n event :ip do\n transition :iac => :idle\n end\n\n event :dont do\n transition :iac => :dont\n end\n\n event :other do\n transition all => :idle\n end\n\n event :do do\n transition :iac => :do\n end\n\n event :wont do\n transition :iac => :wont\n end\n\n before_transition :from => :do, :to => :idle, :do => :send_wont\n before_transition :from => :will, :to => :idle, :do => :send_dont\n before_transition :from => :idle, :to => :idle, :do => :accept_plain\n before_transition :from => :iac, :to => :idle, :on => :other, :do => :accept_unknown_iac\n before_transition :from => :iac, :to => :idle, :on => :iac, :do => :accept_plain\n\n end\n</code></pre>\n\n<p>The state_machine DSL is clean and relatively compact. Unfortunately, it is organized around events that cause transitions, rather than states that have transitions. That's not bad, but it's completely inside-out to how I think about state machines. It also makes you define actions separately from the transitions. The net result is that I can't see the state machine from this definition.</p>\n\n<p>However, the state_machine gem has a rake task to generate a state diagram directly from the code. Here's what it generated for the above code:</p>\n\n<p><img src=\"https://i.stack.imgur.com/GQZS6.png\" alt=\"state diagram\"></p>\n\n<p>Other than the lack of actions, the state diagram generated by state_machine is very nice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T02:29:51.893",
"Id": "32271",
"ParentId": "32144",
"Score": "3"
}
},
{
"body": "<p>Here's a refactoring that extracts the definition of the state machine into a compact data structure. First a few lambdas for the actions:</p>\n\n<pre><code> # State machine actions.\n #\n # @param plain [String] Accumulated plaintext\n # @param reply [String] Accumulated telnet reply\n # @param c [String] The current character\n\n EMIT_PLAIN = lambda do |plain, reply, c|\n plain << c\n end\n\n EMIT_PLAIN_UNKNOWN_SEQUENCE = lambda do |plain, reply, c|\n plain << IAC + c\n end\n\n EMIT_REPLY_DONT = lambda do |plain, reply, c|\n reply << IAC + DONT + c\n end\n\n EMIT_REPLY_WONT = lambda do |plain, reply, c|\n reply << IAC + WONT + c\n end\n</code></pre>\n\n<p>Then the state machine definition itself. Of all of the state-machine approaches I tried, this one has the most succinct definition:</p>\n\n<pre><code> # The definition of the state machine used to recognize and handle\n # Telnet sequences.\n #\n # This is organized as nested hashes and arrays:\n #\n # The outer, or \"state\" hash is:\n # * key: state\n # * value: character hash\n #\n # The character hash is:\n # * key: character code, or :else\n # * value: action array\n #\n # The action array is a list of zero or more:\n # * lambda - The action to perform\n # * symbol - the next state\n\n STATES = {\n :idle => {\n IAC => [:iac],\n :else => [EMIT_PLAIN],\n },\n :iac => {\n IAC => [EMIT_PLAIN, :idle],\n WILL => [:will],\n WONT => [:wont],\n DO => [:do],\n DONT => [:dont],\n IP => [:idle],\n DM => [:idle],\n :else => [EMIT_PLAIN_UNKNOWN_SEQUENCE, :idle],\n },\n :will => {\n :else => [EMIT_REPLY_DONT, :idle],\n },\n :wont => {\n :else => [:idle],\n },\n :do => {\n :else => [EMIT_REPLY_WONT, :idle],\n },\n :dont => {\n :else => [:idle]\n }\n }\n</code></pre>\n\n<p>And, finally, the functions that drive the state machine:</p>\n\n<pre><code> # Parse the the command. Sets @plain and @reply\n #\n # @param command [String] The command to parse\n\n def parse_command(command)\n @plain = ''\n @reply = ''\n @state = :idle\n command.each_char do |c|\n character_hash = STATES[@state]\n raise \"Unknown state #{@state.inspect}\" unless character_hash\n actions = character_hash[c] || character_hash[:else]\n raise \"Missing :else\" unless actions\n apply_actions actions, c\n end\n end\n\n def apply_actions(actions, c)\n actions.each do |action|\n apply_action action, c\n end\n end\n\n def apply_action(action, c)\n if action.is_a?(Symbol)\n @state = action\n elsif action.respond_to?(:call)\n action.call @plain, @reply, c\n else\n raise \"Unknown action #{action.inspect}\"\n end\n end\n</code></pre>\n\n<p>This does a good job of showing the state machine in a compact and clear format, but the machinery that drives the state machine (<code>parse_command</code> and friends) seem like clutter. The state machine definition may be too compact--the amount of comments I felt necessary to describe it are a sign of that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T02:43:32.553",
"Id": "32272",
"ParentId": "32144",
"Score": "1"
}
},
{
"body": "<p>As suggested by @m_x, This solution uses a parser of sorts, driven by the <a href=\"http://ruby-doc.org/stdlib-1.9.2/libdoc/strscan/rdoc/StringScanner.html\" rel=\"nofollow\">StringScanner</a> built-in class. This is very compact, pretty readable, and gets rid of the state machine altogether:</p>\n\n<p>Some methods to handle actions:</p>\n\n<pre><code>def accept(scanner) \n @plain << scanner[1]\nend\n\ndef reply_dont(scanner)\n @reply << IAC + DONT + scanner[1]\nend\n\ndef reply_wont(scanner)\n @reply << IAC + WONT + scanner[1]\nend\n\ndef ignore(scanner)\nend\n</code></pre>\n\n<p>A list of telnet sequences:</p>\n\n<pre><code># Telnet sequences to handle, and how to handle them\n\nSEQUENCES = [\n [/#{IAC}(#{IAC})/, :accept],\n [/#{IAC}#{WILL}(.)/m, :reply_dont],\n [/#{IAC}#{WONT}(.)/m, :ignore],\n [/#{IAC}#{DO}(.)/m, :reply_wont],\n [/#{IAC}#{DONT}(.)/m, :ignore],\n [/#{IAC}#{IP}/, :ignore],\n [/#{IAC}#{DM}/, :ignore],\n [/(.)/m, :accept],\n]\n</code></pre>\n\n<p>And the parser that uses them:</p>\n\n<pre><code># Parse the the command. Sets @plain and @reply\n\ndef parse_command(command)\n @plain = ''\n @reply = ''\n scanner = StringScanner.new(command)\n while !scanner.eos?\n SEQUENCES.each do |regexp, method|\n if scanner.scan(regexp)\n send method, scanner\n break\n end\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T15:50:14.813",
"Id": "51579",
"Score": "0",
"body": "Good job ! I think it's the best solution. I like the usage of the [chain of responsibility pattern](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern), it's extremely readable (each rule is explicit, and their precedence too), extendable, and easily testable. I'm impressed :) Just one more thing though : maybe the instance variables initialization should belong in `#initialize`. Oh, and sorry for not responding the chat invite, I was busy partying ^.^. Anyway, feel free to unaccept my answer and check this one, it's far better"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-11T23:08:29.530",
"Id": "321024",
"Score": "0",
"body": "This is what I ended up using in my code. I left the checkmark on @m_x's solution to reward him for giving me the idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T03:13:16.190",
"Id": "32273",
"ParentId": "32144",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32157",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-10-02T16:08:51.040",
"Id": "32144",
"Score": "6",
"Tags": [
"ruby",
"server",
"state-machine",
"cyclomatic-complexity",
"ftp"
],
"Title": "State machine for handling Telnet sequences for an FTP server"
}
|
32144
|
<p>I'm doing a infix to postfix conversion. The code works, but here are some points I want to improve</p>
<p>1) In the line of </p>
<pre><code>while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))
</code></pre>
<p>If the condition order changes ( check the stack empty later), there'll be a segmentation fault (because I'm calling operators.top() which is NULL)</p>
<p>2) Convert from char to string using:</p>
<pre><code> string s(1, operators.top());
</code></pre>
<p>which I think constantly create a new variable s and delete it.</p>
<p>How to improve this code?</p>
<pre><code>#include "Parser.h"
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
Parser::Parser()
{
Postfix="";
_source="";
operators=std::stack<char>();
}
string Parser::postfix()
{
return Postfix;
}
string Parser::source()
{
return _source;
}
Parser& Parser::parse(string s)
{
Postfix="";
_source="";
operators=std::stack<char>();
_source=s;
string token;
istringstream iss (_source);
while (iss >> token)
{
if (isdigit(token))
Postfix.append(token).append(" ");
if (isoperator(token))
{
if (operators.empty())
{
operators.push(token[0]);
}
else
{
// Pop until get the same order operator
while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))
{
string s(1, operators.top());
Postfix.append(s).append(" ");
operators.pop();
}
operators.push(token[0]);
}
}
cout <<Postfix<<"\n";
}
while(!operators.empty())
{
string s(1, operators.top());
Postfix.append(s).append(" ");
operators.pop();
}
return *this;
}
bool Parser::isdigit(const string &str)
{
return str.find_first_not_of("-0123456789") == std::string::npos;
}
bool Parser::isoperator(const string &str)
{
return (str=="+")||(str=="-")||(str=="*")||(str=="/");
}
int Parser::order(const char& c)
{
if (c=='+')
return 1;
else if (c=='-')
return 1;
else if (c=='*')
return 2;
else if (c=='/')
return 2;
else
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:57:22.683",
"Id": "51404",
"Score": "0",
"body": "To improve it I would write it in a language designed for parsing. Have a look at flex and yacc(bison)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T16:01:02.520",
"Id": "51405",
"Score": "1",
"body": "Are you trying to implement the [Shunting Yard Algorithm](http://en.wikipedia.org/wiki/Shunting-yard_algorithm)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T16:16:06.890",
"Id": "51407",
"Score": "0",
"body": "yes, I'm implementing that algorithm. Rightnow is without paranthesis"
}
] |
[
{
"body": "<blockquote>\n <p>If the condition order changes ( check the stack empty later), there'll be a segmentation fault (because I'm calling operators.top() which is NULL)</p>\n</blockquote>\n\n<p>Calling top() on an empty queue is even worse then returning <code>NULL</code>. It is actually <strong>undefined behavior</strong>. Which means your code is broken.</p>\n\n<p>This though:</p>\n\n<pre><code>while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))\n</code></pre>\n\n<p>Is fine: The <code>&&</code> operator evaluates the left hand side first and only if this evaluation returns true will it evaluates the right hand side. So the above expression is well formed and correct.</p>\n\n<blockquote>\n <p>Convert from char to string using: which I think constantly create a new variable s and delete it.</p>\n</blockquote>\n\n<p>Yes it creates a new variable <code>s</code>.</p>\n\n<p><code>s</code> will be destroyed(and its destructor called) when it goes out of scope (just like all variables are destroyed when they go out of scope). This is not a big deal.</p>\n\n<p>Personally I would have used Flex/Bison to implement the parser.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T16:08:31.690",
"Id": "32193",
"ParentId": "32155",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32193",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T19:25:33.877",
"Id": "32155",
"Score": "2",
"Tags": [
"c++",
"parsing",
"tree"
],
"Title": "Arithmetic expression parsing, and converting infix to postfix notation"
}
|
32155
|
<p>This code review request is <em>tightly coupled</em> with <a href="https://stackoverflow.com/questions/19129232/lifespan-of-dbcontext-in-a-wpf-application">this SO question</a>, this is the solution I implemented to solve the problem being asked about there.</p>
<p>All my ViewModels get constructor-injected with a Model that itself gets constructor-injected with a <code>DbContext</code>-derived class, and that works well in all cases, except when the View has a command to allow the user to <em>discard pending changes</em>, in which case the <code>DbContext</code> should be disposed and then reinstantiated.</p>
<p>Obviously since the <code>DbContext</code> is created by an IoC container it would be a very bad idea to just dispose and reinstantiate the context, so I came up with a solution involving a factory.</p>
<pre><code>public interface IContextFactory<out TContext> where TContext : DbContext
{
TContext Create();
}
public interface IDiscardModelChanges
{
void DiscardChanges();
}
</code></pre>
<p>Now <code>IDiscardModelChanges</code> is implemented by the model, so to facilitate this I've created a base class that will ensure I have a context factory at hand:</p>
<pre><code>public abstract class DiscardableModelBase<TContext> : IDiscardModelChanges, IDisposable
where TContext : DbContext
{
private readonly IContextFactory<TContext> _factory;
protected TContext Context { get; private set; }
protected DiscardableModelBase(IContextFactory<TContext> factory)
{
_factory = factory;
Context = _factory.Create();
}
public virtual void DiscardChanges()
{
Context.Dispose();
Context = _factory.Create();
}
public void Dispose()
{
Context.Dispose();
}
}
</code></pre>
<p>The model that needs to control its <code>DbContext</code> then derives from this class:</p>
<pre><code>public class SomeModel : DiscardableModelBase<SomeContext>, ISomeModel
{
public SomeModel(IContextFactory<SomeContext> factory)
: base(factory)
{ }
/* methods that act upon protected Context property */
}
</code></pre>
<p>And then the ViewModel that needs to discard pending changes can do it like this (given a <code>private readonly ISomeModel _model</code>):</p>
<pre><code>var model = _model as IDiscardModelChanges;
if (model != null) model.DiscardChanges();
</code></pre>
<p>As far as binding conventions are concerned, I'm keeping the existing "Context" convention, and adding a "ContextFactory" one:</p>
<pre><code>_kernel.Bind(t => t.From(_dataLayerAssembly)
.SelectAllClasses()
.Where(type => type.Name.EndsWith("ContextFactory"))
.BindSingleInterface());
</code></pre>
<p>Bottom line, as far as <em>ViewModels</em> are concerned, nothing changes; the <em>Model</em> is still injected as an interface that exposes the available model methods, and the <code>IDiscardModelChanges</code> interface is only needed if the ViewModel needs to use it, and the ViewModel can't assume the interface is implemented by the Model.</p>
<p>Any known issues with this approach, any blatant mistake made?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T07:46:20.370",
"Id": "51381",
"Score": "0",
"body": "AFAICT you don't need to throw away the context? http://code.msdn.microsoft.com/How-to-undo-the-changes-in-00aed3c4"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:33:38.810",
"Id": "51396",
"Score": "0",
"body": "Ugh isn't that painful? Loop through entities, switch upon state, reset state, ...I was referring to [this post](http://stackoverflow.com/a/10536558/1188513); disposing and recreating the context sounds like a much cleaner way to go, especially if I don't want to cherry-pick entity types I want to cancel changes for (i.e. when I want to drop all changes regardless)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T07:57:05.910",
"Id": "102030",
"Score": "0",
"body": "Throwing away context might be even more painful. Saving all changes will have more impact to your performance than discarding them one by one. So why bother?"
}
] |
[
{
"body": "<p>Somewhat similar but still a bit different approach is to encapsulate your context into some container class and put this wrapper into IoC container instead of context itself. Might look like this:</p>\n\n<pre><code>interface IContextManager<TContext> : IDisposable\n{\n TContext Context { get; }\n\n void ReloadContext();\n event Action ContextChanged; \n}\n</code></pre>\n\n<p>The obvious advantage (which might as well be a disadvatage, depending on context) is that this way you will always have a single instace of <code>DbContext</code>, and once it is reloaded - every model will use new instance (given they access it via <code>IContextManager.Context</code> property).</p>\n\n<p>Also <code>IDiscardModelChanges</code> is a bad name for an interface. Interface name should not be a verb. It should either name a property of an object (e.g. <code>IDiscardable</code>), or name object itself (e.g. <code>IDiscardableModel</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:48:25.933",
"Id": "51397",
"Score": "0",
"body": "+1 for pointing out the \"I discard model changes\" bad naming, but I'm not sure get how such an interface would be used, care to add more code? Thanks for your input!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:55:57.677",
"Id": "51444",
"Score": "1",
"body": "@retailcoder, the idea is to move the logic from `DiscardableModelBase<TContext>` to `IContextManager<TContext>`. This way all of your models will consume `IContextManager<TContext>` as their parameter. Essentially it is replacing inheritance with aggregation (by adding another abstraction which sole purpose is \"managing\" `DbContext`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:43:22.693",
"Id": "51471",
"Score": "0",
"body": "I see.. and I like what I'm seeing! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T05:18:51.140",
"Id": "32163",
"ParentId": "32156",
"Score": "2"
}
},
{
"body": "<p>As stated by previous comments, there is no need to throw away the context.\nBut since this is a code review, and not a concept review I'll leave that part aside.</p>\n\n<p>All your <code>TContext</code> generics are to be inheriting from <code>DbContext</code>, but nowhere in any class do you use any of <code>DbContext</code>'s properties or methods. You are only using the <code>.Dispose</code> method, which comes from the <code>IDisposable</code> interface. I've refactored your code to have this result:</p>\n\n<pre><code>public interface IContextFactory<out TContext> where TContext : IDisposable\n{\n TContext Create();\n}\n\npublic interface IDiscardModelChanges\n{\n void DiscardChanges();\n}\n\npublic abstract class DiscardableModelBase<TContext> : IDiscardModelChanges, IDisposable\nwhere TContext : IDisposable\n{\n private readonly IContextFactory<TContext> _factory;\n\n protected TContext Context { get; private set; }\n\n protected DiscardableModelBase(IContextFactory<TContext> factory)\n {\n _factory = factory;\n Context = _factory.Create();\n }\n\n public virtual void DiscardChanges()\n {\n Context.Dispose();\n Context = _factory.Create();\n }\n\n public void Dispose()\n {\n Context.Dispose();\n }\n}\n</code></pre>\n\n<p>The changes might seem small, but the impact is big. In your example, you are going to pull in Entity Framework everywhere you are using this application, which isn't needed at all.\nYou are not doing anything entity framework related, you are doing something with disposable objects. This could be a <code>StreamWriter</code>, etc...</p>\n\n<p>PS: I know this post is old. But people should really be aware of the issue with this code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T16:01:46.100",
"Id": "102595",
"Score": "0",
"body": "Nice answer, it's never too late to review code on CR :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T07:52:39.203",
"Id": "57170",
"ParentId": "32156",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "32163",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T20:03:29.787",
"Id": "32156",
"Score": "4",
"Tags": [
"c#",
"entity-framework",
"wpf",
"dependency-injection"
],
"Title": "Enabling discard pending changes on DbContext"
}
|
32156
|
<p>I'm trying to do something like this:</p>
<pre><code>var loudDogs = dogs.Where(async d => await d.IsYappyAsync);
</code></pre>
<p>The "IsYappyAsync" property would return a <code>Task<bool></code>.</p>
<p>Obviously this isn't supported, so instead I've built an extension method called WhereAsync.</p>
<pre><code>public static async Task<IEnumerable<T>> WhereAsync<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
var results = new List<T>();
var tasks = new List<Task<bool>>();
foreach (var item in items)
{
var task = predicate.Invoke(item);
tasks.Add(task);
}
var predicateResults = await Task.WhenAll<bool>(tasks);
var counter = 0;
foreach (var item in items)
{
var predicateResult = predicateResults.ElementAt(counter);
if (predicateResult)
results.Add(item);
counter++;
}
return results.AsEnumerable();
}
</code></pre>
<p>This probably isn't the best approach, but I'm at a loss for something better. Any thoughts?</p>
|
[] |
[
{
"body": "<p>There are several ways to achieve what you're after and it depends on whether you want the results drip fed to you as they're available or whether you're happy to have them all in one bang.\nThe way you've implemented your method gives it all in one bang - which is fine.</p>\n\n<p>A shorter implementation could be</p>\n\n<pre><code>public static async Task<IEnumerable<T>> WhereAsync2<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)\n{\n var itemTaskList = items.Select(item=> new {Item = item, PredTask = predicate.Invoke(item)}).ToList();\n await Task.WhenAll(itemTaskList.Select(x=>x.PredTask));\n return itemTaskList.Where(x=>x.PredTask.Result).Select(x=>x.Item);\n}\n</code></pre>\n\n<ol>\n<li><p>It builds a list of an anonymous type where the type contains the item and the Task.</p></li>\n<li><p>It then waits for all of the tasks to complete.</p></li>\n<li><p>It then goes through that list from (1) and picks out the items that had a true result from the Task.</p></li>\n</ol>\n\n<p>The other advantage is that you get rid of all of that counter and <code>ElementAt()</code> stuff. Either way still builds a complete List for the items in the given Enumerable... </p>\n\n<p><strong>Aside</strong>: <em>You could investigate something like Rx if you wanted the results via an <code>IObservable<T></code> instead. The result wouldn't even be async Task - it would just be an IObservable.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T10:57:04.783",
"Id": "51387",
"Score": "1",
"body": "This is nice, bookmarked for later usage, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:05:05.023",
"Id": "443112",
"Score": "1",
"body": "I don't like this approach. Using `.Result` is most likely never the correct answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T20:34:04.510",
"Id": "443299",
"Score": "0",
"body": "Thabks for the comment all these years later The tasks are known to be complete, so it's safe in this context. I appreciate that's a distinction often missed by many, but it's OK in this context. (eventually, somewhere in the code, even if it's not your code but something invoked by the async/await state machine, something is calling .Result to actually get the result)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:04:39.087",
"Id": "496705",
"Score": "0",
"body": "Agree with @ElMac. Using `.Result` is usually a code smell, and in this case it certainly is. It is definitely not \"safe\" or \"OK in this context\". You have made the code synchronous as `.Result` blocks. You are also ignoring the return of `await WhenAll` which is also a code smell. The result of `await WhenAll` is _exactly_ what you should be performing the `Where` on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T05:38:16.953",
"Id": "496728",
"Score": "0",
"body": "@neo, Thanks for the comment. `.Result` is synchronous, and blocks if there's no result yet. We *know* that every single one of these Tasks has a result. That's what awaiting `Task.WhenAll` is doing in this code. It is \"OK in this context\" - sorry you disagree. As it turns out, I'd probably write this differently all these years later (and would've at least deliberately noted via comment that .Result was intentional), but it's not *broken*\nUsing Tasks that return an anonymous type, with a bool member, would allow for the filtering you suggest and is probably nicer overall."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T19:22:51.313",
"Id": "496826",
"Score": "0",
"body": "We agree on what `.Result` does it seems, but to make the code synchronous defeats the point of asynchronous programming - this isn't \"OK\". That's why there's no async `Where` in the BCL. It's inherently counterfactual. That's the code smell. Re my other point, I've put code [here](https://dotnetfiddle.net/aV5xFk). Ignoring return of `await WhenAll` is bad practice. This doesn't fix the aforementioned code smell, but you can achieve your solution without ignoring it (`WhereAsync3` in my Fiddle). In fact you can go further and not use it at all. Just use `Task.Run` (`WhereAsync4` in my Fiddle)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T04:57:17.560",
"Id": "32162",
"ParentId": "32160",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "32162",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T01:55:28.600",
"Id": "32160",
"Score": "13",
"Tags": [
"c#",
"linq",
"task-parallel-library",
"async-await"
],
"Title": "Filtering a collection by an async result"
}
|
32160
|
<p>Since Entity Set does not support asqueryable, I have to do this. How can I reduce the amount of redundant code between the two methods?</p>
<pre><code>public static IQueryable<T> WhereCreateWithin<T>(this IQueryable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
if (beginDayParam == null)
{
beginDayParam = DateTime.Today;
}
DateTime beginDay = beginDayParam.Value.Date;
DateTime startRange;
DateTime endRange;
switch (timeRange)
{
case DateManager.TimeRange.All:
return query;
case DateManager.TimeRange.ThisYear:
startRange = new DateTime(beginDay.Year, 1, 1); // January 1, this year
endRange = startRange.AddYears(1);
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ThisMonth:
startRange = new DateTime(beginDay.Year, beginDay.Month, 1);
endRange = startRange.AddMonths(1).Date;
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ThisWeek:
startRange = BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday);
endRange = startRange.AddDays(6);
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ToDay:
return query.Where(p => p.create_date.Date == beginDay);
case DateManager.TimeRange.Last30Day:
startRange = beginDay.AddDays(-29);
endRange = beginDay;
return query.Where(p => p.create_date.Date >= startRange && p.create_date <= endRange);
}
return query;
}
public static IEnumerable<T> WhereCreateWithin<T>(this IEnumerable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
if (beginDayParam == null)
{
beginDayParam = DateTime.Today;
}
DateTime beginDay = beginDayParam.Value.Date;
DateTime startRange;
DateTime endRange;
switch (timeRange)
{
case DateManager.TimeRange.All:
return query;
case DateManager.TimeRange.ThisYear:
startRange = new DateTime(beginDay.Year, 1, 1); // January 1, this year
endRange = startRange.AddYears(1);
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ThisMonth:
startRange = new DateTime(beginDay.Year, beginDay.Month, 1);
endRange = startRange.AddMonths(1).Date;
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ThisWeek:
startRange = BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday);
endRange = startRange.AddDays(6);
return query.Where(p => p.create_date.Date >= startRange && p.create_date < endRange);
case DateManager.TimeRange.ToDay:
return query.Where(p => p.create_date.Date == beginDay);
case DateManager.TimeRange.Last30Day:
startRange = beginDay.AddDays(-29);
endRange = beginDay;
return query.Where(p => p.create_date.Date >= startRange && p.create_date <= endRange);
}
return query;
}
</code></pre>
|
[] |
[
{
"body": "<p>Given that the logic is exactly the same (i did not do a line by line comparision), one of the possible solutions whould be:</p>\n\n<pre><code>private static TCollection WhereCreateWithin<T, TCollection>(TCollection query,\n DateManager.TimeRange timeRange, \n DateTime? beginDayParam,\n Func<TCollection, Func<T, bool>, TCollection> selector) \n where T : IHasCreateDate\n where TCollection : IEnumerable<T>\n{\n //insert your logic here\n //replace query.Where(x => ... ) call with selector(query, x => ... ) call\n}\n\npublic static public static IQueryable<T> WhereCreateWithin<T>(this IQueryable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate\n{\n return WhereCreateWithin<T, IQueryable<T>>(query, timeRange, beginDayParam, (q, f) => q.Where(x => f(x)))\n}\n\n\npublic static public static IEnumerable<T> WhereCreateWithin<T>(this IEnumerable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate\n{\n return WhereCreateWithin<T, IEnumerable<T>>(query, timeRange, beginDayParam, (q, f) => q.Where(f))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:53:31.020",
"Id": "32172",
"ParentId": "32161",
"Score": "1"
}
},
{
"body": "<p>The IQueryable Where extension method takes an Expression whereas the IEnumerable Where extension method takes a normal delegate (Func). Any solution to consolidate the OPs code will have to take this into account. It is easy to convert an expression to a delegate by calling Compile on the expression (but hard the other way around) therefore I have based the below solution on the first principle.</p>\n\n<pre><code>public static IEnumerable<T> WhereCreateWithin<T>(this IEnumerable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate\n{\n return WhereCreateWithin<IEnumerable<T>, T>(query, timeRange, (q, ex) => q.Where(ex.Compile()), beginDayParam); \n}\n\npublic static IQueryable<T> WhereCreateWithin<T>(this IQueryable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate\n{\n return WhereCreateWithin<IQueryable<T>, T>(query, timeRange, (q, ex) => q.Where(ex), beginDayParam); \n}\n\npublic static TColl WhereCreateWithin<TColl, T>(this TColl toBeFiltered, \n DateManager.TimeRange timeRange, \n Func<TColl, Expression<Func<T, bool>>, TColl> getFilteredCollection, \n DateTime? beginDayParam = null) where T : IHasCreateDate\n where TColl : IEnumerable<T>\n{\n if (beginDayParam == null)\n {\n beginDayParam = DateTime.Today;\n }\n\n DateTime beginDay = beginDayParam.Value.Date;\n\n var expressionDictionary = new Dictionary<DateManager.TimeRange, Expression<Func<T, bool>>>();\n expressionDictionary.Add(DateManager.TimeRange.ThisYear, p => p.create_date.Date >= new DateTime(beginDay.Year, 1, 1) && p.create_date < new DateTime(beginDay.Year, 1, 1).AddYears(1));\n expressionDictionary.Add(DateManager.TimeRange.ThisMonth, p => p.create_date.Date >= new DateTime(beginDay.Year, beginDay.Month, 1) && p.create_date < new DateTime(beginDay.Year, beginDay.Month, 1).AddMonths(1).Date);\n expressionDictionary.Add(DateManager.TimeRange.ThisWeek, p => p.create_date.Date >= BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday) && p.create_date < BuilkHelper.DateHelper.StartOfWeek(beginDay, DayOfWeek.Monday).AddDays(6));\n expressionDictionary.Add(DateManager.TimeRange.ToDay, p => p.create_date.Date == beginDay);\n expressionDictionary.Add(DateManager.TimeRange.Last30Day, p => p.create_date.Date >= beginDay.AddDays(-29) && p.create_date <= beginDay);\n\n return expressionDictionary.ContainsKey(timeRange) ? getFilteredCollection(toBeFiltered, expressionDictionary[timeRange]) : toBeFiltered;\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T09:23:50.340",
"Id": "32173",
"ParentId": "32161",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T04:23:23.887",
"Id": "32161",
"Score": "4",
"Tags": [
"c#",
"linq"
],
"Title": "Code duplication where impliment extension method for IEnumerable and IQueryable on entity set"
}
|
32161
|
<p>Within a function, I want to grab a set of parameters from a named array. What is the most efficient way of testing if the parameter exists in the array, and if it does, use it as a variable? I came up with a few alternatives.</p>
<pre><code>target = $('#page_links')
if ( functionobject.target ) {
target = functionobject.target
}
//method 2:
var target = ''
if ( functionobject.target ) {
target = functionobject.target
}
else {
target = final_array
}
//method 3:
target = functionobject.target
if (typeof target == 'undefined') {
target = $('#page_links')
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:36:10.633",
"Id": "51384",
"Score": "0",
"body": "I think the terminology in your question might be bad. Instead of \"parameters from a named array\", you probably mean \"attributes in an object\". Arrays are supposed to sequences of elements, indexed by numeric subscripts. Objects have named attributes. Arrays happen to be objects in JavaScript, but it's bad style to use arrays when just an object will suffice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T09:06:45.427",
"Id": "51385",
"Score": "0",
"body": "Thanks, I was aware that these \"associative arrays\" simply are objects, but since the term \"associative arrays\" and \"named arrays\" seem to be frequently used, I thought that it could be helpful somehow. Thanks for clarifying. I used the term \"parameters\" since the point of my task is to the variables we are collecting as parameters in a function, but that is not really relevant for my question, so right you are. :)"
}
] |
[
{
"body": "<p>I would say</p>\n\n<pre><code>var target = functionobject.target || $('#page_links');\n</code></pre>\n\n<p>How did I arrive at that? The important point to get across is that no matter what happens, you want to assign <em>something</em> to <code>target</code>. One first attempt to express that would be to use the ternary operator</p>\n\n<pre><code>var target = functionobject.target ? functionobject.target : $('#page_links');\n</code></pre>\n\n<p>However, the repetition of <code>functionobject.target</code> is ugly. It would be better to use the short-circuit evaluation feature of the <code>a || b</code> operator. If <code>a</code> is true, then evaluation stops, and the value of the expression is just <code>a</code>. Otherwise, the value of the expression is <code>b</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T09:08:20.683",
"Id": "51386",
"Score": "0",
"body": "Excellent, that worked perfectly. Thanks for the one-liner!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T06:18:28.990",
"Id": "51446",
"Score": "0",
"body": "If that worked for you, then would you please mark this as your accepted answer? Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:24:38.503",
"Id": "32168",
"ParentId": "32166",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32168",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:09:05.353",
"Id": "32166",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Best way to retrieve parameters from associative array in javascript?"
}
|
32166
|
<p>I want a second copy of an <code>std::vector</code> in which all elements are inverted, e.g. <code>0x01</code> in the first vector should be <code>0xFE</code> in the second. </p>
<p>Is this a good solution?</p>
<pre><code>std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A };
std::vector<uint8_t> second_list = first_list;
for(std::vector<uint8_t>::iterator it = second_list.begin(); it != second_list.end(); ++it)
*it = ~*it;
</code></pre>
<p>The for loop sticks out to me as unnecessarily verbose.</p>
|
[] |
[
{
"body": "<p>You can utilize <code>std::transform</code> here (I'll assume C++11 for the lambda):</p>\n\n<pre><code>int main()\n{\n std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A};\n std::vector<uint8_t> second; \n std::transform(first_list.begin(), first_list.end(), std::back_inserter(second),\n [](uint8_t u) { return ~u; });\n}\n</code></pre>\n\n<p>You also don't need to make a copy of the first vector to do this; better to simply use <code>push_back</code> (or <code>back_inserter</code> here, since we're working with iterators).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T00:26:43.610",
"Id": "51428",
"Score": "0",
"body": "Frankly, written out as a for loop is kind of less code than using `transform` with a lambda."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:37:29.497",
"Id": "32169",
"ParentId": "32167",
"Score": "4"
}
},
{
"body": "<p>You can use the new <code>for()</code> in C++11</p>\n\n<pre><code>std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A};\nstd::vector<uint8_t> second; \nfor(uint8_t& it: first_list)\n{ second.push_back(~it);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T09:04:19.840",
"Id": "51456",
"Score": "0",
"body": "This kind of `for` loop is what I've been wishing for every time I've written one with an explicitly incrementing iterator!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:51:18.007",
"Id": "32190",
"ParentId": "32167",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32190",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:22:42.563",
"Id": "32167",
"Score": "2",
"Tags": [
"c++",
"c++11",
"bitwise"
],
"Title": "Copy and bit-invert ints in an std::vector"
}
|
32167
|
<p>I have three types alert dialogue. Each alert dialogue behave differently but I don't like to write three types of alert dialogue in same class because it extends the class size drastically. Here are the three alert dialogue given below:</p>
<pre><code>public boolean onJsAlert(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Alert !")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Confirmation")
.setMessage(message)
.setPositiveButton(android.R.string.yes,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.no,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
}
}).setCancelable(false).create().show();
return true;
}
</code></pre>
<p>And the last alert dialogue is: </p>
<pre><code>public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
final boolean remember = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
WebviewActivity.this);
builder.setTitle("Locations");
builder.setMessage(" Would like to use your Current Location")
.setCancelable(true)
.setPositiveButton("Allow",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, true, remember);
SharedPreferences pref = currentActivity
.getPreferences(currentActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref
.edit();
editor.putBoolean("isLocationAvailable",
true);
editor.commit();
webview.loadUrl(getUrl(gps.getLatitude(),
gps.getLongitude(), "true"));
}
})
.setNegativeButton("Don't Allow",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, false, remember);
webview.loadUrl(getUrl("", "", "false"));
}
});
AlertDialog alert = builder.create();
alert.show();
}
</code></pre>
<p>How can I reduce the code size. Any suggestion please? </p>
|
[] |
[
{
"body": "<p>I also like to keep classes short, but I don't think it should influence your design. You can put the alert building code in another class file if you really want to. </p>\n\n<p>I would not try to coerce the geolocation alert with onJsAlert/onJsConfirm since it is quite different. But you could do something if you really wanted to reuse some code for those two (onJsAlert/onJsConfirm). The positive OnClickListener could be defined outside and shared for onJsAlert/onJsConfirm. You could instead write a common method for building those two alert dialogs, with an if-statement that checks if a negative button should be added or not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T12:41:54.497",
"Id": "32180",
"ParentId": "32175",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T09:51:31.180",
"Id": "32175",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "How to reduce code from different alert-dialogue?"
}
|
32175
|
<p>I am using Codeigniter and it's ActiveRecord.</p>
<p>I had this idea for a base class that provided a generic getter/setter for doing simple queries on a database. I have a lot of database objects that could benefit from not having to duplicate the basic query patterns.</p>
<p>Instead of writing functions whose sole purpose were to chain a few active record queries and return the result, I could instead do it with a generic <code>$parameters</code> array and providing the table name via the function call.</p>
<pre><code><?php
class ORMModel extends CI_Model {
public function __call($name, $args) {
$method = strtolower(substr($name, 0, 3));
$object = substr($name, 3);
// Parsing arguments
$params = (isset($args[0])) ? $args[0] : array();
$single = (isset($args[1])) ? $args[1] : false;
$count = (isset($args[2])) ? $args[2] : false;
$page = (isset($args[3])) ? $args[3] : '';
$per_page = (isset($args[4])) ? $args[4] : '';
if ($method === 'get') {
$this->db->from($object);
} elseif ($method !== 'set') {
throw new Exception('Unsupported method ' . $name);
}
if (method_exists($this, $name)) {
$this->{$name}($params);
} elseif ($method === 'get') {
$this->__getter($params);
} else {
$this->__setter($params);
};
if ($method === 'set') {
// Insert on duplicate method, for both insert/updates, this way the SET can act as the WHERE as well
return $this->db->on_duplicate($object);
}
$this->db->limit($per_page, $page);
$result = $this->db->get();
if (!$result) {
throw new Exception('No result from ' . $name);
}
if ($count) {
return $result->num_rows;
}
if ($single) {
return $result->row_array();
} else {
return $result->result_array();
}
}
private function __getter($params) {
foreach ($params as $field => $value) {
if (method_exists($this, $field)) {
$this->where{$field}($value);
}
$this->db->where_in($field, $value);
}
}
private function __setter($params) {
foreach ($params as $field => $value) {
$this->db->set($field, $value);
}
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>// Returns all orders
$this->ORMModel->getOrder()
// Returns order ID 3
$this->ORMModel->getOrder(array('id' => 3))
// Returns orders before a certain date
function orderWhereDateBefore() {
$this->db->where('date <=', $value);
}
$this->ORMModel->getOrder(array('dateBefore' => '2012-01-01'))
// Huge search query (from a form)
$params = array(
'status' => 'Paid',
'dateBefore' => '2012-01-01',
'name' => 'Some Guy',
...
);
$this->ORMModel->getOrder($params);
// Set an order
$params = array(
'status' => 'Paid',
'dateBefore' => '2012-01-01',
'name' => 'Some Guy',
...
);
$this->ORMModel->setOrder($params);
</code></pre>
<p>The additional arguments also provide more flexibility for standard display of results, such as pagination and full count of the result set.</p>
<p>However, I am concerned whether its reusability can trump the concerns of readability, usability and <strike>debuggability (for lack of a better word)</strike><em>Maintainability</em>, and if so, can it be improved on?</p>
|
[] |
[
{
"body": "<p>Well, for a kickoff, you're concerned about your code's reusability can trump its undeniable downsides. But, if you look at one or two things more closely, your code <em>isn't</em> as reusable as perhaps you think it is:</p>\n\n<pre><code>// Parsing arguments\n$params = (isset($args[0])) ? $args[0] : array();\n$single = (isset($args[1])) ? $args[1] : false;\n$count = (isset($args[2])) ? $args[2] : false;\n$page = (isset($args[3])) ? $args[3] : '';\n$per_page = (isset($args[4])) ? $args[4] : '';\n</code></pre>\n\n<p>This is just a series of hard-coded statements, with a specific goal in mind. This isn't as generic as your object, called <code>ORMModel</code> would have you believe.<br/>\nYou're also being lead astray by CI's rather confusing name <code>ActiveRecord</code>, <a href=\"http://en.wikipedia.org/wiki/Active_record_pattern#PHP\" rel=\"nofollow noreferrer\">which actually doesn't implement the ActiveRecord pattern</a>.</p>\n\n<p>Your code shows signs of a nasty habbit, too, in the sense that you're using <em>magic methods</em> and object overloading. Avoid these things as much as possible, <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">it'll slow your app down</a> when you're accessing/setting properties, and even more so if that requires one or more <a href=\"https://stackoverflow.com/a/19044902/1230836\">magic method calls</a>.</p>\n\n<p>There's another issue with using <code>__call</code> too often: it can bypass the access modifiers:</p>\n\n<pre><code>class Unsafe\n{\n private function mayOnlyBeCalledInternally()\n {\n //do risky things\n }\n public function __call($method, array $args)\n {\n if (method_exists($this, $method))\n {\n return call_usr_func_array(array($this, $method), $args);\n return $this->{$method}($args);//BTW: this is WRONG\n }\n }\n}\n$expose = new Unsafe;\n$expose->mayOnlyBeCalledInternally();//WORKS!!!!\n</code></pre>\n\n<p>You're, essentially, exposing <em>all</em> private and protected methods through this <code>__call</code> method. Just <em>don't</em>!<Br/>\nAs you may have noticed, I'm calling the methods using <code>call_usr_func_array</code>. The <code>__call</code> method receives the arguments as an array, but that doesn't mean the called method accepts an array. It could well be that this method expects three distinct arguments, not 1 array. The way you're calling existing methods:</p>\n\n<pre><code>if (method_exists($this, $name)) {\n $this->{$name}($params);\n} \n</code></pre>\n\n<p>Will give you grief in such cases, but I'm going off topic slightly...</p>\n\n<p>Basically, you've observed the limitations of CI's <code>ActiveRecord</code> and set about building something a bit more <em>powerful</em>. Now that's not a bad idea, except for one thing: <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">It's all been done before</a>, and (without wanting to suggest you're a bad dev) better than you'll be able to implement it. You're just 1 person, writing your own thing, Doctrine and the like have been around for some time, and have been worked on by many people. You can't compete with them.</p>\n\n<p>If, however, you're not quite ready to switch to an existing sollution, I'd split your <code>__call</code> method into truly defined functions. For example, the call <code>getOrder</code> is being translated into <code>get</code> and <code>Order</code>, where <code>Order</code> is the tbl/object name. Why don't you just create a method like:</p>\n\n<pre><code>public function getFrom($tbl, array $params)\n{\n $this->db->from($tbl);\n foreach($params as $field => $value)\n {\n $this->where{$field}($value);\n }\n //... and so on\n}\n</code></pre>\n\n<p>In give time, you might find yourself creating an abstract model for your tables, and passing table objects to this function:</p>\n\n<pre><code>abstract class TableObject\n{\n private $name = null;\n protected $fields = array();\n abstract public function __construct($name);\n final protected function _setName($name)\n {\n if ($this->name !== null)\n {\n throw new BadMethodCallExcpetion('Can\\'t change tbl name once instance is created');\n }\n $this->name = $name;\n return $this;\n }\n final public function _getName()\n {\n return $this->name;\n }\n //bulk setter\n final public function setByRow(stdClass $record)\n {//or hint for array, or Traversable, or whatever\n foreach($record as $name => $value)\n {\n if (method_exists($this, 'set'.ucfirst($name)))\n {\n $this->{'set'.ucfirst($name)}($value);\n }\n }\n }\n //get object values as array\n final public funtion toArray()\n {\n $array = array();\n foreach($this->fields as $name)\n {\n $array[$name] = $this->{'get'.ucfirst($name)}();\n }\n return array_filter($array);\n }\n}\n//then\nclass Order extends TableObject\n{\n public function __construct()\n {\n //set $this->fields here, if not in definition\n $this->_setName('Order');\n }\n}\n</code></pre>\n\n<p>In accordance with my linked answers, it goes without saying that I'd strongly suggest your declaring all properties explicitly, and implementing a getter and setter for each property, too.<br/>\nAnyhow, if you've done that, you can change the <code>getObject</code> method to:</p>\n\n<pre><code>public function getObject(TableObject $model)\n{\n $this->db->form($model->_getName());\n $asArray = $model->toArray();//treat as $params in the snippet above\n}\n</code></pre>\n\n<p>Now this is a more generic, and OO way of working. You could also create an <code>TblArguments</code> object, instead of using an array to determine if there is to be a <code>limit</code>, <code>group by</code>, <code>count</code> set/returned... But if I were you, I'd create specifc methods for <code>count</code> and <code>single</code> and <code>per_page</code>, really...</p>\n\n<p>But really, read through a couple of my more verbose answers on this site, and perhaps on SO, too, I've given more detailed code examples of this approach before, and expanded on certain other benefits, too. But to recap: Your code is not <em>terrible</em>, not at all... it didn't make my eyes water or anything. But your <code>__call</code> method is doing more than it should be doing: it's checking if the particular call was meant to do a specific thing.<br/>\nIf you know that <em>get</em> + <em>someString</em> is meant to be a query, why bother relying on <code>__call</code>, why not implement a generic method for just that purpouse? it'll clean up your code, it'll be more maintainable, and even more reusable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T13:32:24.090",
"Id": "51391",
"Score": "1",
"body": "Thank you for the in-depth analysis, I shall try digesting your post a bit more!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T13:44:57.293",
"Id": "51392",
"Score": "1",
"body": "@xiankai: You're welcome. I'd hardly call my answer in-debpth, though. It's just a stream of jibberish to hold the links together. I'd recommend reading through the linked answer more than trying to make sense of this blurb :P"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T13:18:32.310",
"Id": "32182",
"ParentId": "32176",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T10:43:09.983",
"Id": "32176",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"mvc",
"database",
"codeigniter"
],
"Title": "Builder pattern for Codeigniter ActiveRecord queries"
}
|
32176
|
<p>I've got the following query builder. Some of the cases have the same piece of code (those that have a parameter).</p>
<p>I know it's not good to duplicate code that much if at all.</p>
<p>How would you suggest I improve this loop?</p>
<pre><code>for ($i = 0; $i < $len; ++$i) {
switch ($conditions[$i]['condition']) {
case 'version':
$value_counter++;
$sql .= ' AND `musers`.`app_version` = :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'except_version':
$value_counter++;
$sql .= ' AND `musers`.`app_version` != :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'from_credits':
$value_counter++;
$sql .= ' AND `musers`.`credits` >= :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'to_credits':
$value_counter++;
$sql .= ' AND `musers`.`credits` <= :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'no_credits':
$sql .= ' AND `musers`.`credits` = 0';
break;
case 'register_atleast':
$value_counter++;
$sql .= ' AND DATEDIFF(NOW(), `musers`.`creation_date`) > :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'talked_atleast':
$value_counter++;
$sql .= " AND `musers`.`total_talktime` >= :value".$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'never_talked':
$sql .= " AND `musers`.`total_talktime` = 0";
break;
case 'purchase_atleast':
$value_counter++;
$sql .= " AND `musers`.`purchase_times` >= :value".$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'never_purchase':
$sql .= ' AND `musers`.`purchase_times` = 0';
break;
case 'from_birthdate':
$value_counter++;
$sql .= " AND (`musers`.`birthdate` = '0000-00-00' OR `musers`.`birthdate` >= :value".$value_counter." )";
$values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));
break;
case 'to_birthdate':
$value_counter++;
$sql .= " AND (`musers`.`birthdate` = '0000-00-00' OR `musers`.`birthdate` <= :value".$value_counter." )";
$values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));
break;
case 'from_creation_date':
$value_counter++;
$sql .= " AND (`musers`.`creation_date` = '0000-00-00' OR `musers`.`creation_date` >= :value".$value_counter." )";
$values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));
break;
case 'to_creation_date':
$value_counter++;
$sql .= " AND (`musers`.`creation_date` = '0000-00-00' OR `musers`.`creation_date` <= :value".$value_counter." )";
$values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));
break;
case 'user_id':
$value_counter++;
$sql .= ' AND `musers`.`id` = :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'visit_app_aleast':
$value_counter++;
$sql .= ' AND `musers`.`visit_app_times` >= :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'visit_app_less':
$value_counter++;
$sql .= ' AND `musers`.`visit_app_times` < :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'total_calls_atleast':
$value_counter++;
$sql .= ' AND `musers`.`total_calls` >= :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'total_calls_less':
$value_counter++;
$sql .= ' AND `musers`.`total_calls` < :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
case 'hourdiff':
$value_counter++;
$sql .= ' AND `hourdiff` = :value'.$value_counter;
$values[$value_counter] = $conditions[$i]['value'];
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-02T17:43:17.370",
"Id": "53979",
"Score": "1",
"body": "Get rid of it, and use an existing querybuilder, that has been proven to work. Doctrine, for example. It'll save you a whole lot of time... clone its repo and edit the code, if you must"
}
] |
[
{
"body": "<p>I just separated out the cases with no count increase. I am sure somebody more experienced could come up with a better solution.</p>\n\n<pre><code>for ($i = 0; $i < $len; ++$i) {\nif 'version' = 'no_credits':\n $sql .= ' AND `musers`.`credits` = 0';\n\nelse if 'version' = 'never_talked':\n $sql .= \" AND `musers`.`total_talktime` = 0\";\n\nelse if 'version' = 'never_purchase':\n $sql .= ' AND `musers`.`purchase_times` = 0';\n\nelse\n\n $value_counter++;\n\n switch ($conditions[$i]['condition']) {\n case 'version':\n $sql .= ' AND `musers`.`app_version` = :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'except_version':\n $sql .= ' AND `musers`.`app_version` != :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'from_credits':\n $sql .= ' AND `musers`.`credits` >= :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'to_credits':\n $sql .= ' AND `musers`.`credits` <= :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'register_atleast':\n $sql .= ' AND DATEDIFF(NOW(), `musers`.`creation_date`) > :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'talked_atleast':\n $value_counter++;\n $sql .= \" AND `musers`.`total_talktime` >= :value\".$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'purchase_atleast':\n $sql .= \" AND `musers`.`purchase_times` >= :value\".$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'from_birthdate':\n $sql .= \" AND (`musers`.`birthdate` = '0000-00-00' OR `musers`.`birthdate` >= :value\".$value_counter.\" )\";\n $values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));\n break;\n case 'to_birthdate':\n $sql .= \" AND (`musers`.`birthdate` = '0000-00-00' OR `musers`.`birthdate` <= :value\".$value_counter.\" )\";\n $values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));\n break;\n case 'from_creation_date':\n $sql .= \" AND (`musers`.`creation_date` = '0000-00-00' OR `musers`.`creation_date` >= :value\".$value_counter.\" )\";\n $values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));\n break;\n case 'to_creation_date':\n $sql .= \" AND (`musers`.`creation_date` = '0000-00-00' OR `musers`.`creation_date` <= :value\".$value_counter.\" )\";\n $values[$value_counter] = date('Y-m-d', strtotime($conditions[$i]['value']));\n break;\n case 'user_id':\n $sql .= ' AND `musers`.`id` = :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'visit_app_aleast':\n $sql .= ' AND `musers`.`visit_app_times` >= :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'visit_app_less':\n $sql .= ' AND `musers`.`visit_app_times` < :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'total_calls_atleast':\n $sql .= ' AND `musers`.`total_calls` >= :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'total_calls_less':\n $sql .= ' AND `musers`.`total_calls` < :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n case 'hourdiff':\n $sql .= ' AND `hourdiff` = :value'.$value_counter;\n $values[$value_counter] = $conditions[$i]['value'];\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T16:04:14.153",
"Id": "32192",
"ParentId": "32179",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T12:20:21.900",
"Id": "32179",
"Score": "3",
"Tags": [
"php",
"mysql"
],
"Title": "Query builder improvment"
}
|
32179
|
<p>How can I refactor this?</p>
<pre><code>public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseAtLeast(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)
{
if (date == null)
{
query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||
( (company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count) >= minimum) );
return query;
}
else
{
var notNullDate = date.Value;
var result = (from company in query
let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)
let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)
let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)
let productCount = company.Products.Count(item => item.create_date <= notNullDate)
let referenceCount = company.References.Count(item => item.create_date <= notNullDate)
where (rfqCount + poCount + invoiceCount) >= minimum || (productCount + referenceCount) >= minimum
select company);
return result;
}
}
public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseLessThan(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)
{
if (date == null)
{
query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||
((company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count) < minimum));
return query;
}
else
{
var notNullDate = date.Value;
var result = (from company in query
let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)
let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)
let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)
let productCount = company.Products.Count(item => item.create_date <= notNullDate)
let referenceCount = company.References.Count(item => item.create_date <= notNullDate)
where (rfqCount + poCount + invoiceCount) >= minimum || (productCount + referenceCount) < minimum
select company);
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:28:46.703",
"Id": "51395",
"Score": "1",
"body": "You have a lot of repetition in your 'let' statements, why not separate the building of the initial 'result' object out, without the final comparison, so you aren't re-writing those, and then use linq on the resulting object?"
}
] |
[
{
"body": "<p>From what I can understand you are looking for a way to consolidate this code into one function and specify that the comparrison with minimum can either be less than or greater than or equal to. You could try something like this</p>\n\n<pre><code>public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseAtLeast(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)\n {\n WhereTotalTransactionWithCompare(query, minimum, (x, min) => x >= min, date);\n }\n\n\n public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseLessThan(this IQueryable<T_COMPANY> query, \n int minimum, \n DateTime? date = null)\n {\n WhereTotalTransactionWithCompare(query, minimum, (x, min) => x < min, date);\n\n }\n\n public static IQueryable<T_COMPANY> WhereTotalTransactionWithCompare(this IQueryable<T_COMPANY> query,\n int minimum,\n Func<int, int bool> compareToMinimum,\n DateTime? date = null)\n {\n if (date == null)\n {\n query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||\n (comparer(company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count, minimum)));\n return query;\n }\n else\n {\n var notNullDate = date.Value;\n\n var result = (from company in query\n let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)\n let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)\n let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)\n let productCount = company.Products.Count(item => item.create_date <= notNullDate)\n let referenceCount = company.References.Count(item => item.create_date <= notNullDate)\n where (rfqCount + poCount + invoiceCount) >= minimum || comparer(productCount + referenceCount, minimum)\n select company);\n\n return result;\n }\n\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:21:50.363",
"Id": "51530",
"Score": "0",
"body": "Use Expression instead of Func becouse the queryable type will loose the queryable behavior and will be only an enumerable which means if the data backend is a SQL database all result will downloaded before the last filter would be applied."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T08:26:12.513",
"Id": "32231",
"ParentId": "32183",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T13:35:50.510",
"Id": "32183",
"Score": "1",
"Tags": [
"c#",
"linq"
],
"Title": "Refactor similar queries but reverse side of inequality operator"
}
|
32183
|
<p>Be as harsh as you can! I'm trying to improve my coding style and would like to know if there is anything I could improve.</p>
<p>EDIT: To make this fair, The person who provides the most helpful tips (both in quantity and quality) will get marked as the answer</p>
<p>The code below is the JavaScript file for a CMS application I'm creating:</p>
<p>When the application is complete it will be Open Source for anyone to use.. I'll keep you guys updated if you're interested in trying it out</p>
<pre><code>$(function () {
loadPage(htmlLandingPage, currentSiteName) //added on by previous page
$("#dashBody").css('top', $("#topDash").outerHeight());
$("#dashBody").hide()
$('#dashBody').load(function () {
iFrameContents.find("head").append($("<link/>",
{
rel: "stylesheet",
href: "/cmsCSS/loadedPageCSS.css"
}
));
$(window).on("scroll", function () {
iFrameContents.find("HTML,body").scrollTop($(window).scrollTop());
});
iFrameContents.on("click", ".cmsEdit", function (e) {
e.stopPropagation();
selectedElem = $(this)
if (e.ctrlKey) {
e.preventDefault();
if (!$(e.target).is('.inEdit *') && !$(e.target).hasClass('inEdit')) {
clearEditSection()
}
if (!$(this).hasClass("inEdit")) {
$.when(checkOutStatus(selectedElem.prop("id"))).done(function (result) {
if (!result.d) {
checkOutSection(selectedElem.prop("id"))
selectedElem.addClass("inEdit")
selectedElem.prepend($("<div class='cmsEditBox'/>"));
for (i = 0; i < editBoxButtons.length; i++) {
$("<button/>", {
html: editBoxButtons[i],
addClass: "editButtons",
click: function () { editButtonAction(this, selectedElem) }
}).appendTo(selectedElem.children(".cmsEditBox"))
}
selectedElem.children(".cmsEditBox").css('top', (selectedElem.children(".cmsEditBox").height() * -1) - 10)
selectedElem.children(".cmsEditBox").css('left', ((selectedElem.children(".cmsEditBox").width() / 8) * -1))
selectedElem.children(".cmsEditBox").prop('contenteditable', false)
selectedElem.prop('contenteditable', true)
currentSectionHTML = selectedElem.clone().children(".cmsEditBox").remove().end().html();
} else {
$.when($(".loadProgress").fadeOut(100)).done(function () {
alert("Section Currently Checked Out")
});
}
});
}
}
});
iFrameContents.find('*').on("click", function (e) {
if ($(".inEdit").length > 0) {
e.stopPropagation();
}
if (!e.ctrlKey) {
if (!$(e.target).is('.inEdit *') && !$(e.target).hasClass('inEdit')) {
clearEditSection()
}
}
});
currentPageID = iFrameContents.find("body").prop("id")
if (!currentPageID) {
$("<div/>", {
addClass: "loadProgress",
html: $("<span/>", { addClass: "loadingText", html: "Missing<br/>Body<br/>ID" })
}).appendTo("#topDash").hide().fadeIn();
return false
}
checkDBforPage(currentPageID, currentSiteName)
});
});
function editButtonAction(btnText, selectedElem) { // Add Button Functions Here
buttonText = $(btnText).text()
if (buttonText == "SAVE") {
saveSection(selectedElem.prop("id"), selectedElem.clone().children(".cmsEditBox").remove().end().html())
}
if (buttonText == "CANCEL CHANGE") {
selectedElem.html(currentSectionHTML)
}
if (buttonText == "REVERT TO ORIGINAL") {
revertSection(selectedElem,selectedElem.prop("id"), selectedElem.clone().children(".cmsEditBox").remove().end().html())
}
if (buttonText == "SUBMIT CHANGE") {
submitSection(selectedElem, selectedElem.prop("id"), selectedElem.clone().children(".cmsEditBox").remove().end().html())
}
}
function checkPageSectionsInDB(pageID) {
$.ajax({
type: "POST",
url: "default.aspx/checkPageSections",
data: "{'pageID': " + JSON.stringify(pageID) + ",'sitePageID': " + JSON.stringify(sitePageID) + ",'siteContent': " + JSON.stringify(editableSections) + "}",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$(".loadingText").html("Analyzing <br/> Sections<br/> In DB")
},
dataType: "json",
success: function (data) {
$(".loadingText").html("Done!")
$(".loadProgress").fadeOut();
},
error: function (request, status, errorThrown) {
$(".loadingText").html("Error <br/> Checking<br/> Sections")
}
});
}
function saveSection(sectionID,sectionContent) {
$.ajax({
type: "POST",
url: "default.aspx/saveSection",
data: "{'sectionID': " + JSON.stringify(sectionID) + ",'personID': " + JSON.stringify(personID) + ",'sitePageID': " + JSON.stringify(sitePageID) + ",'sectionContent': " + JSON.stringify(sectionContent) + "}",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$(".loadProgress").fadeIn();
$(".loadingText").html("Saving..")
},
dataType: "json",
success: function (data) {
$(".loadProgress").fadeOut()
},
error: function (request, status, errorThrown) {
$(".loadingText").html("Error<br/>Saving")
return false
}
});
}
function revertSection(sectionSelected,sectionID, sectionContent) {
$.ajax({
type: "POST",
url: "default.aspx/revertSection",
data: "{'sectionID': " + JSON.stringify(sectionID) + ",'personID': " + JSON.stringify(personID) + ",'sitePageID': " + JSON.stringify(sitePageID) + ",'sectionContent': " + JSON.stringify(sectionContent) + "}",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$(".loadProgress").fadeIn();
$(".loadingText").html("Reverting..")
},
dataType: "json",
success: function (data) {
sectionSelected.removeClass("inEdit")
sectionSelected.prop("contentEditable",false)
sectionSelected.html(data.d)
$(".loadProgress").fadeOut();
},
error: function (request, status, errorThrown) {
$(".loadingText").html("Error<br/>reverting")
return false
}
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:54:50.670",
"Id": "51398",
"Score": "1",
"body": "At first glance I'd cache `$(\"#dashBody\")` and `$(\"#topDash\")`, rather than keep searching the DOM every time you want to reference them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:59:43.227",
"Id": "51399",
"Score": "0",
"body": "Wonderful!! this is exactly the kind of critque I'm looking for. Any more suggestions?"
}
] |
[
{
"body": "<p>I'd cache the following jQuery objects...</p>\n\n<pre><code>var $dashBody = $(\"#dashBody\");\nvar $topDash = $(\"#topDash\");\nvar $loadProgress = $(\".loadProgress\");\nvar $loadingText = $(\".loadingText\");\n</code></pre>\n\n<p>In function <code>clearEditSection()</code> you do a second search for elements that can be cut down to 1...</p>\n\n<pre><code>iFrameContents.find('.inEdit')\n .prop('contenteditable', false)\n .removeClass(\"inEdit\");\n</code></pre>\n\n<p>Also, a lot of the functions that perform ajax calls can be merged into 1 function, and you also don't need to do as much work with the data object...</p>\n\n<pre><code>function ajaxPost(sectionID, url, beforeText, errorText) {\n $.ajax({\n type: \"POST\",\n url: url\n data: {\n sectionID: sectionID,\n personID: personID,\n sitePageID: sitePageID\n },\n contentType: \"application/json; charset=utf-8\",\n beforeSend: function () {\n $(\".loadProgress\").fadeIn();\n $(\".loadingText\").html(beforeText)\n },\n dataType: \"json\",\n success: function (data) {\n $(\".loadProgress\").fadeOut()\n },\n error: function (request, status, errorThrown) {\n $(\".loadingText\").html(errorText)\n return false\n }\n });\n}\n</code></pre>\n\n<p><code>function checkOutStatus(sectionID)</code> could then be called like this...</p>\n\n<pre><code>ajaxPost(sectionID, \"default.aspx/checkOutStatus\",\n \"Verifying <br/> Check Out<br/> Status\",\n \"Verifying <br/> Check Out<br/>Error\");\n</code></pre>\n\n<p>There's other places where you duplicate DOM lookups so just be aware that repeated jQuery selections can drastically slow the page, depending on the size of the DOM and what browser you are using.</p>\n\n<p>One other thing that I'd strongly advise is that you get into the habit of ending every single \"line\" of code with a semi-colon. Most of the time you'll get away with it, but there are instances where it can make your code mean something different. Terminate your statements correctly and you won't go wrong :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:19:50.340",
"Id": "51411",
"Score": "0",
"body": "Good idea, Making the Ajax functions in to 1 would drastically reduce the size of the script file. I will be implementing this later on today."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:18:53.900",
"Id": "32187",
"ParentId": "32184",
"Score": "4"
}
},
{
"body": "<p>you can change </p>\n\n<pre><code> sectionSelected.removeClass(\"inEdit\") \n sectionSelected.prop(\"contentEditable\", false) \n sectionSelected.html(data.d)\n</code></pre>\n\n<p>to </p>\n\n<pre><code>sectionSelected.removeClass(\"inEdit\").prop(\"contentEditable\", false).html(data.d);\n</code></pre>\n\n<p>and </p>\n\n<pre><code>selectedElem.children(\".cmsEditBox\").css('top', (selectedElem.children(\".cmsEditBox\").height() * -1) - 10)\nselectedElem.children(\".cmsEditBox\").css('left', ((selectedElem.children(\".cmsEditBox\").width() / 8) * -1))\nselectedElem.children(\".cmsEditBox\").prop('contenteditable', false) \n</code></pre>\n\n<p>for this </p>\n\n<pre><code>selectedElem.children(\".cmsEditBox\").css({\n 'top': (selectedElem.children(\".cmsEditBox\").height() * -1) - 10),\n 'left': ((selectedElem.children(\".cmsEditBox\").width() / 8) * -1)}).prop('contenteditable', false);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:19:03.400",
"Id": "51410",
"Score": "0",
"body": "Very good critiques! I went a head and added the above suggesstions on my application. Thank you for your time!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:26:34.413",
"Id": "32189",
"ParentId": "32184",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32187",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T14:40:18.577",
"Id": "32184",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "JavaScript file for a CMS application"
}
|
32184
|
<p>I have a grid which allows a user to enter a new Grid item. If the grid item exists or the <code>tb</code> is empty it displays the error. Here's the code I came up with.</p>
<p>Can anybody think of a cleaner or more efficient way of doing so? Thinking about it now, I guess I could have done it all in one function, and placed <code>InsertTrack()</code> in the else condition of <code>DoesTrackExist</code> and register the script in the <code>if</code> statement.</p>
<pre><code> private void InsertTrack()
{
if (DoesTrackExist(txtEventTracks.Text))
{
using (EMSEntities db = new EMSEntities())
{
EventTrack newEventTrack = new EventTrack()
{
TrackName = txtEventTracks.Text
};
db.EventTracks.Add(newEventTrack);
db.SaveChanges();
}
}
else
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "Error", "alert('Track name cannot be duplicate or empty')", true);
}
}
private bool DoesTrackExist(string txtValue)
{
using (EMSEntities db = new EMSEntities())
{
var context = from x in db.EventTracks
where x.TrackName.Contains(txtEventTracks.Text)
select x;
if (context.Any() || txtEventTracks.Text == "")
{
return false;
}
else
{
return true;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:14:42.907",
"Id": "51400",
"Score": "0",
"body": "Malachi, I used your edit, but how can I had that code block when I post"
}
] |
[
{
"body": "<p>Some people say that adding private functions which are only called in one place in a class clutter the \"private interface\" of the class. However I actually do prefer it in some cases. In your case I think it makes sense as it makes <code>InsertTrack</code> easier to read so I would not merge the two.</p>\n\n<p>As to <code>DoesTrackExist</code></p>\n\n<ol>\n<li>Check <code>txtEventTracks.Text == \"\"</code> first - this avoids performing any query at all.</li>\n<li>I assume you meant to use the parameter <code>txtValue</code> instead of accessing the textbox directly.</li>\n<li><p>Might not be more efficient but <a href=\"http://msdn.microsoft.com/en-us/library/bb534972.aspx\" rel=\"nofollow\"><code>Any()</code></a> accepts a predicate as well:</p>\n\n<pre><code>private bool DoesTrackExist(string txtValue)\n{\n // maybe even consider IsNullOrWhiteSpace?\n if (string.IsNullOrEmpty(txtValue)) \n return false;\n using (EMSEntities db = new EMSEntities())\n {\n return db.EventTracks.Any(x => x.TrackName.Contains(txtValue))\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:18:21.613",
"Id": "32203",
"ParentId": "32185",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32203",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:07:35.027",
"Id": "32185",
"Score": "2",
"Tags": [
"c#",
"linq",
"asp.net"
],
"Title": "Check if Item exists in Grid using Linq"
}
|
32185
|
<p>Here's some code that I ran through jsperf to assess its performance. The first test (named <strong>EvalLengthBefore++</strong> in the images below) is the way I would consider normally looping through the elements of an array:</p>
<pre><code>var arr = [];
for (var x = 0; x < 1000; x++) {
arr.push(Math.random());
}
var len = arr.length;
for (var y = 0; y < len; y++) {
//do some maths
var el = arr[y];
el++; //meaningless operation
}
</code></pre>
<p>The second test (named <strong>InfiniteLoopWithBreak</strong> in the images below) is the method I found in some code that is supposed to to be run in IE7 (it's part of a CSS fallback):</p>
<pre><code>var arr = [];
for (var x = 0; x < 1000; x++) {
arr.push(Math.random());
}
for (var y = 0;; y += 1) {
//do some maths
var el = arr[y];
if (!el) {
break;
}
el++;
}
</code></pre>
<p>In modern browsers, the second method is much slower, which is kind of what I expected. However in IE7 it is just as fast, occasionally faster, in the jsperf tests:</p>
<p><strong>Test results in Chrome:</strong>
<img src="https://i.stack.imgur.com/Znzvb.png" alt="Test in Chrome"></p>
<p><strong>Test results in IE7</strong>
<img src="https://i.stack.imgur.com/HZERe.png" alt="enter image description here"></p>
<p><a href="http://jsperf.com/elementloop" rel="nofollow noreferrer">Here</a> are the jsperf tests if you want to run them yourselves.</p>
<p><em>Why is the second code snippet faster than the rest in IE7?</em></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:20:37.043",
"Id": "51401",
"Score": "8",
"body": "Not sure if this belongs to codereview.SE but it does look like a pretty interesting question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:22:45.700",
"Id": "51402",
"Score": "0",
"body": "@Josay, I debated for a while whether it was more suited to here or Stack Overflow, but settled for here in the end. Happy to have the question migrated if the mods feel it would be more suitable over at SE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:14:29.333",
"Id": "51409",
"Score": "0",
"body": "Yeah, I'd wait for the mods to decide. However, this doesn't quite fit \"understanding code snippets\" because because you already know what's happening. You just want to know why."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T19:29:32.180",
"Id": "51418",
"Score": "0",
"body": "would be interesting to test also `for (var el, y = 0; el = arr[y]; y++) { el++; }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:09:28.267",
"Id": "51461",
"Score": "1",
"body": "@AndyF: A very interesting question, I must say. Sadly, I think programmers.stackexchange or (though borderline) even computerscience.stackexchange. Anyway, I've posted a (rather verbose) answer here anyway... ;P"
}
] |
[
{
"body": "<p>Since you asked this question here rather than on Stack Overflow, I'm going to propose this <a href=\"http://jsperf.com/elementloop/2\" rel=\"nofollow\">countdown iteration</a>:</p>\n\n<pre><code>for (var y = arr.length - 1; y >= 0; --y) {\n //do some maths\n var el = arr[y];\n el++;\n}\n</code></pre>\n\n<p>The advantages are:</p>\n\n<ul>\n<li>You only calculate <code>arr.length</code> once, and do so without introducing a temporary variable</li>\n<li>Each iteration, you compare <code>y</code> with zero. To compare with any other number, the CPU would first have to load both values into registers before executing the conditional branch instruction. To compare against zero, only the value of <code>y</code> needs to be loaded in a register; there is a special instruction for comparing against zero and conditionally branching.</li>\n</ul>\n\n<p>That said, the performance gain by iterating backward instead of forward is negligible, and you should avoid the countdown technique if</p>\n\n<ul>\n<li>The processing of an element depends on the value of another element</li>\n<li>The processing of an element could fail — premature termination of the loop would be weird if the partial results are at the end of the array</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:42:15.403",
"Id": "32194",
"ParentId": "32186",
"Score": "3"
}
},
{
"body": "<p>To start with, it might be that IE7 is so slow, you can't really tell the differences with such small numbers. Another factor might be that \"length\" calculation is really slow on an array this size (well, back then ...) and that array access is \"optimized\" (at least better, and doesn't hurt much more than static property access).\nBut I think that IE7's just too slow for us to notice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:10:24.177",
"Id": "32202",
"ParentId": "32186",
"Score": "0"
}
},
{
"body": "<p>First of all, microbenchmarks like these don't really tell the whole story. It may only be \"fast\" or \"slow\" in this case. In real-world scenarios, it may tell another story (like when you have to deal with stuff other than just arrays).</p>\n\n<p>Another thing is, with such small numbers in the IE tests... you can't really say it's fast :D</p>\n\n<p>Another thing is (and most likely this would be the cause of the great divide in Chrome) is that modern JS compilers tend to optimize \"hot code\". Other forms of code are internally faster as well due to the browser's implementation of operations.</p>\n\n<p>So in this case, case 2 and case 4 in Chrome might have been optimized internally, whereas case 3 might have been faster for IE7.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T01:56:06.170",
"Id": "32214",
"ParentId": "32186",
"Score": "0"
}
},
{
"body": "<p>The short answer:<Br/>\nIn your code the <code>arr.length</code> is the major bottleneck. Simply because of the differences between the various implementations of JavaScript. Not only the implementations differ, but also what the engines actually <em>do</em> prior to executing your code.<br/>\nWhy do I think this: simple:</p>\n\n<pre><code>for([[expr evaluated at start of loop]];\n [[expr re-evaluated on each iteration + 1(end of loop)]];\n [[expr evaluated for each iteration +1(end of loop)]]\n)\n</code></pre>\n\n<p>The cases that are fastest on IE7 are those where the conditional expression in the for-loop is either missing or is simply comparing the values of 2 variables.</p>\n\n<p>The long answer, without focussing on <code>arr.length</code>, but keep in mind that here, you're getting a property of an object, that is, sort-of, inherited from the prototype.</p>\n\n<p>The reason why is simply because of how Chrome's V8 compiles the code, and how the <code>Object[[GetProperty]]</code> is implemented. Since JS arrays are just augmented objects (<code>Array instanceof Object</code> is <code>true</code>), getting a value from an array is, essentially the same as <code>someObj.someProp</code>.<br/>\nMost JS implementations use either a HashMap or HashTable for the objects. Chrome's V8 engine, is a bit of an odd one out, in a couple of crucial ways.</p>\n\n<p>FF's SpiderMonkey/*Monkey engines compile JS code to intermediate byte-code, that runs on a virtual machine.<br/>\nTheir Rhino engine compiles JS to Java, which is also a VM environment. Cf the hybrid model in the img below<Br/>\nJS <em>\"engines\"</em> of old didn't even go that far, they were just parse-and-execute things. They did no or very little optimization or reflection on the code they were asked to parse.<br/>\n<em>V8</em> does things a bit different: it parses, optimizes and compiles the resulting AST (<em>Abstract Syntax Tree</em>) straight into machine-executable code. No byte-code virtual-machine stuff to hold you back:</p>\n\n<p><img src=\"https://i.stack.imgur.com/jUrHi.jpg\" alt=\"JS engines compilation models\"></p>\n\n<p>So, Chrome's V8 compiles to machine code, which cuts down overall execution time (in most cases). In addition to that, the V8 engine does not use a HashTable for object properties. It creates classes:</p>\n\n<blockquote>\n <p>To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes.</p>\n</blockquote>\n\n<p>What does this mean for <code>arr.length</code>:</p>\n\n<pre><code>//V8:\narr = [];//creates class, that has length property, value 0\narr.push(123);//arr points to class with property 0 = 123, length = 1\n</code></pre>\n\n<p>That means that, <code>arr.length</code> or <code>arr[0]</code> both are simple, atomic operations. In terms of time-complexity, they are as close as makes no difference both: <em>O(1)</em>. Now, I'm not familiar with the internals of IE's JScript engine, but I'm prepared to take a punt on how <code>arr.length</code> works:</p>\n\n<pre><code>arr.length;//->arr @instancelevel->search(length)\n //\n ==>arr.prototype->search(length)\n //\n ==> magic property, probably does something like:\n return max(@instance.keys) +1\n</code></pre>\n\n<p>Now, this may range anywhere from pretty accurate to down-right absurd, but the principle stands: getting the length property from an array on engines that don't create classes for instances, is not atomic, and therefore slower.<br/>\nSadly, because of MS's software being closed source, I can't tell you what kind of AST the parser churns out, nor what the engine then does with that AST. You'll have to get friendly with someone working in Redmond, or send a very polite email, requesting more info (don't expect an answer, though :-P).</p>\n\n<p>So, V8 compiles the AST directly to machine-executable code, and creates classes to speedup property. In theory, accessing a property in JS, running on V8 should be almost as fast as C++ code. In theory, that is :P.<Br/>\nInternet Explorer's JScript engine, especially IE7, is quite dated. It doesn't do optimization very well. It doesn't compile JS as well as modern day engines do.</p>\n\n<p>I can't find the resource ATM, but I also seem to remember that IE's JScript implementation of objects was, in fact, rather lacking, too. I seem to recall it didn't even use a full-blown HashTable for its objects, which would explain why <code>someArray.length</code> takes ages (since it requires a prototype lookup).</p>\n\n<p><a href=\"https://developers.google.com/v8/design?hl=sv&csw=1#prop_access\" rel=\"nofollow noreferrer\">Read more here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-10-04T08:59:57.227",
"Id": "32233",
"ParentId": "32186",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "32233",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:15:13.347",
"Id": "32186",
"Score": "11",
"Tags": [
"javascript",
"performance",
"array"
],
"Title": "Why is this code so much faster (relatively) in IE7?"
}
|
32186
|
<p>I have a large C# Dictionary of string keys and boolean values. Background on the reason for it is this: my program builds up a bunch of the same objects from two different sources, and then compares all the properties to see if there are any disparates. But I want to ignore the differences where I know one source hasn't exposed that property for comparison, so I have this array that lists the properties that are actually 'gathered'.</p>
<p>Then when filtering the differences before user display, I ask <code>if(!gathered[prop])</code> and remove it in that case. It would throw an exception if I hadn't defined a case for the property, and I don't want to ignore that as it may just mean I neglected to specify if it was or wasn't gathered.</p>
<pre><code> public Dictionary<string, bool> TPORGatheredData = new Dictionary<string,bool>()
{
// Represents fields that are actually retrieved from TP data
{ "Reference", true },
{ "Title", true },
{ "Status", true },
{ "Status.State", true },
{ "OriginatorName", true },
{ "InvestigatorName", true },
{ "ManagerName", true },
{ "ObservedOn", true },
{ "RaisedOn", true },
{ "ClosedOn", true },
{ "Project", true },
{ "VariantObservedOn", true },
{ "SoftwareVersionObserved", true },
{ "AreaObservedOn", true },
{ "StageObservedOn", true },
{ "VariantAppliedTo", true },
{ "AreaAppliedTo", true },
{ "FaultClassification", true },
{ "Type", true },
{ "SecurityClassification", true },
{ "CommercialClassification", true },
{ "SecurityGroup", true },
{ "SafetyRelated", true },
{ "Description", false },
{ "Recommendations", true },
{ "Recommendations.PointNumber", true },
{ "Recommendations.Id", true },
{ "Recommendations.Type", true },
{ "Recommendations.RecommendationText", true },
{ "ClosureText", true },
};
</code></pre>
<p>The problem with this is that the value of <code>false</code> is quite significant. How could I differentiate the <code>false</code> from the <code>true</code> here?</p>
<p>Two options I can think of:</p>
<ol>
<li><p>I could tab align all the values but this looks ugly as the farthest extent they need to go for alignment is a bit too far to easily see which value is for which key.</p></li>
<li><p>assume if there's no key then the value is true (although that depends on the context making this a suitable option, and as it stands in my case <em>not</em> having the value may be an indicator of a field that needs checking to see if it is or isn't handled).</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:57:46.353",
"Id": "51412",
"Score": "2",
"body": "We need some more context to know how best to help. What is this dictionary used for? Where/how is it modified? My gut reaction seeing the dictionary defined like that is that you should be using a bitmask with an inverted meaning, i.e., switching TPORGatheredData to instead represent ignored data, so your value only sets the flag for Description."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:20:45.850",
"Id": "51465",
"Score": "0",
"body": "Updated the question @DanLyons"
}
] |
[
{
"body": "<p>Dictionaries don't preserve the order of their entries, so list all keys with <code>false</code> values first, then all keys with <code>true</code> values. I would also sort the keys alphabetically within each group.</p>\n\n<pre><code>// Represents fields that are actually retrieved from TP data\npublic Dictionary<string, bool> TPORGatheredData = new Dictionary<string,bool>()\n{\n // Entries with a false value...\n { \"Description\", false },\n\n // Entries with a true value...\n { \"AreaAppliedTo\", true },\n { \"AreaObservedOn\", true },\n { \"ClosedOn\", true },\n { \"ClosureText\", true },\n { \"CommercialClassification\", true },\n { \"FaultClassification\", true },\n { \"InvestigatorName\", true },\n { \"ManagerName\", true },\n { \"ObservedOn\", true },\n { \"OriginatorName\", true },\n { \"Project\", true },\n { \"RaisedOn\", true },\n { \"Recommendations\", true },\n { \"Recommendations.Id\", true },\n { \"Recommendations.PointNumber\", true },\n { \"Recommendations.RecommendationText\", true },\n { \"Recommendations.Type\", true },\n { \"Reference\", true },\n { \"SafetyRelated\", true },\n { \"SecurityClassification\", true },\n { \"SecurityGroup\", true },\n { \"SoftwareVersionObserved\", true },\n { \"StageObservedOn\", true },\n { \"Status\", true },\n { \"Status.State\", true },\n { \"Title\", true },\n { \"Type\", true },\n { \"VariantAppliedTo\", true },\n { \"VariantObservedOn\", true },\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T18:25:30.577",
"Id": "51414",
"Score": "2",
"body": "But this means that entries that are logically related would be far away."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T17:58:30.100",
"Id": "32195",
"ParentId": "32188",
"Score": "7"
}
},
{
"body": "<p>Is this more like what you're after?</p>\n\n<pre><code>var TPORGatheredData = new[]\n {\n // Add all values in the logical order that you want them\n \"Reference\",\n \"Title\",\n \"Status\",\n \"Status.State\",\n //...omitted for brevity\n \"Description\",\n \"ClosureText\"\n\n }.ToDictionary(x=>x,x=>true);\n\n // This is significant\n TPORGatheredData[\"Description\"] = false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:39:23.663",
"Id": "32221",
"ParentId": "32188",
"Score": "8"
}
},
{
"body": "<p>Given the update...</p>\n\n<p>Since you have a stated requirement of showing properties which do not exist in the collection anyways, then why bother adding entries for properties you want to show at all?</p>\n\n<p>I would only build a collection of the ignored properties, and then check if the collection contains the property during filtering. As such, that <code>if (!gathered[prop])</code> check instead turns into a <code>if(filter.ContainsKey(prop))</code> (if still using an IDictionary) or <code>if(filter.Contains(prop))</code> (for any other collection type).</p>\n\n<p>I would also suggest using a simpler collection like <code>List<T></code> or a string array, because the set of ignored properties seems to be really small (only one in your example). The performance of dictionary lookup versus list traversal will be insignificant at that size, and it seems more natural to have a collection of names than name/(unused) pairs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:38:33.310",
"Id": "51541",
"Score": "0",
"body": "This is a filter of what properties are gathered for two List<object>s. Both created their Lists from different sources. If one of those sources doesn't return a property eg 'Description', then I want to make sure before I complain to the user about differences, I don't waste their time with a difference that one source said \"\" when the other said \"foo bar\" (because obviously the source not gathering it says \"\"). If I don't have an exhaustive list, I run the risk of having neglected to specify a certain property which might get added elsewhere in the code and not in this `gathered` list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:27:19.223",
"Id": "32253",
"ParentId": "32188",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32221",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T15:22:13.670",
"Id": "32188",
"Score": "6",
"Tags": [
"c#",
"hash-map"
],
"Title": "How best to differentiate boolean values in a long list?"
}
|
32188
|
<p>Is this query acceptable in terms of performance (I get the correct data) or can it be optimized?</p>
<pre><code>SELECT
bankInstitution.name,
person.firstName,
person.surname,
offer.offerId,
bank.personId,
bank.bankOtherName,
bank.sortCode,
bank.number,
loan.loanId
offer.campaignId,
FROM bank
JOIN loan ON bank.personId = loan.personId AND bank.isCurrent = 1
JOIN offer ON loan.loanId = offer.loanId
JOIN person ON person.personId = bank.personId
JOIN bankInstitution ON bankInstitution.bankInstitutionId = bank.bankInstitutionId
WHERE offer.CampaignId = 1 AND offer.Processed Is NULL
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T20:32:47.167",
"Id": "51420",
"Score": "0",
"body": "this might be a dumb question but what is `:campaignId` referring to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:05:21.060",
"Id": "51422",
"Score": "0",
"body": "Ooops, sorry. I use this query in C# code, using NHibernate and it's the way to pass a parameter. The question is not dumb, I am."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:09:23.497",
"Id": "51423",
"Score": "0",
"body": "code looks good to me. looks pretty simple and straightforward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:09:36.730",
"Id": "51424",
"Score": "2",
"body": "More importantly, do you have the proper indexes on your tables? What is the result when you prepend `ANALYZE` to your query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:17:59.787",
"Id": "51425",
"Score": "1",
"body": "Well, didn't even know about this ANALYZE. Will do it in the morning as I don't have the laptop with me. Thanks all"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-15T16:49:05.397",
"Id": "52312",
"Score": "0",
"body": "What type of database are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-15T21:36:56.893",
"Id": "52330",
"Score": "0",
"body": "I'm using MS SQL"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T01:57:22.483",
"Id": "52442",
"Score": "1",
"body": "If you execute the command \"SET SHOWPLAN_XML ON;\" then execute your query, and click on the text link displayed, it will give you show you the query plan execution, and how much time it is spending on each step. When you are finished, type \"SET SHOWPLAN_XML OFF;\" This will show you were to focus your optimization efforts. Alternatively, you could highlight your query, then right-click and choose \"Display Estimated Execution Plan.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T03:23:45.603",
"Id": "52445",
"Score": "1",
"body": "Probably the biggest gain you could gain in performance would be to ensure all your tables have a clustered index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T13:29:47.860",
"Id": "52466",
"Score": "0",
"body": "Thanks Roger. Yes, allof them have clustered index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T11:36:49.670",
"Id": "53042",
"Score": "0",
"body": "Where does \"Campaign.Offer.CampaignId = 1 AND Campaign.Offer.Processed Is NULL\" come from? I don't see Campaign defined anywhere previously in the table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:28:47.767",
"Id": "53125",
"Score": "0",
"body": "Yes, sorry. Campaign.Offer is offer. I removed the full name for the sake of clearness and forgot to change the last line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T14:03:52.833",
"Id": "53590",
"Score": "0",
"body": "do the results change if you move the `AND bank.isCurrent = 1` to the where statement? it just looks odd and out of place to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T22:39:43.170",
"Id": "53634",
"Score": "1",
"body": "The next step is to make sure your joins are configured the same as the indexes. For maximum speed those joins would be exactly the indexes. For multiple fields in an index it is preferable to join on the index in the same order as the index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T01:13:01.877",
"Id": "53651",
"Score": "1",
"body": "“Is this query acceptable in terms of performance?” Only you can answer that, depending on what the performance requirements of your application, and other conditions specific to your setup."
}
] |
[
{
"body": "<p>There is an illegal comma before <code>FROM</code>.</p>\n\n<p>I would put <code>bank.isCurrent = 1</code> in the <code>WHERE</code>-clause instead of as a join condition.</p>\n\n<p>For consistency, I would reverse the equalities in the join conditions:</p>\n\n<ul>\n<li><code>JOIN loan ON loan.personId = bank.personId</code></li>\n<li><code>JOIN offer on offer.loanId = loan.loanId</code></li>\n</ul>\n\n<p>… to match …</p>\n\n<ul>\n<li><code>JOIN person ON person.personId = bank.personId</code></li>\n<li><code>JOIN bankInstitution ON bankInstitution.bankInstitutionId = bank.bankInstitutionId</code></li>\n</ul>\n\n<p>None of the above affects performance. What you have is a very ordinary joining of tables, and your query expresses it in the usual way. There's not much more that can be done for performance by tweaking the query.</p>\n\n<p>What you <em>should</em> do, though, is ensure that all of the joins are being performed using <a href=\"http://use-the-index-luke.com\" rel=\"nofollow\">indexes</a>, not full-table scans. You can verify that by prepending <code>ANALYZE</code> to your <code>SELECT</code>, which will give you the query execution plan. If any of the joins is being performed with a full-table scan, create an index on the relevant column. If your schema is properly defined, with the <code>PRIMARY KEY</code>s and <code>FOREIGN KEY</code>s declared, then you should already be fine, I think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T13:34:17.100",
"Id": "53786",
"Score": "0",
"body": "I don't think we are going to get much more answer than this, thank you for taking a look at it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T00:53:41.837",
"Id": "33486",
"ParentId": "32197",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33486",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T18:35:15.840",
"Id": "32197",
"Score": "1",
"Tags": [
"optimization",
"performance",
"sql",
"sql-server"
],
"Title": "SQL with several joins"
}
|
32197
|
<p>I have a server-client environment, where the client connects and synchronizes data with the server every 5 second.</p>
<p>For synchronizing I use a background thread on the client which works fine, but on one specific hardware the method GetNetworkAvailable throws out of memory exceptions occasionaly. The errors occur whitout logic, so I guess somethings just not good with this hardware. Anyways I'd like to get your opinion on my background - polling function.</p>
<pre><code>private void SynchronizedWorker()
{
bool initialization = true;
int initializationTries = 0;
// Sync loop
while (!_shouldStop)
{
// Initialize locals
int syncInterval = _syncInterval; // Reset Sync Interval to default
SyncStatus syncStatus = SyncStatus; // Get current Status
bool hasNetworkConnection = true; // Has Network connection
try
{
//*******************************************
// Check Network connection
//*******************************************
if (!NetworkInterface.GetIsNetworkAvailable())
{
hasNetworkConnection = false;
_syncResetEvent.Set();
syncStatus = SyncStatus.Offline;
}
else if (syncStatus == SyncStatus.Offline) // Is in offline - State, but Network available again recognize going online
{
_syncResetEvent.Set();
hasNetworkConnection = IsServiceAvailable();
// Sync-Status stays offline
if (!hasNetworkConnection)
{
// Wait 1 minute, before retry
syncInterval = 60000;
}
}
//*******************************************
// Proceed with Syncronisation
//*******************************************
if (hasNetworkConnection)
{
syncStatus = SyncStatus.Ok;
// Try Initialization
if (initialization)
{
try
{
// Sync initialization here...
// ..............................
////////////////////////////////////
}
catch (Exception ex)
{
log.LogError(string.Format("Initialization Try {0}", initializationTries), ex);
syncStatus = SyncStatus.InitializationFailed;
}
}
// To many Init-Tries --> Stop
if (initializationTries > 1)
{
// Proceed
_syncResetEvent.Set();
_syncStatus = syncStatus;
break; // Stop Synch
}
// Debug
var sw = System.Diagnostics.Stopwatch.StartNew();
// Do Up/Download
if (!initialization)
{
try
{
// Synchronisation with service here...
// ..............................
////////////////////////////////////
// Proceed
_syncResetEvent.Set();
}
catch (Exception ex)
{
log.LogError("Download", ex);
syncStatus = SyncStatus.SynchFailed;
}
}
}
// Set Sync status
_syncStatus = syncStatus;
}
catch (Exception ex)
{
log.LogError("Sync-Worker", ex);
_syncStatus = Core.Sync.SyncStatus.SynchFailed;
// Proceed
_syncResetEvent.Set();
// Reset Force
_syncForce = false;
}
finally
{
// Set Completed
if (OnSyncCompleted != null)
{
OnSyncCompleted(downloaded, uploaded, executed);
}
// Always Wait for Interval
DateTime sleepuntil = DateTime.Now.AddMilliseconds(syncInterval);
while (sleepuntil > DateTime.Now && !_shouldStop && !_syncForce)
{
// Sleep
Thread.Sleep(100);
}
}
}
// Stop
_syncStatus = SyncStatus.Unknown;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I would do the waiting for interval at the end also with an event - I find it cleaner. Something like this:</p>\n\n<pre><code>AutoResetEvent _syncWaitEvent = new AutoResetEvent(false);\n\n....\n\n// I assume there is a way for external callers to stop sync\npublic void StopSync()\n{\n _syncForce= true;\n _syncWaitEvent.Set();\n}\n\npublic void ForceSync()\n{\n _shouldStop = true;\n _syncWaitEvent.Set();\n}\n\nprivate void SynchronizedWorker()\n{\n ....\n // Sync loop\n while (!_shouldStop)\n {\n ....\n\n // wait for next interval or being woken up\n if (_syncWaitEvent.WaitOne(syncInterval))\n {\n // we have been signaled prior to the timeout expiring\n _syncForce = false;\n }\n }\n}\n</code></pre></li>\n<li><p>I would change <code>syncInterval</code> to a <code>TimeSpan</code> (<code>WaitOne()</code> expects one anyway and I don't like passing values around with implicit units. Just gets you in trouble some day)</p></li>\n<li><p>It's not clear from your code what the <code>_syncResetEvent()</code> is used for. It's seems to be called in pretty much every case. You might want to revisit the name of it.</p></li>\n<li><p>Add a log message in the <code>if (initializationTries > 1)</code> block to state that you are stopping sync because init failed too many times.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T21:06:57.180",
"Id": "32201",
"ParentId": "32198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32201",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T19:17:09.363",
"Id": "32198",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"web-services"
],
"Title": "Synchronization-Thread with Server every 5 secs"
}
|
32198
|
<p>I have made this program to find out the first and following sets of the productions:</p>
<pre><code>E->TA
A->+TA
A->0
T->FB
B->*FB
B->0
F->(E)
F->#
</code></pre>
<p>Here epsilon(NULL) is taken as 0: </p>
<pre><code> #include<stdio.h>
#include<ctype.h>
char a[8][8];
struct firTab
{
int n;
char firT[5];
};
struct folTab
{
int n;
char folT[5];
};
struct folTab follow[5];
struct firTab first[5];
int col;
void findFirst(char,char);
void findFollow(char,char);
void folTabOperation(char,char);
void firTabOperation(char,char);
void main()
{
int i,j,c=0,cnt=0;
char ip;
char b[8];
printf("\nFIRST AND FOLLOW SET \n\nenter 8 productions in format A->B+T\n");
for(i=0;i<8;i++)
{
scanf("%s",&a[i]);
}
for(i=0;i<8;i++)
{ c=0;
for(j=0;j<i+1;j++)
{
if(a[i][0] == b[j])
{
c=1;
break;
}
}
if(c !=1)
{
b[cnt] = a[i][0];
cnt++;
}
}
printf("\n");
for(i=0;i<cnt;i++)
{ col=1;
first[i].firT[0] = b[i];
first[i].n=0;
findFirst(b[i],i);
}
for(i=0;i<cnt;i++)
{
col=1;
follow[i].folT[0] = b[i];
follow[i].n=0;
findFollow(b[i],i);
}
printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=first[i].n;j++)
{
if(j==0)
{
printf("First(%c) : {",first[i].firT[j]);
}
else
{
printf(" %c",first[i].firT[j]);
}
}
printf(" } ");
printf("\n");
}
printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=follow[i].n;j++)
{
if(j==0)
{
printf("Follow(%c) : {",follow[i].folT[j]);
}
else
{
printf(" %c",follow[i].folT[j]);
}
}
printf(" } ");
printf("\n");
}
}
void findFirst(char ip,char pos)
{
int i;
for(i=0;i<8;i++)
{
if(ip == a[i][0])
{
if(isupper(a[i][3]))
{
findFirst(a[i][3],pos);
}
else
{
first[pos].firT[col]=a[i][3];
first[pos].n++;
col++;
}
}
}
}
void findFollow(char ip,char row)
{ int i,j;
if(row==0 && col==1)
{
follow[row].folT[col]= '$';
col++;
follow[row].n++;
}
for(i=0;i<8;i++)
{
for(j=3;j<7;j++)
{
if(a[i][j] == ip)
{
if(a[i][j+1] == '\0')
{
if(a[i][j] != a[i][0])
{
folTabOperation(a[i][0],row);
}
}
else if(isupper(a[i][j+1]))
{ if(a[i][j+1] != a[i][0])
{
firTabOperation(a[i][j+1],row);
}
}
else
{
follow[row].folT[col] = a[i][j+1];
col++;
follow[row].n++;
}
}
}
}
}
void folTabOperation(char ip,char row)
{ int i,j;
for(i=0;i<5;i++)
{
if(ip == follow[i].folT[0])
{
for(j=1;j<=follow[i].n;j++)
{
follow[row].folT[col] = follow[i].folT[j];
col++;
follow[row].n++;
}
}
}
}
void firTabOperation(char ip,char row)
{
int i,j;
for(i=0;i<5;i++)
{
if(ip == first[i].firT[0])
{
for(j=1;j<=first[i].n;j++)
{
if(first[i].firT[j] != '0')
{
follow[row].folT[col] = first[i].firT[j];
follow[row].n++;
col++;
}
else
{
folTabOperation(ip,row);
}
}
}
}
}
/*
input productions
E->TA
A->+TA
A->0
T->FB
B->*FB
B->0
F->(E)
F->#
*/
</code></pre>
<p>Please review this.</p>
|
[] |
[
{
"body": "<p>To start at the top, your two structures <code>firTab</code> and <code>folTab</code> could probably be\ncombined. And given a name than means something.</p>\n\n<p>Your embedded constants 8 and 5 throughout should be replaced by #defined\nconstants to make changing them easier.</p>\n\n<p>You would also do well to restructure <code>main</code> to extract parts that are are\nlogically complete and separate into functions. And place <code>main</code> last to\navoid the need for prototypes. Every other function can be static.</p>\n\n<p>On compiling the code, every array subscript gives a warning: array subscript\nis of type 'char'. char subscripts are generally best avoided because char\ncan be signed or unsigned according to the implementation.</p>\n\n<p>On the details of the code, I can't claim to have followed it through. But\nlooking at the first 30 lines of <code>main</code>...</p>\n\n<p>Your first action is to obtain the 8 rules you expect. The code would be\nbetter is it did not assume a fixed number (8) of rules or a fixed number (5)\nof first/follow.</p>\n\n<p>The first line of main defines some variables, but they would be better defined\nat the point of first use (where possible) or one per line. <code>c</code> and <code>cnt</code> are\nnot sufficiently meaningful.</p>\n\n<p>You then define array <code>b[8]</code>, again with an embedded constant and an\nassumption of the number of input lines. <code>b</code> is left uninitialized and hence\nwill contain junk (whatever is at that stack location).</p>\n\n<p>You then read the 8 input lines into <code>a[][]</code> without any checks that they fit\nin the array entries. Then follows a loop that reads through these eight\nlines and puts the first character of each line into array <code>b</code> without\nduplication. There are numerous issues with these lines, the main one being\nthat it is such a convoluted way of doing this. Here are some more:</p>\n\n<ul>\n<li>array <code>a</code> is badly named</li>\n<li>array <code>b</code> is badly named and is used before being initialized. The loop\nonly works by chance. </li>\n<li>flag <code>c</code> is badly named. It is a boolean indicating that <code>b</code> already holds\na particular letter. </li>\n<li><p>variables <code>i</code> and <code>j</code> should be declared as part of their loops:</p>\n\n<pre><code> for (int i = 0; i < 8; i++)\n</code></pre></li>\n<li><p>you should add some spaces to make expressions more readable, for example\nafter <code>if</code> and <code>for</code>, after <code>;</code>, around <code>=</code> and <code>+</code> etc</p></li>\n<li><p>your layout is inconsistent (eg placement of <code>c=0;</code> compared to other\nopening braces)</p></li>\n</ul>\n\n<p>This whole loop should have been combined with the input loop so that each\ntime you read a new line into <code>a</code>, you checked its first character to see\nwhether it was in <code>b</code> and if not added it. If we rename <code>b</code> as <code>letters</code> and\nmake it a nul terminated string, you can check this easily with</p>\n\n<pre><code> if (!strchr(letters, line[0])) {\n // append new letter\n }\n</code></pre>\n\n<p>where <code>line</code> is the new input line.</p>\n\n<p>I've only covered 50 lines of the code, but I think there is enough there for you to think about. It looks as if you have disappeared, so I'm not sure it is worth digging any further. If you reappear, I might :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-07T17:27:58.893",
"Id": "36867",
"ParentId": "32199",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T19:25:04.913",
"Id": "32199",
"Score": "4",
"Tags": [
"c",
"parsing"
],
"Title": "Computing first and following sets (compiler design)"
}
|
32199
|
<p><strong>This question is the first draft, my new revised code is here:
<a href="https://codereview.stackexchange.com/questions/32246/anagrams-for-a-given-input-2-0">Anagrams for a given input 2.0</a></strong></p>
<p>Here is my code that I wrote, which basically lists the anagrams for a given input.</p>
<p>I did this by reading each line in my dictionary file and comparing it to the anagram. Only if it matched did I add it to the <code>list</code>, instead of adding all the words to the <code>list</code> and then sorting through them.</p>
<p>I compared the words by first checking the length of both words, and then if they matched I put put each word into a list and then sorted the <code>list</code>, then I compared the two lists using the <code>equals()</code> function. And iterated my counter.</p>
<p>The function of my <code>getOutPut()</code> was just to neaten up the printout.</p>
<p>What I would like are some critiques on my work and what I should/could have done differently, especially pertaining to semantic efficiency, code correctness, common practices that I may be unaware of, and code efficiency.</p>
<p>This is only my second project, so I want to learn from it to become a better programmer. That's why I'm asking.</p>
<p>The methods are in the order they are called in:</p>
<p><em>(Note that I split the code up to make it easier to see, all the methods are inside the Anagramatic Class)</em></p>
<pre><code>package anagramatic;
/**
* IDE : NETBEANS
* Additional Libraries : Guava
* @author KyleMHB
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Anagramatic {
static int k;
</code></pre>
<p>-</p>
<pre><code>public static void main(String[] args) throws FileNotFoundException{
String anagram;
anagram=input();
ArrayList<String> words=readFile(anagram);
String output= getOutPut(words);
JOptionPane.showMessageDialog(null,
"The anagram "+anagram+" has "+k+" matches, they are:\n\n"+output);
}//PVSM
</code></pre>
<p>-</p>
<pre><code>private static String input() {
String input;
input = JOptionPane.showInputDialog(null,
"Enter the Word or words you would like to be processed");
return input;
}//input
</code></pre>
<p>-</p>
<pre><code>private static ArrayList readFile(String anag) throws FileNotFoundException{
k=0;
ArrayList<String> list;
ArrayList<Character> a;
ArrayList<Character> b;
try (Scanner s = new Scanner(new File("words.txt"))){
list = new ArrayList<>();
while (s.hasNext()){
String word= s.next();
if (word.length()==anag.length()){
a = new ArrayList<>();
b = new ArrayList<>();
for(int i=0;i!=word.length();i++){
a.add(anag.charAt(i));
b.add(word.charAt(i));
}//forloop to make two lists of the words
Collections.sort(a);
Collections.sort(b);
if(a.equals(b)){
list.add(word);
k++;
}//comparing the two lists
}//if length
}//while
}//try
return list;
}//readfile
</code></pre>
<p>-</p>
<pre><code>private static String getOutPut(ArrayList<String> words) {
String wordz="[";
int x=0;
int y=0;
for(int i=0; i!=words.size()-1;i++){
if(x!=7){
wordz+=words.get(i)+", ";
x++;
}else{wordz+="\n";x=0;}
}//for
wordz+=words.get(words.size()-1)+"]";
return wordz;
}//getOutPut
}//Anagramatic
</code></pre>
|
[] |
[
{
"body": "<p>The organisation of the code is not the best as some methods are probably doing more than they should.</p>\n\n<p>You should write a method to check whether two words are anagrams or not.</p>\n\n<p>There is not point in storing the number of anagrams in k as it corresponds to the length of the list anyway.</p>\n\n<p>You could use <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#join%28java.lang.Object%5B%5D,%20java.lang.String%29\" rel=\"nofollow\">join from StringUtils</a> in <code>getOutput</code>.</p>\n\n<p>If you plan to look for anagrams in the same file multiple time, you could go for a different algorithm in order not to have to reprocess the whole file every time.\nThe trick is to compute for each word its \"sorted\" version and to keep a mapping from \"sorted\" word to the corresponding list of real words. Then checking for the anagrams for a word is nothing but sorting it and looking for it in the mapping.</p>\n\n<p><em>I have to go, I'll try to finish this.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T23:22:56.397",
"Id": "51426",
"Score": "0",
"body": "Yeah I know the `readFile` method does more than it should. But I wanted it to only add the correct entries from the file to this list instead of loading the entire file and add another set of loops to process that list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T23:16:34.193",
"Id": "32206",
"ParentId": "32204",
"Score": "1"
}
},
{
"body": "<p>Well, the most obvious improvement is:</p>\n\n<p>You make list <code>a</code> of the anagram and sort it for every word in the list. You could just do that once before the loop and use that sorted list as reference.</p>\n\n<p>There might be cleverer algorithms for finding anagrams but your approach is fairly simple and easy to understand and read which I'd prefer over clever unless clever gives you a notable performance advantage.</p>\n\n<p>Others:</p>\n\n<p>Do not comment every closed bracket. This adds no value and just clutter. Worse, it makes refactoring code painful as you have to keep the comments updated (no comments are better than wrong comments)</p>\n\n<p><code>getOutPut</code> should be spelled <code>getOutput</code></p>\n\n<p><code>getOutput</code> contains a bug because you compare <code>i != words.size() - 1</code>. This comparison is done before the next iteration starts so you will omit the last element. In generally in for loops over arrays you do something like <code>for (int i = 0; i < size; ++i)</code></p>\n\n<p>I would consider using <a href=\"http://docs.oracle.com/javase/tutorial/java/data/buffers.html\" rel=\"nofollow\"><code>StringBuilder</code></a> in <code>getOutput</code>:</p>\n\n<pre><code>private static String getOutPut(ArrayList<String> words) {\n StringBuilder builder = new StringBuilder(\"[\");\n int last = words.size();\n for (int i = 0; i < last; ++i) {\n builder.append(words.get(i));\n // only append \",\" and new lines if it is not the last word in the list\n if (i < last - 1) {\n builder.append(\", \");\n // every 7th i append a new line\n if ((i + 1) % 7 == 0)\n builder.append(\"\\n\");\n }\n }\n builder.append(\"]\");\n return builder.toString();\n}\n</code></pre>\n\n<p>When you concatenate strings like you did you will potentially create a whole lot of string objects (strings are immutable so <code>wordz += \"a\"</code> will create a new string and not append <code>a</code> to the existing string) which are not really useful as they are only temporary (like \"word1\", \"word1, word2\", \"word1, word2, word3\" etc.). The <code>StringBuilder</code> avoids that but simply keeping a list of all appended strings internally and only building the final string in <code>toString()</code>.</p>\n\n<p>Disclaimer: I'm not doing much Java development so it might be possible to implement <code>getOutput</code> a bit more elegant (it also means that my implementation might contain a bug as I haven't tested it in code). Using <code>join</code> of the string utilities was mentioned but I'm not sure how you could use that to insert an additional delimiter every x-th element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T00:09:24.463",
"Id": "32208",
"ParentId": "32204",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Stop declaring your variables and <em>then</em> setting their values. You can just set the values in the same line that you declare them.</li>\n<li>Always use the appropriate type parameter for generics (i.e., <code>ArrayList<String></code>, not just <code>ArrayList</code> or <code>ArrayList<></code>.</li>\n<li>Don't create variables where you don't need to (i.e., <code>static int k</code>, <code>int x</code>, <code>int y</code>).</li>\n<li>Wherever possible, separate out different functions into different methods. For example, in your refactored code below, I split the anagram generation into a separate method from the actual file IO. This not only improves code readability but also prevents your program from holding a lock on the file for the duration of the run. (Think about it; there's no need for the file to be locked up while we're actually checking the list for the anagrams.)</li>\n<li>People generally use the interface rather than the underlying object whenever possible. (<code>List<String></code> vs. <code>ArrayList<String></code>) Not really sure why, to be honest, but this is the accepted convention.</li>\n<li>The <code>input()</code> function probably doesn't even need to exist, but if you're going to leave it, it can be a one-liner.</li>\n<li>Use variable and method names that are actually meaningful.</li>\n<li>Don't convolute code where it's not necessary. For example, see the refactored <code>formatOutput()</code> method below.</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\nimport javax.swing.JOptionPane; \n\npublic class Anagramatic {\n\n public static void main(String[] args) throws FileNotFoundException {\n String anagram = input();\n List<String> anagrams = getAnagrams(anagram, readFile(anagram));\n String output = formatOutput(anagrams);\n JOptionPane.showMessageDialog(null,\n \"The anagram \"+anagram+\" has \"+anagrams.size()+\" matches, they are:\\n\\n\"+output);\n }\n\n\n private static String input() {\n return JOptionPane.showInputDialog(null, \"Enter the word or words you would like to be processed\");\n }\n\n private static List<String> readFile(String anagram) throws FileNotFoundException {\n List<String> list = new ArrayList<String>();\n try (Scanner s = new Scanner(new File(\"words.txt\"))) {\n while(s.hasNext()) {\n list.add(s.next());\n }\n }\n return list;\n }\n\n private static List<String> getAnagrams(String anagram, List<String> words) {\n List<String> list = new ArrayList<String>();\n List<Character> a, b;\n for(String word : words) {\n if(anagram.length() == word.length()) {\n a = new ArrayList<Character>();\n b = new ArrayList<Character>();\n for(int i = 0; i < word.length(); i++) {\n a.add(anagram.charAt(i));\n b.add(word.charAt(i));\n }\n if(a.containsAll(b)){\n list.add(word);\n }\n }\n }\n return list;\n }\n\n\n private static String formatOutput(List<String> words) {\n String formattedWords = \"[\";\n for(int i = 0; i < words.size(); i++) {\n formattedWords += words.get(i);\n if(i % 7 == 0) formattedWords += \"\\n\";\n else formattedWords += \", \";\n }\n formattedWords += \"]\";\n return formattedWords;\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T00:21:02.793",
"Id": "32209",
"ParentId": "32204",
"Score": "4"
}
},
{
"body": "<p>I'll focus on the heart of your solution first, which is your <code>readFile()</code> method. Here's how I would write it:</p>\n\n<pre><code>public static List<String> anagramsInFile(String word, File f)\n throws FileNotFoundException {\n char[] canonical = canonicalize(original);\n ArrayList<String> anagrams = new ArrayList<String>(); \n try (Scanner s = new Scanner(f)) {\n while (s.hasNext()) {\n String candidate = s.next();\n if ( (candidate.length() == word.length()) &&\n (Arrays.equals(canonical, canonicalize(candidate))) ) {\n anagrams.add(candidate);\n }\n }\n }\n return anagrams;\n}\n\nprivate static char[] canonicalize(String original) {\n char[] array = original.toCharArray();\n Arrays.sort(array);\n return array;\n}\n</code></pre>\n\n<p>Points to note:</p>\n\n<ul>\n<li>Naming is important. <code>handleFile()</code> is vague; <code>anagramsInFile()</code> is meaningful. Also, I find <code>anag</code> to be confusing parameter name.</li>\n<li>Hard-coding the filename inside the method is a bad idea.</li>\n<li>Unless the caller has a reason to require an <code>ArrayList</code>, your method signature should just commit to returning some kind of <code>List</code>. Better yet, consider returning a <code>Set</code>.</li>\n<li>You only have to canonicalize the original string once, not once per word in the file.</li>\n<li>Canonicalization deserves a helper method, since you have to do it to both the original string and to the contents of the file.</li>\n<li>Canonicalizing to a <code>char[]</code> avoids working character by character, since you can take advantage of <code>String.toCharArray()</code>. It's probably more efficient as well.</li>\n<li>There's no point in maintaining <code>k</code>: it's just the <code>size()</code> of the returned list. Maintaining <code>k</code> as a <em>class</em> variable is particularly egregious, as there's no reason for that count to be part of the state of the class.</li>\n<li>If your blocks are so lengthy and deeply nested that you need comments on the closing braces, consider that a Bad Code Smell and address that issue instead. (By the way, your braces were misaligned, which causes confusion that even your close-brace comments can't compensate for.)</li>\n</ul>\n\n<p>Next, let's look at <code>getOutPut()</code>. Here's how I would write it:</p>\n\n<pre><code>private static String formatOutput(List<String> words) {\n StringBuilder out = new StringBuilder('[');\n int wordsPrinted = 0;\n Iterator<String> w = words.iterator();\n while (w.hasNext()) {\n out.append(w.next());\n if (w.hasNext()) {\n out.append((++wordsPrinted % 8 == 0) ? \"\\n\" : \", \");\n }\n }\n return out.append(']').toString();\n}\n</code></pre>\n\n<p>Points to note:</p>\n\n<ul>\n<li>When concatenating so many strings, you really need to use a <code>StringBuilder</code>. Repeated <code>string + string</code> would create a temporary string each time.</li>\n<li>Your output is buggy: you drop every eighth word, replacing it with a newline.</li>\n<li>Be careful with edge cases: your code crashes when <code>words</code> is empty.</li>\n<li>Try to structure your code so it's obvious that certain properties hold true. For example, in my solution, you can see that every word gets printed (because if <code>.hasNext()</code> is true, the next word will get appended). You can also see that every word except the last word is followed by a delimiter (either newline or comma).</li>\n<li>Avoid cryptically named variables like <code>x</code> and <code>y</code>. In fact, you don't even use <code>y</code>.</li>\n<li>Naming your result <code>wordz</code> when there's another variable named <code>words</code> makes the code a pain to read.</li>\n</ul>\n\n<p>Finally:</p>\n\n<pre><code>public static void main(String[] args) throws FileNotFoundException{\n String word = input(\"Enter the word or words you would like to be processed\");\n List<String> anagrams = anagramsInFile(word, new File(\"words.txt\"));\n display(String.format(\"The word %s has %d matches. They are:\\n\\n%s\",\n word, anagrams.size(), formatOutput(anagrams)));\n}\n\nprivate static String input(String prompt) {\n return JOptionPane.showInputDialog(null, prompt);\n}\n\nprivate static void display(String message) {\n JOptionPane.showMessageDialog(null, message);\n}\n</code></pre>\n\n<p>Observations:</p>\n\n<ul>\n<li>I've decomposed the work differently. There's <code>input()</code> and <code>display()</code>, which are analogous to each other, and encapsulate the Swing UI. (If you ever want to convert the program to work in the text console, you just modify those functions.)</li>\n<li>More importantly, you can now see at a glance what the whole program does just by looking at <code>main()</code>. Note that all string constants are there as well: the prompt, the filename, and the output.</li>\n<li>Don't declare any more variables than you need to. If possible, when you declare variables, assign them in the same statement.</li>\n<li>Use <code>String.format()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T08:58:40.963",
"Id": "51454",
"Score": "0",
"body": "Thanks a lot, Im going to go through my program again and see what I can change now. I just need to read up on some of the functions you used there. I will add the reformed code when Im done.\nAnd yeah I also picked up that I didn't need `k`, but only this morning.\nAnd about the declarations I actually generally do not predeclare them but NetBeans suggests to split the declaration and initialization! So I thought it was how it was supposed to be.\nThanks of the detailed reply, its really appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:07:27.563",
"Id": "51460",
"Score": "0",
"body": "out.append((++wordsPrinted % 8 == 0) ? \"\\n\" : \", \"); \n\nIs this a kind of If statement? \n`if(worrdsPrinte%8==0){\n out.append(\"\\n\");\n }else{out.append(\", \");}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:20:14.927",
"Id": "51464",
"Score": "0",
"body": "The ternary operator is like an if-else, but for containing expressions rather than statements. Not only is `if (...) { ... } else { ... }` more verbose, it doesn't convey as effectively the sense that that statement is all about appending _something_ to `out` no matter what."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:25:07.000",
"Id": "51467",
"Score": "0",
"body": "Ok thanks, also I wanted to know aboou the if statement:\n`if (w.hasNext()) {`\nIs it needed? doesnt the `while loop` already check if `w.hasNext`? \n\nThank you for your patience, and excuse my ignorance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:32:08.027",
"Id": "51469",
"Score": "0",
"body": "Nevermind, I missed the `out.append(w.next());` would iterate the position."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:19:54.503",
"Id": "51473",
"Score": "0",
"body": "Should I post my revised code in a new question or as answer here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:56:58.127",
"Id": "51492",
"Score": "0",
"body": "If you want another critique of your revised code, please post a new question, and mention the original question in it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T01:57:13.697",
"Id": "32215",
"ParentId": "32204",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "32215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T22:13:04.470",
"Id": "32204",
"Score": "6",
"Tags": [
"java",
"optimization",
"array"
],
"Title": "Anagrams for a given input"
}
|
32204
|
<p>This is a simple console menu that just holds a main menu and a few menu "buttons" (numbers and titles which the user has to enter for the button to do its action). It does not need submenus or more complicated input handling.</p>
<p>I went with an object-oriented approach and defined three classes: <code>Menu</code>, <code>Button</code>, and <code>Controller</code>. The <code>Menu</code> initialises with a name and a list of menu buttons.</p>
<pre><code>class Menu(object):
"""Base class for the menu"""
def __init__(self, name, buttons):
# Initialize values
self.name = name
self.buttons = buttons
def display(self):
"""Displaying the menu alongside the navigation elements"""
# Display menu name
print self.name
# Display menu buttons
for button in self.buttons:
print " ", button.nav, button.name
# Wait for user input
self.userInput()
def userInput(self):
"""Method to check and act upon user's input"""
# This holds the amount of errors for the
# navigation element to input comparison.
errSel = 0
inputSel = raw_input("Enter selection> ")
for button in self.buttons:
# If input equals to button's navigation element
if inputSel == str(button.nav):
# Do the button's function
button.do()
# If input != navigation element
else:
# Increase "error on selection" by one, for
# counting the errors and checking their
# amount against the total number of
# buttons. If greater to or equal that means
# no elements were selected.
# In that case show error and try again
errSel += 1
# No usable input, try again
if errSel >= len(self.buttons):
print "Error on selection; try again."
</code></pre>
<p>The <code>Button</code> class is accepting a name, a function and a navigation element (the number you have to press for it to do the button's action):</p>
<pre><code>class Button(object):
"""Base class for menu buttons"""
def __init__(self, name, func, nav):
# Initialize values
self.name = name
# Function associated with button
self.func = func
# Navigation element; number which user has to enter to do button action
self.nav = nav
def do(self):
# Do the button's function
self.func()
</code></pre>
<p>Finally, the Controller. Did I do it the right way? I mean it works but having that while loop cycling with only the <code>raw_input()</code> function stopping it from spamming infinite messages - is that correct or should I write something that prevents the while loop while a menu was already displayed and is awaiting user input?</p>
<pre><code>class Controller(object):
def __init__(self, menu):
# Initialize values
self.menu = menu
# Start menu displaying / cycling
self.cycle()
def cycle(self):
"""Method for displaying / cycling through the menus"""
while True:
# Display menu and redisplay after button's function completes
# Is this right? Will this loop correctly and never interfere
# with raw_input()?
self.menu.display()
</code></pre>
<p>Finally, the code that puts it all together:</p>
<pre><code>import sys
def main():
mainMenuButtonName = Button("Show name", showName, 1)
mainMenuButtonVersion = Button("Show version", showVersion, 2)
mainMenuButtonAbout = Button("Show about", showAbout, 3)
mainMenuButtonQuit = Button("Quit", quit, 0)
mainMenuButtons = [mainMenuButtonName, mainMenuButtonVersion, mainMenuButtonAbout, mainMenuButtonQuit]
mainMenu = Menu("Main menu", mainMenuButtons)
controller = Controller(mainMenu)
controller.cycle()
def showName():
print "My name is..."
def showVersion():
print "My version is 0.1"
def showAbout():
print "I am a demo app for testing menus"
def quit():
sys.exit(0)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>I think display() and userInput() would be clearer if you did it like this:</p>\n\n<pre><code>def display(self):\n \"\"\"\n Display the menu alongside the navigation elements\n \"\"\"\n response = None\n while response is None:\n # Display menu buttons\n for button in self.menu:\n print \" \", button.nav, button.name\n\n # Wait for user input\n response = self.userInput()\n\ndef userInput(self):\n \"\"\"\n Method to check and act upon user's input\n \"\"\"\n inputSel = raw_input(\"Enter selection> \")\n for button in self.menu:\n # If input equals to button's navigation element\n if inputSel == str(button.nav):\n button.do()\n return inputSel\n\n return None\n</code></pre>\n\n<p>So display() keeps showing the menu as long as userInput() returns None. userInput() returns None if the user's input doesn't match a button, or the inputSel value if it does match.</p>\n\n<p>I think the way the Controller loops is fine. The program will always stop when it gets to raw_input() and read stdin until the user hits ENTER or RETURN. That's what raw_input() does.</p>\n\n<p>You're managing your buttons as a list, which means you have to scan the whole list until you find the navigation element the user selected. If you put them in a dict, you can simply use the user's input to index directly into the structure and select the correct button (or determine that the user's selection is invalid). However, you still want them as a list for display because you can't control the order in which entries are pulled from a dictionary and I think you want your menu to display in the same order every time. That needs a list.</p>\n\n<p>I would suggest the following for the constructor for the Display class. We're going to pass in a list so it's easy to define, and we'll keep the list, but we'll also have the class internally turn that list into a dict so it can more easily find the user's input on each selection.</p>\n\n<pre><code>class Display\n def __init__(self, menu):\n self.menu_list = menu\n self.menu_dict = {}\n # Initialise values\n for button in menu:\n self.menu_dict[button.nav] = button\n</code></pre>\n\n<p>With the simplification in userInput() and display() above, the shouldCycle member goes away. Now, with the menu defined internally as a dictionary (self.menu_dict) and as a list (self.menu_list), display() and userInput() will look like this:</p>\n\n<pre><code>def display(self):\n \"\"\"\n Display the menu alongside the navigation elements\n \"\"\"\n response = None\n while response is None:\n # Display menu buttons -- use the list so we get the same\n # order every time.\n for button in self.menu_list:\n print \" \", button.nav, button.name\n\n # Wait for user input\n response = self.userInput()\n\ndef userInput(self):\n \"\"\"\n Method to check and act upon user's input\n \"\"\"\n inputSel = raw_input(\"Enter selection> \")\n try:\n # Here we use the dictionary for ease of lookup\n button = self.menu_dict[int(inputSel)]\n except KeyError:\n # The user's selection didn't match any of the button.nav\n # values, so we got a KeyError exception on the dictionary\n return None\n\n button.do()\n return inputSel\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T02:51:00.543",
"Id": "48841",
"ParentId": "32207",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T23:45:35.043",
"Id": "32207",
"Score": "3",
"Tags": [
"python",
"console"
],
"Title": "Console user main menu"
}
|
32207
|
<p>Please feel free to be as harsh as possible.</p>
<p><strong>Implementation file:</strong></p>
<pre><code>#include "Stack.h"
#include <iostream>
using namespace std;
// Initializes an empty Stack.
Stack::Stack() {
this->head = new node();
this->num_elements = 0;
// set default values for head
this->head->next = 0;
this->head->value = 0;
}
// Cleans up memory before the Stack's destruction.
Stack::~Stack() {
while (this->head->next != 0) {
pop();
}
delete this->head;
}
// Pushes value onto the top of the stack.
void Stack::push(int value) {
node* newTopNode = new node();
newTopNode->value = value;
// currentTopNode may be null if stack is empty
node* currentTopNode = this->head->next;
this->head->next = newTopNode;
newTopNode->next = currentTopNode;
this->num_elements++;
}
// Pops the top-most value off the stack and returns its value.
int Stack::pop() {
if (this->head->next == NULL) {
cout << "\nIllegal State Exception: You cannot pop an empty stack." << endl;
return 0;
} else {
node* topNodeToRemove = this->head->next;
// save the value of the node before deleting it
int topNodeValue = topNodeToRemove->value;
this->head->next = this->head->next->next;
delete topNodeToRemove;
this->num_elements--;
return topNodeValue;
}
}
// Returns the value at the top of the stack. Works similarly to pop(), but
// retains the internal structure of the stack. That is, it does not remove
// the top-most element.
int Stack::getTopElement() const {
if (this->head->next == NULL) {
cout << "\nIllegal State Exception: You cannot get the top element of an empty stack." << endl;
return 0;
} else {
return this->head->next->value;
}
}
// Returns the number of elements currently in the stack.
int Stack::size() const {
return this->num_elements;
}
</code></pre>
<p><strong>Header file:</strong></p>
<pre><code>#ifndef STACK_H_
#define STACK_H_
class Stack {
public:
Stack();
~Stack();
void push(int);
int pop();
int getTopElement() const;
int size() const;
private:
struct node {
int value;
node* next;
};
node* head;
int num_elements;
};
#endif // STACK_H_
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Do not use <code>using namespace std</code></a>.</p></li>\n<li><p>In the constructor and <code>push()</code>, it looks like you're calling <code>new</code> on a function. It should be <code>node</code>.</p></li>\n<li><p>Prefer <code>nullptr</code> to <code>NULL</code> and <code>0</code> for the node pointers if you're using C++11. Otherwise, you should choose either <code>NULL</code> or <code>0</code> for node pointers and keep it consistent.</p></li>\n<li><p>You don't need <code>this-></code> everywhere as the code already has the current object in scope.</p></li>\n<li><p>It's needless to call <code>pop()</code> in the destructor. For one thing, <code>pop()</code> returns a value. You should just be using <code>delete</code>.</p>\n\n<p>Instead, have <code>head</code> point to the first element, loop through the stack (stopping when <code>NULL</code> is hit) and call <code>delete</code> on each node. With this, you won't need to <code>delete</code> <code>head</code> at the end.</p></li>\n<li><p><code>pop()</code> and <code>getTopElement()</code> might be best as <code>void</code>. Here, a <code>0</code> is returned if the list is empty. Sure, no errors happening there. But then the calling code will take it as an element <code>0</code>, never knowing whether or not the stack is empty. If you make them <code>void</code>, you can simply <code>return</code> if the stack is empty. As for retrieving an element, that's why you have <code>getTopElement()</code>. Once you get the value with <code>getTopElement()</code>, call <code>pop()</code> after that.</p>\n\n<p>Regarding checking for an empty stack, you could make a <code>public</code> <code>empty()</code> function for calling code. The two functions above should still check for an empty stack, but containers like this usually utilizes such a function. This could go in the header:</p>\n\n<pre><code>bool empty() const { return num_elements == 0; }\n</code></pre></li>\n<li><p>You could make your class more useful by using templates. This will allow you to populate the stack with any type instead of just <code>int</code>s.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T02:29:44.797",
"Id": "51431",
"Score": "0",
"body": "Thank you Jamal for your suggestions. Much appreciated! 1 question: how would I get the top element if both pop and getTopElement are set to void? I don't get it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T02:34:35.547",
"Id": "51432",
"Score": "0",
"body": "@628496: Actually, you can still have `top()` return a value. It's up to you. If you want to make it `void` anyway, then you would pass in a variable from the calling code by reference. `pop()` should still be `void`. Have a look at [std::stack](http://en.cppreference.com/w/cpp/container/stack)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T02:41:33.930",
"Id": "51435",
"Score": "0",
"body": "@628496: The link provided will give you much info on that. Essentially, it's discouraged because it can cause name-clashing (bugs). For instance, if you create your own function with the same name and parameter types as a function in the STL, the compiler will be confused and you'll get undefined behavior. I had to break this habit when I first started, too. :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T00:44:24.997",
"Id": "32211",
"ParentId": "32210",
"Score": "6"
}
},
{
"body": "<p>You are using a Sentinel at the beginning of the list, but this is not really needed.</p>\n\n<p>Sentinel are very useful for double linked list but don't make things easier for singly linked list. Your code will be simlified by removing it.</p>\n\n<p>You can make your code simpler by moving the initialization of the node into its constructor.</p>\n\n<p>The destructor can be made simpler just be running accross the nodes and deleting them. There is no point in the extra work in pop() to keep the object in a valid state.</p>\n\n<pre><code>class Stack\n{\n struct Node\n {\n int value;\n Node* next;\n Node(int v, Node* n): value(v), next(n) {}\n };\n\n Node* head;\n int size;\n\n Stack() :head(NULL), size(0) {}\n void push(int v) { head = new Node(v, head);++size;}\n void pop() { Node* old = head; head = old->next;delete old;--size;}\n bool empty() { return size == 0;}\n // Calling this when empty() is true is undefined behavior.\n // Make sure you know that the list is valid before calling.\n int top() { return head->value;}\n int size() { return size;}\n ~Stack()\n {\n for(Node* next = head;next;)\n {\n Node* old = next;\n next = old->next;\n delete old;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:18:02.883",
"Id": "32220",
"ParentId": "32210",
"Score": "5"
}
},
{
"body": "<p>I see it has been some time since you asked this question.\nI found out that your implementation of <code>pop()</code> function is deleting top element from stack but does not assign second as new top.\nHere is my suggestion on how to implement this:</p>\n\n<pre><code>int Stack::pop() {\n if (head->next == NULL) {\n std::cout << \"\\nIllegal State Exception: You cannot pop an empty stack.\" << std::endl;\n return 0;\n }\n int val = head->next->value; // Value to return\n node *newTopElemen = head->next->next; // Second element from top assigned to temp\n delete head->next; // Deleting a pointer to old top element\n head->next = newTopElemen; // Second element from top is now first element\n num_elements--;\n return val;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-04T19:22:10.013",
"Id": "221509",
"Score": "1",
"body": "`this->head->next = this->head->next->next;` assigns second as the new top in the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-04T17:07:38.503",
"Id": "118901",
"ParentId": "32210",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32211",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T00:28:55.017",
"Id": "32210",
"Score": "7",
"Tags": [
"c++",
"linked-list",
"stack"
],
"Title": "Linked stack implementation in C++"
}
|
32210
|
<p>I would like to do these actions step by step:</p>
<ol>
<li>first DB update</li>
<li>copy file</li>
<li>unlink file</li>
<li>second DB update</li>
</ol>
<p>It is working, but I don't know if my code is correct/valid:</p>
<pre><code>$update1 = $DB->query("UPDATE...");
if ($update1)
{
if (copy("..."))
{
if (unlink("..."))
{
$update2 = $DB->query("UPDATE ...");
}
}
}
</code></pre>
<p>Is it possible to use if statement this way?</p>
<p>I found that it is usually used with <em>PHP operators</em> and <em>PHP MySQL select</em>, for example:</p>
<pre><code>$select = $DB->row("SELECT number...");
if ($select->number == 2) {
...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:17:49.643",
"Id": "51452",
"Score": "0",
"body": "What class is `$DB` an instance of..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T12:23:19.027",
"Id": "51478",
"Score": "0",
"body": "`$DB` is global variable, but that's not important, it was only an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T12:45:39.310",
"Id": "51480",
"Score": "0",
"body": "No, that's not what I was asking... Though globals are bad practice, and that _is_ important to keep in mind. I was asking what `$DB` actually _IS_. Is it a `PDO` instance, is it `MySQLi`? or some wrapper class? because `$DB->row('select...');` does not make sense to me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T21:02:51.543",
"Id": "51546",
"Score": "0",
"body": "It is `MySQLi`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T11:14:19.677",
"Id": "51574",
"Score": "1",
"body": "Well then your code just can't work! [There is no `row` method](http://www.php.net/manual/en/class.mysqli.php), not on MySQLi itself, not on the stmt, or result classes either... it's hard to review code, without actually seeing the real code/working code first"
}
] |
[
{
"body": "<blockquote>\n <p>Is it possible to use if statement this way?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>Whether it is a good style depends on other factors.</p>\n\n<p>Let us look at a few alternatives. First, your code (with cuddled braces):</p>\n\n<pre><code>if ( $update1 ) {\n if ( copy( \"...\" ) ) {\n if ( unlink( \"...\" ) ) {\n $update2 = $DB->query( \"UPDATE ...\" );\n }\n }\n}\n</code></pre>\n\n<p>Then the same code using logical <em>AND</em> (&&).</p>\n\n<pre><code>if ( $update1 && copy( \"...\" ) && unlink( \"...\" ) ) {\n $update2 = $DB->query( \"UPDATE ...\" );\n}\n</code></pre>\n\n<p>And another one without the braces <code>{}</code>;</p>\n\n<pre><code>if ( $update1 && copy( \"...\" ) && unlink( \"...\" ) )\n $update2 = $DB->query( \"UPDATE ...\" );\n</code></pre>\n\n<p>And finally, an example that doesn't use <code>if</code>.</p>\n\n<pre><code>$update1\n && copy( '...' )\n && unlink( '...' ) )\n && $update2 = $DB->query( \"UPDATE ...\" );\n</code></pre>\n\n<p>All these examples perform the same operations.</p>\n\n<p>If the <em>...</em> stuff is long, the latter methods can get very wide conditionals making it difficult to read the code to see what is going on.</p>\n\n<pre><code>if ( $update1 && copy( 'a/very/long/source/path', 'a/very/long/destination/path' ) && unlink( 'a/very/long/source/path' ) )\n $update2 = $DB->query( \"UPDATE ...\" );\n</code></pre>\n\n<p>You could rewrite it like this:</p>\n\n<pre><code>if ( $update1\n && copy( 'a/very/long/source/path', 'a/very/long/destination/path' )\n && unlink( 'a/very/long/source/path' ) )\n $update2 = $DB->query( \"UPDATE ...\" );\n</code></pre>\n\n<p>But it looks little clunky. It is hard to see where the conditional ends.</p>\n\n<p>The last style makes this prettier:</p>\n\n<pre><code>$update1\n && copy( 'a/very/long/source/path', 'a/very/long/destination/path' )\n && unlink( 'a/very/long/source/path' ) )\n && $update2 = $DB->query( \"UPDATE ...\" );\n</code></pre>\n\n<p>I do not care for this style, but it looks pretty and it tells you exactly what is happening at a glance.</p>\n\n<p>One problem with most of the alternatives to the first method is debugging and maintenance.</p>\n\n<p>If I want to log the unlink error is some special way I can do this in the first method:</p>\n\n<pre><code>if ( $update1 ) {\n if ( copy( \"...\" ) ) {\n if ( unlink( \"...\" ) ) {\n $update2 = $DB->query( \"UPDATE ...\" );\n } else {\n log_unlink_error( '...' );\n }\n }\n}\n</code></pre>\n\n<p>To quickly add that code to the other methods described here, may require more rewriting.</p>\n\n<p>So, in this case, your style for handling multiple conditions might depend on the age of your code and how much testing you expect to be doing.</p>\n\n<ul>\n<li><p>If it is well tested and you never need to edit it, then one of the alternatives is fine <em>if</em> you use that style consistently throughout all your code.</p></li>\n<li><p>If this is new code, write it out the long way. It may be easier to test and maintain.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T17:06:44.947",
"Id": "32332",
"ParentId": "32212",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32332",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T01:01:17.917",
"Id": "32212",
"Score": "3",
"Tags": [
"php"
],
"Title": "Using if statement in PHP"
}
|
32212
|
<p>So I have this Pygame 3.3.2 code of 2 classes. I tried to make it as simpler as possible, but ofcourse to show the problems I have with thedesign.</p>
<pre><code>import pygame
import sys
class MainWindow(object):
''' Handles main surface '''
def __init__(self, width, height):
self.WIDTH = width
self.HEIGHT = height
self.SURFACE = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Placeholder')
self.draw_rect = DrawRect(self) # <-- this line looks really strange to me
def update(self):
pygame.display.update()
class DrawRect(object):
''' Draw rect on the surface '''
def __init__(self, window):
self.window = window
self.my_rect = pygame.Rect((50, 50), (50, 50))
def update(self):
pygame.draw.rect(self.window.SURFACE, (0, 0, 255), self.my_rect)
def main():
pygame.init()
Window = MainWindow(900, 500)
Draw = DrawRect(Window)
Window.draw_rect.update() # <-- this looks very missleading to me
Window.update()
main()
</code></pre>
<p>According to <a href="https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance">StackOverflow question</a> -
If <code>B</code> want to expose the complete interface of <code>A</code> - Indicates <code>Inheritance</code>.
If <code>B</code> want to expose only some part of <code>A</code> - Indicates <code>Composition</code>.</p>
<p>I don't need all of the content of the <code>MainWindow</code> so I use composition.</p>
<p>The naming conventions and specialy the line <code>Window.draw_rect.update()</code> in the <code>main()</code> function.</p>
<p>Later on, I will use a class <code>Player</code>, do I need to put something like <code>self.player = Player(self)</code>, inside the <code>MainWindow __init__</code> method?
Let's say I want to use the <code>width, height</code> of the window to perform some method for positioning the Player.</p>
<p>Is there a better way to write this code, to look profesional and clear?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T23:03:43.953",
"Id": "51552",
"Score": "0",
"body": "I suspect I'm doing a wrong object composition."
}
] |
[
{
"body": "<p>When you're composing, think about how you want to access the components you're putting together. In this example, you are asking the window to include a DrawRect that always draws to a 50 x 50 pixsel square. Does the window really need to include that rect? The DrawRect has all the info it needs -- you add the window reference in the constructor -- so what's the rationale for including it in the window? In the example code you create a DrawRect outside the window, and another inside the Window - and then never update the independent DrawRect so it never shows up. This seems less like composition and more like gluing things together which don't need to be connected.</p>\n\n<p>Consider the alternative:</p>\n\n<pre><code>def main():\n pygame.init()\n\n Window = MainWindow(900, 500)\n ## removing the self.draw_rect field from __init__\n\n Rect1 = DrawRect(Window)\n Rect1.my_rect = pyGame.Rect((0,0), (50,50))\n\n Rect2 = DrawRect(Window)\n Rect2.my_rect = pyGame.Rect((60,60), (50,50))\n\n Rect1.update()\n Rect2.update()\n Window.update()\n</code></pre>\n\n<p>Here the DrawRects are completely independent of the Window, which seems like what you'd want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T00:09:00.367",
"Id": "51598",
"Score": "0",
"body": "I want to take few attributes from the Window class, but I suspect my given example is not the correct stylist way to do it, it is working, but I don't see it as a good design. I cant's seem to find a good topic to read about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T00:11:35.777",
"Id": "51599",
"Score": "0",
"body": "I hit enter too early; recheck. Basically, it seems like the DrawRects and Window don't need to be connected in any way other than the need for the rect to get the surface (btw, it would be cleaner to init the DrawRects with the surface directly, since that's all they care about...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T00:26:24.917",
"Id": "51600",
"Score": "0",
"body": "This seems constructive but, when I instance DrawRect, I put the instance of the Window, as a prameter to the instance of DrawRect. What if I composit from multiple base classes in the DrawRect class. Then I would include all of those classes as a parameter when I instance DrawRect. Doesn't this makes the instantiation long and less readable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T19:28:06.407",
"Id": "51632",
"Score": "0",
"body": "You get to control the constructor of the DrawRect, so you can decide how much or how little you want to require for the constructor. In general you want to require the absolute minimum information; in the example, passing in the surface is all you'd need to do drawing and DrawRect doesn't care about, for example, the window title, or whether it's in a main window or a secondary window, etc. Always design so that class X knows as little as possible about class Y and vice-versa. Passing in the contents explicitly makes things more future proof, if slightly wordier"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T00:04:22.590",
"Id": "32308",
"ParentId": "32213",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T01:50:53.747",
"Id": "32213",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"pygame"
],
"Title": "Object Composition"
}
|
32213
|
<p>I was trying to solve a challenge. The execution time should not exceed 5s, but for some value my code took longer. I want to know if I can optimize my code for performance.</p>
<pre><code>public class Solution {
int n;long k;int count=0;
public static void main(String[] args) {
new Solution().readInput();
}
public void readInput(){
try {
BufferedReader k=new BufferedReader(new InputStreamReader(new FileInputStream("/home/tittanium/NetBeansProjects/HackerRank/src/input.txt")));
parseNK(k.readLine());
readAndParse(k.readLine());
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Solution.class.getName()).log(Level.SEVERE, null, ex);
}
}
int cities[];
public void readAndParse(String line){
int i1=0;
cities=new int[n];
StringTokenizer st = new StringTokenizer(line," ");
while (st.hasMoreElements()) {
cities[i1]=Integer.parseInt(st.nextToken());
i1++;
}
for(int i=0;i<n;i++){
final int x=i;
new Runnable() {
@Override
public void run() {
for(int j=x;j<n;j++){
final int a=cities[x];
final int b=cities[j];
count = (a>b ? a-b : b-a) == k ? count+1 : count;
}
}
}.run();
}
}
public void parseNK(String line){
n= Integer.parseInt(line.split(" ")[0]);
k= Integer.parseInt(line.split(" ")[1]);
}
}
</code></pre>
<p>This question is trying to solve a problem. I want to know if any changes can be made to make the program run faster.
This is what I am trying to complete. <a href="https://www.hackerrank.com/challenges/pairs" rel="nofollow">challenge</a></p>
|
[] |
[
{
"body": "<p>What exactly your code does? It is not obvious, maybe you should name your variables better. Specially <code>count = (a>b ? a-b : b-a) == k ? count+1 : count;</code>\nWhat <code>a</code> anb <code>b</code> is? <code>count</code> of what?</p>\n\n<p>Instead of splitting line twice. Split it once and reuse the array. It also reduce count of space literal used.</p>\n\n<pre><code>String[] splittedLine = line.split(\" \");\nn= Integer.parseInt(splittedLine[0]);\n k= Integer.parseInt(splittedLine[1]);\n</code></pre>\n\n<p>And you are trying to use thread but you are not starting any. You are just wraping your implementation in <code>Runnable</code> object. See <a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html\">http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html</a> for Thread useage examples.\nMaybe you dont need threads at all, but i cant tell without knowing what exactly you are trying to solve. Running many threads may result into slower code because of switching from one thread to another and their creating take some time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T06:05:31.100",
"Id": "32223",
"ParentId": "32217",
"Score": "5"
}
},
{
"body": "<p>Before you go for performance, you really need to focus on clarity and correctness.</p>\n\n<p>First of all, what is your code trying to accomplish? After staring at it for five minutes, I'm guessing that it takes a list of locations of <em>n</em> cities along a line, and tries to count the number of pairs of cities that are distance <em>k</em> apart. Stating that in the question would have been appreciated, and stating that in JavaDoc would be even better. Your class name (<code>Solution</code>) is absolutely unhelpful. Your method names <code>readInput()</code> and <code>readAndParse()</code> are downright misleading — they do much more than that!</p>\n\n<p><strike>Another major problem is that you are using threads completely incorrectly. You're nuts to spawn <em>n</em> threads, because:</p>\n\n<ul>\n<li>There is bookkeeping overhead involved for each thread.</li>\n<li>The bookkeeping and context-switching overhead probably vastly outweighs the amount of real work done by each thread.</li>\n<li>The number of threads should be commensurate with the number of CPU cores available; any more than that just hurts performance.</li>\n<li>The problem you are trying to solve isn't really that parallelizable anyway.</li>\n</ul>\n\n<p>That last point deserves special mention. You are going to get an <strong>incorrect</strong> result because you don't understand threading. All of your threads want to read and increment <code>count</code>. There will be a race condition. Suppose that two threads both want to increment <code>count</code> at roughly the same time, such that the first thread reads a value for <code>count</code> (say it's 3), then the second thread reads <code>count</code> (also 3), then the first thread increments <code>count</code> (to 4), and finally the second thread also increments count (also to 4). In the end, <code>count</code> will be 4, even though it should have been 5.</p>\n\n<p>To prevent such a race condition, all reads and writes to <code>count</code> would need to be protected by a lock. But then, all the threads would end up queuing in contention for that lock anyway, defeating the purpose of threading in the first place.</p>\n\n<p>In summary, focus on clarity and correctness, and forget about threading.</strike></p>\n\n<p><strong>Edit:</strong> Sorry, I mistook your <code>Runnable</code> for a <code>Thread</code>. There's no reason to do <code>(new Runnable() { ... }).run()</code>. You should get rid of the <code>Runnable</code> then, and just execute its code normally.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T06:14:37.097",
"Id": "51445",
"Score": "0",
"body": "I've modified the question title to reflect what I think the problem is that you're trying to solve, because this site would be a mess if all questions had non-descriptive titles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:14:28.470",
"Id": "51451",
"Score": "0",
"body": "Thank you for your answer, you have correctly identified my question (problem). But I've said that no threading is possible. I have to manage by replacing code for short processing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T06:08:01.253",
"Id": "32224",
"ParentId": "32217",
"Score": "4"
}
},
{
"body": "<p>Besides the stylistic issues I mentioned in my other response, your problem is that you are using an O(<em>n</em><sup>2</sup>) algorithm. You can easily see that your code is O(<em>n</em><sup>2</sup>) because you have two levels of for-loops: the outer <code>i</code> loop taking <code>n</code> iterations, and the inner <code>j</code> loop taking an average of <code>n / 2</code> iterations.</p>\n\n<p>You should be able do it in O(<em>n</em>) with the help of a data structure. Put all your numbers into a <code>HashSet</code>. Then iterate through the elements, and check whether <code>element + k</code> is also in the set. There are <em>n</em> elements, and each check takes constant time, giving you an O(<em>n</em>) algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:12:53.367",
"Id": "51527",
"Score": "0",
"body": "Thank you very much, By your solution I've completed my task with maximum time 0.25 seconds :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:52:47.813",
"Id": "32229",
"ParentId": "32217",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T03:32:56.890",
"Id": "32217",
"Score": "1",
"Tags": [
"java",
"optimization",
"performance",
"multithreading",
"programming-challenge"
],
"Title": "Optimize calculation of distances between pairs of points"
}
|
32217
|
<p>I have the following method that's in a common library. I want to know how to write it better, but mostly, I want to know how to think about this better so I don't end up with code like this.</p>
<pre><code>public virtual void PrintConsoleAndLog(string verboseMessage = null, Exception e = null,
OnErrorEventsArgs.ShowExceptionLevel exceptionLevel =
OnErrorEventsArgs.ShowExceptionLevel.Error)
{
switch (exceptionLevel)
{
case OnErrorEventsArgs.ShowExceptionLevel.Info:
if (e == null)
{
Logger.Info("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
Console.WriteLine("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
}
else
{
if (verboseMessage == null)
{
Logger.Info(String.Format("\n[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace);
}
else
{
Logger.Info(String.Format("\n[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace);
}
}
break;
case OnErrorEventsArgs.ShowExceptionLevel.Debug:
if (e == null)
{
Logger.Debug("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
Console.WriteLine("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
}
else
{
if (verboseMessage == null)
{
Logger.Debug(String.Format("\n[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace);
}
else
{
Logger.Debug(String.Format("\n[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace);
}
}
break;
// note that OnErrorEventsArgs.ShowExceptionLevel.Error will end up here also
default:
if (e == null)
{
Logger.Error("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
Console.WriteLine("\n[{0}] {1}", DateTime.Now.ToShortTimeString(), verboseMessage);
}
else
{
if (verboseMessage == null)
{
Logger.Error(String.Format("\n[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}]Base Exception: {1}\n\nStacktrace: {2}",
DateTime.Now.ToShortTimeString(),
e.GetBaseException(), e.StackTrace);
}
else
{
Logger.Error(String.Format("\n[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace));
Console.WriteLine("[{0}] Error: {1}\n\nBase Exception: {2}\n\nStacktrace: {3}",
DateTime.Now.ToShortTimeString(), verboseMessage,
e.GetBaseException(), e.StackTrace);
}
}
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:28:12.550",
"Id": "51440",
"Score": "5",
"body": "Which logger are you using? Instead of doing logging everything twice (once with your logger and once to console) can't you just reconfigure your logger to also write to the console? ie: log4net.Appender.ConsoleAppender && log4net.Appender.RollingFileAppender"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:36:27.870",
"Id": "51442",
"Score": "0",
"body": "I'm using Nlog - I'm not sure if that's possible with it but I will look into it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:44:24.950",
"Id": "51443",
"Score": "2",
"body": "It is, look [here](https://github.com/nlog/nlog/wiki/Tutorial) under multiple targets"
}
] |
[
{
"body": "<p>In the comments it was already mentioned to configure the logger to determine the logging target which avoids logging everything twice.</p>\n\n<p>Another thing to improve: Eliminate duplicate code (statements and expressions).\nFrom looking at the code there are many things which are repeated over and over again</p>\n\n<ol>\n<li>Remove the time stamps. NLog can do that for you.\n<ul>\n<li>Especially <code>ShortTimeString</code> usually omits the seconds (at least in most standard locales I have seen). Not sure what kind of application you have but for error logging I would assume that it is usually better to have the timestamp as accurate as possible.</li>\n</ul></li>\n<li>You log basically three types of messages:\n<ul>\n<li>Something when you do not have an exception object</li>\n<li>Base Exception and Stacktrace</li>\n<li>Base Exception and Stacktrace with extra error message </li>\n</ul></li>\n</ol>\n\n<p>So: build them first and then simply decide the logging level. Something like this:</p>\n\n<pre><code>private const string NOMESSAGE = \"<NOMESSAGE>\";\n\npublic virtual void PrintConsoleAndLog(string verboseMessage = null, Exception e = null,\n OnErrorEventsArgs.ShowExceptionLevel exceptionLevel =\n OnErrorEventsArgs.ShowExceptionLevel.Error)\n{\n var message = verboseMessage ?? NOMESSAGE;\n if (e != null)\n {\n var additionalMessage = GetAdditionalFormattedMessage(verboseMessage);\n message = string.Format(\"{0}Base Exception: {1}\\n\\nStacktrace: {2}\", \n additionalMessage, e.GetBaseException(), e.StackTrace);\n }\n switch (exceptionLevel)\n {\n case OnErrorEventsArgs.ShowExceptionLevel.Info:\n Logger.Info(message);\n break;\n case OnErrorEventsArgs.ShowExceptionLevel.Debug:\n Logger.Debug(message);\n break;\n case OnErrorEventsArgs.ShowExceptionLevel.Error:\n default:\n Logger.Error(message);\n break;\n }\n}\n\nprivate string GetAdditionalFormattedMessage(string verboseMessage)\n{\n return verboseMessage != null ? string.Format(\"Error: {0}\\n\\n\", verboseMessage) : \"\";\n}\n</code></pre>\n\n<p>Looks slightly cleaner to me. If you require the additional timestamp then it should be easy enough to add.</p>\n\n<p><strong>Update</strong>: Incorporated suggestions from comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:34:03.307",
"Id": "51519",
"Score": "4",
"body": "OP indicated he uses NLog, which has a `Log (LogLevel, string)` overload. You could get rid of the switch as long as you had a way to convert from `OnErrorEventsArgs.ShowExceptionLevel` to the appropriate NLog `LogLevel` value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T05:38:40.757",
"Id": "51659",
"Score": "1",
"body": "I see a 'magic constant' (the string \"<NO MESSAGE>\") there: convert it to a constant. Also the creation of the `additionalMessage` should be refactored (i.e. move to a two-line methode) to give the method a constant level of abstraction."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:51:40.180",
"Id": "32228",
"ParentId": "32218",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "32228",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T04:48:49.710",
"Id": "32218",
"Score": "3",
"Tags": [
"c#",
"console",
"error-handling"
],
"Title": "Console printing and logging method for a common library"
}
|
32218
|
<p>I have a implementation of following code block,</p>
<pre><code>public class FileFormatConversion {
public static enum File_TYPES {
PDF, PNG, OTHERS, ALL
}
public static void processOtherFileType(String arg1) {
System.out.println("Other file output -- " + arg1 + " file");
}
public static void processPNGPDFALL(String arg1, String arg2) {
System.out
.println("General block for processing PDF/PNG or ALL other file format -- "
+ arg2
+ "\\"
+ arg1
+ " parameter validation/check file availability");
}
public static void processPDF(String arg1, String arg2) {
System.out.println("Block for processing PDF file -- " + arg2 + "\\"
+ arg1 + ".pdf");
}
public static void processALL(String arg1, String arg2) {
System.out.println("Block for processing ALL file types -- " + arg2
+ "\\" + arg1 + ".all");
}
public static void processPNGALL(String arg1, String arg2) {
System.out
.println("Common block for manipulating file formats such as PNG or ALL files");
}
/**
* @param args
*/
public static void main(String[] args) {
args = new String[3];
args[0] = "ALL";
args[1] = "fileName";
args[2] = "C:\\filePath";
File_TYPES fileFormatInput = File_TYPES.valueOf(args[0]);
if (File_TYPES.OTHERS == fileFormatInput) {
processOtherFileType(args[1]);
} else {
processPNGPDFALL(args[1], args[2]);
if (File_TYPES.ALL == fileFormatInput
|| File_TYPES.PNG == fileFormatInput)
processPNGALL(args[1], args[2]);
if (File_TYPES.ALL == fileFormatInput)
processALL(args[1], args[2]);
if (File_TYPES.PDF == fileFormatInput)
processPDF(args[1], args[2]);
}
System.out.println("Completed");
}
</code></pre>
<p>I might need to add more options in <code>ENUM</code> in future. so using if-else will make it complex while debugging/adding. Is there any better alternative way to improve this block - improve understandability/maintenance. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:33:55.413",
"Id": "51441",
"Score": "1",
"body": "Please provide a more concrete use case, with real working code, not pseudocode, so that we can better understand your problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:10:12.983",
"Id": "51449",
"Score": "0",
"body": "@200_success: i have updated the code block. though it is not exact snippet, i have added all required methods (with exact input/output parameters) in class to replicate the process involved. hope this is helpful"
}
] |
[
{
"body": "<p>To avoid the <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\">messy <code>switch</code> block</a>, you should probably create an interface or abstract class called <code>FileConversionHandler</code>:</p>\n\n<pre><code>public abstract class FileConversionHandler {\n public abstract void process(File f);\n}\n</code></pre>\n\n<p>Then, for each type of file, make a subclass that implements <code>process()</code> differently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T07:28:27.510",
"Id": "32227",
"ParentId": "32219",
"Score": "7"
}
},
{
"body": "<p>What is interesting about the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/File.html\" rel=\"nofollow noreferrer\">java.io.File</a> is that it is not final, which means that it can be subclassed to add behaviour. Object-Oriented Programming is all about behaviour, encapsulation, and information hiding. Often <code>switch</code> statements (or compounded <code>if-else</code> statements) can be replaced with a <a href=\"http://en.wikipedia.org/wiki/Command_pattern#Java\" rel=\"nofollow noreferrer\">command pattern</a>.</p>\n\n<p>The reason it isn't immediately apparent how this can be accomplished is because the code, as written, violates information hiding. The violation occurs when clients to the <code>File</code> class need to determine the extension themselves and then use the extension to determine the file type. Consider the following:</p>\n\n<pre><code>public class ImageFile extends java.io.File {\n public boolean isImageType( ImageType imageType ) {\n return getImageType().equals( imageType );\n }\n\n public ImageType getImageType() {\n String extension = \"OTHER\";\n String fileName = getName();\n\n int i = fileName.lastIndexOf('.');\n\n // Probably an issue here, for the reader to fix. What happens\n // when there is only a dot, but no characters after the dot?\n if (i > 0) {\n extension = fileName.substring(i+1).trim().toUpperCase();\n }\n\n return ImageType.valueOf( extension );\n }\n}\n</code></pre>\n\n<p>Note that <code>getImageType()</code> could use Apache Commons IO:</p>\n\n<pre><code> public ImageType getImageType() {\n // Make sure getExtension never returns null!\n return ImageType.valueOf( FilenameUtils.getExtension( getName() ).toUpperCase() );\n }\n</code></pre>\n\n<p>How the extension is parsed becomes an abstraction that the calling code uses, rather than implements. This keeps behaviour with its data, a key concept of OOP. (As an aside, even Apache Commons gets this wrong, as evidenced by the <code>FilenameUtils</code> class, which isn't a true class, because it has no attributes.)</p>\n\n<p>The answer from 200_success is almost correct. Ultimately, though, the FileConversionHandler would also need to know the file's extension, which unnecessarily imposes some constraints. </p>\n\n<p>You can now create an <code>ImageFileProcessor</code> interface and implementations, which uses the command pattern and the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern#Java\" rel=\"nofollow noreferrer\">factory pattern</a>.</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic ImageFileProcessorFactory {\n private static Map<ImageType, ImageFileProcessor> processors = new HashMap<>();\n\n static {\n // For processing PNG files...\n processors.put( ImageType.PNG, new PNGImageFileProcessor() );\n }\n\n public static ImageFileProcessor createProcessor( ImageFile imageFile ) {\n ImageFileProcessor ifp = processors.get( imageFile.getImageType() );\n ifp.setPrimaryFile( imageFile );\n return ifp;\n }\n}\n</code></pre>\n\n<p>You could change the factory above to allow for processing a specific combination of files by using MapEntry and SimpleEntry instances. See <a href=\"https://stackoverflow.com/a/11253710/59087\">this answer</a> for details. Whichever implementation is required, you'd need to define:</p>\n\n<pre><code>public interface ImageFileProcessor {\n public void setPrimaryFile( ImageFile primaryFile );\n public void process( ImageFile other );\n}\n</code></pre>\n\n<p>Then, the <code>PNGImageFileProcessor</code> becomes:</p>\n\n<pre><code>public class PNGImageFileProcessor extends AbstractImageFileProcessor {\n public void process( ImageFile other ) {\n // Process the PNG image.\n }\n}\n</code></pre>\n\n<p>Along with an abstract implementation to avoid duplicate code:</p>\n\n<pre><code>public abstract class AbstractImageFileProcessor implements ImageFileProcessor {\n private ImageFile primary;\n\n public void setPrimaryFile( ImageFile primary ) { this.primary = primary; }\n protected ImageFile getPrimaryFile() { return this.primary; }\n}\n</code></pre>\n\n<p>Then <code>main</code> reduces to:</p>\n\n<pre><code> public static void main( String args... ) {\n ImageFileProcessor ifp = ImageFileProcessorFactory.createProcessor( args[1] );\n ifp.process( args[2] );\n System.out.println( \"Done\" );\n }\n</code></pre>\n\n<p>If you want to add more processors, it's trivial, and the <code>main</code> method never need change. Once the code is so crafted, it would be straightforward to dynamically add new image processors to the code base while the application is running.</p>\n\n<p>Consider a text file such as:</p>\n\n<pre><code>JPG,JPGImageProcessor\nJPEG,JPGImageProcessor\nTIF,TIFFImageProcessor\nTIFF,TIFFImageProcessor\n</code></pre>\n\n<p>Reloading this file would repopulate the <code>processors</code> command map:</p>\n\n<pre><code> processors.put( ImageType.PNG, new PNGImageFileProcessor() );\n</code></pre>\n\n<p>All you would need to do is create a new <code>XImageProcessor</code> class (where <code>X</code> is the file type), ensure the class exists on the classpath, and then use reflection to dynamically instantiate the class.</p>\n\n<p>The Factory would need a method to refresh itself, which could then be tied to a file monitor process that kicks off the refresh event automatically when the file has changed. So many possibilities.</p>\n\n<p>At the risk of evoking ire, you could encapsulate the processor creation and execution mechanisms. In theory, you could make <code>getImageType()</code> a <code>private</code> method, then re-write <code>main</code>:</p>\n\n<pre><code> public static void main( String args... ) {\n (new ImageFile( args[1] )).process( args[2] );\n System.out.println( \"Done\" );\n }\n</code></pre>\n\n<p>That is an exercise for the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:39:42.340",
"Id": "32257",
"ParentId": "32219",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32227",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T05:09:10.357",
"Id": "32219",
"Score": "3",
"Tags": [
"java",
"optimization"
],
"Title": "Optimizing code block using Switch Case"
}
|
32219
|
<p>Here is my code. Is there anyway to make it more efficient?</p>
<pre><code>/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
char* revStr = (char*)malloc(strlen(str));
int i;
for(i = strlen(str)-1; i >= 0; i--)
revStr[strlen(str)-1-i] = str[i];
return revStr;
}
</code></pre>
|
[] |
[
{
"body": "<p>What about this:</p>\n\n<pre><code>/*\nIN: string to have characters reversed\nOUT: string containing characters in reversed order\n*/\nchar* reverStr(const char *str)\n{\n int index=strlen(str);\n char* revStr = (char*)malloc(index--);\n int destIndex=0;\n while (0<=index)\n revStr[destIndex++] = str[index--];\n revStr[destIndex]=0; \n return revStr;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:20:51.183",
"Id": "51466",
"Score": "3",
"body": "Nice solution. Cave: `malloc` does not fill the allocated space with zeros (by itself) - the operating system does though. But I would add `\\0` explicitely at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:55:20.187",
"Id": "51472",
"Score": "1",
"body": "@Lilith2k3: You are right, I added it. The same problem has the implementation given in the question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T09:36:49.627",
"Id": "32235",
"ParentId": "32234",
"Score": "5"
}
},
{
"body": "<p><code>strlen()</code> is expensive, don't use it inside the loops. Use <code>size_t</code> for indices. Don't hesitate to use auxiliary variables. Oh, and the string has to be null-terminated.</p>\n\n<pre><code>/*\nIN: string to have characters reversed\nOUT: string containing characters in reversed order\n*/\nchar* reverStr(const char *str)\n{\n size_t len = strlen(str); \n char* revStr = (char*)malloc(len + 1);\n\n size_t dst, src;\n for (dst = len - 1, src = 0; src < len; src++, dst--) {\n revStr[dst] = str[src];\n }\n revStr[len] = '\\0';\n return revStr;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:01:47.250",
"Id": "51458",
"Score": "0",
"body": "I thought the optimizer does that sort of thing in c?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:17:42.220",
"Id": "51463",
"Score": "0",
"body": "@Celeritas: only if the compiler can determine that `strlen()` has no side effects and the the result does not change during the loop. I would not count of that complicated auto-optimizations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:28:11.700",
"Id": "51468",
"Score": "2",
"body": "You mean cahcing the return value of the function? I've just checked, and VS2010 C compiler with `/O2` flag produces practically identical binaries for your original code and the variant of mine. So yes, it apparently does, but... I wouldn't rely on it. `strlen()` is a standard function and it can be treated by the compiler specially, and such optimization is not guaranteed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T10:32:30.850",
"Id": "51470",
"Score": "1",
"body": "By the way, even with `/O2`, if you turn `Enable intrinsic functions` off, then `stlren()` gets inlined twice, and no memoization of its result occurs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:41:06.567",
"Id": "51474",
"Score": "0",
"body": "Question: how is it faster to use two variables for the `dst` and `src` instead of using math and having 1 variable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:16:12.433",
"Id": "51528",
"Score": "0",
"body": "@Celeritas The perfect algorithm of optimizing register usage was discovered by the end of the seventies; every optimizing compiler implements it, because local integer variables don't even have to go on the stack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T10:09:32.093",
"Id": "63986",
"Score": "0",
"body": "@Joker_vD what is the name of the algorithm you refer to? I'm curious how something can be proven to be perfect?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T10:39:59.253",
"Id": "64851",
"Score": "1",
"body": "@Celeritas G. J. Chaitin, \"Register Allocation & Spilling via Graph Coloring\". Okay, that's the beginning of the eighties, and there was future development to increase the algorithm's speed (it's important for jitters)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T09:55:56.783",
"Id": "32237",
"ParentId": "32234",
"Score": "2"
}
},
{
"body": "<p>Here's another alternative:</p>\n\n<pre><code>char* reverStr(const char *str)\n{\n size_t len = strlen(str); \n char *rev = malloc(len + 1);\n if (rev) {\n char *to = rev;\n const char *from = str + len - 1;\n while (from > str) {\n *to++ = *from--;\n }\n *to++ = '\\0';\n }\n return rev;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T17:16:11.760",
"Id": "32540",
"ParentId": "32234",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32237",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T09:31:15.827",
"Id": "32234",
"Score": "4",
"Tags": [
"c",
"strings"
],
"Title": "Is this the best way to reverse a string in C (not in place)?"
}
|
32234
|
<p>I wonder if there is a more "functional" way of implementing something like this:</p>
<pre><code>@months.zipWithIndex.foreach { case (month, index) =>
if (index%3 == 0) {
<tr>
}
<td>@month</td>
if (index%3 == 0) {
</tr>
}
}
</code></pre>
<p>Can these two if-statements be removed by using something other than <code>foreach</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T13:45:24.253",
"Id": "51776",
"Score": "0",
"body": "There are many ways, of which my answer is one example, but the key is to structure your code around rows rather than months. Unless the list of months is empty, you will always be generating at least one row and so at least one pair of <tr></tr> tags, so there should be nothing conditional about them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T15:08:18.390",
"Id": "51867",
"Score": "1",
"body": "Is there not an error in your code? It would generate `<td>Jan</td><td>Feb</td><tr><td>Mar</td></tr>` and not `<tr><td>Jan</td><td>Feb</td><td>Mar</td></tr>`. I've assumed the latter is what you actually intended."
}
] |
[
{
"body": "<p>I don't believe there's any kind of functional looping structure that will allow you to obtain this behavior without the 'if' statements. The fact is, you have to include something conditionally, and so you have to check that condition somehow. This is a bit more idiomatic way to do it, I believe, and I think it's prettier:</p>\n\n<pre><code>@months.zipWithIndex.foreach { \n case (month, index) if (index % 3 == 0) => <tr><td>@month</td></tr>\n case (month, _) => <td>@month</td>\n}\n</code></pre>\n\n<p>I'm guessing you're using Play or something like that based on the <code>@months</code>. I've never used Play much so I'm not sure what the return type needs to be for a function like this but it might be possible to do something along the lines of </p>\n\n<pre><code>@months.zipWithIndex.foreach { case (month, index) => \n @str = <td>@month</td>\n if(index % 3 == 0) @str = \"<tr>\" + @str + \"<\\tr>\"\n @str\n}\n</code></pre>\n\n<p>but I don't personally think that's helping anything. Hope that was helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T13:30:06.943",
"Id": "51775",
"Score": "0",
"body": "Of course you can remove the if statements. As long as *@months* is not empty, this code is going to create at least one row, each of which will be bounded by *<tr>* and *</tr>*, so there should be no need for *if* at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T08:46:18.627",
"Id": "32320",
"ParentId": "32239",
"Score": "0"
}
},
{
"body": "<p>I am not sure which framework you are using, but this is how you could do it using Scala´s native XML library:</p>\n\n<pre><code> <div>\n { for (row <- months grouped 3) yield (<tr> { for (month <- row) yield (<td> {month} </td>) } </tr>) }\n </div>\n</code></pre>\n\n<p>Rendered slightly more prettily, the code looks like this:</p>\n\n<pre><code>for (row <- months grouped 3) yield {\n <tr> \n { for (month <- row) yield (<td> {month} </td>) }\n </tr>\n}\n</code></pre>\n\n<p>Which hopefully makes the structure clear.</p>\n\n<p>If your framework works with yield, all you need to do is add @ in the appropriate places. If it does not, you might have to do something like this:</p>\n\n<pre><code>for (row <- @months grouped 3) {\n <tr>\n for (month <- @row) {\n <td> @month </td>\n }\n </tr>\n}\n</code></pre>\n\n<p>Your code is structured only around months, so has to use conditional logic to create your rows. My code is structured around rows (and within that around months), so needs no conditionals. My code also only has the value for the number of months in one place, which is less error prone and makes it easier to change the number of months in a row.</p>\n\n<p>You don't have to use a list comprehension, though. The important thing is simply to slice the list up into groups of 3 (or <code>n</code>, where <code>n</code> is the number of months you want in each row) and iterate over those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T13:40:48.043",
"Id": "32424",
"ParentId": "32239",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T13:15:47.827",
"Id": "32239",
"Score": "1",
"Tags": [
"scala",
"functional-programming"
],
"Title": "More functional approach"
}
|
32239
|
<p>This is very simple: the user inputs his/her name, the program then truncates it on a consonant at a specified position, if possible if not it will truncate it on a vowel. It then adds an extension from a list of extensions to make the complete nickname and displays it.</p>
<pre><code> /**
* @author :KyleMHB
* Project Number :0001
* Project Name :Nick Namer
* IDE :NETBEANS
* Goal of Project -
* Use a given name and create a nick name using an extension.
*/
package nicknamer;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.JOptionPane;
</code></pre>
<p></p>
<pre><code>public class NickNamer {
public static void main(String[] args) {
String word = getName("Enter your name!");
List<String> nickExtension = Arrays.asList("anosorus","asaur","asaurus","onosorus","apede");
String output=getRandomNick(truncateName(word,"AEIOUaeiou",2),nickExtension);
showOutput(word+" your Nickname is "+output);
}
</code></pre>
<p></p>
<pre><code>private static String getName(String prompt){
String input=JOptionPane.showInputDialog(null,prompt);
return input;
}
</code></pre>
<p>This method below is meant to truncate the name on a consonant, at a position of my choosing (via the position <code>int</code>) or until it finds one after that position. E.g.: James becomes Jam and Jaemes becomes Jaem.</p>
<pre><code>private static String truncateName(String word,String vowels, int position) {
char[] wordArray = word.toCharArray();
String output;
int iterate=position;
while(iterate!=word.length()){
if(vowels.indexOf(wordArray[iterate]) < 0){
return word.substring(0,iterate+1);
}else{iterate++;}
}
return word.substring(0,position);
}
</code></pre>
<p></p>
<pre><code>private static String getRandomNick(String word,List nickExtension) {
Random r = new Random();
return word + nickExtension.get (r.nextInt(nickExtension.size()));
}
</code></pre>
<p></p>
<pre><code>private static void showOutput(String output) {
JOptionPane.showMessageDialog(null,output);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:33:54.017",
"Id": "51483",
"Score": "0",
"body": "Why is this used? `nickExtension.size() - 0`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:36:46.703",
"Id": "51484",
"Score": "0",
"body": "`nickExtension.size() - 0` is the range in which the random number must be generated so it doesn't try access a list entry that doesn't exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:40:53.030",
"Id": "51485",
"Score": "1",
"body": "You don't need to subtract 0 to anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:43:00.457",
"Id": "51486",
"Score": "0",
"body": "Yeah I just noticed that. Thank you. Will change it now."
}
] |
[
{
"body": "<pre><code>private static String getName(String prompt){\n String input=JOptionPane.showInputDialog(null,prompt);\n return input;\n}\n</code></pre>\n\n<p>I like what you've done here. But I would rename the method to <code>getInput(String prompt)</code> since you've made it reusable. You can get anything from the user with this method, since you're passing in the <code>prompt</code>! I would also make it a one-liner instead of storing the variable for no reason.</p>\n\n<p>i.e.,</p>\n\n<pre><code>private static String getInput(String prompt) {\n return JOptionPane.showInputDialog(null, prompt);\n}\n</code></pre>\n\n<p>Now in this method ...</p>\n\n<pre><code>private static String getRandomNick(String word,List nickExtension) {\n Random r = new Random();\n return word + nickExtension.get (r.nextInt(nickExtension.size() - 0));\n}\n</code></pre>\n\n<p>The <code>Random</code> should probably be a constant in your overarching class. Meaning it should be <code>private static final Random RANDOM = new Random()</code>. There's no need to create a new object each time you want to generate a number.</p>\n\n<p>Even if you wanted to do it this way, there would be no reason to store it in a variable.</p>\n\n<p>Also, why are you doing <code>nickExtension.size() - 0</code>? Get rid of the <code>- 0</code> since it does nothing.</p>\n\n<pre><code>private static String truncateName(String word,String vowels, int position) {\n char[] wordArray = word.toCharArray();\n String output;\n int iterate=position;\n while(iterate!=word.length()){\n if(vowels.indexOf(wordArray[iterate]) < 0){\n return word.substring(0,iterate+1); \n }else{iterate++;}\nreturn word.substring(0,position);\n}\n</code></pre>\n\n<p>This entire method is really confusing. It looks like you're trying to return a substring of the name when you hit a vowel? But this would do the opposite and actually only continue as long as it finds vowels, since <code>indexOf()</code> will return <code>-1</code> (and thus be less than 0) if the letter is not present. So as soon as you hit a consonant, your method will return. If this is actually what you were trying to achieve, then I don't get it.</p>\n\n<p>I would rewrite the whole thing. Also, since the vowels are a constant and would never change, I would put that at the top as a constant field as well: <code>private static final List<Character> VOWELS = Arrays.asList('a','e','i','o','u','A','E','I','O','U');</code> There's also no need to pass in the <code>position</code> either, since it's a constant.</p>\n\n<pre><code>private static String truncateName(String name) {\n char[] characters = name.toCharArray();\n for(int i = 3; i < characters.length; i++) {\n if(!VOWELS.contains(Character.toLowerCase(characters[i]))) {\n return name.substring(0, i + 1);\n }\n }\n return name.substring(0, 3);\n}\n</code></pre>\n\n<p>Throw in some general renaming of variables and methods to be more descriptive, cleanup of tabs, indentation, and spaces, clearing of unused variables ...</p>\n\n<p><strong>AND IN THE END, THERE WAS CODE</strong></p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.Random;\nimport javax.swing.JOptionPane;\n\npublic class NickNamer {\n\n private static final Random RNG = new Random();\n private static final List<String> NICKNAME_EXTENSIONS = Arrays.asList(\"anosaurus\", \"asaur\", \"asaurus\", \"onosaurus\", \"apede\");\n private static final List<Character> VOWELS = Arrays.asList('a', 'e', 'i', 'o', 'u');\n\n public static void main(String[] args) {\n String name = getInput(\"Enter your name!\");\n String output = getRandomNickname(truncateName(name));\n displayOutput(name + \", your nickname is \" + output + \"!\");\n }\n\n private static String getInput(String prompt){\n return JOptionPane.showInputDialog(null, prompt);\n }\n\n private static String truncateName(String name) {\n char[] characters = name.toCharArray();\n for(int i = 3; i < characters.length; i++) {\n if(!VOWELS.contains(Character.toLowerCase(characters[i]))) {\n return name.substring(0, i + 1);\n }\n }\n return name.substring(0, 3);\n }\n\n private static String getRandomNickname(String word) {\n return word + NICKNAME_EXTENSIONS.get(RNG.nextInt(NICKNAME_EXTENSIONS.size()));\n }\n\n private static void displayOutput(String output) {\n JOptionPane.showMessageDialog(null,output);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:44:13.387",
"Id": "51487",
"Score": "0",
"body": "Yeah it returns on a consonant, so James would be Jam. I dont want the extra vowel.\nThe position is something I have so I can set at what char it starts looking for a consonant.\nAnd for the random isnt it better to only create it when needed? I was always taught to be efficient and not have more variables initialized than I needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:44:29.697",
"Id": "51488",
"Score": "0",
"body": "In `Arrays.asList(\"anosaurus, asaur, asaurus, onosaurus, apede\")`, don't you mean `Arrays.asList(\"anosaurus\", \"asaur\", \"asaurus\", \"onosaurus\", \"apede\")`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:47:39.437",
"Id": "51490",
"Score": "0",
"body": "@KyleMHB Gotcha. Makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:56:16.310",
"Id": "51491",
"Score": "0",
"body": "@JeffGohlke Thanks, some nifty things I missed.\nI changed my `getName` `return` to this `return JOptionPane.showInputDialog(null, prompt);`\nAnd deleted a `String output` that never got used. \nBut I will still pass position because if I want to change it I only have to change it in one place.\n\nAs for the static variables I like to keep them localized to methods if I can."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:02:01.553",
"Id": "51493",
"Score": "0",
"body": "@KyleMHB Well, you *definitely* shouldn't be creating a `new Random()` each time you want to make a nickname. The others you can just pass around from `main()` if you really want to, but it's somewhat poor design practice. And passing in the position makes sense, depending on what the API would be used for in the future, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:05:16.047",
"Id": "51494",
"Score": "0",
"body": "@JeffGohlke Obviously as you say its not a good idea but I dont know why... Could you please explain? Im still new to this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:42:40.663",
"Id": "51506",
"Score": "0",
"body": "@KyleMHB So it's for efficiency purposes. Every time that method executes, it will create a new object (allocate memory for it, run through all its constructor code, etc.) then garbage collect it. That's actually the majority of the work load of the method, as you have it written, and you get absolutely no benefits from it. Sure, efficiency is trivial with such a small program, but these are the things you should think about early on as you're learning so that you can make good decisions when you develop something bigger."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:47:34.730",
"Id": "51507",
"Score": "0",
"body": "@JeffGohlke Thank you for clarifying. I was under the impression that have the variables preloaded into memory in a large program would be detrimental as they take up space when it could be free. That was probably true 10 years ago!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:35:53.083",
"Id": "32244",
"ParentId": "32240",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T13:48:41.960",
"Id": "32240",
"Score": "3",
"Tags": [
"java",
"strings"
],
"Title": "Simple Nick Namer"
}
|
32240
|
<p>A few years ago I started building a tiny (~300 SLOC) JavaScript framework for scalable and maintainable Single-Page-Applications written in CoffeeScript.</p>
<ul>
<li><a href="https://github.com/flosse/scaleApp" rel="nofollow">GitHub</a></li>
<li><a href="http://www.scaleapp.org/" rel="nofollow">www.scaleapp.org</a></li>
</ul>
<p>It's inspired by the talk "Scalable JavaScript Application Architecture" by Nicholas Zakas. The project was starred on GitHub by some people but that is quite useless since that doesn't give any qualified feedback.</p>
<p>The framework consists of two classes:</p>
<ul>
<li>The <code>Mediator</code> (responsible for events; similar to node.js <code>EventEmitter</code>)</li>
<li>The <code>Core</code> (it mainly starts and stops modules within a sandbox)</li>
</ul>
<p>Now here is the <code>Core</code> class that needs to be refactored:</p>
<pre><code>checkType = (type, val, name) ->
"#{name} has to be a #{type}" unless typeof val is type
class Core
constructor: (@Sandbox) ->
# define private variables
@_modules = {}
@_plugins = []
@_instances = {}
@_sandboxes = {}
@_running = {}
@_mediator = new Mediator
# define public variables
@Mediator = Mediator
@Sandbox ?= (core, @instanceId, @options = {}, @moduleId) ->
core._mediator.installTo @
@
# define dummy logger
log:
error: ->
log: ->
info: ->
warn: ->
enable:->
# register a module
register: (moduleId, creator, opt = {}) ->
err =
checkType("string", moduleId, "module ID") or
checkType("function", creator, "creator") or
checkType("object", opt, "option parameter")
if err
@log.error "could not register module '#{moduleId}': #{err}"
return @
if @_modules[moduleId]?
@log.warn "module #{moduleId} was already registered"
return @
@_modules[moduleId] =
creator: creator
options: opt
id: moduleId
@
# start a module
start: (moduleId, opt={}, cb=->) ->
if arguments.length is 0
return @_startAll()
if moduleId instanceof Array
return @_startAll moduleId, opt
if typeof moduleId is "function"
return @_startAll null, moduleId
if typeof opt is "function"
cb = opt; opt = {}
e =
checkType("string", moduleId, "module ID") or
checkType("object", opt, "second parameter") or
("module doesn't exist" unless @_modules[moduleId])
return @_startFail e, cb if e
id = opt.instanceId or moduleId
if @_running[id] is true
return @_startFail (new Error "module was already started"), cb
initInst = (err, instance, opt) =>
return @_startFail err, cb if err
try
if util.hasArgument instance.init, 2
# the module wants to init in an asynchronous way
# therefore define a callback
instance.init opt, (err) =>
@_running[id] = true unless err
cb err
else
# call the callback directly after initialisation
instance.init opt
@_running[id] = true
cb()
catch e
@_startFail e,cb
@boot (err) =>
return @_startFail err, cb if err
@_createInstance moduleId, opt, initInst
_startFail: (e, cb) ->
@log.error e
cb new Error "could not start module: #{e.message}"
@
_createInstance: (moduleId, o, cb) ->
id = o.instanceId or moduleId
opt = o.options
module = @_modules[moduleId]
return cb @_instances[id] if @_instances[id]
iOpts = {}
for obj in [module.options, opt] when obj
iOpts[key] ?= val for key,val of obj
Sandbox =
if typeof o.sandbox is 'function' then o.sandbox
else @Sandbox
sb = new Sandbox @, id, iOpts, moduleId
@_runSandboxPlugins 'init', sb, (err) =>
instance = new module.creator sb
unless typeof instance.init is "function"
return cb new Error "module has no 'init' method"
@_instances[id] = instance
@_sandboxes[id] = sb
cb null, instance, iOpts
_runSandboxPlugins: (ev, sb, cb) ->
tasks =
for p in @_plugins when typeof p.plugin?[ev] is "function" then do (p) ->
fn = p.plugin[ev]
(next) ->
if util.hasArgument fn, 3
fn sb, p.options, next
else
fn sb, p.options
next()
util.runSeries tasks, cb, true
_startAll: (mods=(m for m of @_modules), cb) ->
startAction = (m, next) => @start m, @_modules[m].options, next
done = (err) ->
if err?.length > 0
mdls = ("'#{mods[i]}'" for x,i in err when x?)
e = new Error "errors occoured in the following modules: #{mdls}"
cb? e
util.doForAll mods, startAction, done, true
@
stop: (id, cb=->) ->
if arguments.length is 0 or typeof id is "function"
util.doForAll (x for x of @_instances), (=> @stop arguments...), id, true
else if instance = @_instances[id]
delete @_instances[id]
@_mediator.off instance
@_runSandboxPlugins 'destroy', @_sandboxes[id], (err) =>
# if the module wants destroy in an asynchronous way
if util.hasArgument instance.destroy
# then define a callback
instance.destroy (err) ->
# rereference if something went wrong
@_instances[id] = instance if err
cb err
else
# else call the callback directly after stopping
instance.destroy?()
cb()
@
# register a plugin
use: (plugin, opt) ->
if plugin instanceof Array
for p in plugin
switch typeof p
when "function" then @use p
when "object" then @use p.plugin, p.options
else
return @ unless typeof plugin is "function"
@_plugins.push creator:plugin, options:opt
@
# load plugins
boot: (cb) ->
core = @
tasks = for p in @_plugins when p.booted isnt true then do (p) ->
if util.hasArgument p.creator, 3
(next) ->
plugin = p.creator core, p.options, (err) ->
if not err
p.booted = true
p.plugin = plugin
next()
else
(next) ->
p.plugin = p.creator core, p.options
p.booted = true
next()
util.runSeries tasks, cb, true
@
on: -> @_mediator.on.apply @_mediator, arguments
off: -> @_mediator.off.apply @_mediator, arguments
emit: -> @_mediator.emit.apply @_mediator, arguments
</code></pre>
<p>This is working quite well but reading and understanding is still not optimal.</p>
<p>Here are my questions:</p>
<ul>
<li>How could that <code>checkType</code> helper method replaced without repeating the same lines again and again?</li>
<li>How could the error-handling be improved? E.g. I'd like to check a module that gets registered. Should I throw an error? Just log a warning? Returning <code>false</code> would break the chainable API.</li>
<li>How could the logging be improved? Does it make sense to define a dummy logger? Or should <code>console.log</code> be used?</li>
<li>How could the core be structured for better readability?</li>
<li>What else could be done in a better way?</li>
<li>Which parts are totally weird?</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:09:08.947",
"Id": "32241",
"Score": "4",
"Tags": [
"node.js",
"api",
"coffeescript"
],
"Title": "Core class of a JavaScript framework for Single-Page-Applications"
}
|
32241
|
<p>Just got done implementing a shortest path algo of a unit cost DAG BFS in Hadoop and wanting to get anyone's opinion on how I could have done it better. The main issue I see is that I lose the parallel nature of hadoop by forcing the mappers to wait for the output of the previous mapper before beginning.</p>
<p>The thing works and finds the shortest path given two input files: nodes.txt and edges.txt. </p>
<p>nodes.txt represents all the nodes in the DAG and is of the form </p>
<pre><code>1 "A"
2 "B"
3 "C"
4 "D"
5 "E"
6 "F"
7 "G"
8 "Z"
9 "X"
</code></pre>
<p>edges.txt represents all the edges of the DAG and is of the form</p>
<pre><code>1 2
1 3
1 4
2 5
2 6
3 5
3 6
4 7
5 8
6 8
7 8
</code></pre>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class ShortestPathDAGBFS
{
public static class Map extends Mapper<LongWritable, Text, Text, Text>
{
HashMap<String, String> nodes = new HashMap<>();
HashMap<String, LinkedList<String>> edges = new HashMap<>();
String sourceNodeId;
String destNodeId;
Pattern pattern = Pattern.compile("[^\\S\\n]{1,4}");
boolean found = false;
@Override
public void setup(Context context) throws IOException
{
nodes = GlobalFunctions.parseNodesFile(context.getConfiguration().get("Nodes"));
edges = GlobalFunctions.parseEdgesFile(context.getConfiguration().get("Edges"));
sourceNodeId = GlobalFunctions.findNodeId(context.getConfiguration().get("Source"), nodes).trim();
destNodeId = GlobalFunctions.findNodeId(context.getConfiguration().get("Dest"), nodes).trim();
}
@Override
public void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException
{
String[] edge = pattern.split(line.toString());
edge[0] = edge[0].trim();
edge[1] = edge[1].trim();
LinkedList<String> outNodes = edges.get(edge[1]);
String newPath = edge[0] + "->" + nodes.get(edge[1]);
if (outNodes != null && !found)
{
for (String nextNodeId : outNodes)
{
context.write(new Text(newPath.toString()), new Text(nextNodeId.toString()));
if (nextNodeId.toString().equalsIgnoreCase(destNodeId))
{
context.getCounter("FoundDest", "FoundDest").increment(1);
found= true;
context.write(new Text(edge[0].toString()), new Text(edge[1].toString()));
return;
}
}
}
}
}
public static class Reduce extends Reducer<Text, Text, Text, Text>
{
String destNodeId;
HashMap<String, String> nodes = new HashMap<>();
boolean written = false;
@Override
public void setup(Context context) throws IOException
{
nodes = GlobalFunctions.parseNodesFile(context.getConfiguration().get("Nodes"));
destNodeId = GlobalFunctions.findNodeId(context.getConfiguration().get("Dest"), nodes);
}
@Override
public void reduce(Text prevPath, Iterable<Text> values, Context context) throws IOException, InterruptedException
{
for (Text newestNode : values)
{
if (newestNode.toString().trim().equals(destNodeId) && !written)
{
String destNode = context.getConfiguration().get("Dest");
String path = prevPath.toString().replace("->", " ");
path += " " + destNode;
context.write(new Text(path), null);
written = true;
}
else if (!written)
{
context.write(new Text(prevPath.toString()), new Text(newestNode.toString()));
System.out.println("Reducer output: " + prevPath.toString() + " " + newestNode.toString());
}
}
}
}
public static class GlobalFunctions
{
public static HashMap<String, String> parseNodesFile(String nodesPath) throws IOException
{
HashMap<String, String> nodes = new HashMap<>();
Path path = new Path(nodesPath);
FileSystem fs = FileSystem.get(path.toUri(), new Configuration());
InputStream is = (fs.open(new Path(path.toUri().toString())));
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset())))
{
String line;
while ((line = reader.readLine()) != null)
{
String[] node = line.replace(' ', '\0').split("\"");
nodes.put(node[0].trim(), node[1].trim());
}
}
return nodes;
}
public static HashMap<String, LinkedList<String>> parseEdgesFile(String edgesPath) throws IOException
{
HashMap<String, LinkedList<String>> edges = new HashMap<>();
Path path = new Path(edgesPath);
FileSystem fs = FileSystem.get(path.toUri(), new Configuration());
InputStream is = (fs.open(new Path(path.toUri().toString())));
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset())))
{
String line;
Pattern pattern = Pattern.compile("[^\\S\\n]{1,4}");
while ((line = reader.readLine()) != null)
{
String[] edge = pattern.split(line);
LinkedList<String> adjacencyList = edges.get(edge[0]);
if (adjacencyList == null && !edge[0].equals(edge[1]))
{
LinkedList<String> list = new LinkedList<>();
list.add(edge[1]);
edges.put(edge[0], list);
}
else if (!edge[0].equals(edge[1]))
{
adjacencyList.add(edge[1]);
}
}
}
return edges;
}
public static String findNodeId(String source, HashMap<String, String> nodes)
{
for (Entry<String, String> e : nodes.entrySet())
{
if (e.getValue().equals(source))
{
return e.getKey();
}
}
return null;
}
}
public static class FirstMap extends Mapper<LongWritable, Text, Text, Text>
{
HashMap<String, String> nodes = new HashMap<>();
Pattern pattern = Pattern.compile("[^\\S\\n]{1,4}");
String sourceNodeId;
@Override
public void setup(Context context) throws IOException
{
nodes = GlobalFunctions.parseNodesFile(context.getConfiguration().get("Nodes"));
sourceNodeId = GlobalFunctions.findNodeId(context.getConfiguration().get("Source"), nodes).trim();
}
@Override
public void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException
{
String[] edge = pattern.split(line.toString());
edge[0] = edge[0].trim();
if (sourceNodeId.equals(edge[0]))
{
context.write(new Text(nodes.get(edge[0])), new Text(edge[1]));
System.out.println("Writing for first iteration" + edge[0] + " " + edge[1]);
}
}
}
public static void main(String[] args) throws Exception
{
GenericOptionsParser parser = new GenericOptionsParser(args);
String[] arguments = parser.getRemainingArgs();
if (arguments.length != 5)
{
usage(System.out);
System.exit(-1);
}
Configuration conf = parser.getConfiguration();
conf.set("Source", arguments[3]);
conf.set("Dest", arguments[4]);
conf.set("Nodes", arguments[0]);
conf.set("Edges", arguments[1]);
Job job = new Job(conf);
job.setJarByClass(ProblemIII.class);
job.setMapperClass(FirstMap.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPaths(job, arguments[1]);
FileOutputFormat.setOutputPath(job, new Path("tmpout-part0"));
job.waitForCompletion(true);
boolean found;
long outputBytes;
int iteration = 0;
do
{
job = initJob(conf);
FileInputFormat.addInputPath(job, new Path("tmpout-part" + iteration));
FileOutputFormat.setOutputPath(job, new Path("tmpout-part" + (iteration + 1)));
job.waitForCompletion(true);
found = job.getCounters().findCounter("FoundDest", "FoundDest").getValue() == 1 ? true : false;
outputBytes = job.getCounters().findCounter("org.apache.hadoop.mapred.Task$Counter", "MAP_OUTPUT_BYTES").getValue();
++iteration;
} while (!found && outputBytes != 0);
if (outputBytes == 0)
{
FileSystem fs = FileSystem.get(new Configuration());
FSDataOutputStream file = FileSystem.get(new Configuration()).create(new Path(arguments[2]+"/output.txt"));
file.writeChars(arguments[3] + " null " + arguments[4]);
file.close();
System.exit(0);
}
else
{
Job finalJob = initJob(conf);
FileInputFormat.addInputPaths(finalJob, "tmpout-part" + (iteration));
FileOutputFormat.setOutputPath(finalJob, new Path(arguments[2]));
System.exit(finalJob.waitForCompletion(true) ? 0 : 1);
}
}
private static void usage(PrintStream out)
{
out.println("usage: ProblemIII <nodes path> <edges path> <output path> <source protein> <destination protein>");
}
private static Job initJob(Configuration conf) throws IOException
{
Job job = new Job(conf);
job.setJarByClass(ProblemIII.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
return job;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with Hadoop, take my advice with care.</p>\n\n<ol>\n<li><p>Are you sure that you want to use the default charset?</p>\n\n<blockquote>\n<pre><code>try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()))) {\n</code></pre>\n</blockquote>\n\n<p>It could vary from system to system. Usually it's a good idea using UTF-8 explicitly.</p></li>\n<li><p>Since both <code>newPath</code> and <code>nextNodeId</code> are <code>String</code>s,</p>\n\n<blockquote>\n<pre><code>context.write(new Text(newPath.toString()), new Text(nextNodeId.toString()));\n</code></pre>\n</blockquote>\n\n<p>could be</p>\n\n<pre><code>context.write(new Text(newPath), new Text(nextNodeId));\n</code></pre>\n\n<p>It's the same, since <code>String.toString</code> has the following implementation:</p>\n\n<pre><code>public String toString() {\n return this;\n}\n</code></pre>\n\n<p>(There are other similar occurrences in the code, find them.)</p></li>\n<li><p>As far as I see <code>Text</code> has a constructor which accepts <code>Text</code> parameters. You might want to use that instead of converting it back to <code>String</code>:</p>\n\n<blockquote>\n<pre><code>context.write(new Text(prevPath.toString()), new Text(newestNode.toString()));\n</code></pre>\n</blockquote></li>\n<li><p>The <code>setup</code> method also queries <code>Dest</code>. You might want to store that in a field or move it outside the loop:</p>\n\n<blockquote>\n<pre><code>for (Text newestNode: values) {\n if (newestNode.toString().trim().equals(destNodeId) && !written) {\n String destNode = context.getConfiguration().get(\"Dest\");\n</code></pre>\n</blockquote></li>\n<li><p>You could invert the conditon in the <code>map</code> method to <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">make the code flatten</a>:</p>\n\n<pre><code>@Override\npublic void map(LongWritable offset, Text line, Context context) \n throws IOException, InterruptedException {\n String[] edge = pattern.split(line.toString());\n edge[0] = edge[0].trim();\n edge[1] = edge[1].trim();\n List<String> outNodes = edges.get(edge[1]);\n String newPath = edge[0] + \"->\" + nodes.get(edge[1]);\n if (outNodes == null || found) {\n return;\n }\n for (String nextNodeId: outNodes) {\n context.write(new Text(newPath), new Text(nextNodeId));\n if (nextNodeId.toString().equalsIgnoreCase(destNodeId)) {\n context.getCounter(\"FoundDest\", \n \"FoundDest\").increment(1);\n found = true;\n context.write(new Text(edge[0].toString()), \n new Text(edge[1].toString()));\n return;\n }\n }\n}\n</code></pre></li>\n<li><p>Actually, I guess the found check could be right at the beginning:</p>\n\n<pre><code>@Override\npublic void map(LongWritable offset, Text line, Context context) \n throws IOException, InterruptedException {\n if (found) {\n return;\n }\n ...\n}\n</code></pre></li>\n<li><p>The <code>reduce</code> method also could use a <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clause</a>. If I'm right it could even break the loop since if <code>written</code> is <code>true</code> both nested conditions will be <code>false</code>.</p>\n\n<pre><code>@Override\npublic void reduce(Text prevPath, \n Iterable<Text> values, Context context) \n throws IOException, InterruptedException {\n for (Text newestNode: values) {\n if (written) {\n break;\n }\n ...\n }\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>sourceNodeId = GlobalFunctions.findNodeId(context.getConfiguration().get(\"Source\"), nodes).trim();\n</code></pre>\n</blockquote>\n\n<p><code>findNodeId</code> could be a little bit smarter. All of the four uses of it trim its output and pass an object which is get\nfrom <code>context.getConfiguration().get(\"somekey\")</code>. A wrapper like this could eliminate some duplication:</p>\n\n<pre><code>public static String findTrimmedNodeId(\n Configuration configuration, \n String key, Map<String, String> nodes) {\n return findNodeId(configuration.get(key), nodes).trim();\n}\n</code></pre></li>\n<li><p>The <code>fs</code> variable is unused here:</p>\n\n<blockquote>\n<pre><code>FileSystem fs = FileSystem.get(new Configuration());\n</code></pre>\n</blockquote>\n\n<p>Are you sure that these statements are required?</p></li>\n<li><p>I'd change <code>ShortestPathDAGBFS</code> to <code>ShortestPathDagBfs</code></p>\n\n<p>From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n<li><p>Calling the mapper <code>Map</code> is confusing. I'd choose <code>DagBfsMapper</code> or something descriptive. The same is true for <code>Reduce</code>.</p></li>\n<li><p><code>HashMap<...></code> reference types should be simply <code>Map<...></code>, as well as <code>LinkedList<...></code> could be <code>List<...></code> (<em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em>) </p></li>\n<li><p>Consider using <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/LineIterator.html\" rel=\"nofollow\"><code>LineIterator</code></a>, it would simplify the code a little bit.</p></li>\n<li><p>Try to use more descriptive variable names:</p>\n\n<blockquote>\n<pre><code>Pattern pattern = Pattern.compile(\"[^\\\\S\\\\n]{1,4}\");\n</code></pre>\n</blockquote>\n\n<p>What is this pattern supposed to match?</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:24:28.423",
"Id": "43176",
"ParentId": "32243",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T14:21:48.490",
"Id": "32243",
"Score": "6",
"Tags": [
"java",
"algorithm",
"graph",
"breadth-first-search",
"hadoop"
],
"Title": "Shortest Path in a Unit Cost DAG BFS in Hadoop"
}
|
32243
|
<p><strong>This question follows on from :<a href="https://codereview.stackexchange.com/questions/32204/anagrams-for-a-given-input">Previous Question</a></strong></p>
<p>Here is what my reworked code looks like. I neatened it up as much as I could. Changed some of the semantics of it. I also tried to add some faster exit points and checks to prevent errors.</p>
<p><strong>Any further critiques?</strong></p>
<pre><code> /**
* @author :KyleMHB
* Project Number :0002
* Project Name :Anagramatic
* IDE :NETBEANS
* Goal of Project -
* Capture user input, compare to a dictionary file for anagrams,
* output number of matches and the matches.
*/
package anagramatic;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;
</code></pre>
<p>-</p>
<pre><code>public class Anagramatic {
public static void main(String[] args) throws FileNotFoundException{
String anagram=getInput("Enter the word you would like to process");
List<String> words=readAnagramsFromFile(anagram, new File("words.txt"));
String output= formatOutput(anagram,words);
displayOutput(output);
}//pvsm
</code></pre>
<p>-</p>
<pre><code>private static String getInput(String prompt) {
String input = JOptionPane.showInputDialog(null,prompt);
return input;
}//getInput
</code></pre>
<p>-</p>
<pre><code> private static List readAnagramsFromFile(String word, File f)
throws FileNotFoundException{
ArrayList<String> anagrams = new ArrayList<>();
try(Scanner s = new Scanner(f)){
while(s.hasNext()){
String candidate=s.next();
if ( (candidate.length()==word.length()) &&
(checkMatch(word,candidate)==true)){
anagrams.add(candidate);
}
}
}
return anagrams;
}//readFile
</code></pre>
<p>-</p>
<pre><code>private static boolean checkMatch(String word, String candidate) {
char[] wordArray = word.toCharArray();
char[] candidateArray = candidate.toCharArray();
if (Arrays.equals(wordArray, candidateArray)){
return false;
}
Arrays.sort(wordArray);
Arrays.sort(candidateArray);
if(Arrays.equals(wordArray, candidateArray)){
return true;
}
/**I did not use an else function for the the below return
*because if (Arrays.equals(wordArray, candidateArray))==true
*it will break on the return*/
return false;
}//match
</code></pre>
<p>-</p>
<pre><code>private static String formatOutput(String original, List<String> words) {
StringBuilder output=new StringBuilder("[ ");
int counter=0;
Iterator<String> wordIt =words.iterator();
while(wordIt.hasNext()){
output.append(wordIt.next());
if(wordIt.hasNext()){
output.append((++counter % 8 == 0)? ",\n" : ", ");
}
}
output.append(" ]");
return ("The Anagram "+original+" has "+words.size()+" matches.\n\nThey are:\n"+output.toString());
}//formatOutput
</code></pre>
<p>-</p>
<pre><code>private static void displayOutput(String output){
JOptionPane.showMessageDialog(null,output);
}//displayOutput
}
</code></pre>
|
[] |
[
{
"body": "<p>Four issues with <code>private static boolean checkMatch(String word, String candidate)</code>:</p>\n\n<ul>\n<li><code>checkMatch</code> is not as descriptive as a name could be. I think <code>private static boolean isAnagram(String a, String b)</code> would be better. I would also rename the parameters to acknowledge that they are symmetrical: it doesn't matter which is the original word, and which is the candidate.</li>\n<li>You don't need to end with an if-else. You can just say <code>return Arrays.equals(wordArray, candidateArray);</code></li>\n<li>You would be re-sorting the characters of the original word each time you test a candidate. That's OK, I suppose, if you prefer clean code over efficiency.</li>\n<li><p>Why not start with</p>\n\n<pre><code>private static boolean isAnagram(String a, String b) {\n if (a.length() != b.length()) {\n return false;\n }\n\n // Continue with a thorough comparison...\n ...\n}\n</code></pre>\n\n<p>Then the code in <code>readAnagramsFromFile()</code> can read very smoothly:</p>\n\n<pre><code>if (isAnagram(word, candidate)) {\n anagrams.add(candidate);\n}\n</code></pre></li>\n</ul>\n\n<p>Note that the return type of <code>readAnagramsFromFile()</code> should be <code>List<String></code>, not just a generic <code>List</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:05:25.647",
"Id": "51534",
"Score": "0",
"body": "So is having `if ( (candidate.length()==word.length()) && (checkMatch(word,candidate)==true))` in my `readAnagramsFromFile()` less efficient than the solution you suggested?\nI was trying to create an earlier exit point.\nI changed the `String` names as you suggested as well as the method name to `checkAnagram()`.\nFinally what is the difference between using the return type of `List<String>` for `readAnagramsFromFile()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:28:56.323",
"Id": "51538",
"Score": "0",
"body": "Moving the length check inside `isAnagram()` makes `isAnagram()` fulfill its duty the way it should, and is therefore better code. You _might_ be able to save the overhead of a function call by checking the length before calling `isAnagram()`, but since `isAnagram()` is `private static`, there is a good chance that the JIT will inline the function call anyway, especially if you also declare `isAnagram()` to be `final`. However, considering that you are willing to re-sort the characters of the original word, it makes no sense to obsess over the overhead of a function call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:35:01.010",
"Id": "51539",
"Score": "0",
"body": "`readAnagramsFromFile()` returns a list of strings, so your code should state that. Otherwise, it could be returning a list of who-know-what kind of objects. (The runtime behaviour would be identical either way. However, using Java Generics consistently lets the compiler do its job better by catching programming mistakes and reducing the need for casting.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:35:22.387",
"Id": "51540",
"Score": "0",
"body": "And it makes the code a lot cleaner in the `readAnagramsFromFile()`.\nThat makes sense, about the `List<String>`.\nThanks for the explanations and your patience. Answer Accepted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:48:29.050",
"Id": "32259",
"ParentId": "32246",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:03:07.863",
"Id": "32246",
"Score": "2",
"Tags": [
"java",
"optimization",
"array"
],
"Title": "Anagrams for a given input 2.0"
}
|
32246
|
<p>I'm new to using fragments in Android. I'm working on an app using a sliding panel layout and I just came up with an idea for changing my fragments. I decided to create the following method:</p>
<pre><code> private void changeFrag(Object newFrag){
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_secondpane, (Fragment) newFrag).commit();
}
</code></pre>
<p>I'm calling the method in the following way:</p>
<pre><code> changeFrag(new myFragment());
</code></pre>
<p>Could this cause problems for me in the long run? I was hoping that by writing it this way, I could avoid extra code and hopefully cut down on any extra processing power the device would need for something like this:</p>
<pre><code> Fragment frag;
frag= new myFragment();
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_secondpane, (Fragment) frag).commit();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:20:51.823",
"Id": "51516",
"Score": "0",
"body": "have you tested this? does it work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:20:10.527",
"Id": "51529",
"Score": "1",
"body": "Sorry Forgot mention that. Yes is seems to work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T11:22:34.313",
"Id": "51575",
"Score": "2",
"body": "Why did you declare `newFrag` as `Object`, not `Fragment`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T15:17:35.293",
"Id": "51615",
"Score": "0",
"body": "And where is `frag` defined? Is it `newFrag` in the first block and `fragment` in the second? If so, both blocks look identical save for putting the code into a method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T13:46:31.603",
"Id": "51703",
"Score": "0",
"body": "@David Harkness Thank you for spotting the coding errors I made when I change made the variable names generic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T13:48:30.677",
"Id": "51705",
"Score": "0",
"body": "@Andrey Breslav I used Object because Fragment didn't seem to work when I tried it."
}
] |
[
{
"body": "<p>You could make it more dynamic. Because this method adds the Fragment only to the <code>R.id.fragment_secondpane</code> layout. If this is all what you desire, it's ok. Otherwise add a parameter for the layout. This way you can use your method to add a Fragment to different layouts.</p>\n\n<p>Because every type of Fragment like ListFragment, DialogFragment or even a SherlockFragment is using Fragment as super class, you can use <code>Fragment</code> as the parameter type. There's no need to use <code>Object</code>. Note that you should avoid to mix the Fragment types of different librarys.</p>\n\n<p>With methods like this you can avoid extra code in this situation, replacing different Fragments of a specific layout. </p>\n\n<p>The processing will be the same. The creation of the necessary objects have to be done. There will be no difference if this happens in e.g. onCreate or the method you wrote. The only thing you could avoid is to hold an extra reference of the FragmentManager.</p>\n\n<p>To sum all up you would have something like this:</p>\n\n<pre><code>private void changeFrag(int layout, Fragment newFrag){\n\n getSupportFragmentManager() // gets the FragmentManager of the Activity, no need to hold a reference\n .beginTransaction()\n .replace(layout, newFrag) // use the layout and the fragment, no need for a cast\n .commit();\n\n}\n</code></pre>\n\n<p>Note that this method will work and is straightforward. If you have an approach with adding some Fragments to the backstack and some not or using different kind of animations, your method will be more complex and lacks performance. That's why I would not use this in every situation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T13:53:35.320",
"Id": "51707",
"Score": "0",
"body": "Thank you very much for your input I appreciate everyone's help on this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T13:19:11.867",
"Id": "32328",
"ParentId": "32247",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32328",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:07:58.033",
"Id": "32247",
"Score": "1",
"Tags": [
"java",
"android",
"casting"
],
"Title": "Can casting to fragment be more efficient than using a variable?"
}
|
32247
|
<p>Considering the following Makefile:</p>
<pre><code>%.o: %.cpp
$(C) $(CF) -c $< -o $@
Audio/%.o: Audio/%.cpp
$(C) $(CF) -c $< -o $@
Game/%.o: Game/%.cpp
$(C) $(CF) -c $< -o $@
Generation/%.o: Generation/%.cpp
$(C) $(CF) -c $< -o $@
Input/%.o: Input/%.cpp
$(C) $(CF) -c $< -o $@
Particle/%.o: Particle/%.cpp
$(C) $(CF) -c $< -o $@
Screen/%.o: Screen/%.cpp
$(C) $(CF) -c $< -o $@
Utility/%.o: Utility/%.cpp
$(C) $(CF) -c $< -o $@
</code></pre>
<p>How can I simplify it so that it only depends on a list of directories, such as:</p>
<pre><code>SUBD = Audio/\
Game/\
Generation/\
Input/\
Particle/\
Screen/\
Utility/
</code></pre>
|
[] |
[
{
"body": "<p>All of these rules</p>\n\n<pre><code>Audio/%.o: Audio/%.cpp\n $(C) $(CF) -c $< -o $@\n\n# etc.\n</code></pre>\n\n<p>are redundant! Your first pattern rule</p>\n\n<pre><code>%.o: %.cpp\n $(C) $(CF) -c $< -o $@\n</code></pre>\n\n<p>already covers them all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T17:51:51.447",
"Id": "51523",
"Score": "0",
"body": "So my first rule covers all the subdirectories as well? (and sub-sub directories)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:12:38.860",
"Id": "51526",
"Score": "0",
"body": "Yes. If `Audio/a/b/c/something.cpp` exists, then it will use the first rule to make `Audio/a/b/c/something.o` if it needs `Audio/a/b/c/something.o`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T16:56:39.173",
"Id": "32252",
"ParentId": "32249",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32252",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T15:21:25.113",
"Id": "32249",
"Score": "4",
"Tags": [
"makefile"
],
"Title": "How do I simplify the following slice of a Makefile?"
}
|
32249
|
<pre><code>#include <iostream>
#include <vector>
void getUserNum(int &);
int rFib(int n);
void dispSeq(std::vector<int> &vRef);
int main()
{
int userNum;
getUserNum(userNum);
rFib(userNum);
return 0;
}
void getUserNum(int &refVal)
{
std::cout << "Enter a positive integer:\n";
std::cin >> refVal;
}
int rFib(int n)
{
static std::vector<int> fib;
static bool baseReached = false;
fib.push_back(n);
if (baseReached)
{
dispSeq(fib);
}
if (n <= 1)
{
baseReached = true;
return n;
}
else
{
return rFib(n-2) + rFib(n-1);
}
}
void dispSeq(std::vector<int> &v)
{
for (size_t i = 0; i < v.size(); i++)
{
std::cout << v[i] << " ";
}
std::cout << std::endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T16:58:19.000",
"Id": "51511",
"Score": "2",
"body": "Asking how to do something is best done on SO. Though a good code review here will definitely push you in the correct direction."
}
] |
[
{
"body": "<p>Its normal to put parameter names even in the declarations:</p>\n\n<pre><code>void getUserNum(int &);\n</code></pre>\n\n<p>We use this to help us identify what the function is doing.</p>\n\n<p>In C++ the <code>'*'</code> and the <code>'&'</code> are part of the type information. So it is usual to push these left towards the type rather than the name. Note this is basically the opposite of <code>C</code> conventions. But <code>C++</code> is much more rigorous on types and safety than <code>C</code>.</p>\n\n<pre><code>void dispSeq(std::vector<int> &vRef);\n\n// Normally in C++ code I would expect this:\nvoid dispSeq(std::vector<int>& vRef);\n</code></pre>\n\n<p>Be careful with your use of out parameters.</p>\n\n<pre><code>void getUserNum(int &refVal)\n</code></pre>\n\n<p>It seems more natural to return a value from a function then get sombody inside to set an external value via a reference (not unheard of and it will depend a lot on the context). But in this situation I would return a value. It will then make using the code eaiser.</p>\n\n<pre><code> int userNum = getUserNum();\n</code></pre>\n\n<p>Error Checking (especially input from a human) needs to be more rigorous.</p>\n\n<pre><code>void getUserNum(int &refVal)\n{\n std::cout << \"Enter a positive integer:\\n\";\n std::cin >> refVal;\n}\n</code></pre>\n\n<p>If a user enters a non positive value things will go bad. If the user inputs a string the value of <code>refVal</code> I believe is left unaltered (which leaves your code with an uninitialized variable).</p>\n\n<pre><code>int getUserNum()\n{\n int result;\n\n // user input is done by the line.\n // so read a line at a time and validate it.\n std::string line;\n std::getline(std::cin, line);\n\n std::stringstream linestream(line);\n\n int result;\n if (linestream >> result)\n {\n // The read worked.\n // Lets check the user did not type ofther crap on the line.\n //\n char x;\n if (!(linestream >> x))\n {\n // Reading more data worked. This means the input was good.\n // As the user typed a number followed by some other stuff\n // like 56.4 (the .4 is illegal)\n // 5Plop (the Plop is illegal)\n //\n // The the above would have successfully read a value into\n // `x` this with the ! it would have failded and this\n // this condition would not have been entered.\n\n // We only return if:\n // 1. We read an integer. \n // 2. There is no other data on the line except white space.\n return result;\n }\n }\n // invalid input\n std::cout << \"Stupid user input aborting\\n\";\n exit(1); // Reading failed.\n // Leave as an exercise on how to repeat the question.\n // You can also compress that very verbose if statement into a single\n // line without it looking too bad.\n}\n\n// Single line if\nif ((linestream >> result) && !(linestream >> x))\n{ return result;\n}\n</code></pre>\n\n<p>In Fib() you should probably not use recursion. Prefer a while loop. Loop from 0 upto the point you want to reach. This makes using a vector easy. You can also start from where you left off last time rather than 0.</p>\n\n<pre><code>int fib(int n)\n{\n static std::vector<int> values = {1,1};\n if (n < values.size()-1) }return values[n];\n\n int start = values.size();\n for(int loop = start; loop < n; ++loop)\n {\n values[loop] = values[loop-2] + values[loop-1];\n }\n return values[n];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:58:54.690",
"Id": "32261",
"ParentId": "32251",
"Score": "2"
}
},
{
"body": "<p>@Loki Astari has covered the important points, so I won't repeat those. I'll just address recommended integer and size types:</p>\n\n<ul>\n<li><p>For <code>getUserNum()</code>, you're specifically asking the user for a positive number. So, instead of reading into an <code>int</code>, use an <code>unsigned int</code>. You should still include validation. This also better reveals your intent to the reader.</p>\n\n<p>You could also instead have <code>main()</code> get this input. That way, if you don't want to hound the user for proper input, you could just return <code>EXIT_FAILURE</code> if the first attempt fails.</p></li>\n<li><p><code>size_t</code> is <em>not quite</em> close enough for <code>std::vector</code> (and <code>std::size_t</code> is more C++-like anyway). Although it is an STL container, it's best not to assume that each one is of this type. <a href=\"https://stackoverflow.com/a/409396/1950231\">For all STL containers, prefer <code>size_type</code> as it's more portable</a>:</p>\n\n<pre><code>standardContainerType::size_type;\n</code></pre>\n\n<p>For your vector:</p>\n\n<pre><code>std::vector<int>::size_type;\n</code></pre>\n\n<p>In <code>fib()</code>'s for-loop, use this type for <code>i</code>:</p>\n\n<pre><code>// this could go before the loop\n// if it looks too long to go inside\nstd::vector<int>::size_type i;\n\n// since this is an integer type,\n// post-increment is okay here\nfor (i = 0; i < v.size(); i++)\n{\n // ...\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T03:41:47.030",
"Id": "51559",
"Score": "0",
"body": "Thanks Jamal again for your help, slightly confused about the data types mentioned will do some reading on the subject."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T03:56:53.200",
"Id": "51560",
"Score": "0",
"body": "@ao2130: Sounds good. I'd say the second point about `size_type` is more important. The `unsigned int` just looks nicer, but it shouldn't cause problems."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T21:06:30.783",
"Id": "32263",
"ParentId": "32251",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T16:44:33.237",
"Id": "32251",
"Score": "1",
"Tags": [
"c++",
"recursion",
"beginner",
"vectors"
],
"Title": "How can I store the fibonacci sequence in a vector during each recursive call?"
}
|
32251
|
<p>I'm working my way through <em>The Java Programming Language, Fourth Edition - The Java Series</em>. This is Exercise 7.3:</p>
<blockquote>
<p>Write a program that calculates Pascal's triangle to a depth of 12, storing each row of the triangle in an array of the appropriate length and putting each of the row arrays into an array of 12 int arrays. Design your solution so that the results are printed by a method that prints the array of arrays using the lengths of each array, not a constant 12. Now change the code to use a constant other than 12 without modifying your printing method.</p>
</blockquote>
<p>Is the following an adequate solution? Is my use of exception handling reasonable for this use case?</p>
<pre><code>/**
* Defines Pascal's Triangle
*/
public class PascalsTriangle {
private final long[][] triangle;
/**
* Sole constructor
*
* @param depth the depth of the triangle
*/
PascalsTriangle(int depth) {
triangle = new long[depth][];
long upperLeft;
long upperRight;
for (int i = 0; i < depth; i++) {
triangle[i] = new long[i + 1];
for (int j = 0; j < i + 1; j++) {
if(i == 0) {
triangle[i][j] = 1; //seed the triangle
}
else {
try {
upperLeft = triangle[i - 1][j - 1];
} catch (ArrayIndexOutOfBoundsException e) {
upperLeft = 0; //upperLeft is 0 if not found
}
try {
upperRight = triangle[i - 1][j];
} catch (ArrayIndexOutOfBoundsException e) {
upperRight = 0; //upperRight is 0 if not found
}
triangle[i][j] = upperLeft + upperRight;
}
}
}
}
/**
* Prints the triangle to System.out
*/
public void printTriangle() {
for (long[] iTriangle : triangle) {
for (long jTriangle : iTriangle) {
System.out.printf("%d ", jTriangle);
}
System.out.println();
}
}
/**
* Main method - create and print a triangle
*/
public static void main(String[] arg) {
PascalsTriangle triangle = new PascalsTriangle(10);
triangle.printTriangle();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are 2½ things wrong with your code, otherwise it's fine.</p>\n\n<ol>\n<li><p>Use exception handling with <code>try</code>/<code>catch</code> for exceptional circumstances, not for trivial bounds checking which you can do! The snippet</p>\n\n<pre><code>try {\n upperLeft = triangle[i - 1][j - 1];\n} catch (ArrayIndexOutOfBoundsException e) {\n upperLeft = 0; //upperLeft is 0 if not found\n}\n</code></pre>\n\n<p>throws an error if <code>j == 0</code> – you already handled the <code>i == 0</code> case. You can avoid this by starting the loop one index later, and just putting a <code>1</code> in the first field. The same considerations hold for the last array entry.</p>\n\n<p>When we initialize the bounds outside of the loops, we get something like:</p>\n\n<pre><code>// init first row\ntriangle[0] = new long[]{ 1 };\n\nfor (int i = 1; i < depth; i++) {\n triangle[i] = new long[i + 1];\n\n // init first and last element \n triangle[i][0] = 1;\n triangle[i][i] = 1;\n\n for (int j = 1; j < i; j++) {\n long left = triangle[i - 1][j - 1];\n long right = triangle[i - 1][j ];\n triangle[i][j] = left + right;\n }\n}\n</code></pre>\n\n<p>By handling these edge cases <em>seperately</em>, I can radically shorten the code, and can omit exception handling.</p></li>\n<li><p>In- and Output should happen in the <code>main</code> method, not in helpers. You have written a <code>printTriangle</code> method, which hardcodes the <code>System.out</code> stream. It would be better to assemble a string representation in a <code>toString()</code> method, and then print out the result from that:</p>\n\n<pre><code>public String toString() {\n Formatter formatter = new Formatter(new StringBuilder(), null);\n for (long[] row : triangle) {\n for (long i : row) {\n formatter.format(\"%d \", i);\n }\n formatter.format(\"\\n\");\n }\n return formatter.toString();\n}\n</code></pre>\n\n<p>Then in <code>main</code>: <code>System.out.print(triangle.toString())</code>.</p></li>\n</ol>\n\n<p>What I haven't addressed until now is your usage of variables. You should declare your variables as close to their point of usage as possible, and in the tightest possible scope. Your <code>upperLeft</code> etc. is only relevant inside the <code>else</code> branch of your original code – if you look at my version, you see I declared the corresponding variable inside the loop as well.</p>\n\n<p>Oh, and your names for the loop variables in <code>printTriangle()</code> are weird. The letters <code>i</code> and <code>j</code> usually denote integers in loops, a convention taken from mathematics into programming. It is better to use names that are actually connected to the problem you are solving. If you look at my snippet, you'll see that I iterate over each <code>row</code> in the <code>triangle</code>, and then over each long integer <code>i</code> in that row.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:51:33.010",
"Id": "51542",
"Score": "1",
"body": "You don't need the `// init first row` special case. Just let `i` start from zero, as in `for (int i = 0; i < depth; i++) { ... }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:52:14.637",
"Id": "51543",
"Score": "2",
"body": "Also, slightly more compact: `triangle[i][0] = triangle[i][i] = 1` on one line."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T19:10:20.350",
"Id": "32260",
"ParentId": "32255",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "32260",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:20:17.320",
"Id": "32255",
"Score": "4",
"Tags": [
"java",
"classes"
],
"Title": "Critique of Pascal's Triangle Class"
}
|
32255
|
<p><strong>Reason for script:</strong></p>
<p><a href="http://www.w3.org/International/tests/html5/the-dir-attribute/results-dir-auto" rel="nofollow"><code>dir="auto"</code> is an attribute value from the HTML 5 spec with current poor support in IE and Opera browsers</a>. The project I am working on only cares about IE, Firefox and Safari browsers and handles text in both left to right LTR and right to left RTL languages. For cases where the directionality of the text coming from the data source is unkown, I would like to use <code>dir="auto"</code> to handle most cases of directionality. For IE, I would like to simulate this functionality using JavaScript.</p>
<p><strong>Goal of review:</strong></p>
<p>I am hopeful that a review of my work will identify areas where I can improve the code to be more in line with its stated purpose as well as aligning the code to best practices and identifying any bugs that may exist.</p>
<p><strong>Implementation:</strong></p>
<ul>
<li><p>An <code>isLTR</code> function was used as I figured most use cases would be against LTR text as opposed to RTL.</p></li>
<li><p>In my research, I wandered across <a href="http://www.w3.org/International/tests/html5/the-dir-attribute/results-dir-auto" rel="nofollow">a script by Nicholas Zakas</a> which I thought would be useful and have integrated it into my solution.</p></li>
<li><p>The project uses Dojo 1.8.1.</p></li>
</ul>
<p><strong>XHTML:</strong></p>
<p>Script call in <code>head</code> tag after call to Dojo library:</p>
<pre><code><!--[if IE]><script type="text/javascript" src="./PatternsTools/PatternsBidi.js"></script><![endif]-->
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>window.Patterns = window.Patterns || {};
window.Patterns.Bidi = window.Patterns.Bidi || {};
window.Patterns.Bidi.Strings = window.Patterns.Bidi.Strings || {};
window.Patterns.Bidi.Strings.LTRcharacters = "\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u202A\u202D\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
window.Patterns.Bidi.Strings.RTLcharacters = "\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC";
window.Patterns.Bidi.Strings.NeutralWeakCharacters = "\u0000-\u0040\u005B-\u0060\u007B-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF\u2010-\u2029\u202C\u202F-\u2BFF";
(function(/*Class Object*/ Bidi){
function getDirection(/*HTML Element*/ element) {
/*Copyright 2010 Nicholas C. Zakas. All rights reserved.*/
/*MIT Licensed*/
var result = null;
if (element){
if (window.getComputedStyle){
result = window.getComputedStyle(element,null).direction;
} else if (element.currentStyle){
result = element.currentStyle.direction;
}
}
return result;
}
function prependOverride(/*HTML Element*/ element, /*Boolean*/ isLTR) {
var direction = getDirection(element) === "ltr";
if (isLTR !== direction) {
element.innerHTML = (isLTR ? "&#8237;" : "&#8238;") + element.innerHTML + "&#8236;";
}
}
function isLTR(/*String*/ s) {
var ltrDirCheck = new RegExp("^[" + Bidi.Strings.NeutralWeakCharacters + "]*?[" + Bidi.Strings.LTRcharacters + "]");
return ltrDirCheck.test(s);
};
(function init() {
require(["dojo/ready", "dojo/_base/array"], function(/*Function*/ ready, /*Object*/ array) {
ready(function() {
array.forEach(dojo.query("[dir=auto]"), function(/*HTML Element*/ element, /*Integer*/ i) {
prependOverride(element, isLTR(element.innerHTML));
});
});
});
})();
})(window.Patterns.Bidi);
</code></pre>
|
[] |
[
{
"body": "<p>My 2 cents:</p>\n\n<ul>\n<li>Code looks really good overall</li>\n<li>In <code>prependOverride</code>, the naming is unfortunate\n<ul>\n<li>The parameter isLTR is really what you request, not what it is</li>\n<li>The var direction really is a boolean, not the direction of the element</li>\n<li>If you are going to /** type **/ variables, you might as well go Spartan and use <code>e</code> instead of <code>element</code></li>\n</ul></li>\n<li><code>prependOverride</code> has 4 magical constants </li>\n<li>isLTR should cache the regex, not rebuild it in every call </li>\n</ul>\n\n<p>for prependOverride the following might be cleaner:</p>\n\n<pre><code>function prependOverride(/*HTML Element*/ e, /*Boolean*/ requiresLTR) {\n var hasLTR = getDirection(e) === \"ltr\";\n if (hasLTR !== requiresLTR) {\n e.innerHTML = (requiresLTR? \"&#8237;\" : \"&#8238;\") + e.innerHTML + \"&#8236;\";\n }\n}\n</code></pre>\n\n<p>or, even you could pass the direction you require</p>\n\n<pre><code>function prependOverride(/*HTML Element*/ e, /*String*/ requiredLTR) {\n var actualLTR = getDirection(e);\n if (actualLTR !== requiredLTR) {\n e.innerHTML = (requiredLTR==\"ltr\"? \"&#8237;\" : \"&#8238;\") + e.innerHTML + \"&#8236;\";\n }\n}\n</code></pre>\n\n<p>I will leave the naming of the magical constants to you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T14:47:15.680",
"Id": "37593",
"ParentId": "32256",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T18:32:06.223",
"Id": "32256",
"Score": "8",
"Tags": [
"javascript",
"regex",
"i18n",
"unicode",
"dojo"
],
"Title": "dir=\"auto\" JavaScript shim for IE"
}
|
32256
|
<pre><code>public class ArrayList<E> implements List<E> {
private static final int defaultMaxSize = 10;
private int maxSize;
private int size;
private int currentPosition;
private E[] array;
/**
* Create a new ArrayList object.
*
* @param maxSize
*/
@SuppressWarnings("unchecked")
public ArrayList(int maxSize) {
this.maxSize = maxSize;
this.size = this.currentPosition = 0;
this.array = (E[]) new Object[this.maxSize];
}
/**
* Create a new ArrayList object.
*/
public ArrayList() {
this(defaultMaxSize);
}
@Override
public void insert(E item) {
assert this.size < this.maxSize : "ArrayList capacity exceeded";
for (int i = this.size; i > this.currentPosition; i--) {
// Shift elements up to make room
this.array[i] = this.array[i - 1];
}
this.array[this.currentPosition] = item;
this.size++;
}
@Override
public void append(E item) {
assert this.size < this.maxSize : "ArrayList capacity exceeded";
this.array[this.size++] = item;
}
@Override
public E remove() {
if ((this.currentPosition < 0) || (this.currentPosition >= this.size)) {
return null;
}
E item = this.array[this.currentPosition];
for (int i = this.currentPosition; i < this.size - 1; i++) {
this.array[i] = this.array[i + 1];
}
this.size--;
return item;
}
@Override
public void clear() {
this.size = this.currentPosition = 0;
}
@Override
public void moveToStart() {
this.currentPosition = 0;
}
@Override
public void moveToEnd() {
this.currentPosition = this.size;
}
@Override
public boolean previous() {
if (this.currentPosition != 0) {
this.currentPosition--;
return true;
} else {
return false;
}
}
@Override
public boolean next() {
if (this.currentPosition < this.size) {
this.currentPosition++;
return true;
} else {
return false;
}
}
@Override
public int length() {
return this.size;
}
@Override
public int currentPosition() {
return this.currentPosition;
}
@Override
public void moveCurrentToPosition(int position) {
assert (position >= 0) && (position <= this.size) : "position is out of range";
this.currentPosition = position;
}
@Override
public E getValue() {
assert (this.currentPosition >= 0) && (this.currentPosition < this.size) :
"No current element";
return this.array[this.currentPosition];
}
}
</code></pre>
<p>And here is the List interface!</p>
<pre><code>public interface List<E> {
/**
* Insert an element behind the current position. Must check that the linked
* list's capacity is not exceeded.
*
* @param item
* Item to be inserted.
*/
public void insert(E item);
/**
* Insert an element after the last element in the list.
*
* @param item
* Item to be appended.
*/
public void append(E item);
/**
* Remove the element after the current element and return the value of the
* removed element.
*
* @return The element that was removed.
*/
public E remove();
/**
* Remove all contents from the list.
*/
public void clear();
/**
* Move current position to first element.
*/
public void moveToStart();
/**
* Move current position to last element.
*/
public void moveToEnd();
/**
* Move the current position one element before. No change if already at the
* beginning.
*
* @return True if moved to previous position; otherwise return false.
*/
public boolean previous();
/**
* Move the current position one element after. No change if already at the
* end.
*
* @return True if moved to current position; otherwise return false.
*/
public boolean next();
/**
* @return The number of items in the list.
*/
public int length();
/**
* @return The current position.
*/
public int currentPosition();
/**
* @param position
* Position to move current to.
*/
public void moveCurrentToPosition(int position);
/**
* @return The current item in the current position.
*/
public E getValue();
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>First and foremost : why are you writing this class? It doesn't look like an improvement or a specialized version of <code>java.util.ArrayList</code>.</li>\n<li>the <code>insert()</code> contract states : \"Must check that the linked list's capacity is not exceeded.\" (wait, linked list?). You implement this with an <code>assert</code>. Yet asserts can be disabled. Don't use <code>assert</code> to honor the contract. It also is worth mentioning that the contract is unclear about what to do when the capacity is insufficient.</li>\n<li><code>remove()</code>, <code>moveToStart()</code>, <code>moveToEnd()</code>, <code>previous()</code>, <code>next()</code>, <code>getValue()</code> and <code>currentPosition()</code> are things that belong on a <code>ListIterator</code>. This allows for more flexibility - having multiple iterators at the same time for instance.</li>\n<li>Since the underlying array does not grow when the original capacity is insufficient, your class adds little value compared to a naked array.</li>\n<li>naming wise the documentation talks about <em>capacity</em>, yet the implementation names it <code>maxSize</code>, it's better to name this field consistent with the documentation. There is a similar mismatch with '<em>length</em>' and '<em>size</em>'.</li>\n<li><code>insert()</code> manually shifts elements, instead of using the more efficient <code>System.arrayCopy()</code> - the same goes for <code>remove()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T23:05:27.803",
"Id": "51553",
"Score": "0",
"body": "I'd assume he's writing it just as a fun exercise for himself, not in an attempt to improve the existing API. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T00:38:47.183",
"Id": "51555",
"Score": "0",
"body": "Ya it's just an exercise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T06:50:20.900",
"Id": "51561",
"Score": "0",
"body": "In that case, why don't you implement the `java.util.List` interface?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T22:59:09.197",
"Id": "32264",
"ParentId": "32262",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32264",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T20:58:42.620",
"Id": "32262",
"Score": "2",
"Tags": [
"java",
"array"
],
"Title": "Can someone review my implementation of an ArrayList?"
}
|
32262
|
<p>I wrote a <a href="https://bitbucket.org/bigstones/automatica" rel="nofollow noreferrer">small library</a> to learn Haskell while studying Automata theory. I have <a href="https://softwareengineering.stackexchange.com/q/213441/50398">some concerns</a> on my algorithm to evaluate state reachability. That is, I think it might be improved if I can avoid checking paths already excluded in other branches of the search for a valid path. This one recursively checks each path separately.</p>
<p>I hope I didn't forget anything. Other suggestions are obviously welcome!</p>
<h2>Automaton data type</h2>
<pre><code>-- | Represents an automaton in the form
-- /G = (X, E, f, Gamma, x_0, X_m)/
--
-- NB: we're not including Gamma in the definition of Automaton
data Automa st ev = Automa {
states :: [st], -- ^ /X/, set of states
events :: [ev], -- ^ /E/, set of events
mapTrans :: M.Map (st,ev) st, -- ^ not /f/, but a map of
-- transitions (see 'trans')
initial :: st, -- ^ /x_0/, initial state
marked :: [st] -- ^ /X_m/, set of marked states
} deriving (Show, Read)
</code></pre>
<h2>Reachability function</h2>
<pre><code>-- | True if a state can reach another for some string of events.
canReach :: (Ord st, Ord ev)
=> st -- ^ starting state 's'
-> st -- ^ arrival state 's''
-> Automa st ev
-> Bool
canReach s s' au = canReachExcluding s s' au []
-- | True if a state can reach another for some string of events,
-- excluding passing from specified states.
canReachExcluding :: (Ord st, Ord ev)
=> st -- ^ starting state 's'
-> st -- ^ arrival state 's''
-> Automa st ev
-> [st] -- ^ the states to be excluded
-> Bool
canReachExcluding s s' au ex = s == s' || any (== s') rs
|| any (\x -> canReachExcluding x s' au (s:ex)) rs
where rs = reach1From s au \\ ex
-- | Returns states reachable from specified state in one step.
reach1From :: (Ord st, Ord ev) => st -> Automa st ev -> [st]
reach1From s au = [ trans' (s,e) au | e <- gammaL s au ]
</code></pre>
<h2>Accessory functions</h2>
<pre><code>-- | Indicator function of active states for an automaton
gamma :: (Ord st, Ord ev)
=> (st,ev) -- ^ state-event pair of interest
-> Automa st ev
-> Bool -- ^ 'True' if 'ev' is active for 'st'
gamma (s,e) au = M.member (s,e) $ mapTrans au
-- | Returns a list of active events for a state of a given 'Automa'
gammaL :: (Ord st, Ord ev) => st -> Automa st ev -> [ev]
gammaL s au = [ e | e <- events au, gamma (s,e) au ]
-- | Transition function: where do I get if 'ev' happens when in 'st'?
trans :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> Maybe st
trans (s,e) au = M.lookup (s,e) $ mapTrans au
-- | Like 'trans', but to be used if you're sure it's a valid
-- transition (i.e. saves you a 'fromJust').
trans' :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> st
trans' (s,e) au = fromJust $ M.lookup (s,e) $ mapTrans au
</code></pre>
|
[] |
[
{
"body": "<p>This is neat, methinks. </p>\n\n<p>A couple of questions/points:</p>\n\n<ol>\n<li>Is the <code>|| any (== s') rs</code> part of <code>canReachExcluding</code> necessary?</li>\n<li>In the same definition, the part <code>rs = reach1From s au \\\\ ex</code> takes time linear in the size of <code>ex</code>. Using a set (or hash) instead of a list for <code>ex</code> would probably improve your running time significantly in practice. But of course, that'd likely be at the expense of the clarity of your beautiful program. </li>\n<li>You are of course right that your program checks \"states excluded in other branches\". What you are \"really\" implementing is <a href=\"http://en.wikipedia.org/wiki/Depth-first_search\" rel=\"nofollow noreferrer\">depth-first search</a> (DFS) on the graph defined by the automaton, and so you might want to look for a more efficient (functional) implementation of DFS. In that case, you could either look at the <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/containers-0.5.0.0/Data-Graph.html\" rel=\"nofollow noreferrer\">Haskell Library implementation</a>, or maybe just this <a href=\"https://stackoverflow.com/questions/12739028/dfs-implementation-in-haskell\">quick-and-dirty approach</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:04:15.290",
"Id": "43812",
"ParentId": "32266",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T23:37:35.637",
"Id": "32266",
"Score": "6",
"Tags": [
"algorithm",
"haskell",
"state-machine"
],
"Title": "Automata theory, state reachability in Haskell"
}
|
32266
|
<pre><code>public class KeyValuePair implements Comparable {
private Comparable key;
private Object value;
public KeyValuePair(Comparable key, Object value) {
this.key = key;
this.value = value;
}
@Override
public int compareTo(Object item) throws ClassCastException {
if (!(item instanceof KeyValuePair)) {
throw new ClassCastException("A KeyValuePair object was expected");
}
return this.key.compareTo(((KeyValuePair) item).key);
}
public Comparable getKey() {
return this.key;
}
public Object getValue() {
return this.value;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You shouldn't need to throw <code>ClassCastException</code> explicitly; it would be thrown automatically by the JVM if the cast actually fails.</p>\n\n<p>However, you shouldn't have to deal with casting at all if you use Java Generics properly.</p>\n\n<pre><code>public class KeyValuePair<K extends Comparable<K>, V>\n implements Comparable<KeyValuePair<K, V>> {\n\n private K key;\n private V value;\n\n public KeyValuePair(K key, V value) {\n this.key = key;\n this.value = value;\n }\n\n @Override\n public int compareTo(KeyValuePair<K, V> item) {\n return this.key.compareTo(item.key);\n }\n\n public K getKey() {\n return this.key;\n }\n\n public V getValue() {\n return this.value;\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> As @ortang points out, there's more work to be done! Since the key and value are immutable, marking them <code>final</code> is helpful. Also, the class needs to override <code>.equals()</code>, and when that happens, <code>.hashCode()</code> needs to be overridden too. Finally, it may be worthwhile to handle some odd cases in <code>.compareTo()</code>.</p>\n\n<pre><code>public class KeyValuePair<K extends Comparable<K>, V> implements Comparable<KeyValuePair<K, V>> {\n\n private final K key;\n private final V value;\n\n public KeyValuePair(K key, V value) {\n this.key = key;\n this.value = value;\n }\n\n // Arbitrarily decide to sort null keys first. Values are disregarded for\n // the purposes of comparison.\n @Override\n public int compareTo(KeyValuePair<K, V> item) {\n if (this.key == null) {\n return (item.key == null) ? 0 : -1;\n } else {\n return this.key.compareTo(item.key);\n }\n }\n\n public K getKey() {\n return this.key;\n }\n\n public V getValue() {\n return this.value;\n }\n\n @Override\n public boolean equals(Object other) {\n if (other == null || !this.getClass().equals(other.getClass())) {\n return false;\n }\n KeyValuePair item = (KeyValuePair)other;\n return (this.key == null ? item.key == null : this.key.equals(item.key)) &&\n (this.value == null ? item.value == null : this.value.equals(item.value));\n }\n\n @Override\n public int hashCode() {\n return ((this.key == null) ? 0 : this.key.hashCode()) ^\n ((this.value == null) ? 0 : this.value.hashCode());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T16:43:31.463",
"Id": "51581",
"Score": "2",
"body": "Also mark the `key` and `value` as `final`, maybe even the class to be immutable and implement at least `equals()` as it is [required](http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T04:47:10.650",
"Id": "32274",
"ParentId": "32267",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "32274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T01:31:27.547",
"Id": "32267",
"Score": "3",
"Tags": [
"java"
],
"Title": "Can someone review my implementation of a KeyValuePair?"
}
|
32267
|
<p>So here is my Queue interface:</p>
<pre><code>public interface Queue<E> {
/**
* Add an item to the rear of the queue.
*
* @param item
* Item to be added.
*/
public void enqueue(E item);
/**
* Remove and return the item at the front of the queue.
*
* @return The item that was removed.
*/
public E dequeue();
/**
* @return The item at the front of the queue.
*/
public E frontValue();
/**
* @return How many elements are in the queue.
*/
public int length();
/**
* Remove all the items in the queue.
*/
public void clear();
}
</code></pre>
<p>And here is my actual implementation:</p>
<pre><code>public class LinkedQueue<E> implements Queue<E> {
private SinglyLinkedListNode<E> front;
private SinglyLinkedListNode<E> rear;
private int size;
/**
* Create a new LinkedQueue object.
*/
public LinkedQueue() {
this.init();
}
private void init() {
// only one object is constructed
this.front = this.rear = new SinglyLinkedListNode<E>(null, null);
this.size = 0;
}
@Override
public void enqueue(E value) {
this.rear.setNextNode(new SinglyLinkedListNode<E>(value, null));
this.rear = this.rear.getNextNode();
this.size++;
}
@Override
public E dequeue() {
if (this.size == 0) {
throw new IllegalStateException("In method dequeue of class "
+ "LinkedQueue the linked queue is empty can cannot"
+ " be dequeued");
}
E item = this.front.getNextNode().getValue();
this.front.setNextNode(this.front.getNextNode().getNextNode());
if (this.front.getNextNode() == null) {
this.rear = this.front;
}
this.size--;
return item;
}
@Override
public E frontValue() {
if (this.size == 0) {
throw new IllegalStateException("In method frontValue of class "
+ "LinkedQueue the linked queue is empty");
}
return this.front.getNextNode().getValue();
}
@Override
public int length() {
return this.size;
}
@Override
public void clear() {
this.init();
}
/**
* Creates a easy to read String representation of the linked queue's
* contents.
*
* Example: < 1 2 3 4 5 6 >
*/
public String toString() {
StringBuilder linkedQueueAsString = new StringBuilder();
linkedQueueAsString.append("< ");
System.out.println("front.getNextNode: " + this.front.getNextNode());
for (SinglyLinkedListNode<E> node = this.front.getNextNode(); node != null; node = node.getNextNode()) {
linkedQueueAsString.append(node.getValue());
System.out.println(node.getValue() + ",");
linkedQueueAsString.append(" ");
}
linkedQueueAsString.append(">");
return linkedQueueAsString.toString();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You should <strong>not</strong> name your interface <code>Queue</code>, since <code>java.util.Queue</code> already exits.</p>\n\n<p>Also it would be helpful if you post the source of <code>SingleLinkedListNode</code>. </p>\n\n<p>The source looks fine to me, you could however add two methods like (append/en-queue, remove/de-queue):</p>\n\n<p><code>SingleLinkedListNode<E> append(SingleLinkedListNode<E> newNode)</code> that will replace</p>\n\n<pre><code> this.rear.setNextNode(new SingleLinkedListNode<E>(value, null));\n this.rear = this.rear.getNextNode();\n</code></pre>\n\n<p>and returns the next node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T16:59:58.543",
"Id": "32293",
"ParentId": "32268",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32293",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T01:39:01.847",
"Id": "32268",
"Score": "1",
"Tags": [
"java",
"queue"
],
"Title": "Can someone review my implementation of a Queue?"
}
|
32268
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.