body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is code of a rails app. The code has the logic used in a search form. It queries a MySQL database. Any thoughts on something that would make this unsafe or violated a rails principle?</p>
<p>/app/models/query.rb</p>
<pre><code>class Query < ActiveRecord::Base
attr_accessible :customer_email, :customer_first_name, :customer_last_name,
:max_total_amount, :min_total_amount, :order_id, :order_is_deleted,
:order_max_date, :order_min_date, :results_limit, :postal_code,
:subscribes_to_daily_emails
def orders
@orders ||= find_orders
end
#TO DO:
#1. Pagination:
#2. Add limit if not present when there could be too many results. DONE! Set limit to 50.
#3. Add export feature and remove limit for export.
private
def find_orders
@results_limitVar = nil
if results_limit.nil? == true
@results_limitVar = 50
else
@results_limitVar = results_limit
end
@subscribes_to_daily_emailsVar = nil
if subscribes_to_daily_emails.nil? == false
if subscribes_to_daily_emails
@subscribes_to_daily_emailsVar = 1
else
@subscribes_to_daily_emailsVar = 0
end
end
@order_is_deletedVar = nil
if order_is_deleted.nil? == false
if order_is_deleted
@order_is_deletedVar = 1
else
@order_is_deletedVar = 0
end
end
#Added orders explicitly because otherwise first_name, etc is ambiguous
#since it is in multiple models.
orders = Order.order(:order_id)
orders = orders.where("orders.first_name LIKE ?", "%#{customer_first_name}%") if customer_first_name.present?
orders = orders.where("orders.last_name LIKE ?", "%#{customer_last_name}%") if customer_last_name.present?
orders = orders.where("orders.email_address LIKE ?", "%#{customer_email}%") if customer_email.present?
orders = orders.where("orders.order_id like ?", "%#{order_id}%") if order_id.present?
orders = orders.where("orders.is_deleted = ?", "#{@order_is_deletedVar}") if !@order_is_deletedVar.nil?
orders = orders.where("total_amount >= ?", min_total_amount) if min_total_amount.present?
orders = orders.where("total_amount <= ?", max_total_amount) if max_total_amount.present?
orders = orders.where("order_date >= ?", order_min_date) if order_min_date.present?
orders = orders.where("order_date <= ?", order_max_date) if order_max_date.present?
orders = orders.joins("INNER JOIN customers ON customers.customer_id = orders.customer_id AND customers.postal_code LIKE ", "'%#{postal_code}%'") if postal_code.present?
orders = orders.joins("INNER JOIN email_preferences ON email_preferences.customer_id = orders.customer_id AND email_preferences.subscribes_to_daily_emails = ", "#{@subscribes_to_daily_emailsVar}") if !@subscribes_to_daily_emailsVar.nil?
orders = orders.limit(@results_limitVar) if !@results_limitVar.nil?
orders
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I think you could change your code to this :</p>\n\n<pre><code>class Query < ActiveRecord::Base\n attr_accessible :customer_email, :customer_first_name, :customer_last_name, \n :max_total_amount, :min_total_amount, :order_id, :order_is_deleted,\n :order_max_date, :order_min_date, :results_limit, :postal_code,\n :subscribes_to_daily_emails\n\n def orders\n @orders ||= find_orders\n end\n\n #TO DO:\n #1. Pagination:\n #2. Add limit if not present when there could be too many results. DONE! Set limit to 50.\n #3. Add export feature and remove limit for export.\n\n private\n def find_orders\n @results_limitVar = results_limit || 50\n\n @subscribes_to_daily_emailsVar = nil\n\n if subscribes_to_daily_emails\n @subscribes_to_daily_emailsVar = subscribes_to_daily_emails ? 1 : 0\n end\n\n @order_is_deletedVar = nil\n\n if order_is_deleted\n @order_is_deletedVar = order_is_deleted ? 1 : 0\n end\n\n #Added orders explicitly because otherwise first_name, etc is ambiguous \n #since it is in multiple models.\n\n orders = Order.order(:order_id)\n orders = orders.where(\"orders.first_name LIKE ?\", \"%#{customer_first_name}%\") if customer_first_name\n orders = orders.where(\"orders.last_name LIKE ?\", \"%#{customer_last_name}%\") if customer_last_name\n orders = orders.where(\"orders.email_address LIKE ?\", \"%#{customer_email}%\") if customer_email \n orders = orders.where(\"orders.order_id like ?\", \"%#{order_id}%\") if order_id\n orders = orders.where(\"orders.is_deleted = ?\", \"#{@order_is_deletedVar}\") if @order_is_deletedVar.present?\n orders = orders.where(\"total_amount >= ?\", min_total_amount) if min_total_amount\n orders = orders.where(\"total_amount <= ?\", max_total_amount) if max_total_amount\n orders = orders.where(\"order_date >= ?\", order_min_date) if order_min_date\n orders = orders.where(\"order_date <= ?\", order_max_date) if order_max_date\n orders = orders.joins(\"INNER JOIN customers ON customers.customer_id = orders.customer_id AND customers.postal_code LIKE \", \"'%#{postal_code}%'\") if postal_code\n orders = orders.joins(\"INNER JOIN email_preferences ON email_preferences.customer_id = orders.customer_id AND email_preferences.subscribes_to_daily_emails = \", \"#{@subscribes_to_daily_emailsVar}\") if @subscribes_to_daily_emailsVar.present?\n orders = orders.limit(@results_limitVar)\n orders\n end\n\nend\n</code></pre>\n\n<p>I refactored your if conditions. Instead of :</p>\n\n<blockquote>\n<pre><code>if var.nil? == false\nif !var.nil?\n</code></pre>\n</blockquote>\n\n<p>It's better to write like this:</p>\n\n<pre><code>if var.present?\n</code></pre>\n\n<p>In your case you can simply do :</p>\n\n<pre><code>if var\n</code></pre>\n\n<p>For your query, please watch look at <a href=\"http://guides.rubyonrails.org/active_record_querying.html#scopes\" rel=\"nofollow\">the scopes</a>.</p>\n\n<p>You can do this :</p>\n\n<pre><code>class Query < ActiveRecord::Base\n scope :first_name_like, lambda { |first_name| where(\"orders.first_name LIKE ?\", \"%#{first_name}%\") }\n ...\n def find_orders\n ...\n orders = orders.first_name_like(customer_last_name)\n ...\n end\nend\n</code></pre>\n\n<p>It's interessent for your loooooong inner join. </p>\n\n<p>I think if you column is a boolean you don't need to convert the value and you could do this :</p>\n\n<pre><code>orders.where(\"orders.is_deleted = ?\", \"#{order_is_deleted}\")\n</code></pre>\n\n<p>The last thinks. Instead of this : </p>\n\n<blockquote>\n<pre><code>@results_limitVar\n</code></pre>\n</blockquote>\n\n<p>Write like this (by convention) :</p>\n\n<pre><code>@results_limit_var\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T16:31:46.303",
"Id": "13542",
"ParentId": "13530",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T05:26:44.897",
"Id": "13530",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "Rails app query form code behind"
}
|
13530
|
<p>I have a <code>FileAsset</code> class. I have a set of 'filters' with which I determine if a <code>FileAsset</code> should be written to my database. Below is a telescoped version of how the filters work now. My big question is this: Is there a better way? Any advice would be awesome!</p>
<p>(By the way, the <code>Attribute</code> key in the filters allows me to test other attributes of the <code>FileAsset</code> class which I have not demonstrated for simplicity's sake, but the concept is the same.)</p>
<pre><code>import os
from fnmatch import fnmatch
import operator
class FileAsset:
def __init__(self, filename):
self.filename = filename
@property
def is_asset(self):
filters = [
{'Test':'matches','Attribute':'filename','Value':'*'},
{'Test':'ends with','Attribute':'filename','Value':'txt'},
{'Test':'does not end with','Attribute':'filename','Value':'jpg'}]
results = []
try:
results.append(file_filter(self, filters))
except Exception as e:
results.append(True)
return True in results
def __repr__(self):
return '<FileAsset: %s>' % self.filename
def file_filter(file_asset,filters):
results = []
for f in filters:
try:
attribute = operator.attrgetter(f['Attribute'])(file_asset)
try:
result = filter_map(f['Test'])(attribute,f['Value'])
results.append(result)
except Exception as e:
print e
results.append(False)
except AttributeError as e:
print e
results.append(False)
return not False in results
def filter_map(test):
if test == u'is file':
return lambda x, y: os.path.isfile(x)
elif test == u'contains':
return operator.contains
elif test == u'matches':
return lambda x, y: fnmatch(x,y)
elif test == u'does not contain':
return lambda x, y: not y in x
elif test == u'starts with':
return lambda x, y: x.startswith(y)
elif test == u'does not start with':
return lambda x, y: not x.startswith(y)
elif test == u'ends with':
return lambda x, y: x.endswith(y)
elif test == u'does not end with':
return lambda x, y: not x.endswith(y)
# etc etc
fa1 = FileAsset('test.txt')
fa2 = FileAsset('test.jpg')
print '%s goes to db: %s' % (fa1.filename, fa1.is_asset)
print '%s goes to db: %s' % (fa2.filename, fa2.is_asset)
</code></pre>
|
[] |
[
{
"body": "<p>You have written a small DSL to map tests to Python operations. The DSL uses <code>dict</code>s which imposes some limitations. Try this approach instead:</p>\n\n<pre><code>filter1 = FileFilter().filenameEndsWith('.txt').build()\n\nnames = ['test.txt', 'test.jpg']\nto_save = filter(filter1, names)\n</code></pre>\n\n<p>How does that work? <code>FileFilter</code> is a builder. Builders are like flexible factories. Internally, the code could look like so:</p>\n\n<pre><code>class FileFilter:\n def __init__(self):\n self.conditions = []\n\n def filenameEndsWith(self, pattern):\n def c(filename):\n return filename.endswith(pattern)\n self.conditions.append(c)\n return self\n\n def build(self):\n def f(filename, conditions=self.conditions):\n for c in conditions:\n if not c(filename): return False\n return True\n return f\n</code></pre>\n\n<p>Notes: This is just an example. You will probably use lambdas and return an object that implements the filter API in <code>build()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T09:14:20.473",
"Id": "13532",
"ParentId": "13531",
"Score": "2"
}
},
{
"body": "<pre><code>import os\nfrom fnmatch import fnmatch\nimport operator\n\nclass FileAsset:\n def __init__(self, filename):\n self.filename = filename\n\n @property\n def is_asset(self):\n filters = [\n {'Test':'matches','Attribute':'filename','Value':'*'},\n {'Test':'ends with','Attribute':'filename','Value':'txt'},\n {'Test':'does not end with','Attribute':'filename','Value':'jpg'}]\n results = []\n try:\n results.append(file_filter(self, filters))\n except Exception as e:\n</code></pre>\n\n<p>Don't ever do this. Python will throw exceptions in the case of many bugs in your code. If you catch all exceptions, you'll eventually catch and hide a legitimate bug. Can this even happen? Don't you catch all the interesting exceptions in <code>file_filter</code>?</p>\n\n<pre><code> results.append(True)\n</code></pre>\n\n<p>Why do you make a list if you are only going to store a single value in it? It seems to you should just be doing <code>return file_filter(...</code></p>\n\n<pre><code> return True in results\n</code></pre>\n\n<p>Why do you construct a list, only to put a single item in it.</p>\n\n<pre><code> def __repr__(self):\n return '<FileAsset: %s>' % self.filename\n\ndef file_filter(file_asset,filters):\n results = []\n for f in filters:\n</code></pre>\n\n<p>I recommend spelling out <code>filter</code>, just for the extra clarity. </p>\n\n<pre><code> try:\n attribute = operator.attrgetter(f['Attribute'])(file_asset)\n</code></pre>\n\n<p>Just use <code>attribute = getattr(file_asset, f['Attribute'])</code>, there is no point in introducing operator here. </p>\n\n<pre><code> try:\n result = filter_map(f['Test'])(attribute,f['Value'])\n</code></pre>\n\n<p>This really looks like <code>filter_map</code> should take three arguments, and not be split across two function calls</p>\n\n<pre><code> results.append(result)\n except Exception as e:\n</code></pre>\n\n<p>If something goes wrong, do you really want to carry on as though nothing has happened? If the requested filter was invalid in some way an exception should be raised</p>\n\n<pre><code> print e\n results.append(False)\n</code></pre>\n\n<p>And why in the yellow tarnekey chicken is this False, when last time an exception made it True?</p>\n\n<pre><code> except AttributeError as e:\n print e\n results.append(False)\n</code></pre>\n\n<p>This is more acceptable, because you are attempting to specifically catch one exception, that of the attrgetter above. But you should the rest of the logic into an <code>else</code> block on the exception. But again, you should really throw an exception to indicate the filter was invalid.</p>\n\n<pre><code> return not False in results\n</code></pre>\n\n<p>Instead use, <code>return all(results)</code></p>\n\n<pre><code>def filter_map(test):\n if test == u'is file':\n return lambda x, y: os.path.isfile(x)\n</code></pre>\n\n<p>This would be a great place to use a dictionary. Have the dictionary from the test strings to the lambdas, and then you look them up. </p>\n\n<p>Here is my really big problem with your code. You've build this filtering logic system and created something harder to use, less powerful, and slower then just using python.</p>\n\n<p>Consider:</p>\n\n<pre><code>@property\ndef is_asset(self):\n return (\n fnmatch(self.filename, '*'),\n and self.filename.endswith('txt'),\n and not self.filename.endswith('jpg')\n )\n</code></pre>\n\n<p>It seems to me that this is: shorter, easier to follow, and more flexible then your system. And that's not even considering a better way to implement this</p>\n\n<pre><code>@property\ndef extension(self):\n return os.path.splitext(self.filename)[-1]\n\n@property\ndef is_asset(self):\n return self.extension == 'txt'\n</code></pre>\n\n<p>So I can't see how your system makes any sort of sense. But perhaps it makes more sense in the broader context of your system. If so, I'd like to see more of the broader context because I have trouble believing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T00:59:27.757",
"Id": "22140",
"Score": "0",
"body": "Thanks Winston. Sorry I'm not able to include the broader context of the problem. I understand it is difficult to provide more help without it. That being said, I learned a few things from your post. Appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T00:13:25.977",
"Id": "13552",
"ParentId": "13531",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13532",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T06:55:44.737",
"Id": "13531",
"Score": "2",
"Tags": [
"python"
],
"Title": "Filtering logic"
}
|
13531
|
<p>I have a MySQL result set in a PHP multidimensional array.</p>
<p>I want to iterate through it and output it sanitized. Considering the two alternatives below, are there any performance differences?</p>
<p><strong>filter_var_array on the whole result set before iterating:</strong></p>
<pre><code>$sql_rows = filter_var_array($sql_rows, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
foreach ($sql_rows as $sql_row) {
print '<p>' . $sql_row['first_name'] . $sql_row['last_name'] . '</p>';
}
</code></pre>
<p><strong>filter_var_array on each row inside the iteration:</strong></p>
<pre><code>foreach ($sql_rows as $sql_row) {
$sql_row = filter_var_array($sql_row, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
print '<p>' . $sql_row['first_name'] . $sql_row['last_name'] . '</p>';
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T13:34:18.170",
"Id": "21936",
"Score": "3",
"body": "It could go either way. On one hand, you run a function once, on the other you run it multiple times but on much smaller pieces. I'm not sure which would be the better bet for you. I'd try both, wrap `microtime()`s around each and see how long it took to perform each and then use whichever had better performance."
}
] |
[
{
"body": "<p>Is this really the bottleneck in you application? If not choose the readable one. See <em>Effective Java, 2nd Edition, Item 55: Optimize judiciously</em> I know that this is a Java book but this chapter (and many others) is useful for every developer.</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>I'd call the filtered variable something which shows that the data has been filtered, like <code>$filtered_row</code>. It would improve readability and help maintainers.</p></li>\n<li><p>The code prints the first name and the last name without any separator character. I'd consider printing a separator there:</p>\n\n<pre><code>print '<p>' . $sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';\n</code></pre></li>\n<li><p>If you use only the <code>first_name</code> and the <code>last_name</code> maybe you should only filter these fields not the whole array. (I don't know whether it contains other values or not.)</p></li>\n<li><p>Consider memory usage too. If I'm right the first one have to store the input and output array in the memory during the filtering which needs two times of the array size of memory temporarily. In the second case it's much smaller since it filters only one row at a time so it needs memory for the array once and two times of the size of a row during the filtering.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T23:53:58.753",
"Id": "21959",
"Score": "1",
"body": "Instead of: `print '<p>' . $sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';` do: `echo \"<p>{$sql_row['first_name']} {$sql_row['last_name']}</p>\";` - it's considerably more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T13:16:14.150",
"Id": "21965",
"Score": "1",
"body": "Many interesting and insightful points in your answer, thanks a lot!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T23:12:10.807",
"Id": "13551",
"ParentId": "13534",
"Score": "4"
}
},
{
"body": "<p>Instead of:</p>\n\n<pre><code>print '<p>' . $sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';\n</code></pre>\n\n<p>do:</p>\n\n<pre><code>echo \"<p>{$sql_row['first_name']} {$sql_row['last_name']}</p>\";\n</code></pre>\n\n<p>It's considerably more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T18:12:32.020",
"Id": "13595",
"ParentId": "13534",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T12:15:54.023",
"Id": "13534",
"Score": "2",
"Tags": [
"php",
"performance"
],
"Title": "Use filter_var_array on whole array, or inside iteration"
}
|
13534
|
<p>I have few controls on my page which I want to show/hide and/or enable/disable on some condition.</p>
<p>Images to help illustrate the requirements:</p>
<p><img src="https://i.stack.imgur.com/Vx1aD.png" alt="screenshot1">
<img src="https://i.stack.imgur.com/yQPOV.png" alt="screenshot2">
<img src="https://i.stack.imgur.com/isKNQ.png" alt="screenshot3"></p>
<p>Following is the code to show/hide, enable/disable the controls. Please review it and tell me how I can extract common code.<br>
Any other suggestion are also more than welcome.</p>
<pre><code>// Change controls status (enable/disable, show/hide) on the basis of selected item
protected void ddlLocationType_SelectedIndexChanged(object sender, EventArgs e)
{
int locationType = 0;
int.TryParse(ddlLocationType.SelectedItem.Value, out locationType);
EnableRelavantLocaitonControls(locationType);
}
private void EnableRelavantLocaitonControls(int locationType)
{
switch (locationType)
{
case 0:
DefaultControlsPosition();
break;
case 1:
EnableControlsForProvince();
break;
case 2:
EnableControlsForDistrict();
break;
case 3:
EnableControlsForTehsil();
break;
case 4:
EnableControlsForUC();
break;
case 6:
EnableControlsForVillage();
break;
default:
DefaultControlsPosition();
break;
}
}
// Show all drop downs.
// Hide all textboxes and disable all controls.
private void DefaultControlsPosition()
{
ddlProvince.Enabled = false;
ddlProvince.Visible = true;
txtProvince.Enabled = false;
txtProvince.Visible = false;
ddlDistrict.Enabled = false;
ddlDistrict.Visible = true;
ddlDistrict.Enabled = false;
txtDistrict.Visible = false;
ddlTehsil.Enabled = false;
ddlTehsil.Visible = true;
txtTehsil.Enabled = false;
txtTehsil.Visible = false;
ddlUC.Enabled = false;
ddlUC.Visible = true;
txtUC.Enabled = false;
txtUC.Visible = false;
ddlVillage.Enabled = false;
ddlVillage.Visible = true;
txtVillage.Enabled = false;
txtVillage.Visible = false;
}
// Show all drop downs except province drop down and disable all.
// Show and enable TextBox for province instead of drop down so user can
// enter name of province.
private void EnableControlsForProvince()
{
ddlProvince.Enabled = false;
ddlProvince.Visible = false;
txtProvince.Enabled = true;
txtProvince.Visible = true;
ddlDistrict.Enabled = false;
ddlDistrict.Visible = true;
ddlDistrict.Enabled = false;
txtDistrict.Visible = false;
ddlTehsil.Enabled = false;
ddlTehsil.Visible = true;
txtTehsil.Enabled = false;
txtTehsil.Visible = false;
ddlUC.Enabled = false;
ddlUC.Visible = true;
txtUC.Enabled = false;
txtUC.Visible = false;
ddlVillage.Enabled = false;
ddlVillage.Visible = true;
txtVillage.Enabled = false;
txtVillage.Visible = false;
}
// Show and Enable 'Province' drop down.
// Hide and Disable 'District' drop down.
// Show and Enable 'District' text box.
// Show and Disable all other drop downs beneath District.
private void EnableControlsForDistrict()
{
ddlProvince.Enabled = true;
ddlProvince.Visible = true;
txtProvince.Enabled = false;
txtProvince.Visible = false;
ddlDistrict.Enabled = false;
ddlDistrict.Visible = false;
txtDistrict.Enabled = true;
txtDistrict.Visible = true;
ddlTehsil.Enabled = false;
ddlTehsil.Visible = true;
txtTehsil.Enabled = false;
txtTehsil.Visible = false;
ddlUC.Enabled = false;
ddlUC.Visible = true;
txtUC.Enabled = false;
txtUC.Visible = false;
ddlVillage.Enabled = false;
ddlVillage.Visible = true;
txtVillage.Enabled = false;
txtVillage.Visible = false;
}
private void EnableControlsForTehsil()
{
ddlProvince.Enabled = true;
ddlProvince.Visible = true;
txtProvince.Enabled = false;
txtProvince.Visible = false;
ddlDistrict.Enabled = true;
ddlDistrict.Visible = true;
txtDistrict.Enabled = false;
txtDistrict.Visible = false;
ddlTehsil.Enabled = false;
ddlTehsil.Visible = false;
txtTehsil.Enabled = true;
txtTehsil.Visible = true;
ddlUC.Enabled = false;
ddlUC.Visible = true;
txtUC.Enabled = false;
txtUC.Visible = false;
ddlVillage.Enabled = false;
ddlVillage.Visible = true;
txtVillage.Enabled = false;
txtVillage.Visible = false;
}
private void EnableControlsForUC()
{
ddlProvince.Enabled = true;
ddlProvince.Visible = true;
txtProvince.Enabled = false;
txtProvince.Visible = false;
ddlDistrict.Enabled = true;
ddlDistrict.Visible = true;
txtDistrict.Enabled = false;
txtDistrict.Visible = false;
ddlTehsil.Enabled = true;
ddlTehsil.Visible = true;
txtTehsil.Enabled = false;
txtTehsil.Visible = false;
ddlUC.Enabled = false;
ddlUC.Visible = false;
txtUC.Enabled = true;
txtUC.Visible = true;
ddlVillage.Enabled = false;
ddlVillage.Visible = true;
txtVillage.Enabled = false;
txtVillage.Visible = false;
}
private void EnableControlsForVillage()
{
ddlProvince.Enabled = true;
ddlProvince.Visible = true;
txtProvince.Enabled = false;
txtProvince.Visible = false;
ddlDistrict.Enabled = true;
ddlDistrict.Visible = true;
txtDistrict.Enabled = false;
txtDistrict.Visible = false;
ddlTehsil.Enabled = true;
ddlTehsil.Visible = true;
txtTehsil.Enabled = false;
txtTehsil.Visible = false;
ddlUC.Enabled = true;
ddlUC.Visible = true;
txtUC.Enabled = false;
txtUC.Visible = false;
ddlVillage.Enabled = false;
ddlVillage.Visible = false;
txtVillage.Enabled = true;
txtVillage.Visible = true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T14:02:34.540",
"Id": "21939",
"Score": "1",
"body": "You need to put your requirements in words here or a embedded picure... you can't expect us to click through your links just to figure out what you're doing..."
}
] |
[
{
"body": "<p>First possible refactoring: define an enumeration for the three possible states</p>\n\n<pre><code>enum InputState{\n Hidden,\n Disabled,\n Enabled\n}\n</code></pre>\n\n<p>and use it with an extension method (or by extending the class)</p>\n\n<pre><code>public static void SetVisibility(this Control ctrl, InputState state){\n switch(state){\n case InputState.Hidden:\n ctrl.Enabled = false;\n ctrl.Visible = false;\n break;\n case InputState.Disabled:\n ctrl.Enabled = false;\n ctrl.Visible = true;\n break;\n case InputState.Enabled:\n ctrl.Enabled = true;\n ctrl.Visible = true;\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T16:05:49.580",
"Id": "13540",
"ParentId": "13535",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Start by creating a list of objects which contain the connection between a <strong>location type</strong> and the relevant <strong>controls</strong>. First create a new class to hold this information:</p>\n\n<pre><code>public enum LocationType\n{\n Undefined = 0,\n Province = 1,\n District = 2,\n ...\n}\n\npublic class LocationControl\n{\n public LocationType Type { get; set; }\n public TextBox TextBox { get; set; }\n public ComboBox ComboBox { get; set; }\n}\n\nprivate List<LocationControl> _myControls = new List<LocationControl>();\n</code></pre></li>\n<li><p>Then, create type-control links:</p>\n\n<pre><code>private void InitControls()\n{\n // a better approach might be to create all controls here,\n // but if you want to use the VS designer, this will do\n // (just call it inside OnLoad or something)\n\n _myControls.Add(new LocationControl()\n {\n Type = LocationType.Province,\n TextBox = txtProvince,\n ComboBox = ddlProvince\n });\n\n _myControls.Add(new LocationControl()\n {\n Type = LocationType.District,\n TextBox = txtDistrict,\n ComboBox = ddlDistrict\n });\n\n ...\n}\n</code></pre></li>\n<li><p>Once you have this information, enabling the right control is trivial:</p>\n\n<pre><code>private void EnableRelevantLocationControls(LocationType type)\n{\n // enable this input\n var activeLocation = _myControls.Find(c => c.Type == type);\n Enable(activeLocation);\n\n // disable all other inputs\n var inactiveLocations = _myControls.Where(c => c.Type != type);\n foreach (var location in inactiveLocations)\n Disable(location);\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:31:59.120",
"Id": "13566",
"ParentId": "13535",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T13:32:03.460",
"Id": "13535",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Extract common code to enable/disable, show/hide controls on some condition"
}
|
13535
|
<p>I was having a problem with the TCP/IP socket communications in a web app where the server that the app was talking to would occasionally send bursts of data that would overflow the low level stream buffer, resulting in lost data.</p>
<p>The solution I came up with is basically an unthreaded form of the <a href="http://code.google.com/p/ganymed-ssh-2/source/browse/trunk/src/main/java/ch/ethz/ssh2/StreamGobbler.java?r=37">StreamGobbler</a> and I have been calling it a <code>GreedyBufferedInputStream</code>. The basic idea is that just about any call to this class will include draining the source <code>InputStream</code>.</p>
<p>I'm still fairly new to Scala, so please let me know how this code could be improved. Also, is there anything in the code which could be done more efficiently? Performance is critically important.</p>
<pre><code>package edu.stsci.util
import org.slf4j.Logger
import java.io.InputStream
import java.util
class GreedyBufferedInputStream extends InputStream {
private var logger: Logger = null
private var source: InputStream = null
private val data: util.LinkedList[DataBlock] = new util.LinkedList[DataBlock]()
private var currentBlock: DataBlock = null
def this(logger: Logger, source: InputStream) {
this()
this.logger = logger
this.source = source
drainSource()
}
def this(source: InputStream) {
this(null, source)
}
def read() = {
prepareToRead()
if (currentBlock == null) -1
else currentBlock.read()
}
override def read(destination: Array[Byte], offset: Int, length: Int): Int = {
prepareToRead()
if (currentBlock == null) return -1
var bytesRead = currentBlock.read(offset, length, destination)
while (bytesRead < length) {
prepareToRead()
if (currentBlock == null) {// EOF
return bytesRead
}
else {
bytesRead += currentBlock.read((offset + bytesRead), (length - bytesRead), destination)
}
}
bytesRead
}
override def read(destination: Array[Byte]) = read(destination, 0, destination.length)
override def skip(length: Long): Long = {
prepareToRead()
if (currentBlock == null) return -1
var bytesSkipped = currentBlock.skip(length)
while (bytesSkipped < length) {
prepareToRead()
if (currentBlock == null) { // EOF
return bytesSkipped
}
else {
bytesSkipped += currentBlock.skip(length - bytesSkipped)
}
}
bytesSkipped
}
override def close() {
super.close()
}
override def available() = {
drainSource()
var result = 0
if (currentBlock != null) result += currentBlock.available
val it = data.iterator()
while (it.hasNext) {
val next = it.next()
result += next.available
}
result
}
private def drainSource() {
if (source == null) return // EOF
if (source.available() > 0) {
val raw = new Array[Byte](source.available())
val length = source.read(raw)
val block = new DataBlock(raw, length)
data.add(block)
}
}
private def prepareToRead() {
drainSource()
if (currentBlock != null) {
val done = currentBlock.isDone
if (done) currentBlock = null
else return // we have a current block
}
if (data.isEmpty) { // no choice but to block
if (source == null) return // have reached EOF
val raw = new Array[Byte](1024)
val length = source.read(raw)
if (length < 0) {
source = null
return
}
currentBlock = new DataBlock(raw, length)
}
else currentBlock = data.remove()
}
}
class DataBlock(data: Array[Byte], length: Int) {
var readPos = -1
def isDone: Boolean = (readPos >= length)
def available: Int = {
if (readPos < 0) length
else (length - readPos)
}
def read(): Int = {
if (readPos < 0) readPos = 0
val raw = data(readPos)
readPos += 1
raw & 0xff
}
def read(offset: Int, length: Int, destination: Array[Byte]): Int = {
if (readPos < 0) readPos = 0
var readCount = {
if (available >= length) length
else available
}
Array.copy(data, readPos, destination, offset, readCount)
readPos += readCount
readCount
}
def skip(length: Long): Long = {
if (readPos < 0) readPos = 0
var readCount = {
if (available >= length) length
else available
}
readPos += readCount.toInt
readCount
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T14:30:53.273",
"Id": "22207",
"Score": "0",
"body": "Would it be at all helpful if I added the unit tests?"
}
] |
[
{
"body": "<p>To be precise I have no real solution to your problem, but if I think about it there should be a few possibilities to find one: First you could think about limiting data send by the App. A limitation could mean a two way communication and/or a sending buffer on side of the App. So you can regulate the data sent and maybe zip it to be more efficient etc. A second solution could be a pool of multiple stream buffers which can be chosen in case of a data burst to handle all incomming data.\nBecause I am a Python programmer I cant tell you if your Scala code can be improved or not. I hope I could help a bit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T11:54:00.793",
"Id": "22152",
"Score": "0",
"body": "Thank you for your answer. However, I tried to be clear - the code I gave *is* the answer to my original problem and I am now looking for a review of this code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T10:43:53.940",
"Id": "13703",
"ParentId": "13536",
"Score": "0"
}
},
{
"body": "<p>No time to read it in any detail, but as a general observation of scala style most scala users would be looking to make far more use of immutable ways of doing things. I use var very sparingly these days and never use null as an indicator of failure or empty something - I use Option[X] instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:44:11.417",
"Id": "22261",
"Score": "0",
"body": "I actually understand Option - it's a startlingly useful construct. However, I fail to see, within the context of this class, where using Option would add any value. I could be wrong, but you'll have to provide some actual justification to convince me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:01:40.240",
"Id": "22263",
"Score": "0",
"body": "I specifically said I have no time to look in detail at your classes. You may be right. Null creeps in from java - I try to wrap it up as soon as possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:35:29.867",
"Id": "13788",
"ParentId": "13536",
"Score": "0"
}
},
{
"body": "<p>Just some random bits of feedback, not really addressing the code as a whole.</p>\n\n<p>First, I would handle constructing the class as follows:</p>\n\n<pre><code>class GreedyBufferedInputStream(logger: Logger = null, initialSource: InputStream)\nextends InputStream {\n\n private var source: InputStream = initialSource\n private val data: util.LinkedList[DataBlock] = new util.LinkedList()\n private var currentBlock: DataBlock = null\n\n drainSource()\n</code></pre>\n\n<p>This eliminates a <code>var</code> and both auxiliary constructors.</p>\n\n<p>I would rewrite the <code>available()</code> method as follows:</p>\n\n<pre><code> override def available() = {\n drainSource()\n import collection.JavaConverters._\n data.asScala.map(_.available).sum +\n Option(currentBlock).map(_.available).getOrElse(0)\n }\n</code></pre>\n\n<p>And I would replace this:</p>\n\n<pre><code>var readCount = {\n if (available >= length) length\n else available\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>val readCount = length min available\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T11:53:52.243",
"Id": "22367",
"Score": "0",
"body": "I like this answer, but I thought that Dominik's answer was slightly more useful. If I could, I would have split the bonus."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:22:41.710",
"Id": "13793",
"ParentId": "13536",
"Score": "3"
}
},
{
"body": "<p>I think that the use of a <code>LinkedList</code> is not optimal. In every invocation of <code>drainSource</code> you potentially add a new <code>DataBlock</code> ant the end of the linked list; this has performance O(n) (length of the list). I propose to use a <code>Vector</code> instead of the <code>LinkedList</code>.</p>\n\n<p>Another point (but this is not Scala specific): Why do you initialize the field <code>readPos</code> in class <code>DataBlock</code> with -1? You have many special cases due to this choice. I would implement class <code>DataBlock</code> as follows:</p>\n\n<pre><code>class DataBlock(data: Array[Byte], length: Int) {\n require(length > 0)\n\n private var readPos = 0\n\n def isDone: Boolean = readPos >= length\n\n def available: Int = length - readPos\n\n def read(): Int = try { data(readPos) & 0xff } finally { readPos += 1 }\n\n def read(offset: Int, length: Int, destination: Array[Byte]): Int = {\n val readCount = length min available\n Array.copy(data, readPos, destination, offset, readCount)\n readPos += readCount\n readCount\n }\n\n def skip(length: Long): Long = {\n val readCount = length min available\n readPos += readCount.toInt\n readCount\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T17:53:00.867",
"Id": "22272",
"Score": "0",
"body": "I used `java.util.LinkedList` as I believe that it offers constant time adds at the end as well as constant time removes from the beginning. I dropped your DataBlock implementation in and it passed all the tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T19:48:52.813",
"Id": "22278",
"Score": "0",
"body": "@Donald.McLean you are right, missed that you use a Java list and not the Scala one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:35:59.423",
"Id": "13795",
"ParentId": "13536",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13795",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T14:04:48.067",
"Id": "13536",
"Score": "11",
"Tags": [
"scala",
"networking"
],
"Title": "Alternate form of BufferedInputStream"
}
|
13536
|
<p>Which of these 3 python snippets is more pythonic?</p>
<p>This 1 liner list comprehensions which is a little overcomplex</p>
<pre><code>users_to_sent = [(my_database.get_user_by_id(x), group['num_sent'][x]) for x in user_ids]
</code></pre>
<p>or this multi liner which is 'too many lines of code'</p>
<pre><code>users_to_sent = []
for id in user_ids:
t1 = my_database.get_user_by_id(id)
t2 = group['num_sent'][id]
users_to_sent.append( (t1,t2) )
</code></pre>
<p>or should the 1 liner be spun out into a separate function and called from a list comprehension? </p>
<pre><code>def build_tuple(x, my_database, group):
return (my_database.get_user_by_id(x), group['num_sent'][x])
users_to_sent = [build_tuple(x, my_database, group) for x in user_ids]
</code></pre>
|
[] |
[
{
"body": "<p>You'd definitely need to name your function something more descriptive than <code>build_tuple</code> for it to be a good idea (and same with <code>t1</code> and <code>t2</code> in the multi-liner!). </p>\n\n<p>I'd use a function if it's something you do more than once or twice, otherwise I'd probably stick with the list comprehension - I find it easier to read than the multi-liner version.</p>\n\n<p>If I was doing a function, I'd probably make it generate the whole list - is there any reason not to do that?</p>\n\n<pre><code>def make_users_to_sent(user_ids, my_database, group):\n return [(my_database.get_user_by_id(x), group['num_sent'][x]) for x in user_ids]\n\nusers_to_sent = make_users_to_sent(user_ids, my_database, group)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T18:16:01.867",
"Id": "13544",
"ParentId": "13541",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13544",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T16:14:54.093",
"Id": "13541",
"Score": "1",
"Tags": [
"python"
],
"Title": "Pythonic style guide"
}
|
13541
|
<p>I have some C# I/O code that can take one <strong>or</strong> two input files. I would like to wrap the <code>Stream</code> objects in a <code>using</code> block, but cannot find a way to succinctly express this in code.</p>
<p>Currently, I have two large files (>1GB), that contain concatenated TIFF files and PDF files respectively that need to be extracted into individual files. The metadata of the individual files (TIFF Tags and PDF Keywords) cross-reference one another, so the processing rules are different if I receive both files at once, i.e. there is more information and verification logic.</p>
<p>I have a <code>FileProcessor</code> class than implements an <code>IEnumerable<Range></code> to return the byte ranges of each individual file within the archive. My current implementation just wraps the main processing loop in a <code>try/finally</code> block and calls <code>Dispose</code> manually.</p>
<pre><code>// Struct to represent the byte range of a file in the archive
struct Range
{
public long start;
public long end;
}
// Custom class that takes a Stream object in the constructor and implements IEnumerable<Range> to return the individual files in sequence
public class FileProcessor : IDisposable, IEnumerable, IEnumerable<Range>
{
private Stream _stream;
public FileProcessor(Stream stream) { this._stream = stream; }
public virtual void Dispose()
{
if (_stream != null) { _stream.Dispose(); _stream = null; }
}
}
public class TiffProcessor : FileProcessor { ... }
public class PdfProcessor : FileProcessor { ... }
// Snippet of the dispatching/processing logic
TiffProcessor infile1 = null,
PdfProcessor infile2 = null;
try
{
if (HasFirstInputFile)
{
infile1 = new TiffProcessor(File.OpenRead(FirstInputFileName));
}
if (HasSecondInputFile)
{
infile2 = new PdfProcessor(File.OpenRead(SecondInputFileName));
}
if (infile1 != null && infile2 == null)
{
foreach (var range in infile1) { ... }
}
if (infile1 == null && infile2 != null)
{
foreach (var range in infile2) { ... }
}
if (infile1 != null && infile2 != null)
{
foreach (var ranges in infile1.Zip(infile2, (tiff, pdf) => new Range[] { tiff, pdf })) { ... }
}
}
finally
{
if (infile1 != null) { infile1.Dispose(); }
if (infile2 != null) { infile2.Dispose(); }
}
</code></pre>
<p>Is there any construct that can help clean up and organize this code structure. It's not too bad now, but could become exponentially more complex if additional input streams are required in the future.</p>
<p><strong>Edit</strong></p>
<p>Based on the comments received, perhaps creating an intermediate <code>Strategy</code> object that managed resources would work?</p>
<pre><code>using (var strategy = StrategyFactory.Create(CommandLineArgs))
{
strategy.Process();
}
public static class StrategyFactory
{
public static IStrategy Create(CommandLineArguments args)
{
if (args.FirstInputFile != null && args.SecondInputFile == null)
{
return new FirstStrategy(args.FirstInputFile);
}
if (args.FirstInputFile == null && args.SecondInputFile != null)
{
return new SecondStrategy(args.SecondInputFile);
}
if (args.FirstInputFile != null && args.SecondInputFile != null)
{
return new ThirdStrategy(args.FirstInputFile, args.SecondInputFile);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T17:02:30.227",
"Id": "21944",
"Score": "0",
"body": "If you expect additional input streams in the future, then you should treat the input as a *collection* of files, not something like “maybe one, maybe two, maybe three, possibly four files”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T17:15:43.283",
"Id": "21946",
"Score": "0",
"body": "Unfortunately, not possible. Each input file is in a different, semi-structured text format. The processing needs are different based on combination of the files. Ideally, I'd like to do some sort of dynamic dispatch or Strategy pattern based on the file format combination."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T17:43:00.737",
"Id": "21947",
"Score": "1",
"body": "How about having an abstract superclass that implements the shared code and have three subclasses for the first, second or both files?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T17:59:30.913",
"Id": "21948",
"Score": "0",
"body": "Well, after some thought I think my solution will end up being four-fold: 1) have an abstract superclass that implements IDisposable. 2) Create a set of small classes to use as stongly-typed input parameters, 3) Have each strategy inherit from the superclass and implement a constructor using the classes from (2), and 4) Implement the Factory.Create method to use reflection to iterate over all the inherited class and their constructors and then instantiate the class that can consume the most non-null input parameter types via Activator.CreateInstance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:01:33.390",
"Id": "21969",
"Score": "0",
"body": "If each input file is in a different format, how come you use the same `FileProcessor` class to parse them? And parsed items are also of the same type, since you `Zip` them, right? It would be helpful if you would add some background on what you are trying to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:34:32.833",
"Id": "21970",
"Score": "0",
"body": "@Groo: I expanded the question to provide more context. I didn't think the distiction of difference `FileProcessor` types was necessary because their `IEnumerable` interface returns items of the same type (as you point out)."
}
] |
[
{
"body": "<p>The only think that I would do different is that I wouldn't dispose streams inside your <code>FileProcessor</code> classes. Disposing of resources should be done at the same level (or scope) where they were initialized. Unfortunately, even BCL classes like <code>StreamWriter</code> and <code>BinaryWriter</code> <a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/164680/streamwriter-incorrectly-disposes-underlying-stream\" rel=\"nofollow\">dispose underlying streams when disposed</a>, so I cannot claim that this is unexpected behavior either.</p>\n\n<p>IMO, there is nothing wrong with your code. Going out of your way simply to save two lines of code might make your code less readable, so your first version might easily be the simplest one.</p>\n\n<p>Having said that, if you really want to wrap it in a single <code>using</code> block, one idea (and I don't actually find it \"better\" than yours in any way) might be to wrap all your disposable resources into a single class:</p>\n\n<pre><code>public class InputFiles : IDisposable\n{\n private readonly Dictionary<string, Stream> _files \n = new Dictionary<string, Stream>();\n\n public Stream GetStream(string type)\n {\n Stream input = null;\n _files.TryGetValue(type, out input);\n return input;\n }\n\n public InputFiles(string[] args)\n {\n // this is just an idea, you probably don't\n // use the extension to determine the type,\n // but it still seems a bit more general than\n // having strongly typed properties\n foreach (var path in args)\n {\n var ext = Path.GetExtension(path); // pdf or tif?\n _files[ext] = File.OpenRead(path);\n }\n }\n\n public void Dispose()\n {\n foreach (var stream in _files)\n stream.Value.Dispose();\n }\n}\n</code></pre>\n\n<p>And then dispose the entire object when done:</p>\n\n<pre><code>static void Main(string[] args)\n{\n using (var input = new InputFiles(args))\n {\n var pdf = input.GetStream(\"pdf\");\n var tif = input.GetStream(\"tif\");\n\n // use the appropriate strategy\n // (parsing strategy should not be concerned with\n // disposing of resources)\n Process(pdf, tif);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:26:17.920",
"Id": "21973",
"Score": "0",
"body": "I like this since it's a totally different approach. I had not considered moving the management of the files into a stand-alone class. I might give this a try....Also, your comment nails the core problem on the head -- the parsing strategy should not have to manage the resources."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T14:26:21.707",
"Id": "22320",
"Score": "0",
"body": "I ended up using this approach and am pretty happy with it. It's nice that there's no resource management in the different strategy implementations. I did go with a strongly-typed implementation for stream lookups, i.e. `var pdf = input.GetStream(typeof(PdfArchiveFile));`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:17:45.277",
"Id": "13569",
"ParentId": "13543",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13569",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T16:47:22.013",
"Id": "13543",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Restucture code to wrap optional resources in a using block"
}
|
13543
|
<p>Any suggestions how I could simplify this LINQ query?</p>
<pre><code>from type in assembly.GetTypes()
where type.IsPublic && !type.IsSealed && type.IsClass
where (from method in type.GetMethods()
from typeEvent in type.GetEvents()
where method.Name.EndsWith("Async")
where typeEvent.Name.EndsWith("Completed")
let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
where typeEvent.Name == operationName + "Completed"
select new { method, typeEvent }).Count() > 0
select type;
</code></pre>
<p><code>assembly</code> is of type <code>System.Reflection.Assembly</code>.
If you need more information, just ask.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T18:38:04.620",
"Id": "21950",
"Score": "2",
"body": "What I can see immediately is that you could replace `Count() > 0` with `Any()`, which is simpler and also more efficient."
}
] |
[
{
"body": "<p>You can do a join between the methods and events :</p>\n\n<pre><code>from type in assembly.GetTypes()\nwhere type.IsPublic && !type.IsSealed && type.IsClass\nwhere (from method in type.GetMethods()\n join typeEvent in type.GetEvents()\n on method.Name.Replace(\"Async\", \"Completed\") equals typeEvent.Name\n select new { method, typeEvent }).Any()\nselect type;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T19:33:03.987",
"Id": "21951",
"Score": "0",
"body": "The way you're using `Replace()` means this code will most likely work, but it's not guaranteed to work for methods with “weird” names (like `PerformAsyncOperationAsync`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T22:27:54.780",
"Id": "21954",
"Score": "0",
"body": "Well other than the rare case that @svick mentioned, this could work. I'll probably just make a utility method to make sure only \"Async\" at the end is replaced."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T18:57:21.187",
"Id": "13546",
"ParentId": "13545",
"Score": "4"
}
},
{
"body": "<p>Original code (wrapped up in a method):</p>\n\n<pre><code>public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)\n{\n return from type in assembly.GetTypes()\n where type.IsPublic && !type.IsSealed && type.IsClass\n where (from method in type.GetMethods()\n from typeEvent in type.GetEvents()\n where method.Name.EndsWith(\"Async\")\n where typeEvent.Name.EndsWith(\"Completed\")\n let operationName = method.Name.Substring(0, method.Name.Length - \"Async\".Length)\n where typeEvent.Name == operationName + \"Completed\"\n select new { method, typeEvent }).Count() > 0\n select type;\n}\n</code></pre>\n\n<p>The first thing I notice is that the overall structure of the query is:</p>\n\n<ul>\n<li>Find me all types in the assembly</li>\n<li>Where the type is a public, non-sealed class</li>\n<li>And where the type passes a complicated looking filter.</li>\n</ul>\n\n<p>I'd split the complicated looking filter out into a method to start with:</p>\n\n<pre><code>public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)\n{\n return from type in assembly.GetTypes()\n where type.IsPublic && !type.IsSealed && type.IsClass\n where IsAsyncCompletableType(type)\n select type;\n}\n\nprivate static bool IsAsyncCompletableType(Type type)\n{\n return (from method in type.GetMethods()\n from typeEvent in type.GetEvents()\n where method.Name.EndsWith(\"Async\")\n where typeEvent.Name.EndsWith(\"Completed\")\n let operationName = method.Name.Substring(0, method.Name.Length - \"Async\".Length)\n where typeEvent.Name == operationName + \"Completed\"\n select new { method, typeEvent }).Count() > 0;\n}\n</code></pre>\n\n<p>That gives us two simpler queries to look at. The only thing I can see in the first part is that the repeated <code>where</code> can be collapsed into a single one:</p>\n\n<pre><code>public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)\n{\n return from type in assembly.GetTypes()\n where type.IsPublic && !type.IsSealed && type.IsClass && IsAsyncCompletableType(type)\n select type;\n}\n</code></pre>\n\n<p>Onto the second part. The lines in the query seem to alternate between being related to the methods and the events - reordering the lines will make it clearer what's going on:</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n return (from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n let operationName = method.Name.Substring(0, method.Name.Length - \"Async\".Length)\n from typeEvent in type.GetEvents()\n where typeEvent.Name.EndsWith(\"Completed\")\n where typeEvent.Name == operationName + \"Completed\"\n select 0).Any();\n}\n</code></pre>\n\n<p>We're now using the <code>method</code> variable up to the <code>let</code> operation, and never using it again, so we can <code>select</code> the <code>operationName</code> in a subquery instead of using <code>let</code>.</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var operationNames = from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length);\n\n return (from operationName in operationNames \n from typeEvent in type.GetEvents()\n where typeEvent.Name.EndsWith(\"Completed\")\n where typeEvent.Name == operationName + \"Completed\"\n select 0).Any();\n}\n</code></pre>\n\n<p>You may notice that the two <code>where</code> lines don't make a lot of sense together at this point:</p>\n\n<ul>\n<li>Pick events</li>\n<li>Where the name ends with <code>\"Completed\"</code></li>\n<li>And where the name starts with <code>operationName</code> and ends with <code>\"Completed\"</code></li>\n</ul>\n\n<p>The first line is redundant. So we can remove it:</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var operationNames = from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length);\n\n return (from operationName in operationNames\n from typeEvent in type.GetEvents()\n where typeEvent.Name == operationName + \"Completed\"\n select 0).Any();\n}\n</code></pre>\n\n<p>The only thing we ever do to <code>operationName</code> is add <code>\"Completed\"</code> to it - we might as well do that when we create the <code>operationName</code> (and rename it appropriately):</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var eventNamesFromMethods = from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length) + \"Completed\";\n\n return (from eventNameFromMethod in eventNamesFromMethods\n from typeEvent in type.GetEvents()\n where typeEvent.Name == eventNameFromMethod\n select 0).Any();\n}\n</code></pre>\n\n<p>We're now asking the computer to iterate over all the events and select its name for every <code>eventNameFromMethod</code>. We can pre-compute these and put them into a fast lookup container - a <code>HashSet</code>:</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var eventNamesFromMethods = from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length) + \"Completed\";\n\n var eventNames = new HashSet<string>(\n from typeEvent in type.GetEvents()\n select typeEvent.Name);\n\n return (from eventNameFromMethod in eventNamesFromMethods\n where eventNames.Contains(eventNameFromMethod)\n select 0).Any();\n}\n</code></pre>\n\n<p>That last bit is now really just a <code>where</code> and an <code>Any</code>. But <code>Any</code> has an overload that takes a condition, so let's use it:</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var eventNamesFromMethods = from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length) + \"Completed\";\n\n var eventNames = new HashSet<string>(\n from typeEvent in type.GetEvents()\n select typeEvent.Name);\n\n return eventNamesFromMethods.Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));\n}\n</code></pre>\n\n<p>And with a little bit of rearranging to remove the <code>eventNamesFromMethods</code> variable that only gets used once:</p>\n\n<pre><code>private static bool IsAsyncCompletableType(Type type)\n{\n var eventNames = new HashSet<string>(\n from typeEvent in type.GetEvents()\n select typeEvent.Name);\n\n return (from method in type.GetMethods()\n where method.Name.EndsWith(\"Async\")\n select method.Name.Substring(0, method.Name.Length - \"Async\".Length) + \"Completed\")\n .Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));\n}\n</code></pre>\n\n<p>Personally (and feel free to disagree here), I find the extension method syntax far easier to read and reason about (especially when you have to use things like <code>Any</code> anyway), so here's what it looks like using that:</p>\n\n<pre><code>public static IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)\n{\n return assembly.GetTypes()\n .Where(type => type.IsPublic && !type.IsSealed && type.IsClass && IsAsyncCompletableType(type));\n}\n\nprivate static bool IsAsyncCompletableType(Type type)\n{\n var eventNames = new HashSet<string>(type.GetEvents().Select(typeEvent => typeEvent.Name));\n\n return type.GetMethods()\n .Where(method => method.Name.EndsWith(\"Async\"))\n .Select(method => method.Name.Substring(0, method.Name.Length - \"Async\".Length) + \"Completed\")\n .Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-12T08:29:17.783",
"Id": "116537",
"ParentId": "13545",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "13546",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T18:25:42.147",
"Id": "13545",
"Score": "4",
"Tags": [
"c#",
"linq"
],
"Title": "Simplify a complex LINQ query"
}
|
13545
|
<p>I wrote this code (except the getting text from clipboard part) a while back, and I'm wondering if it could be written better? Can anyone help me improve this code?</p>
<p>This code basically takes HTML from the clipboard, and then attempts to fix the indentation and writes it to a new file.</p>
<pre><code>public static class Clipboard
{
[DllImport("user32.dll")]
static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("user32.dll")]
static extern bool IsClipboardFormatAvailable(uint format);
[DllImport("user32.dll", SetLastError = true)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
static extern bool CloseClipboard();
[DllImport("kernel32.dll")]
static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern bool GlobalUnlock(IntPtr hMem);
const uint CF_UNICODETEXT = 13;
public static string GetText()
{
if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
return null;
if (!OpenClipboard(IntPtr.Zero))
return null;
string data = null;
var hGlobal = GetClipboardData(CF_UNICODETEXT);
if (hGlobal != IntPtr.Zero)
{
var lpwcstr = GlobalLock(hGlobal);
if (lpwcstr != IntPtr.Zero)
{
data = Marshal.PtrToStringUni(lpwcstr);
GlobalUnlock(lpwcstr);
}
}
CloseClipboard();
return data;
}
}
</code></pre>
<hr>
<pre><code>class Program
{
static string fix_encoding(string src_str)
{
src_str = src_str.Replace("a€‹", "");
src_str = src_str.Replace("&amp;", "&");
src_str = src_str.Replace("&nbsp;", " ");
src_str = src_str.Replace("&#8206;", "");
src_str = src_str.Replace("&#38;", "&");
src_str = src_str.Replace("&#160;", " ");
src_str = src_str.Replace("&#39;", "'");
src_str = src_str.Replace("&quot;", "\"");
return src_str;
}
static string slice(string src_str, int start, int end)
{
if (start < 0)
{
start = src_str.Length + start;
}
if (end < 0)
{
end = src_str.Length + end;
}
return src_str.Substring(start, end-start);
}
static Boolean prefix_check(string item, string[] tag_exception)
{
string b = item.ToLower();
for (var i=0; i<tag_exception.Length; i++)
{
if (b.IndexOf(tag_exception[i]) == 0)
{
return true;
}
}
return false;
}
static void fix_tags(string src_str, StreamWriter file_id)
{
src_str = fix_encoding(src_str);
int count = 0;
List<String> item_list = new List<String>();
while (src_str != "")
{
int start_tag_index = src_str.IndexOf("<");
if (start_tag_index == -1)
{
break;
}
item_list.Add(slice(src_str, 0, start_tag_index));
src_str = slice(src_str, start_tag_index, src_str.Length);
count++;
int _g_ = src_str.IndexOf("<!--");
if (_g_ == 0)
{
int _f_ = src_str.IndexOf("-->");
item_list.Add(slice(src_str, _g_, _f_ + 3));
count++;
src_str = slice(src_str, _f_ + 3, src_str.Length);
continue;
}
int end_tag_index = src_str.IndexOf(">");
string tag = slice(src_str, 0, end_tag_index + 1);
item_list.Add(tag);
count++;
src_str = slice(src_str, end_tag_index + 1, src_str.Length);
}
string[] tag_exception = {"<img","<link","<meta","<br","<hr","<img","<input","<area","<param"};
string indent = "";
Boolean script = false;
for (var i = 0; i < count; i++)
{
string item = item_list[i];
if (item.Trim() == "")
{
continue;
}
int start = item.IndexOf("<");
int end = item.IndexOf(">");
int end2 = item.IndexOf("</");
Boolean is_script = item.IndexOf("<script")==0;
Boolean is_end_script = item.Length >= 9 && slice(item, -9, item.Length) == "</script>";
Boolean is_tag = start == 0 && end == item.Length-1;
Boolean is_closing_tag = end2 == 0;
Boolean is_comment = item.IndexOf("<!") == 0;
Boolean is_exception = prefix_check(item, tag_exception);
if (script)
{
if (is_end_script)
{
indent = slice(indent,0,-1);
file_id.Write(indent + item.Trim().Replace("\n","") + "\n");
script = false;
}
else {
file_id.Write(indent + item.Trim() + "\n");
}
}
else if (is_comment)
{
file_id.Write(indent + item.Trim() + "\n");
}
else if (is_closing_tag)
{
indent = slice(indent, 0, -1);
file_id.Write(indent + item.Trim().Replace("\n", "") + "\n");
}
else if (is_exception)
{
file_id.Write(indent + item.Trim().Replace("\n", "") + "\n");
}
else if (is_tag)
{
file_id.Write(indent + item.Trim().Replace("\n", "") + "\n");
indent += "\t";
if (is_script)
{
script = true;
}
}
else {
file_id.Write(indent + item.Trim() + "\n");
}
}
}
static void Main(string[] args)
{
StreamWriter file_id = new StreamWriter("./fixed_html.html", false, System.Text.Encoding.UTF8);
fix_tags(Clipboard.GetText(), file_id);
file_id.Close();
System.Diagnostics.Process.Start("batch.bat");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T21:04:35.443",
"Id": "21952",
"Score": "3",
"body": "Quick superficial suggestions. I believe CamelCasing is the standard convention for c# variables and Pascalcase method calls. StyleCop would go along way to addressing this. Also fix_tags seems kinda large. Perhaps breaking it into smaller routines might be a start? See also Microsoft naming guidelines - http://msdn.microsoft.com/en-us/library/xzf533w0%28VS.71%29.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-15T16:20:45.967",
"Id": "23893",
"Score": "1",
"body": "Quick comment: get rid of your own `Clipboard` class and start using the one that is provided by the framework. http://msdn.microsoft.com/en-us/library/kz40084e.aspx#Y0"
}
] |
[
{
"body": "<ul>\n<li>What everyone else said about camelCase & style-cop</li>\n<li>slice: need to be careful if start and end values are valid. </li>\n<li>prefix_check: why not put incoming items into hash to this goes from order(n) operation to order(1)?</li>\n<li>fix_tags: name is unclear. Suggest: Adjust tabbing or somesuch. </li>\n<li>fix_tags: maybe a better way to do this entire method is to load the document into a .NET DOM and then print out that DOM with your preferred indentation. </li>\n<li>fix_tags: <em>g</em>, <em>f</em> etc need readable names</li>\n<li>fix_tags: calls to slice are magic-number city, save calculation ints to named values or use string.Length</li>\n<li>fix_tags: tag_exception: exception to what, need comment</li>\n<li>fix_tags: tag_exception: as mentioned above make into dictionary or lookup etc. </li>\n<li>fix_tags: as mentioned by other reviewers this method is too large, suggested refactor locations: the while, the for and then further within those blocks. </li>\n<li>fix_tags: suggest change bool calculations and repetitive code with a switch containing a few cases and default of: file_id.Write(indent + item.Trim().Replace(\"\\n\", \"\") + \"\\n\");</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-22T19:22:18.810",
"Id": "17815",
"ParentId": "13547",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T19:50:59.500",
"Id": "13547",
"Score": "2",
"Tags": [
"c#",
"html"
],
"Title": "Fixing indentations in HTML files"
}
|
13547
|
<p>Here is the current code for the <code>BitArray</code> class needing optimization (implemented on big integers):</p>
<pre><code>import itertools
################################################################################
class BitArray:
def __init__(self, values=[], max_size=128):
self.__data = []
self.__size = 0
self.__bits = max_size << 3 # Bytes -> Bits
self.extend(values)
########################################################################
# String Operators
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__,
self, self.__bits >> 3)
def __str__(self):
return repr(list(self))
########################################################################
# Iteration Methods
def __iter__(self):
size = len(self)
for index in range(size):
if len(self) != size:
raise RuntimeError()
yield self[index]
def __reversed__(self):
size = len(self)
for index in range(size - 1, -1, -1):
if len(self) != size:
raise RuntimeError()
yield self[index]
########################################################################
# Container Methods
def __len__(self):
return self.__size
def __contains__(self, item):
return any(value == item for value in self)
def __getitem__(self, key):
div, mod = divmod(self.__get_index(key), self.__bits)
return bool(self.__data[div] >> mod & 1)
def __setitem__(self, key, value):
div, mod = divmod(self.__get_index(key), self.__bits)
if value:
self.__data[div] |= 1 << mod
else:
self.__data[div] &= ~(1 << mod)
def __delitem__(self, key):
div, mod = divmod(self.__get_index(key), self.__bits)
value = self.__data[div]
self.__data[div] = value >> 1 & -(1 << mod) | value & (1 << mod) - 1
set_mask = 1 << (self.__bits - 1)
for div in range(div + 1, len(self.__data)):
value = self.__data[div]
if value & 1:
self.__data[div - 1] |= set_mask
self.__data[div] = value >> 1
self.__size -= 1
if not len(self) % self.__bits:
del self.__data[-1]
########################################################################
# Comparison Operators
def __eq__(self, other):
return self.__cmp__(other) == 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __le__(self, other):
return self.__cmp__(other) <= 0
########################################################################
# Math Operators
def __add__(self, other):
value = self.__class__(self, self.__bits >> 3)
value.extend(other)
return value
def __mul__(self, other):
value = self.__class__([], self.__bits >> 3)
for _ in range(other):
value.extend(self)
return value
def __rmul__(self, other):
return self * other
def __iadd__(self, other):
self.extend(other)
return self
def __imul__(self, other):
size = len(self)
for _ in range(other - 1):
for index in range(size):
self.append(self[index])
return self
########################################################################
# List Methods
def append(self, item):
index = len(self) % self.__bits
if not index:
self.__data.append(0)
if item:
self.__data[-1] |= 1 << index
self.__size += 1
def extend(self, iterable):
for item in iterable:
self.append(item)
def count(self, item):
return sum(1 for value in self if value == item)
def index(self, item, start=None, stop=None):
for index in range(
0 if start is None else self.__get_index(start),
len(self) if stop is None else self.__get_index(stop)):
if self[index] == item:
return index
raise ValueError()
def reverse(self):
for index in range(len(self) >> 1):
self[index], self[~index] = self[~index], self[index]
def pop(self, index=None):
index = len(self) - 1 if index is None else self.__get_index(index)
value = self[index]
del self[index]
return value
def remove(self, item):
for index, value in enumerate(self):
if value == item:
del self[index]
return
raise ValueError()
def sort(self, *, key=lambda item: item, reverse=False):
reverse, lo, hi = bool(reverse), 0, len(self) - 1
while lo < hi:
if bool(key(self[lo])) is not reverse:
while lo < hi:
if bool(key(self[hi])) is reverse:
break
hi -= 1
else:
break
self[lo], self[hi] = self[hi], self[lo]
lo += 1
def insert(self, index, item):
for index in range(self.__get_index(index), len(self)):
temp = item
item = self[index]
self[index] = temp
self.append(item)
########################################################################
# Helper Methods
def __cmp__(self, other):
for a, b in itertools.zip_longest(self, map(bool, other)):
if a != b:
if None in {a, b}:
return (b is None) - (a is None)
return a - b
return 0
def __get_index(self, key):
size = len(self)
if key < 0:
key += size
if not 0 <= key < size:
raise IndexError()
return key
</code></pre>
<p>These are some tests used to make sure that the code is still working after making various changes to it:</p>
<pre><code># Test Range Check
x = BitArray([], 1)
x.append(True)
try:
x[5] = True
except IndexError:
pass
else:
raise RuntimeError()
try:
y = x[5]
except IndexError:
pass
else:
del y
raise RuntimeError()
# Test Append, Set, Get
x = BitArray([], 1)
for _ in range(7):
x.append(False)
x.append(True)
assert x[7]
assert not x[6]
x[6] = True
x[7] = False
assert x[6]
assert not x[7]
# Test Extend and Compare
x = BitArray([False, False])
y = BitArray([False, False])
assert x.__cmp__(y) == 0
x[0] = True
assert x.__cmp__(y) == +1
y[0] = y[1] = True
assert x.__cmp__(y) == -1
x[1] = True
x.append(False)
assert x.__cmp__(y) == +1
x[2] = True
assert x.__cmp__(y) == +1
y.append(True)
y.append(False)
assert x.__cmp__(y) == -1
y[3] = True
assert x.__cmp__(y) == -1
# Test Addition, Multiplication
x = BitArray([False, True])
y = BitArray([True, False])
assert x + y == BitArray([False, True, True, False])
assert x * 3 == x + x + x
assert y * 3 == y + y + y
assert 3 * x == x + x + x
z = BitArray(x)
x += y
assert x == z + y
z = BitArray(y)
y *= 3
assert y == z + z + z
# Test Reverse
x = BitArray([False, True])
y = BitArray([True, False])
x.reverse()
assert x == y
# Test Remove
x = BitArray([False, True])
x.remove(False)
x.remove(True)
try:
x.remove(False)
except ValueError:
pass
else:
raise RuntimeError()
try:
x.remove(True)
except ValueError:
pass
else:
raise RuntimeError()
# Test Delete, Pop
x = 0b1110011111100111
y = BitArray((x >> shift & 1 for shift in range(x.bit_length())), 1)
del y[15], y[2], y[-1]
assert len(y) == 13
del y[-1]
assert len(y) == 12
assert not y[11] and not y[10] and y[8]
y[8] = False
del y[6]
assert y._BitArray__data[0] == 0b1110011
assert y.pop(0)
assert not y.pop()
</code></pre>
<p><strong>Edit:</strong> Sometimes I write code for fun and the benefit of others. It was disappointing to not find a module like this in the standard library. This is an exercise of writing a good <code>BitArray</code> class that anyone can use. As a result, this code was created to:</p>
<ol>
<li>act similarly to the <code>list</code> data type</li>
<li>have an efficient implementation</li>
<li>use <code>int</code> array with maximum bit length</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T00:49:16.717",
"Id": "21960",
"Score": "0",
"body": "In order to optimize this, we first need to know how you are using it. Are you really using all those operations? What kind of bitstrings are you storing? It'd be really useful to have a benchmark."
}
] |
[
{
"body": "<h2>Overall implementation decisions</h2>\n\n<p>The first question is whether you have implemented this in the correct language. Python has its low level data structures implemented in C for a reason. A BitArray will be used like those low level data structures, and I suspect it would be better implemented in C for speed.</p>\n\n<p>The second question is your choice of data structure. You use a list of ints. There are two alternative strategies you could consider. One is to use a <code>byte array</code> It works like a list, but it specialized to hold byte sized ints as you are doing. The other is to use the <code>mpz</code> type from the <code>gmpy</code> module. It holds long integers, of any size you need. It provides methods to get and set bits. Of course it will end up doing something similar to what you've done here, but by using the <code>gmpy</code> module, you can have it be done in C.</p>\n\n<h2>Comments on some of the code</h2>\n\n<pre><code>def __iter__(self):\n size = len(self)\n</code></pre>\n\n<p>Its going to be slightly less efficient to call <code>len</code>, rather then accessing size directly.</p>\n\n<pre><code> for index in range(size):\n if len(self) != size:\n raise RuntimeError()\n</code></pre>\n\n<p>I wouldn't check this. Python doesn't consistently give exceptions when modifying an object while iterating over it. It only does it in cases where it necessary to avoid a SEGFAULT. So I'd just going on and let the chips fall where they may.</p>\n\n<pre><code> yield self[index]\n</code></pre>\n\n<p>You can actually also just remove this function. If you don't provide a <code>__iter__</code> function, python handles it by calling <code>__getitem__</code> with increasing indexes until getting a <code>IndexError</code> All you've done here is implement the default handling.</p>\n\n<pre><code>def sort(self, *, key=lambda item: item, reverse=False):\n</code></pre>\n\n<p>I'm not really sure why you would ever want to sort a list of 1s and 0s. </p>\n\n<pre><code> reverse, lo, hi = bool(reverse), 0, len(self) - 1\n while lo < hi:\n if bool(key(self[lo])) is not reverse:\n</code></pre>\n\n<p>What if somebody uses a key like <code>lambda item: int(item) + 5</code> Because you convert everything to bool, you won't detect the difference between 5 and 6. And you won't sort the same way as a python list.</p>\n\n<p>You also call key a lot, but since there are only two values, True and False, perhaps you should only call it twice and store the values. </p>\n\n<pre><code> while lo < hi:\n if bool(key(self[hi])) is reverse:\n break\n hi -= 1\n else:\n break\n self[lo], self[hi] = self[hi], self[lo]\n</code></pre>\n\n<p>This swap operation is actually going to be fairly expensive. You have to jump into another function, do a division, bit twiddling, etc and you have to do it four times for the swap. </p>\n\n<pre><code> lo += 1\n</code></pre>\n\n<p>I think the whole method could be faster by building a new <code>__data</code> from scratch. </p>\n\n<pre><code>one_bytes, one_bits = divmod(total_ones, 8)\nzero_bytes, zero_bits = divmod(total_zeros, 8)\nself.__data = [0] * zero_bytes + [255] * one_bytes \n# handling the leftover bits is a bit tricky, but hopefully you get the idea\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:16:49.617",
"Id": "13568",
"ParentId": "13549",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13568",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T21:44:21.667",
"Id": "13549",
"Score": "1",
"Tags": [
"python",
"array",
"bitwise",
"bit-twiddling"
],
"Title": "What specific optimizations can be made to this BitArray class, and how can they be implemented?"
}
|
13549
|
<p>If I'm working in a 2D environment and have hundreds of objects, brute force collision-checking would be out of the question, but would my method below work?</p>
<p>For example, let's say I have a</p>
<pre><code>std::vector<GameObj*> objectsVector
</code></pre>
<p>to hold all objects and a</p>
<pre><code>std::multimap<Point2D, GameObj*> objectsMap
</code></pre>
<p>(basically a map which takes a 2D point representing a GameObject's coordinate as a key and the object itself as a value)</p>
<p>to get any object associated with a point. If I want to do collision-checking for an object, I could use a function that looks like this:</p>
<pre><code>void World::checkForCollisions()
{
for (int i = 0; i < objectsVector; ++i) {
GameObj* currObj = objectsVector[i];
for (
int x = (int)currObj->getX() - (int)currObject->getWidth();
x < currObj->getX() + 2*currObj->getWidth();
x++
)
{
for (
int y = (int)currObj->getY() - (int)currObject->getHeight();
y < currObj->getY() + 2*currObj->getHeight();
y++
)
{
pair< multimap<Point2D, GameObj*>::iterator, multimap<Point2D, GameObj*> > \
range = objectsMap.equal_range(Point2D(x, y));
for (
multimap<Point2D, GameObj*>::iterator it=range.first;
it!=range.second;
++it
)
{
if (checkCollision(currObj, it->second))
currObj->handleCollision(it->second);
}
}
}
}
}
</code></pre>
<p>Is this even remotely efficient? Because it doesn't seem to be. It basically just scrolls through the vector and checks to see if it collides with nearby objects. Problem is, I have to use 2 containers AND when things move, I have to pretty much reinitialize the entire map, because the keys would be invalid! Is there any way to improve this collision-checking function, or should I scrap the whole thing altogether and use spatial hashes or a quad-tree? Any suggestions would be helpful.</p>
|
[] |
[
{
"body": "<p>If I'm understanding things correctly, (x,y) is an anchor point of your object (say, bottom left), and you're iterating over every single point that could be an anchor point for an object that it's in collision with, then checking if it's an actual anchor point of an existing object.</p>\n\n<p>My suggestion (assuming that your shapes are small and circle/box-like) would be to check for exclusion rather than inclusion. If you consider that each obj has a bounding rectangle around it, then do the following checks:</p>\n\n<pre><code>curr-x > test-x + test-width\ncurr-x + curr-width <= test-x\ncurr-y > test-y + test-height\ncurr-y + curr-height <= test-y\n</code></pre>\n\n<p>If <em>any</em> of these are true, then you're no longer interested.</p>\n\n<p>So your function then becomes something like:</p>\n\n<pre><code>typedef std::multimap<Point2D, GameObj*> ObjectSpace;\nvoid World::checkForCollisions()\n{\n for (int i = 0; i < objectsVector; ++i) {\n GameObj* currObj = objectsVector[i];\n for ( ObjectSpace::iterator ito = objectsmap.begin(); ito != objectsMap.end(); ito++ ) {\n const GameObj* test = it->second;\n if ( test == currObj ) continue;\n if ( outsideBoundingRectangle( currObj, test ) ) continue;\n if ( checkCollision( currObj, test ) ) {\n currObj->handleCollision( test );\n }\n }\n }\n}\n</code></pre>\n\n<p>This may be enough for a reasonable speed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T18:06:00.273",
"Id": "22022",
"Score": "0",
"body": "So the `outsideBoundingBox()` function replaces the 2 `for()` loops right? And is there a way around re-initializing the map in order to update the keys (the `Point2D`'s), meaning, can keys be updated in an `std::multimap` WITHOUT creating a new object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T08:57:33.893",
"Id": "22054",
"Score": "0",
"body": "If the only purpose of the map is to do your spatial collision detection, then you can do without it altogether - just replace it with something like a list. Otherwise, I think you're out of luck (those keys are const for a good reason!), unless most of the objects aren't moving, in which case you can try erasing/re-inserting elements from the existing map without creating a new one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:17:56.077",
"Id": "22086",
"Score": "0",
"body": "yeah but then to check collisions, I have to iterate through _every single item_! Is there _really_ no way to update keys or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T06:32:21.213",
"Id": "22099",
"Score": "0",
"body": "Is it a real problem, or a problem that you think _might_ exist (otherwise known as _Beware of Premature Optimisation_)? If your objects are 50x50, with 250 that you're checking against, you've just reduced your searchspace by 10x. Get it working the simplest way first, then optimise if required."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T13:15:31.180",
"Id": "13562",
"ParentId": "13556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T03:58:31.770",
"Id": "13556",
"Score": "5",
"Tags": [
"c++",
"optimization",
"collision"
],
"Title": "Collision-checking optimizations"
}
|
13556
|
<p>This is the pattern I've been using for "if the variable is empty, set a default value", and for variables like <code>$muffin</code>, it has all seemed well and good. But in the following real example, this pattern gives me a super long line which smells a bit to me. Is there a cleaner way to do this?</p>
<pre><code>$newsItems[0]['image_url']= $newsItems[0]['image_url']=='' ? '/img/cat_placeholder.jpg' : $newsItems[0]['image_url'];
</code></pre>
<p>Maybe:</p>
<pre><code>$newsItems[0]['image_url']= $newsItems[0]['image_url']=='' ?
'/img/cat_placeholder.jpg' :
$newsItems[0]['image_url']; //this doesn't look much better to me?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-24T10:08:00.087",
"Id": "300436",
"Score": "0",
"body": "Starting with PHP 7.0, [Langen's answer](http://codereview.stackexchange.com/a/114326/80949) is probably the best: `$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?? '/img/cat_placeholder.jpg';` \n http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:04:14.943",
"Id": "480058",
"Score": "0",
"body": "Starting with PHP 7.4 [there is a native operator - ??=](https://codereview.stackexchange.com/a/244534/226766)"
}
] |
[
{
"body": "<p>Before dealing with your question, I'd like to point out that you probably want to use <code>empty()</code> instead of comparing with an empty string and that if you really want to compare to an empty string, use the <code>===</code> operator.</p>\n\n<p>Anyway, default initialization <em>is</em> a real problem in many languages. C# even has a <a href=\"http://msdn.microsoft.com/en-US/library/ms173224(v=vs.80)\" rel=\"noreferrer\">?? operator</a> to solve this kind of issue! So, let's try to make it better to make your code better step by step.</p>\n\n<h2>Ternary operator no more</h2>\n\n<p>The one-liner is too long, and using the ternary operator on multiple lines is a bad idea: that's what if-statement are for:</p>\n\n<pre><code>if (empty($newsItems[0]['image_url'])) {\n $newsItems[0]['image_url'] = '/img/cat_placeholder.jpg';\n}\n</code></pre>\n\n<p>This is more readable for two reasons : it's easier to understand the syntax, but more importantly, it's easier to see that you simply want a default value when there's nothing. We don't need the 'else' part which is confusing with the ternary operator.</p>\n\n<p>Note: as mentioned by Simon Scarfe and corrected by mseancole, PHP also has some special ternary syntax to do this:</p>\n\n<pre><code>$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?: 'img/cat_placeholder.jpg';\n</code></pre>\n\n<h2>Factorize it!</h2>\n\n<p>If you're doing this only once or twice, then all is good, but otherwise you'd want to factorize it into a function, since you don't repeat yourself, right? The simple way is:</p>\n\n<pre><code>function default_value($var, $default) {\n return empty($var) ? $default : $var;\n}\n\n$newsItems[0]['image_url'] = default_value($newsItems[0]['image_url'], '/img/cat_placeholder.jpg');\n</code></pre>\n\n<p>(The ternary operator does make sense here since variable names are short and both branches of the condition are useful.)</p>\n\n<p>However, we're looking up <code>$newsItems[0]['image_url']</code> when calling <code>default_value</code>, and this is possibly not defined, and will raise an error/warning. If that's a concern (it should), stick to the first version, or look at <a href=\"https://codereview.stackexchange.com/a/75849\">this other answer</a> that gives a more robust solution at the expense of storing PHP code as a a string and thus cannot be checked syntactically.</p>\n\n<h2>Still too long</h2>\n\n<p>If we don't care about the warning/error, can we do better? Yes we can! We're writing the variable name twice, but <a href=\"http://www.php.net/manual/en/language.references.pass.php\" rel=\"noreferrer\">passing by reference</a> can help us here:</p>\n\n<pre><code>function default_value(&$var, $default) {\n if (empty($var)) {\n $var = $default;\n }\n}\n\ndefault_value($newsItems[0]['image_url'], '/img/cat_placeholder.jpg');\n</code></pre>\n\n<p>It's much shorter, and feels more declarative: you can look at a bunch of <code>default_value</code> calls and see what the default values are instantly. But we still have the same warning/error issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-06T21:39:16.597",
"Id": "138007",
"Score": "1",
"body": "The second two options presented here will raise an error and also (because of this) impact performance. I shouldn't have to mention the performance bit, though, as the fact that an error (Warning, in this case, undefined index) should simply be enough. Even if reporting/logging is turned off, the fact that the interpreter notices at all incurs more performance impact than `empty` and `isset` in conjunction with an `if`. Stick to the `if`, or use a solution like mine below."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-07T07:57:03.360",
"Id": "139076",
"Score": "0",
"body": "Thank you, upvoted. Of course, the performance does not matter here, unless it is proven that this code is part of a bottleneck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-07T08:03:02.630",
"Id": "139077",
"Score": "0",
"body": "@MichaelJMulligan does my edit seem fair?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-07T15:45:08.890",
"Id": "139127",
"Score": "0",
"body": "@QuentinPradet, Fair. As for the syntactic check, can you elaborate on my answer? I'd be interested."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T10:16:30.447",
"Id": "13559",
"ParentId": "13558",
"Score": "36"
}
},
{
"body": "<h1>Doing it OOP style</h1>\n\n<p>If you are doing OOP you could also reconsider if using a plain array is the way to go. I guess <code>image_url</code> is not the only attribute of your news items, so <a href=\"http://sourcemaking.com/refactoring/replace-array-with-object\" rel=\"nofollow\">convert this array structure to an object</a>. Furthermore, <code>$newsItems</code> may get changed to an array of <code>NewsItem</code> instances.</p>\n\n<p><code>/img/cat_placeholder.jpg</code> could be the default value of the attribute <code>image_url</code> in your new class NewsItem. Either your client code decides whether to set a new value (e.g. based on being <code>!empty()</code>) or your <code>NewsItem</code> class has a setter method for the attribute <code>image_url</code>' that automatically sets the default value if it gets an empty string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T11:14:17.403",
"Id": "13560",
"ParentId": "13558",
"Score": "5"
}
},
{
"body": "<p>From <a href=\"http://us2.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\">here</a>:</p>\n\n<blockquote>\n <p>Since PHP 5.3, it is possible to leave out the middle part of the\n ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1\n evaluates to TRUE, and expr3 otherwise.</p>\n</blockquote>\n\n<p>So could you write?:</p>\n\n<pre><code>$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?: '/img/cat_placeholder.jpg';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T02:06:29.313",
"Id": "22123",
"Score": "3",
"body": "This is one of my favorite things to write in PHP. It feels elegant and naughty at the same time! :) I normally only use it when assigning to another variable or return from a function, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T14:59:16.617",
"Id": "91520",
"Score": "7",
"body": "Note that if your variable is undefined, PHP will throw notices about it. This, unfortunately, is no replacement for `$var = isset($var) ? $var : 'default value';`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-28T20:23:45.773",
"Id": "267622",
"Score": "0",
"body": "That's amazing, so clean and elegant :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:09:27.773",
"Id": "13565",
"ParentId": "13558",
"Score": "19"
}
},
{
"body": "<p><a href=\"http://www.php.net/extract\" rel=\"nofollow\">The <code>extract()</code> function</a> can also help.</p>\n\n<p>It doesn't work for individual array keys like you have here, but it could be useful in other circumstances.</p>\n\n<pre><code>extract(array('foo'=>'bar'), EXTR_SKIP);\n</code></pre>\n\n<p>This will assign <code>bar</code> to <code>$foo</code> as a default value only if it's not already set. If <code>$foo</code> is already set it will skip it. You can include multiple variables in the array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T18:20:33.990",
"Id": "13596",
"ParentId": "13558",
"Score": "5"
}
},
{
"body": "<p><strong>Warning</strong></p>\n\n<p>Do not do either of these two things:</p>\n\n<pre><code>$array['index'] = $array['index'] ?: $default;\n\nfunction default_value(&$var, $default) {\n if (empty($var)) {\n $var = $default;\n }\n}\n\ndefault_value($array['index'], $default);\n</code></pre>\n\n<p>Both will raise errors due to an undefined index (both first attempt getting the value at the index first) if the index is not set. This is a small thing, but even if you have error reporting AND logging turned off, the error is raised, is built, and propagates through the stack before it is checked if there is anywhere to report the error. And thus, simply doing something that CAN raise an error, incurs a performance hit.</p>\n\n<p>Keep this in mind, because this goes for all Error Types (Notices, Warnings, etc), and in large apps can be a big deal. To avoid this you must use a function that does not raise an error on a missing index, like <code>isset($array['index'])</code> or <code>empty($array['index'])</code>, and not use the shortened ternary form.</p>\n\n<p><strong>Try a function like:</strong></p>\n\n<pre><code>function apply_default(Array &$array, $path, $default) {\n // may need to be modified for your use-case\n preg_match_all(\"/\\[['\\\"]*([^'\\\"]+)['\\\"]*\\]/im\",$path,$matches);\n if(count($matches[1]) > 0) {\n $destinaion =& $array;\n foreach ($matches[1] as $key) {\n if (empty($destinaion[$key]) ) {\n $destinaion[$key] = array();\n }\n $destinaion =& $destinaion[$key];\n }\n if(empty($destinaion)) {\n $destinaion = $default;\n return TRUE;\n }\n }\n return FALSE;\n}\n\n$was_applied = apply_default($array,\n \"['with a really long name']['and multiple']['indexes']\",\n $default_value);\n</code></pre>\n\n<p>This doesn't raise errors, and will create the path if it does not exist. It also benefits from consolidating the logic to set defaults in one place, rather than <code>if</code>s everywhere.</p>\n\n<p>As mentioned elsewhere, the other option is to:</p>\n\n<pre><code>if(empty($array['key'])) {\n $array['key'] = $default;\n}\n</code></pre>\n\n<p>Which is just as good, and probably more performant.</p>\n\n<p><em>However</em>, all that said, ideally this should only be handled in the consuming service. If the value is empty, the consumer (whether a view or another client [like javascript]) should be allowed to make this choice on it's own. As, in actuality, the semantic data is empty for the model. How this is handled should be up to the consumer it's self, ie, if this is going to a template/view, the conditional should be handled during display. If it is sent as JSON, the client should be able to make the choice.</p>\n\n<p><strong>You are asking about styles</strong>, that is probably the most important. The best style is, if you are providing data to a client, don't fake it (but document the possible empty response).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-07T21:02:26.757",
"Id": "139178",
"Score": "0",
"body": "Great answer, and nobody had seen this before. So you asked about the syntax errors. Say you write \"['with a really long name'][and multiple']\". If this wasn't in a PHP string, but actually interpreted by PHP as PHP code, you would get a meaningful error, but in your function the regex would simply fail, I guess?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-07T22:12:27.820",
"Id": "139183",
"Score": "0",
"body": "It would, you are correct. I will think on how to make that not suck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-08T07:52:45.723",
"Id": "139210",
"Score": "0",
"body": "You could send an array of strings instead. Not sure this is worth thinking about, though!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-06T19:58:13.207",
"Id": "75849",
"ParentId": "13558",
"Score": "2"
}
},
{
"body": "<p>Lo and behold, the power of PHP 7's <a href=\"https://wiki.php.net/rfc/isset_ternary\" rel=\"noreferrer\">null coalesce operator!</a> It is also called the isset ternary operator, for obvious reasons.</p>\n<p>Here's a passage from php.net's wiki page about it</p>\n<blockquote>\n<p><strong>Proposal</strong></p>\n<p>The coalesce, or ??, operator is added, which returns the result of its first operand if it exists and is not NULL, or else its second operand. This means the <code>$_GET['mykey'] ?? ""</code> is completely safe and will not raise an <code>E_NOTICE</code>.</p>\n</blockquote>\n<p>This is what it looks like</p>\n<p><code>$survey_answers = $_POST['survey_questions'] ?? null;</code></p>\n<p>It can even be chained. It'll use the first value that exists and isn't null, consider the following:</p>\n<pre><code>$a = 11;\n$b = null;\n$c = 'test';\n\n$d = $a ?? $b ?? $c;\n\nprint $d;\n</code></pre>\n<p>This would result in <code>11</code>, however if <code>$a = null;</code> it would print <code>test</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-24T10:05:47.173",
"Id": "300434",
"Score": "0",
"body": "This is now integrated: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-17T20:42:37.570",
"Id": "114326",
"ParentId": "13558",
"Score": "14"
}
},
{
"body": "<p>PHP 7.4 adds <code>??=</code>, the <a href=\"https://www.php.net/manual/en/migration74.new-features.php\" rel=\"nofollow noreferrer\">null coalescing assignment operator</a>, which is exactly what you need.</p>\n<pre><code>$newsItems[0]['image_url'] ??= '/img/cat_placeholder.jpg';\n</code></pre>\n<p>This is functionally equivalent to the following, or to your examples:</p>\n<pre><code>if (!isset($newsItems[0]['image_url'])) {\n $newsItems[0]['image_url'] = '/img/cat_placeholder.jpg';\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:00:43.180",
"Id": "244534",
"ParentId": "13558",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13559",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T09:32:52.730",
"Id": "13558",
"Score": "37",
"Tags": [
"php",
"formatting"
],
"Title": "Setting a default value if a variable is empty"
}
|
13558
|
<p>I have got a an object that has values true and false for certain keys.I need to find which keys has got a boolean value and convert them to 1 and 0 respectively.Please find the code below.I wanted to check for keys in an object that has got boolean values and then convert them to numbers.Im a noob in Javascript and i got some help from fellow programmers in SO.This works but im sure there is a better way of doing this.</p>
<pre><code> var obj ={
"label":'test',
"tel":123456,
"settings": {
"playback": false,
"attachfile": true,
},
"setTime":true,
"setDay":false,
"arrSettings" :[
'Testing',
{"playback": false,"attachfile": true},
{"playback": false,"attachfile": true},
123456789
]
}
function changeBooleanToNumber(o){
for(var key in o){
if(/^boolean$/i.test(typeof o[key])){
o[key] = Number(o[key]);
}
if (Object.prototype.toString.call(o[key]) === '[object Object]'){
changeBooleanToNumber(o[key]);
}
else if( Object.prototype.toString.call( o[key]) === '[object Array]' ) {
for(var i=0;i<=o[key].length-1;i++){
if(Object.prototype.toString.call(o[key][i]) === '[object Object]'){
changeBooleanToNumber(o[key]);
}
}
}
}
}
changeBooleanToNumber(obj);
</code></pre>
|
[] |
[
{
"body": "<p>I would ask in return: Why do you want to convert booleans to numbers? First of all there must have been a reason to use booleans and not numbers in the first place and second most programming languages use the integer values 1 and 0 respectively for True and False (as I am a Python programmer I am not 100% sure but I think the concept extends to truethy and falsy in JS) and can be used like that.</p>\n\n<p>The following is a copy/paste of a Python console and I also tested the same in an online JS interpreter which worked fine.</p>\n\n<pre><code>>>>> True + True\nOut[0]: 2\n>>>> False + True\nOut[1]: 1\n>>>> True - 1\nOut[2]: 0\n>>>> True * 3\nOut[3]: 3\n</code></pre>\n\n<p><strong>Therefore you don't have to convert the booleans to numbers, just use them as such!</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:35:12.717",
"Id": "21971",
"Score": "0",
"body": "its a valid comment mate.its a bit weird actually,i am posting this object back to an API that only accepts 1 and 0 for boolean values.Dont ask me why :) i didnt write the API so i wouldnt know.Thanks for your comment though"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T13:31:03.250",
"Id": "13563",
"ParentId": "13561",
"Score": "0"
}
},
{
"body": "<p>Before I do anything else I feel compelled to clean up your spacing convert \" to ' to consistantly use only one type of strings</p>\n\n<pre><code>var obj = {\n 'label': 'test',\n 'tel': 123456,\n 'settings': {\n 'playback': false,\n 'attachfile': true,\n },\n 'setTime': true,\n 'setDay': false,\n 'arrSettings': [\n 'Testing',\n {'playback': false, 'attachfile': true},\n {'playback': false, 'attachfile': true},\n 123456789\n ]\n};\n\nfunction changeBooleanToNumber(o) {\n for (var key in o) {\n if (/^boolean$/i.test(typeof o[key])) {\n o[key] = Number(o[key]);\n }\n\n if (Object.prototype.toString.call(o[key]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n } else if (Object.prototype.toString.call(o[key]) === '[object Array]') {\n for (var i = 0; i < o[key].length - 1; i++) {\n if(Object.prototype.toString.call(o[key][i]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n }\n }\n }\n }\n}\n\nchangeBooleanToNumber(obj);\n</code></pre>\n\n<p>Now:</p>\n\n<ol>\n<li><p>Use <code>+x</code> instead of <code>Number(x)</code>; it is shorter and faster in all cases I've ever bothered to test.</p></li>\n<li><p>Don't use <code>var</code> inline, javascript doesn't have block scope (only function scope) so it is better to declare all necessary variables at the start of your functions.</p></li>\n<li><p>Cache <code>Object.prototype.toString</code> to make code more readable.</p></li>\n<li><p>Use toString instead of a regex test for checking for the bool type</p></li>\n<li><p>simplify <code>for</code> loop and store the upper bound in a variable instead of computing it every time</p></li>\n<li><p>Use a <code>hasOwnProperty</code> check on the <code>for in</code> loop.</p></li>\n</ol>\n\n<p>This leaves me with this:</p>\n\n<pre><code>function changeBooleanToNumber(o) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n key, \n i,\n len;\n for (key in o) {\n if (hasOwn.call(o,key)) {\n if (toString.call(o[key]) === '[object Boolean]') {\n o[key] = +o[key];\n } else if (toString.call(o[key]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n } else if (toString.call(o[key]) === '[object Array]') {\n len = o[key].length;\n for (i = 0; i < len; i++) {\n if(toString.call(o[key][i]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>This resulting code looks to me like it has too many indents. I also notice that it fails on passing in an object that is an array or contains an array of arrays. Reordering some code we can check both of those cases at the root level:</p>\n\n<pre><code>function changeBooleanToNumber(o) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n key,\n len;\n if (toString.call(o) === '[object Object]') {\n for (key in o) {\n if (hasOwn.call(o, key)) {\n if (toString.call(o[key]) === '[object Boolean]') {\n o[key] = +o[key];\n } else if (toString.call(o[key]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n } else if (toString.call(o[key]) === '[object Array]') {\n changeBooleanToNumber(o[key]);\n }\n }\n }\n } else if (toString.call(o) === '[object Array]') {\n len = o.length;\n for (key = 0; key < len; key++) {\n if (toString.call(o[key]) === '[object Boolean]') {\n o[key] = +o[key];\n } else if (toString.call(o[key]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n } else if (toString.call(o[key]) === '[object Array]') {\n changeBooleanToNumber(o[key]);\n }\n }\n }\n}\n</code></pre>\n\n<p>However now there is a bunch of duplicate code. This can be reduced by abstracting a function:</p>\n\n<pre><code>function changeBooleanToNumberHelper(o, key) {\n var toString = {}.toString;\n if (toString.call(o[key]) === '[object Boolean]') {\n o[key] = +o[key];\n } else if (toString.call(o[key]) === '[object Object]') {\n changeBooleanToNumber(o[key]);\n } else if (toString.call(o[key]) === '[object Array]') {\n changeBooleanToNumber(o[key]);\n }\n}\nfunction changeBooleanToNumber(o) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n key,\n len;\n if (toString.call(o) === '[object Object]') {\n for (key in o) {\n if (hasOwn.call(o, key)) {\n changeBooleanToNumberHelper(o, key);\n }\n }\n } else if (toString.call(o) === '[object Array]') {\n len = o.length;\n for (key = 0; key < len; key++) {\n changeBooleanToNumberHelper(o, key);\n }\n }\n}\n</code></pre>\n\n<p>Here, the <code>if</code> statements look very similar. It turns out we can inline this helper function:</p>\n\n<pre><code>function changeBooleanToNumber(o, key) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n len;\n if (key) {\n if (toString.call(o[key]) === '[object Boolean]') {\n o[key] = +o[key];\n return;\n }\n o = o[key];\n }\n if (toString.call(o) === '[object Object]') {\n for (key in o) {\n if (hasOwn.call(o, key)) {\n changeBooleanToNumber(o, key);\n }\n }\n } else if (toString.call(o) === '[object Array]') {\n len = o.length;\n for (key = 0; key < len; key++) {\n changeBooleanToNumber(o, key);\n }\n }\n}\n</code></pre>\n\n<p>Without going farther I recognize this pattern as a depth first graph traversal with a little additional functionality. I would abstract that a little and see this helper function:</p>\n\n<pre><code>function depthVisit(node, visit, key) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n len;\n if (key) {\n if (visit(node, key) === false) {\n return;\n }\n node = node[key];\n }\n if (toString.call(node) === '[object Object]') {\n for (key in node) {\n if (hasOwn.call(node, key)) {\n depthVisit(node, visit, key);\n }\n }\n } else if (toString.call(node) === '[object Array]') {\n len = node.length;\n for (key = 0; key < len; key++) {\n depthVisit(node, visit, key);\n }\n }\n}\n\nfunction changeBooleanToNumber(o) {\n depthVisit(o, function (parent, key) {\n if ({}.toString.call(parent[key]) === '[object Boolean]') {\n parent[key] = +parent[key];\n }\n });\n}\n</code></pre>\n\n<p>However I know this function has a bug: javascript can have cyclic references (causing infinite recursion). To fix that I need to either limit the traversal to a particular depth or check if I have already visited an object. Here I'll do the latter:</p>\n\n<pre><code>function depthVisit(node, visit) {\n var set = [];\n function seen(node) {\n var i = set.length - 1;\n while (set[i] !== node && i > 0) { i--; }\n set.push(node);\n return i !== -1 && set[i] === node;\n }\n function inner(node, key) {\n var toString = {}.toString,\n hasOwn = {}.hasOwnProperty,\n len;\n if (key) {\n if (visit(node, key) === false) {\n return;\n }\n node = node[key];\n }\n if (seen(node)) {\n return;\n }\n if (toString.call(node) === '[object Object]') {\n for (key in node) {\n if (hasOwn.call(node, key)) {\n inner(node, key);\n }\n }\n } else if (toString.call(node) === '[object Array]') {\n len = node.length;\n for (key = 0; key < len; key++) {\n inner(node, key);\n }\n }\n }\n inner(node);\n}\n\nfunction changeBooleanToNumber2(o) {\n depthVisit(o, function (parent, key) {\n if ({}.toString.call(parent[key]) === '[object Boolean]') {\n parent[key] = +parent[key];\n }\n });\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/JBavW/\" rel=\"nofollow\">JsFiddle to show it works.</a></p>\n\n<p>Interestingly this version is also about 20% faster than the original code. (see: <a href=\"http://jsperf.com/graph-traversal\" rel=\"nofollow\">http://jsperf.com/graph-traversal</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:10:12.163",
"Id": "13604",
"ParentId": "13561",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T12:39:40.827",
"Id": "13561",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Check for boolean values in an object and convert them to numbers"
}
|
13561
|
<p>I have an array of points:</p>
<pre><code> Point[] line; // { Point(1,1), Point(2,3), Point(1,1) }
</code></pre>
<p>Assuming Point has the relevant operators, what's the most linq-y way of computing the length of this line?</p>
<p>My best effort so far is:</p>
<pre><code>float length = Enumerable.Range(0, line.Length-2)
.Select(pointIndex => (line[pointIndex+1] - line[pointIndex]).Magnitude)
.Sum();
</code></pre>
<p>Seems like there's a lot of subscripting in there though.</p>
<p>I would think there's a way to do something like this pseudocode:</p>
<pre><code>float length = line.PairwiseMap(p1, p2 => (p2 - p1).Magnitude).Sum();
</code></pre>
<p>?</p>
|
[] |
[
{
"body": "<p>You could use linq <code>Zip</code> instead of <code>PairwiseMap</code>. There is a drawback, you have to create two new enumerations with points:</p>\n\n<pre><code>// collection of point/tuples\nvar points = new[] { \n Tuple.Create(1f, 1f), \n Tuple.Create(2f, 3f), \n Tuple.Create(5f, 5f), \n Tuple.Create(0f, 0f) \n};\n\n// your implementation\nEnumerable\n .Range(0, points.Length - 1)\n .Select(index => Math.Sqrt(Math.Pow(points[index].Item1 - points[index + 1].Item1, 2) + Math.Pow(points[index].Item2 - points[index + 1].Item2, 2)))\n .Sum();\n\nvar left = points.Take(points.Length - 1); // starting points of verctors\nvar right = points.Skip(1); // ending points of verctors\n\n// zip and calculate magnitude\nleft\n .Zip(right, (x, y) => \n Math.Sqrt(Math.Pow(x.Item1 - y.Item1, 2f) + Math.Pow(x.Item2 - y.Item2, 2f)))\n.Sum()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T16:43:22.317",
"Id": "13576",
"ParentId": "13567",
"Score": "2"
}
},
{
"body": "<p>Use <code>.Aggregate()</code> which is a way to fold an operation over a list with an accumulator</p>\n\n<pre><code>if (line.Any())\n length = line.Skip(1)\n .Aggregate(\n new { Point = line.First(), Length = 0d }, //seed\n (accum, point) => new { Point = point, Length = accum.Length + (point - accum.Point).Magnitude })\n .Length\nelse\n length = 0;\n</code></pre>\n\n<p>In this case, our accumulator is a <code>Tuple<Point, double></code>, where the <code>double</code> is the length so far.</p>\n\n<p>One advantage to this approach is that your points collection doesn't need to be an array or even have random access, just be an <code>IEnumerable<Point></code>. OTOH, <code>.Aggregate()</code> can be clunky, and you may prefer the readability of @akim's answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T08:36:53.670",
"Id": "22577",
"Score": "0",
"body": "You're right, it's almost too slick. Very nice though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T19:16:38.300",
"Id": "13599",
"ParentId": "13567",
"Score": "2"
}
},
{
"body": "<p>Another possible answer (first time I've ever suggested two answers) is to keep your existing approach, but modified just a little bit by using <code>.Select()</code>'s under-appreciated little brother that gives you access to an index variable:</p>\n\n<pre><code>float length = line.Skip(1)\n .Select((point, index) => (point - line[index]).Magnitude)\n .Sum();\n</code></pre>\n\n<p>Heck, speaking of overloads. You can also keep your existing approach but use <code>.Sum()</code>'s overload:</p>\n\n<pre><code>Enumerable.Range(0, line.Length - 1)\n .Sum(pointIndex => (line[pointIndex + 1] - line[pointIndex]).Magnitude)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T19:21:44.257",
"Id": "13600",
"ParentId": "13567",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "13600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:06:59.230",
"Id": "13567",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "Use linq to compute length of line defined as array of points"
}
|
13567
|
<p>I am trying to hide and show tooltips depending on what element is hovered over. This works as expected and I could continue to rinse and repeat. However, I am wondering if there is a good way to simplify this or make it more compact. Also I was assuming I could use <code>.hover()</code>, but that didn't seem to work for me. So instead I am using mouseover and mouseout.</p>
<pre><code>$('.remove').eq(0).mouseover(function(){
$('.tooltip').eq(0).show();
});
$('.remove').eq(0).mouseout(function(){
$('.tooltip').eq(0).hide();
});
$('.remove').eq(1).mouseover(function(){
$('.tooltip').eq(1).show();
});
$('.remove').eq(1).mouseout(function(){
$('.tooltip').eq(1).hide();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:25:55.643",
"Id": "21974",
"Score": "0",
"body": "What is the HTML for .remove and .tooltip, how are they related in the DOM?"
}
] |
[
{
"body": "<p>Use an <code>.each</code> \"loop\":</p>\n\n<pre><code>var tooltips = $('.tooltip');\n\n$('.remove').each(function(i) {\n var tooltip = tooltips.eq(i);\n\n $(this).on({\n mouseover: function() { tooltip.show(); },\n mouseout: function() { tooltip.hide(); }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:36:17.763",
"Id": "21978",
"Score": "0",
"body": "@KrisHollenbeck: No problem! Some more details about the ever-useful `each` can be found here: http://api.jquery.com/each"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:40:31.343",
"Id": "21979",
"Score": "0",
"body": "Isn't an each loop unnecessary? Why just attach to all `.remove` elements at once? Like [this](http://stackoverflow.com/a/11454283/144665)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:18:12.187",
"Id": "21980",
"Score": "0",
"body": "@anonymousdownvotingislame: Please see all my other comments about why `index` won't work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:54:22.593",
"Id": "21981",
"Score": "0",
"body": "Also, I agree with @anonymousdownvotingislame's username. A comment when you downvote me would be much appreciated, random person."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:59:21.680",
"Id": "21982",
"Score": "0",
"body": "I see no comments regarding `index()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:59:59.627",
"Id": "21983",
"Score": "0",
"body": "@anonymousdownvotingislame: Looks like they've all been deleted now! :D Really sorry. I'll post another"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:26:14.413",
"Id": "13571",
"ParentId": "13570",
"Score": "6"
}
},
{
"body": "<p>Have a single mouse move event handler that tracks the element id it's currently on and set the tooltip based on it. For improved performance you could instead poll mouse's position every say 500 ms and set the tooltip based on that.</p>\n\n<p>You would have a single function to manage all your tooltips in a switch(){} block of code with a \"default\" case that sets the tooltip to empty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:28:29.527",
"Id": "13572",
"ParentId": "13570",
"Score": "0"
}
},
{
"body": "<p>If i'm not totally wrong try referencing your target through a custom attribute on the trigger:</p>\n\n<pre><code><div id=\"tooltip1\" style=\"display:none\">TOOLTIP 1 CONTENT</div>\n<div id=\"tooltip2\" style=\"display:none\">TOOLTIP 2 CONTENT</div>\n<div id=\"tooltip3\" style=\"display:none\">TOOLTIP 3 CONTENT</div>\n\n\n\n<a href=\"javascript:;\" class=\"remove\" data-ref=\"#tooltip1\">TRIGGER 1</a>\n<a href=\"javascript:;\" class=\"remove\" data-ref=\"#tooltip2\">TRIGGER 2</a>\n<a href=\"javascript:;\" class=\"remove\" data-ref=\"#tooltip3\">TRIGGER 3</a>\n\n<script type=\"text/javascript\">\n $('.remove').mouseover(function(){\n $($(this).attr(\"data-ref\")).show();\n });\n\n $('.remove').mouseout(function(){\n $($(this).attr(\"data-ref\")).hide();\n });\n</script>\n</code></pre>\n\n<p>there's room for improvement but should help.</p>\n\n<p>Happy coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:34:46.323",
"Id": "13573",
"ParentId": "13570",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13571",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:23:20.847",
"Id": "13570",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"event-handling"
],
"Title": "Simplifying multiple mouseover and mouseout functions"
}
|
13570
|
<p>Right now in my weather app, I have one section of code in my View Controllers to set up the condition image and the background image. It has about 400 lines of <code>if</code>-<code>else</code> statement at the end.</p>
<p>The app's performance is fine, but is it bad to have this? Would it be something that, say, Apple would consider rejecting? The code is very easy to read, and makes perfect sense in my opinion.</p>
<pre><code>- (void)updateImages:(ICB_WeatherConditions *)weather {
if ([condition isEqualToString:@"113"]) {
conditionsImageView.image = [UIImage imageNamed:@"Sun.png"];
BGView.image = [UIImage imageNamed:@"Sun.jpg"];
} else {
if ([condition isEqualToString:@"116"]) {
conditionsImageView.image = [UIImage imageNamed:@"Mostly_Sunny.png"];
BGView.image = [UIImage imageNamed:@"Partly_Cloudy.jpg"];
} else {
if ([condition isEqualToString:@"119"]) {
conditionsImageView.image = [UIImage imageNamed:@"Overcast.png"];
BGView.image = [UIImage imageNamed:@"Overcast.jpg"];
}
else {
if ([condition isEqualToString:@"122"]) {
conditionsImageView.image = [UIImage imageNamed:@"Overcast.png"];
BGView.image = [UIImage imageNamed:@"Overcast.jpg"];
}
else {
if ([condition isEqualToString:@"143"]) {
conditionsImageView.image = [UIImage imageNamed:@"Mist.png"];
BGView.image = [UIImage imageNamed:@"Foggy.jpg"];
}
else {
if ([condition isEqualToString:@"176"]) {
conditionsImageView.image = [UIImage imageNamed:@"Scattered_Thunderstorms.png"];
BGView.image = [UIImage imageNamed:@"Scat_Tstorms.jpg"];
}
</code></pre>
<p>It keeps going on after that. As you can see, I have a lot of nearly identical statements, which is because I have a lot of conditions. Is it bad practice to do this? If it is, then how can this become more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:12:09.563",
"Id": "21989",
"Score": "5",
"body": "Does objective C allow switch-case with strings like the newer versions of Java? If it does I would use switch-case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:13:22.900",
"Id": "21990",
"Score": "0",
"body": "@JonTaylor I'm pretty sure it does, I think I've seen it in other code, but is this any less efficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:14:21.483",
"Id": "21991",
"Score": "0",
"body": "I have no idea about the efficiency of switch-case vs if/else in objective c however it will be more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:15:09.580",
"Id": "21992",
"Score": "4",
"body": "Objective-C doesn't support switch on `NSString`. But your code would be more readable if you write your conditions like this: [Can Objective-C switch on NSString?](http://stackoverflow.com/questions/8161737/can-objective-c-switch-on-nsstring)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:18:43.170",
"Id": "21994",
"Score": "3",
"body": "@Programmer20005 use `[NSString integerValue]` for a switch statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:13:17.590",
"Id": "21995",
"Score": "1",
"body": "why do you care about the performance of this branching? it almost certainly isn't a bottleneck compared with actually reading a jpg off disc and displaying it? use the most readable implementation (a dictionary imho) and then profile"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-04T03:52:21.717",
"Id": "202068",
"Score": "2",
"body": "Also, \"what is best practice?\" questions are off-topic for Code Review. Reverted to Rev 2 to keep it a \"does my code follow best practices?\" question."
}
] |
[
{
"body": "<p>Why don't you just rename your Files to the matching Number?</p>\n\n<pre><code>conditionsImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@\"%@.png\", condition]]; \nBGView.image = [UIImage imageNamed:[NSString stringWithFormat:@\"%@.jpg\", condition]];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:15:09.193",
"Id": "22001",
"Score": "0",
"body": "Probably because one file e.g. Overcast.jpg is used for more than one number - so only works if you can use hard links in the file system"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:15:12.717",
"Id": "22002",
"Score": "1",
"body": "This one is actually a very good response. Since the images are static, this is the best approach ever possible and saves from redundancy of switch and if-else statements. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:16:28.583",
"Id": "22003",
"Score": "0",
"body": "@Mark of course this could happen. Nevertheless the example states nothing like this. Exceptions could be hardcoded."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:13:45.607",
"Id": "13578",
"ParentId": "13577",
"Score": "3"
}
},
{
"body": "<p>You should look at switch statements for this. The template code in Xcode looks something like this:</p>\n\n<pre><code>switch (condition) {\n case 113:\n // do something\n break;\n case 116:\n // do something\n break;\n /* etc. */\n default:\n // when all else fails, do something\n break;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:14:06.450",
"Id": "13579",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>I'd say a <code>switch</code> statment would be preferable here, especially as you are performing the <code>If</code> on the same expression each time.</p>\n\n<p>Were all the <code>If</code> conditions different variables then I'd say keep it as it is, but a <code>switch</code> is ideal here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:14:28.957",
"Id": "13580",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>In theory there is nothing against such a thing but you are repaeting a lot of code for setting the image therefore i would recomment to use a switch statement instead of the if-elses and make a own method for the inner part of the if-elses. And to make it even more readable use a enum:</p>\n\n<p>The enum:</p>\n\n<pre><code>enum {\n WeatherTypeSun = 115,\n WeatherTypeMostlySunny = 116;\n} WeatherType;\n</code></pre>\n\n<p>and here the switch statement with use of the enums:</p>\n\n<pre><code>- (void)setWeatherImages:(NSString *)weather {\n conditionsImageView.image = [UIImage imageNamed:[weather stringByAppendingString:@\".png\"]];\n BGView.image = [UIImage imageNamed:[weather stringByAppendingString:@\".jpg\"]];\n}\n\n- (void)updateImages:(ICB_WeatherConditions *)weather {\n\n int weatherCondition = [condition intValue];\n\n switch (weatherCondition) {\n case WeatherTypeSun: \n [self setWeatherImages:@\"sun\"];\n break;\n case WeatherTypeMostlySunny:\n [self setWeatherImages:@\"mostly_sunny\"];\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-25T08:40:12.020",
"Id": "375632",
"Score": "0",
"body": "This is the best answer here. The image name extensions are unnecessary though, just use `[UIImage imageNamed:@\"Sunny\"]` etc"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:14:53.260",
"Id": "13581",
"ParentId": "13577",
"Score": "3"
}
},
{
"body": "<p>Use <code>else if</code>!</p>\n\n<pre><code>if (foo) {\n //do something\n}\nelse if (bar) {\n //do something else\n}\n</code></pre>\n\n<p>Apple will definitely not reject you for what you have, but using <code>else if</code> will make it much easier to read and get rid of all that indenting. A <code>switch</code> statement is really no faster, and plus you usually have to have a <code>break;</code> for every <code>case</code>, which is kind of silly to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:18:00.500",
"Id": "22004",
"Score": "0",
"body": "else if is what he has already the `{ }` make no difference since its a single line executed after the else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:19:44.303",
"Id": "22005",
"Score": "0",
"body": "@JonTaylor It's logically the same, but so much more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:21:38.723",
"Id": "22006",
"Score": "0",
"body": "True, you didn't really explain this in your post though, it seemed more like you were giving it as an alternative when actually its essentially a code style difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:33:50.713",
"Id": "22007",
"Score": "0",
"body": "@JonTaylor Ok, I improved my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T16:46:41.080",
"Id": "22008",
"Score": "0",
"body": "@ woz: In your comment, you have mentioned that: \"A switch statement is really no faster\"...Can you please explain?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:01:29.123",
"Id": "22009",
"Score": "0",
"body": "@Vikram I mean the program won't run any faster because you use a switch statement instead of an if/else statement."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:17:08.030",
"Id": "13582",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>You should combine your else and if so you don't over nest since it's all at the same level.</p>\n\n<pre><code> if (condition) {\n // Do something.\n } else if (someOtherCondition) {\n // Something else.\n }\n</code></pre>\n\n<p>Another thing you could do (it would just have a long piece of code else where) is to set up a Dictionary, I think you could even use an XML file or something to load and it would be a bit cleaner and shorter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:18:53.760",
"Id": "13583",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>If you can convert the strings to integers, it would be more readable if you use the <a href=\"http://www.techotopia.com/index.php/The_Objective-C_switch_Statement\" rel=\"nofollow noreferrer\">switch statement</a>.</p>\n\n<p>Otherwise, <a href=\"https://stackoverflow.com/questions/2906955/iphone-os-making-a-switch-statement-that-uses-string-literals-as-comparators-in\">here's a similar question</a>, with several different solutions offered. I'd suggest shipping as is, since you've already measured performance and it's fine. </p>\n\n<p>Alternative solutions include </p>\n\n<ul>\n<li>using enums (which you can switch over) </li>\n<li>having the strings be values in a dictionary (with ints as keys that you can switch over).</li>\n<li><p>using elseif to make the indentation look nicer:</p>\n\n<pre><code>if { \n ...\nelse if{\n ...\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:19:02.947",
"Id": "13584",
"ParentId": "13577",
"Score": "3"
}
},
{
"body": "<p>In my opinion, <strong>if a switch is not an option</strong>, there is nothing wrong with multiple ifs, I would just rewrite the code in the following manner for better readability and less indentations.</p>\n\n<pre><code>- (void)updateImages:(ICB_WeatherConditions *)weather\n{\n if ([condition isEqualToString:@\"113\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Sun.png\"];\n BGView.image = [UIImage imageNamed:@\"Sun.jpg\"];\n }\n else if ([condition isEqualToString:@\"116\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Mostly_Sunny.png\"];\n BGView.image = [UIImage imageNamed:@\"Partly_Cloudy.jpg\"];\n }\n else if ([condition isEqualToString:@\"119\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Overcast.png\"];\n BGView.image = [UIImage imageNamed:@\"Overcast.jpg\"];\n }\n else if ([condition isEqualToString:@\"122\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Overcast.png\"];\n BGView.image = [UIImage imageNamed:@\"Overcast.jpg\"];\n }\n else if ([condition isEqualToString:@\"143\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Mist.png\"];\n BGView.image = [UIImage imageNamed:@\"Foggy.jpg\"];\n }\n else if ([condition isEqualToString:@\"176\"])\n {\n conditionsImageView.image = [UIImage imageNamed:@\"Scattered_Thunderstorms.png\"];\n BGView.image = [UIImage imageNamed:@\"Scat_Tstorms.jpg\"];\n }\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:19:36.543",
"Id": "13585",
"ParentId": "13577",
"Score": "6"
}
},
{
"body": "<p>The main readability problem here has to do with the indentation.</p>\n\n<p>Don't open a bracket after the else and put the if statement directly:</p>\n\n<pre><code>if (...) {\n} else if (...) {\n} else if (...) {\n}\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>if (...) {\n} else {\n if (...) {\n } else {\n if (...) {\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:20:36.360",
"Id": "13586",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>In this case, your indentation makes the code drift over to the right so does make the code difficult to read so does need some changes.</p>\n\n<p>First I would note that a lot of code is repeated and also as noted a switch after converting the <code>condition</code> to an int is possible.</p>\n\n<p>However in this case your code is effectively doing multiple lookups so I would look at using NSDictionaries (or NSArrays if the conditions are 0 to a number) and then do a straight lookup</p>\n\n<p>e.g. \nsetup</p>\n\n<pre><code>NSDictionary* conditionsImages = [NSDictionary dictionaryWithObjectsAndKeys: \n @\"113\", @\"Sun.png\",\n @\"116\", @\"Mostly_Sunny.png\",\n ...\n nil];\n</code></pre>\n\n<p>Or read the dictionaries from a file</p>\n\n<p>Access them by</p>\n\n<pre><code>- (void)updateImages:(ICB_WeatherConditions *)condition {\n conditionsImageView.image = [UIImage imageNamed:\n [conditionsImages objectForKey:condition]];\n BGView.image = [UIImage imageNamed:[otherImages objectForKey:condition]];\n\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:29:10.077",
"Id": "22010",
"Score": "0",
"body": "This seems like the best way so far, I'll try it out and come back! Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:45:33.903",
"Id": "22011",
"Score": "0",
"body": "A dictionary is definitely the DRYest method. Perhaps also, since there is a limited amount of pictures, make a second dictionary with image description and image path, so that if the path changes, the english name remains: `pictograms = dictionary(\"sun\" => \"/path/to/lage-sun.png); conds = dictionary(\"113\" => \"sun\");`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:46:09.140",
"Id": "22012",
"Score": "1",
"body": "It's not just the indentation. The code really does have nested ifs, as if the programmer was not aware of the \"else if\" construct."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:27:22.273",
"Id": "13587",
"ParentId": "13577",
"Score": "17"
}
},
{
"body": "<p>There is a lot of overhead in calling the string methods on the objects + strings can not be used as the condition in switch statements.\nYou are lucky that the values you are driving your logic by are ints.\nSo just convert the value to an int value and run your code in a switch statement like so:</p>\n\n<pre><code> - (void)updateImages:(ICB_WeatherConditions *)weather {\n\n //convert string to int value\n NSString *conditionS = [weather condition];\n int var = [conditionS intValue];\n\n switch(var){\n case 113:\n conditionsImageView.image = [UIImage imageNamed:@\"Sun.png\"];\n BGView.image = [UIImage imageNamed:@\"Sun.jpg\"];\n break;\n case 116:\n conditionsImageView.image = [UIImage imageNamed:@\"Mostly_Sunny.png\"];\n BGView.image = [UIImage imageNamed:@\"Partly_Cloudy.jpg\"];\n break;\n case 119:\n conditionsImageView.image = [UIImage imageNamed:@\"Overcast.png\"];\n BGView.image = [UIImage imageNamed:@\"Overcast.jpg\"]; \n break;\n\n (etc)\n .\n .\n .\n default:\n (default code)\n }\n\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:44:25.910",
"Id": "13589",
"ParentId": "13577",
"Score": "13"
}
},
{
"body": "<p>Put your image mapping in a property list:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>113</key>\n <dict>\n <key>condition</key>\n <string>Sun.png</string>\n <key>background</key>\n <string>Sun.jpg</string>\n </dict>\n <key>116</key>\n <dict>\n <key>condition</key>\n <string>Mostly_Sunny.png</string>\n <key>background</key>\n <string>Partly_Cloudy.jpg</string>\n </dict>\n</dict>\n</plist>\n</code></pre>\n\n<p>And rewrite your method:</p>\n\n<pre><code>- (void)updateImages:(ICB_WeatherConditions *)weather {\n NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@\"your.plist\"];\n NSDictionary *images = [dict objectForKey:condition];\n\n if (images) {\n conditionsImageView.image = [UIImage imageNamed:[images objectForKey:@\"condition\"]];\n BGView.image = [UIImage imageNamed:[images objectForKey:@\"background\"]]; \n }\n else {\n // fallback\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:44:39.307",
"Id": "13590",
"ParentId": "13577",
"Score": "8"
}
},
{
"body": "<p>I'd suggest a more object oriented solution:</p>\n\n<hr>\n\n<p>First create a model class <code>ICBWeatherConditionImage</code>:</p>\n\n<pre><code>@property (nonatomic, assign, readonly) NSUInteger identifier;\n@property (nonatomic, strong, readonly) UIImage *backgroundImage;\n@property (nonatomic, strong, readonly) UIImage *image;\n\n- (id)initWithIdentifier:(NSUInteger)identifier imageName:(NSString *)imageName backgroundImageName:(NSString *)backgroundImageName;\n</code></pre>\n\n<hr>\n\n<p>Then create a manager class <code>ICBWeatherConditionImageManager</code> that loads the basic data from an XML file:</p>\n\n<pre><code>- (id)initWithDataAtURL:(NSURL *)url;\n</code></pre>\n\n<p>It can then search and return the correct ICBWeatherConditionImage object based on a given weatherCondition.</p>\n\n<pre><code>- (ICBWeatherConditionImage *)conditionImageForWeatherCondition:(ICB_WeatherConditions *)weatherCondition;\n</code></pre>\n\n<hr>\n\n<p>Finally you have to check whether you create all ICBWeatherConditionImage during the initialization of the manager object or, to reduce memory consumption, create them on the fly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T08:15:53.713",
"Id": "28637",
"ParentId": "13577",
"Score": "0"
}
},
{
"body": "<p>You can put the resources in a dictionary, and loop it.</p>\n\n<pre><code>[@{@\"113\": @\"Sun.png\", @\"116\": @\"Mostly_Sunny.png\", ...} enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {\n if ([condition isEqualToString: (NSString *)key]) {\n conditionsImageView.image = [UIImage imageNamed: (NSString *)obj];\n BGView.image = [UIImage imageNamed: (NSString *)obj];\n break;\n }\n}];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-05T01:30:20.410",
"Id": "184330",
"ParentId": "13577",
"Score": "2"
}
},
{
"body": "<p>You need to do a few things to clean this up.</p>\n\n<ol>\n<li>Move this logic out of the VC and into a model object.</li>\n<li>Get rid of string comparisons, so convert to a number and use switch()</li>\n<li>All these magic numbers are meaningless without good names so enumerate and name them (WeatherTypeSunny, WeatherTypeMisty, etc) Now they make sense to you, and also to the compiler which can now warn you if any are missing in your switch.</li>\n<li>UIImage imageNamed: doesn't require file type extensions so you can remove them all.</li>\n<li>You are calling the same image filenames in multiple places so clean that up too (in your helper class)</li>\n</ol>\n\n<p>All that should be left in the VC is something like.</p>\n\n<pre><code>MyWeather *weather = [[MyWeather alloc] initWithCondition:condition.intValue];\nconditionsImageView.image = weather.image;\nBGView.image = weather.backgroundImage;\n</code></pre>\n\n<p>Now you can flesh it out with any extra weather related logic too</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-28T08:52:16.663",
"Id": "195321",
"ParentId": "13577",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T14:09:18.830",
"Id": "13577",
"Score": "19",
"Tags": [
"objective-c",
"ios"
],
"Title": "Updating images in a weather app"
}
|
13577
|
<p>This is my feed parser method using feedzirra. It works, but I feel dirty because I can't figure out how to improve this code. Any suggestions?</p>
<pre><code>class Feed < ActiveRecord::Base
attr_accessible :name, :summary, :url, :published_at, :guid
def self.update_from_feed
feed_urls = ["url1", "url2", "ulr3", "url4"]
feeds = Feedzirra::Feed.fetch_and_parse(feed_urls)
feeds.each do |url|
feeds = url.last.entries
feeds.each do |entry|
logger.debug "Questo e l'oggetto #{entry}"
unless exists? :guid => entry.entry_id
create!(
:name => entry.title,
:summary => entry.summary,
:url => entry.url,
:published_at => entry.published,
:guid => entry.entry_id
)
end
end
end
end
end
</code></pre>
<p>This is the object returned from the fetch_and_parse method: <strong>with just the first URL</strong></p>
<pre><code>{"http://www.agichina24.it/home/agenzia-nuova-cina/rss2"=>#<Feedzirra::Parser::RSS:0x00000005db8e68 @title="rss", @url="http://www.agichina24.it/home/agenzia-nuova-cina", @entries=[#<Feedzirra::Parser::RSSEntry:0x00000005db6500 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207121646-cro-rt10178-prestiti_denominati_in_yuan_in_crescita", @entry_id="dY_9w7JofPUA7twYye5aMg", @title=" PRESTITI DENOMINATI IN YUAN IN CRESCITA", @summary="Pechino, 12 lug. ? Impennata per i nuovi prestiti denominati in\nyuan nel mese di giugno, grazie all'iniziativa del governo per\nstimolare l'economia in rallentamento.", @published=2012-07-12 14:45:17 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005dc8fe8 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207121645-cro-rt10177-pechino_stretta_su_spese_funzionari_pubblici", @entry_id="3PxPS6grfUl2G2d0NyLahA", @title=" PECHINO, STRETTA SU SPESE FUNZIONARI PUBBLICI", @summary="Pechino, 12 lug. ? Il governo municipale di Pechino rafforzerà\ni controlli sui viaggi all'estero dei funzionari per\npartecipare ad attività di formazione.", @published=2012-07-12 14:44:42 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005dc6ce8 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207091655-cro-rt10173-colata_di_fango_nel_sichuan_14_morti_confermati", @entry_id="h74sGs2DolJKaZZyZWl84g", @title=" COLATA DI FANGO NEL SICHUAN, 14 MORTI CONFERMATI", @summary="Chengdu, 9 lug.- I soccorritori hanno recuperato i corpi di 14\npersone dopo che una colata di fango, provocata dalle piogge,\naveva colpito la provincia del Sichuan lo scorso 28 giugno.", @published=2012-07-09 14:55:11 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ebb1f8 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207091655-cro-rt10171-attivisti_giapponesi_sulle_diaoyu_proteste_cinesi", @entry_id="7bh55Qqb5dcEijmhCbtLYA", @title=" ATTIVISTI GIAPPONESI SULLE DIAOYU, PROTESTE CINESI", @summary="Pechino, 9 lug.- La Cina ha presentato solenni rimostranze e\nproteste verso il Giappone per aver violato la sua sovranita'\nterritoriale, dopo che due attivisti giapponesi sono sbarcati\nsulle isole Diaoyu.", @published=2012-07-09 14:54:29 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ec0ef0 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207091654-cro-rt10170-incontro_tra_funzionari_di_cina_e_asean", @entry_id="fIrGROI7wDYX0pxsoiS9og", @title=" INCONTRO TRA FUNZIONARI DI CINA E ASEAN", @summary="Phnom Penh, 9 lug.- Domenica si sono incontrati alti funzionari\nin rappresentanza di Cina e Asean, in vista della prossima\nriunione dei ministri degli Esteri.", @published=2012-07-09 14:54:07 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ebebf0 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207061449-cro-rt10139-eclac_si_a_piu_cooperazione_cina_america_latina", @entry_id="K7sni4Vq4wnUEQvtxjKbmg", @title=" ECLAC, SI' A PIU' COOPERAZIONE CINA-AMERICA LATINA", @summary="Santiago, 6 lug. - Elogio alle recenti proposte di Wen Jiabao\nper rafforzare le relazioni di cooperazione tra Cina e America\nLatina.", @published=2012-07-06 12:48:26 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ec7048 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207061448-cro-rt10138-maxi_retata_contro_traffico_di_bambini", @entry_id="aeJgnkQBbTr6finnow2Ckw", @title=" MAXI RETATA CONTRO TRAFFICO DI BAMBINI", @summary="Pechino, 6 lug. - La polizia cinese ha sgominato lunedi' due\ngrandi bande di traffico di bambini: 802 i sospettati\narrestati, 181 i bambini liberati.", @published=2012-07-06 12:47:57 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ec4d48 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207061448-cro-rt10137-hong_kong_record_di_investimenti_esteri", @entry_id="UNxnzwr3oPFEOtES1W4YPg", @title=" HONG KONG, RECORD DI INVESTIMENTI ESTERI", @summary="Hong Kong, 6 lug. - Nel 2011 gli investimenti diretti esteri\n(Fdi) a Hong Kong hanno superato gli 83 miliardi di dollari\nstatunitensi, un record storico, per un piu' 17% rispetto al\n2010.", @published=2012-07-06 12:47:17 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ecda60 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207051516-cro-rt10164-xinjiang_esercitazioni_antiterrorismo", @entry_id="lxvg0rXeNbKGaHiiueQ2tA", @title=" XINJIANG, ESERCITAZIONI ANTITERRORISMO", @summary="Urumqi, 5 lug. - Effettuata un'esercitazione antiterrorismo da\nparte di forze speciali a Urumqi, nella regione autonoma del\nXinjiang Uygur.", @published=2012-07-05 13:15:29 UTC>, #<Feedzirra::Parser::RSSEntry:0x00000005ecb760 @url="http://www.agichina24.it/home/agenzia-nuova-cina/notizie/201207051515-cro-rt10163-raul_castro_a_pechino_per_visita_di_stato", @entry_id="kJjP4UZ_rmbMTyIBKpNRcA", @title=" RAUL CASTRO A PECHINO PER VISITA DI STATO", @summary="Pechino, 5 lug. - Raul Castro Ruz e' giunto mercoledi' a\nPechino per una visita di Stato in Cina, su invito del\npresidente Hu Jintao.", @published=2012-07-05 13:14:25 UTC>], @feed_url="http://www.agichina24.it/home/agenzia-nuova-cina/rss2", @etag=nil, @last_modified=nil>}
</code></pre>
<p>I've tried everything, but only that solution works.</p>
|
[] |
[
{
"body": "<p>Slight cleanup:</p>\n\n<pre><code>class Feed < ActiveRecord::Base\n # ...\n\n def self.update_from_feed\n feed_urls = [\"url1\", \"url2\", \"ulr3\", \"url4\"]\n Feedzirra::Feed.fetch_and_parse(feed_urls).each do |_, feeds|\n feeds.entries.each do |entry|\n # ...\n end\n end\n end\nend\n</code></pre>\n\n<ol>\n<li><p>No need to store a local variable called feeds anymore.</p></li>\n<li><p>If you call .each on a hash, you can use |key, value| in the block.</p></li>\n</ol>\n\n<p>2a. Since url isn't getting used anymore, |url, feeds| becomes |_, feeds|.</p>\n\n<p>Thoughts?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-14T22:21:44.060",
"Id": "36882",
"Score": "0",
"body": "Oops -- super necro here. Didn't realize how unpopulated codereview.stackexchange was..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-08T18:22:06.910",
"Id": "60748",
"Score": "0",
"body": "Sorry for the late comment, but we're working on that, Kyle :) I stumbled on your answer and I think it looks good. I hope you will stick around here more."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T14:47:50.677",
"Id": "23855",
"ParentId": "13591",
"Score": "2"
}
},
{
"body": "<p>The variable names in your blocks are very confusing, especially where you introduce another <code>feeds</code>. Just go with the least surprising names possible:</p>\n\n<pre><code>feed_urls = [\"url1\", \"url2\", \"ulr3\", \"url4\"]\nfeeds = Feedzirra::Feed.fetch_and_parse(feed_urls)\n\nfeeds.each do |feed|\n entries = feed.last.entries\n entries.each do |entry|\n # ...\n end\nend\n</code></pre>\n\n<p>Also, adding parentheses would help make this easier for programmers to parse:</p>\n\n<pre><code>exists?(:guid => entry.entry_id)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-08T18:52:22.447",
"Id": "36921",
"ParentId": "13591",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:17:06.877",
"Id": "13591",
"Score": "4",
"Tags": [
"optimization",
"ruby",
"ruby-on-rails",
"parsing"
],
"Title": "Improving Rails feed parser"
}
|
13591
|
<p>I want to insert parameters dynamically to statements at sqlite.
I now write as follows: </p>
<pre><code> tx.executeSql('SELECT Data from Table Where something = "'+ anyvariable+ '"',[],successFn, errorCB);
</code></pre>
<p>But I guess there is a better (cleaner) method to do it.. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:58:26.180",
"Id": "22018",
"Score": "0",
"body": "No I said I want a better method. the one with \"?\","
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:31:51.867",
"Id": "22019",
"Score": "0",
"body": "Why in the world would you be using js to execute SQL statements... use prepared statements on the server to ensure proper sanitization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:34:25.827",
"Id": "22020",
"Score": "0",
"body": "@rlemon: It might be WebSQL or server-side JS which is just wrongfully tagged with [tag:jquery]"
}
] |
[
{
"body": "<p>I would create an object to model my dynamic parameters using the following interfaces:</p>\n\n<pre><code>{ //reduced format\n clause: string,\n params: an array of parameters if more than one is used\n}\n{ //simple entry format\n clause: string\n param: the parameter if only one is used\n}\n{ //or format\n or: an array of dynamic parameter interfaces to be joined as part of an or clause\n}\n{ //and format\n and: an array of dynamic parameter interfaces to be joined as part of an and clause\n}\n</code></pre>\n\n<p>From here I could use the following functions:</p>\n\n<pre><code>function reduce(param) {\n var clause = [], params = [], nest, nestType;\n if (param.clause !== undefined && param.params) {\n //already in reduced format \n return param;\n }\n if (param.clause !== undefined && param.param !== undefined) {\n //convert simple format to reduced\n return { clause: param.clause, params: [param.param] };\n }\n if (param.clause) {\n //special case (clause without additional parameter)\n //parameters without clause would be done by using empty string\n return { clause: param.clause, params: [] };\n }\n //convert nested forms (and and or)\n if (param.and) {\n nest = param.and;\n nestType = ' AND ';\n } else if (param.or) {\n nest = param.or;\n nestType = ' OR ';\n } else {\n throw new Error('Invalid dynamic parameter found');\n }\n nest.forEach(function (p) {\n p = reduce(p);\n clause.push(p.clause);\n params.push.apply(params, p.params);\n });\n return {\n clause: '(' + clause.join(nestType) + ')',\n params: params\n };\n}\n\nfunction executeDynamicSql(tx, base, dynamicparameter, onSuccess, onError) {\n var reduction = reduce(dynamicparameter);\n tx.executeSql(base + reduction.clause, reduction.params, onSuccess, onError);\n}\n</code></pre>\n\n<p>And call it (in your test case) like so:</p>\n\n<pre><code>executeDynamicSql(tx, 'SELECT Data from Table Where ', {\n clause: 'something = ?',\n param: anyvariable\n}, successFn, errorCB);\n</code></pre>\n\n<p>What is nice about this function is that it can handle a far more complex where clause such as:</p>\n\n<pre><code>var dynamicwhere = {\n or: [\n {clause: 'something = ?', param: somethingid},\n {clause: 'somethingelse = ?', param: somethingelse},\n {clause: 'somedate between ? and ?', params: [d1, d2]},\n {\n and: [\n {clause: 'amt > ?', param: min},\n {clause: 'amt < ?', param: max},\n ]\n }\n ]\n };\n\nexecuteDynamicSql(tx, 'SELECT Data from Table Where ', dynamicwhere, successFn, errorCB);\n</code></pre>\n\n<p>Ultimately executing:</p>\n\n<pre><code>SELECT Data from Table Where (something = ?\n or somethingelse = ?\n or somedate between ? and ?\n or (amt > ? and amt < ?))\n</code></pre>\n\n<p>With the in order parameter list:</p>\n\n<pre><code>[somethingid, somethingelse, d1, d2, min, max]\n</code></pre>\n\n<p>You could do something more fancy using a regex replace or whatever, but I don't think it should be necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T22:19:16.617",
"Id": "13610",
"ParentId": "13592",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T15:44:53.030",
"Id": "13592",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"sqlite"
],
"Title": "Insert dynamic parameters to sqlite database statements"
}
|
13592
|
<p>I've written a simple scraper that parses HTML using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> and collects the data (schedule of sports events), then clubs them together in a list of dicts.</p>
<p>The code works just fine, but the way I process the data is pretty horrible IMO. I use an <code>if...else</code> to parse the data selectively, because the output of the dicts are alternative, that is <code>{venue, result (if available)}</code>, and time of match, and team information. </p>
<p>So basically, is there a better, more reliable way to parse the data? </p>
<pre><code>import requests
import re
from BeautifulSoup import BeautifulSoup
from datetime import datetime
class cricket(object):
def getMatches(self, url):
""" Scrape the given url for match schedule """
headers = {'Accept':'text/css,*/*;q=0.1',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding':'gzip,deflate,sdch',
'Accept-Language':'en-US,en;q=0.8',
'User-Agent':'Mozilla/5 (Solaris 10) Gecko'}
page = requests.get(url, headers = headers)
page_content = page.content
soup = BeautifulSoup(page_content)
result = soup.find('div', attrs={'class':'bElementBox'})
tags = result.findChildren('tr')
match_type_list = ['TEST', 'ODI', 'T20']
match_info = []
for elem in range(1,len(tags)):
dict_ = {}
x = tags[elem].getText()
x = x.replace(r'&nbsp;', '')
if 'Venue' in x:
for a in match_type_list:
if a in x:
match_type = a
x = x.replace('Venue', '')
if 'Result' in x:
x = x.replace('Result', '')
x = x.split(': ')
# print x
venue = x[1]
result = x[2]
dict_.update({'venue':venue,'result':result,
'match_type':match_type})
else:
x = x.split(': ')
venue = x[1]
dict_.update({'venue':venue})
else:
match = re.search(r'\b[AP]M', x)
date_time = x[0:match.end()]
date_time = date_time.replace(',','')[4:]
teams = x[match.end():].split('vs')
home_team = teams[0].strip()
away_team = teams[1].strip()
# print date_time, home_team, away_team
time_obj = datetime.strptime(date_time, '%b %d %Y %I:%M %p')
timings = time_obj.strftime('%Y-%m-%dT%H:%MZ')
dict_.update({'home_team':home_team,
'away_team':away_team,
'timings':timings
})
match_info.append(dict_)
# print match_info
final_list = [] # final list of dicts that we need
for i in range(0, len(match_info), 2):
final_list.append(dict(match_info[i].items() +
match_info[i+1].items()))
# for i in final_list:
# print i
# print final_list
if __name__ == '__main__':
url = 'http://icc-cricket.yahoo.net/match_zone/series/fixtures.php?seriesCode=ENG_WI_2012' # change seriesCode in URL for different series.
#url = 'http://localhost:6543/lhost/static/icc_cricket.html'
c = cricket()
c.getMatches(url)
</code></pre>
|
[] |
[
{
"body": "<p>Personally, I don't like dependencies (in this case requests and BeautifulSoup). Why just not to use the standard modules?</p>\n\n<pre><code>import urllib, re\n\nURL = 'http://icc-cricket.yahoo.net/match_zone/series/fixtures.php?seriesCode=ENG_WI_2012'\npage = urllib.urlopen(URL).read()\n\n# just for the testing - the url above is unavailable, grab it from google cache and write to the page.txt\n#page = open(\"page.txt\").read() \n\n# find the table\ntable = re.match('<div class=\"bElementBox\">.+<tbody>(.+).+</tbody>.+</div>', page).group(1)\n\n# extract all columns\ncolumns = re.compile('<td.*?>(.*?)</td>', re.DOTALL | re.M).findall(table)\nresult = []\n\n# process them by 8\nfor index in range(0, len(columns), 8):\n row = {\n 'home_team' : columns[index + 2], \n 'away_team' : columns[index + 5], \n 'match_type': re.match('.+<b>([A-Z,0-9]+)</b>',columns[index + 6]).group(1), \n 'venue' : re.match(\"<b>Venue</b>: ([\\s,\\w\\']+)\", columns[index + 7]).group(1), \n 'timings' : columns[index], \n }\n m = re.match('.+Result</b>:([\\w, ]+)', columns[index + 7]) \n if m: \n row['result'] = m.group(1)\n result.append(row)\n\nfor r in result:\n print(r)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:05:27.323",
"Id": "22025",
"Score": "0",
"body": "Yeah, I was thinking about going back and using urllib, but won't you agree that parsing raw HTML can be a too much with just regex?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T23:17:14.690",
"Id": "22041",
"Score": "3",
"body": "No, you can't parse HTML with regex. Really. http://stackoverflow.com/a/1732454/282912"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T15:01:30.920",
"Id": "22070",
"Score": "0",
"body": "It's possible and it's easy :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T12:05:33.440",
"Id": "86325",
"Score": "0",
"body": "What do you have against using libraries? From a [recent question of mine](http://codereview.stackexchange.com/questions/48258/well-be-counting-stars) I was told to avoid using `urllib`. There's an item in *Effective Java* stating that you should know and use the libraries, I'm sure this applies to Python as well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:00:24.347",
"Id": "13601",
"ParentId": "13593",
"Score": "0"
}
},
{
"body": "<pre><code>import requests\nimport re\nfrom BeautifulSoup import BeautifulSoup\nfrom datetime import datetime\nclass cricket(object):\n</code></pre>\n\n<p>Python conventions state that classes should CamelCase.</p>\n\n<pre><code> def getMatches(self, url):\n</code></pre>\n\n<p>Python convention states that methods should be lowercase_with_underscores. Also, there isn't really a reason to have this method in a class anyway. Seems to me that it should be a function.</p>\n\n<pre><code> \"\"\" Scrape the given url for match schedule \"\"\"\n\n headers = {'Accept':'text/css,*/*;q=0.1',\n 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding':'gzip,deflate,sdch',\n 'Accept-Language':'en-US,en;q=0.8',\n 'User-Agent':'Mozilla/5 (Solaris 10) Gecko'}\n</code></pre>\n\n<p>I'd move this out of the function into a global constant.</p>\n\n<pre><code> page = requests.get(url, headers = headers)\n page_content = page.content\n soup = BeautifulSoup(page_content)\n</code></pre>\n\n<p>I'd combine these three lines</p>\n\n<pre><code>soup = BeatifulSoup(request.get(url, headers = headers).content)\n\n\n result = soup.find('div', attrs={'class':'bElementBox'})\n tags = result.findChildren('tr')\n</code></pre>\n\n<p>I'd avoid non-descriptive names like result. Tags is a bit better, but not by a whole lot. I'd also combine these two lines</p>\n\n<pre><code>tags = soup.find('div', attr={'class':'bElementBox'}).findChildren('tr')\n\n\n\n\n match_type_list = ['TEST', 'ODI', 'T20'] \n match_info = []\n\n for elem in range(1,len(tags)):\n</code></pre>\n\n<p>It'd make more sense to process things two rows at a time.</p>\n\n<pre><code> dict_ = {}\n</code></pre>\n\n<p>Useless name alert.</p>\n\n<pre><code> x = tags[elem].getText()\n x = x.replace(r'&nbsp;', '')\n</code></pre>\n\n<p>At this point, you extract the text and throw out the html. But the data is divided in table cells, so why in the world wouldn't you want to take advantage of that? At this point you drop down to trying to extract data straight from the text which much harder then if you can use the tags as hints.</p>\n\n<pre><code> if 'Venue' in x:\n for a in match_type_list:\n if a in x:\n match_type = a\n\n x = x.replace('Venue', '')\n if 'Result' in x:\n x = x.replace('Result', '')\n x = x.split(': ')\n # print x\n venue = x[1]\n result = x[2]\n</code></pre>\n\n<p>All this work to extract data from the string is something you really should use a regular expression for. This is exactly the kind of situation it excells at.</p>\n\n<pre><code> dict_.update({'venue':venue,'result':result,\n 'match_type':match_type})\n</code></pre>\n\n<p>Its not clear why you would choose to update rather then simply assign. There is no way that any other line of code in this loop can assign to it.</p>\n\n<pre><code> else:\n x = x.split(': ')\n venue = x[1]\n dict_.update({'venue':venue})\n\n else:\n match = re.search(r'\\b[AP]M', x)\n date_time = x[0:match.end()]\n date_time = date_time.replace(',','')[4:]\n teams = x[match.end():].split('vs')\n home_team = teams[0].strip()\n away_team = teams[1].strip()\n\n # print date_time, home_team, away_team\n\n time_obj = datetime.strptime(date_time, '%b %d %Y %I:%M %p') \n</code></pre>\n\n<p>Organization seems a little suspect. You jump from working on the date, over to the teams, and then back to the date. I'd stick with date until it was finished. You also spend a bunch of lines massaging the date. However, strptime lets you specify any format you want, so you should just be able to have it parse the data</p>\n\n<pre><code> timings = time_obj.strftime('%Y-%m-%dT%H:%MZ')\n</code></pre>\n\n<p>If I'm parsing, I wouldn't convert the time back into a date in another object. I'd keep it as a date object.</p>\n\n<pre><code> dict_.update({'home_team':home_team,\n 'away_team':away_team,\n 'timings':timings\n })\n\n match_info.append(dict_)\n\n\n # print match_info\n\n final_list = [] # final list of dicts that we need\n\n for i in range(0, len(match_info), 2):\n final_list.append(dict(match_info[i].items() +\n match_info[i+1].items()))\n</code></pre>\n\n<p>I'd do this:</p>\n\n<pre><code>for i in range(0, len(match_info), 2):\n left, right = match_info[i:i+2]\n final_list.append( dict(left.items() + right.items() )\n</code></pre>\n\n<p>I think it makes things a bit clearer.</p>\n\n<pre><code> # for i in final_list:\n # print i\n # print final_list\n</code></pre>\n\n<p>this function probably needs to return that list or something.</p>\n\n<pre><code>if __name__ == '__main__':\n url = 'http://icc-cricket.yahoo.net/match_zone/series/fixtures.php?seriesCode=ENG_WI_2012' # change seriesCode in URL for different series.\n #url = 'http://localhost:6543/lhost/static/icc_cricket.html'\n c = cricket()\n c.getMatches(url)\n</code></pre>\n\n<p>Good</p>\n\n<p>Here is my reworking of your code:</p>\n\n<pre><code>def get_cricket_matches(content):\n \"\"\" Scrape the given content for match schedule \"\"\"\n\n soup = BeautifulSoup(content)\n\n all_rows = soup.find('div', attrs={'class':'bElementBox'}).findChildren('tr')\n\n match_info = []\n\n for index in range(1, len(all_rows), 2):\n rows = [row.findChildren('td') for row in all_rows[index:index+2]]\n\n data = {\n 'match_type' : rows[1][0].findChildren('b')[1].getText(),\n 'home_team': rows[0][2].getText(),\n 'away_team' : rows[0][5].getText(),\n 'match_time' : datetime.strptime(rows[0][0].getText(), '%a, %b %d, %Y %I:%M %p'),\n }\n for line in rows[1][1].findAll('b'):\n content = str(line.nextSibling)[1:]\n if line.getText() == 'Venue':\n data['venue'] = content\n else:\n data['result'] = content\n\n match_info.append(data)\n\n return match_info\n</code></pre>\n\n<blockquote>\n <p>Personally, I don't like dependencies (in this case requests and\n BeautifulSoup). Why just not to use the standard modules?</p>\n</blockquote>\n\n<p>Here I have to strongly disagree with @cat_baxter. Dependencies are the best part of python. That is, the availability and ease of installing all these different libraries to make it easier to write code is a great asset of Python. You should never be worried about taking on dependencies that are easy to install if it helps.</p>\n\n<p>Having said that, you don't get a whole lot out of the <code>requests</code> module. So an argument can be made that this code would be better off using urllib. </p>\n\n<p>But then the question is whether its a good idea to parse HTML with regex. With scraping you can get away with using a regex because regardless of the technique you use, changes to the page's structure will probably break it. The question at that point is which version has simpler and easier to write code.</p>\n\n<p>Compare:</p>\n\n<pre><code>re.match('<div class=\"bElementBox\">.+<tbody>(.+).+</tbody>.+</div>', page).group(1)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>soup.find('div', attrs={'class':'bElementBox'})\n</code></pre>\n\n<p>The HTML parser method takes advantage of knowing the structure of html to make it fairly easy to find the element. Is the regex entirely correctly? (Technically no, because simply regex can't parse HTML correctly, but is it good enough for job? I assume so, but I have more confidence in the HTML parser.)</p>\n\n<pre><code>columns = re.compile('<td.*?>(.*?)</td>', re.DOTALL | re.M).findall(table)\n</code></pre>\n\n<p>An equivalent would be</p>\n\n<pre><code>columns = table.findall('td')\n</code></pre>\n\n<p>Again, HTML parser wins hands down.</p>\n\n<pre><code> 'home_team' : columns[index + 2], \n</code></pre>\n\n<p>VS:</p>\n\n<pre><code> 'home_team': rows[0][2].getText(),\n</code></pre>\n\n<p>The difference between <code>rows[0][2]</code> and <code>columns[index + 2]</code> is the fact that I choose to structure the parser after the rows, whereas <code>cat_baxter</code> decided to throw away the rows and look just at the columns. Either approach can be done either way, so that's incidental to this question. But here the HTML parser method is slightly more complicated because it has to use <code>.getText()</code></p>\n\n<pre><code> 'venue' : re.match(\"<b>Venue</b>: ([\\s,\\w\\']+)\", columns[index + 7]).group(1), \n\nm = re.match('.+Result</b>:([\\w, ]+)', columns[index + 7]) \nif m: \n row['result'] = m.group(1)\n</code></pre>\n\n<p>Vs</p>\n\n<pre><code> for line in rows[1][1].findAll('b'):\n content = str(line.nextSibling)[1:]\n if line.getText() == 'Venue':\n data['venue'] = content\n else:\n data['result'] = content\n</code></pre>\n\n<p>I think this one is hard to call. I think my lines of code have less going on in them, but I think it might be somewhat more obvious what is happening in the regular expression. </p>\n\n<p>My ending conclusion is that HTML parsers for scraping is often much nicer then using a regex, and sometimes a little worse. On the balance, I think its a way better idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:02:19.963",
"Id": "13640",
"ParentId": "13593",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "13640",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:43:12.747",
"Id": "13593",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Beautifulsoup scraper for sport events"
}
|
13593
|
<p>I'm quite new to JavaScript and wrote this clone method to be able to clone any kind of object. It works quite well for the cases I've tested until now, but for JSON objects it seemed kind of slow to me. I'm sure there is some additional speed to to squeeze out and a lot of overall improvement to make. But I don't know enough about JavaScript to optimize this.</p>
<pre><code>Object.prototype.clone = function(deep, falseArray/*check*/) {
var type = Object.prototype.toString.call(this).match(/^\[object (.+?)\]$/)[1];
/*var falseArray;
if(check) {
falseArray = (Object.keys(this).length - this.length);
}*/ //takes around 400ms additional at 500k array to check if it has additional properties, just pass it as argument decide if oy
switch (type) {
case "Array" :
var clone = [];
if (!falseArray) {
if (!deep)
clone = this.concat();
else
this.forEach(function(e) {
if(typeof e !== "undefined" && e !== null)
clone.push((typeof e !== "object"?e:e.clone((typeof deep == "boolean"?deep:(deep-1)))));
else
clone.push("");
});
} else {// Variable is an 'Array' but has an extra propertie e.g: var arr = [1,2,3]; arr.a = "b" //its the slowest possibility but normally Objects would be used
for (var prop in this ) {
clone[prop] = this[prop];
}
}
break;
case "Object":
var clone = {};
if (!deep) {
for (var prop in this) {
clone[prop] = this[prop];
}
} else {
for (var prop in this) {
if(typeof this[prop] !== "undefined" && this[prop]!== null)
clone[prop] = (typeof this [prop] !== "object"?this[prop]:this[prop].clone((typeof deep == "boolean"?deep:(deep-1))));
else
clone[prop] = "";
}
}
break;
default : var clone = this.valueOf();
break;
}
return clone;
};
Object.defineProperty(Object.prototype, "clone", {
enumerable : false
});
</code></pre>
<p>And here are some links:</p>
<p><a href="http://jsbin.com/abotoh/3/edit#javascript,html" rel="nofollow">JS Bin example</a><br>
<a href="http://jsperf.com/deepclone-test/4" rel="nofollow">jsPerf</a></p>
<p>I've changed it a little bit to have it in <code>Array.Prototype</code> and <code>Object.prototype</code>
to avoid the switch for the <code>Object</code> type, but I can't tell if it makes a difference.</p>
<pre><code>Object.prototype.clone = function(deep, falseAray) {
var type = Object.prototype.toString.call(this).match(/^\[object (.+?)\]$/)[1];
var test = this;
if (!type == "Object") {
return this.valueOf;
}
/*var falseArray;
if(check) {
falseArray = (Object.keys(this).length - this.length);
}*/ //takes around 400ms additional at 500k array to check if it has additional properties, just pass it as argument
var clone = {};
if (!deep) {
for (var prop in this) {
clone[prop] = this[prop]
}
} else {
for (var prop in this) {
if ( typeof this[prop] !== "undefined" && this[prop] !== null)
clone[prop] = ( typeof this[prop] !== "object" ? this[prop] : this[prop].clone(( typeof deep == "boolean" ? deep : (deep - 1))));
else
clone[prop] = "";
}
}
return clone;
};
Object.defineProperty(Object.prototype, "clone", {
enumerable : false
});
Array.prototype.clone = function(deep, falseArray) {
var test = this;
/*var falseArray;
if(check) {
falseArray = (Object.keys(this).length - this.length);
}*/ //takes around 400ms additional at 500k array to check if it has additional properties, just pass it as argument
var clone = [];
if (!falseArray) {//For me around 15-20ms at [500k]
if (!deep)
clone = this.concat();
else
this.forEach(function(e) {
if ( typeof e !== "undefined" && e !== null)
clone.push(( typeof e !== "object" ? e : e.clone(( typeof deep == "boolean" ? deep : (deep - 1)))));
else
clone.push("");
});
} else {// Variable is an 'Array' but has an extra propertie e.g: var arr = [1,2,3]; arr.a = "b" //its the slowest possibility but normally Objects would be used
for (var prop in this ) {//around 630 - 700ms
clone[prop] = this[prop];
}
}
return clone;
};
Object.defineProperty(Array.prototype, "clone", {
enumerable : false
});
</code></pre>
<p><a href="http://jsperf.com/deepclone-test/5" rel="nofollow">JS Bin example</a><br>
<a href="http://jsperf.com/deepclone-test/5" rel="nofollow">jsPerf</a></p>
<p>I tested it in Titanium where some code creates tables from JSON Objects (1000 rows with 29 properties per row (which contain array objects and primitive and null Values). The clone method copies the JSON object.</p>
<p>The first needed:</p>
<blockquote>
<p>1: 400ms , 2: 361ms , 3: 314ms , 4: 317ms , 5: 318ms </p>
</blockquote>
<p>The second needed:</p>
<blockquote>
<p>1: 294ms , 2: 329ms , 3: 298ms , 4: 298ms , 5: 299ms</p>
</blockquote>
<p>(Complete execution time, not only the copying)</p>
<p>I tried to change this:</p>
<pre><code>(typeof deep == "boolean" ? deep : (deep - 1))
</code></pre>
<p>to</p>
<pre><code>(deep - 1)
</code></pre>
<p>and call the method with <code>x.clone(Infinity)</code>instead of <code>x.clone(true)</code> to save one if clause per level of depth, but it turned out the execution speed varies from 300 to 370ms. Why is subtracting from infinity that slow/unstable compared to a type check through + a <code>if</code> clause? (its type is a number, so I thought it might do simply nothing if subtracting/adding etc sth to infinity).</p>
<p>It seems this is a problem for Titanium, benchmarks on Jsperf are around the same for both. I also tested both Codes with an 2k array where each entry contains arrays to a depth of 500. But the speed of both is the same. Is the cause this the branch prediction? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T22:47:36.970",
"Id": "22040",
"Score": "0",
"body": "Why are you extending `Object.prototype`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T23:38:41.343",
"Id": "22042",
"Score": "0",
"body": "to be able to invoke the method to clone directly from any Object like `var y = x.clone()`"
}
] |
[
{
"body": "<p>One thing I noticed was that you are using advanced (ECMAScript 5) parts of JavaScript - this will not work in old browsers, such as IE8 (I don't know where you are planning on using this).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T17:53:09.253",
"Id": "22214",
"Score": "0",
"body": "I would mainly use it in titanium (if not only)\ntherefore i don't have to worry about browser compatibility\nbut it would be nice to get some more speed out of it, when processing big json Objects (and of course i would be happy to learn javascript a little better )"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T05:09:40.790",
"Id": "13673",
"ParentId": "13594",
"Score": "2"
}
},
{
"body": "<p>When you say \"big JSON objects\", do you mean a string containing JSON?</p>\n\n<p>If I were you, I'd compare your method with serializing to a JSON string and deserializing from that string (that's cloning, too). As it is probably implemented in native code and directly supported by the VM, it should be really fast. I expect it to beat anything you can write - and it's way more compact, too. But I didn't test it, YMMV. Just consider and benchmark it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T14:34:53.773",
"Id": "24124",
"Score": "0",
"body": "i tried it right at the beginning when i wrote this ,and serializing/deserializing was way slower for me ( chrome )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T07:16:19.303",
"Id": "26173",
"Score": "0",
"body": "Did you use the native JSON object or did you import a JS-version?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-09T09:53:46.007",
"Id": "26573",
"Score": "0",
"body": "http://jsperf.com/deep-clone-test/3\nfor me its 0.58 (clone method) vs 0.26 Ops/sec (serializing/deserializing) with JSON.parse/stringify"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T07:43:20.177",
"Id": "26662",
"Score": "0",
"body": "Ok, it was worth a shot. Sorry :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T15:54:07.350",
"Id": "26697",
"Score": "0",
"body": "that sure is right, \nThx anyway for the suggestion:)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-20T10:59:24.267",
"Id": "14848",
"ParentId": "13594",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T17:44:58.673",
"Id": "13594",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"performance",
"titanium"
],
"Title": "Deep clone method"
}
|
13594
|
<p>I have multiple drop down lists (select & option) that are populated by data from the server. They all have the same options, but I need the use to be able to select every option only once - it can appear as selected only on one list.</p>
<p>This is the HTML of a single list - simple select & options list:</p>
<pre><code><div class="social-option">
<select name="hex_theme_options[social-service-1]">
<option selected="selected" value="0"></option>
<option value="facebook">facebook</option>
<option value="twitter">twitter</option>
<option value="linkedin">linkedin</option>
<option value="e-mail">e-mail</option>
<option value="phone">phone</option>
<option value="instagram">instagram</option>
<option value="flickr">flickr</option>
<option value="dribbble">dribbble</option>
<option value="skype">skype</option>
<option value="picasa">picasa</option>
<option value="google-plus">google-plus</option>
<option value="forrst">forrst</option>
</select>
</div>
</code></pre>
<p>And this is the JS code for managing them the way I described. It works, but it looks pretty ugly to me, and I'd like to improve it's structure. Any suggestions are welcome.</p>
<p><a href="http://jsfiddle.net/ilyaD/4BBcZ/7/" rel="nofollow">jsFiddle</a></p>
<pre><code>(function($){
$(document).ready(function() {
var siblings = {
lock: function (newSelected){
var selectedSiblings = $('.social-option select').find("option[value=" + newSelected.val() + "]");
selectedSiblings.not(newSelected).attr('disabled', 'disabled');
},
unlock: function (oldSelected){
var selectedSiblings = $('.social-option select').find("option[value=" + oldSelected.val() + "]");
selectedSiblings.removeAttr('disabled');
},
unlockZero: function (){
$('.social-option select').find("option[value='0']").removeAttr('disabled');
}
};
function checkSiblings(oldSelected, newSelected) {
if (oldSelected === '0') {
siblings.lock(newSelected);
} else if (newSelected === '0') {
siblings.unlock(oldSelected);
} else {
siblings.unlock(oldSelected);
siblings.lock(newSelected);
}
}
$('.social-option select').each(function() {
siblings.lock($('option:selected', this));
siblings.unlockZero();
});
$('.social-option select').on('focus', function () {
var oldSelected = $('option:selected', this);
$('.social-option select').on('change', function () {
var newSelected = $('option:selected', this);
checkSiblings(oldSelected, newSelected);
});
});
});
})(jQuery);
</code></pre>
|
[] |
[
{
"body": "<p>I could be wrong, but I think you could shorten ALOT of the code as follows:</p>\n\n<pre><code>$(function () {\n $(\".social-option select\").on(\"change\", function(e) {\n $(\".social-option select option:disabled\").prop(\"disabled\", false);\n $(\".social-option select option:selected\").each(function(i) {\n var $val = $(this).val();\n if ($val !== '0') {\n $(\".social-option select option[value=\"+$val+\"]\").prop(\"disabled\", true);\n };\n });\n }).change();\n});\n</code></pre>\n\n<p>See fiddle with dynamic drop down <a href=\"http://jsfiddle.net/SpYk3/2vaUW/\" rel=\"nofollow\"><h2>added here</h2></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:48:36.803",
"Id": "22038",
"Score": "0",
"body": "Sorry, I deleted the comment as soon as I realized I was wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T04:16:11.397",
"Id": "22045",
"Score": "0",
"body": "@BillBarry LoL, it's ok, i deleted mine too!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T08:43:04.100",
"Id": "22053",
"Score": "0",
"body": "@SpYk3HH tahnx, why did you use `$val.length > 1` and not simply `$val !== '0'`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T18:12:44.320",
"Id": "22111",
"Score": "0",
"body": "eh, coulda gone either way. a string compare maybe less intensive by a nanosecond or two, but its all up to the end coder."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:14:21.510",
"Id": "13605",
"ParentId": "13602",
"Score": "1"
}
},
{
"body": "<p>This might be a little more generic:</p>\n\n<pre><code>(function($) {\n var checkSiblings = function(group, oldSelected, newSelected) {\n group.find(\"option[value=\" + oldSelected.val() + \"]\").removeAttr('disabled');\n group.find(\"option[value=\" + newSelected.val() + \"]\").not(newSelected).attr('disabled', 'disabled');\n };\n $.fn.distinctValues = function() {\n var group = this;\n this.each(function(idx, selectBox) {\n $(selectBox).on('change', function() {\n var $this = $(this);\n var newSelected = $('option:selected', this);\n checkSiblings(group, $this.data('oldSelected'), newSelected);\n $this.data('oldSelected', newSelected);\n }).data('oldSelected', $('option:selected', this));\n });\n };\n}(jQuery));\n\n\njQuery('.social-option select').distinctValues();\n</code></pre>\n\n<p>It doesn't handle something it looks like you were trying to do but had only partially implemented, namely allow multiple different select boxes to share the empty option. I'm sure it can be done fairly simply, but my first attempt didn't work, and I'm out of time at the moment. (In other words, that's left as an exercise for the reader :-) ) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T02:01:51.633",
"Id": "13613",
"ParentId": "13602",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13605",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:01:45.533",
"Id": "13602",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Social network list management"
}
|
13602
|
<p>Can this be improved?</p>
<pre><code>static int find(string term, string text)
{
int found = -1;
int termIndex = 0;
for (int textIndex = 0; textIndex < text.Length; textIndex++)
{
if (term[termIndex] == text[textIndex])
{
if (termIndex == term.Length-1)
return found;
if (termIndex == 0)
found = textIndex;
termIndex++;
}else
{
termIndex = 0;
found = -1;
}
}
return found;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:28:21.957",
"Id": "22028",
"Score": "3",
"body": "I don't code in C#, but is there a reason you can't use `text.indexOf(term)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:32:35.553",
"Id": "22031",
"Score": "0",
"body": "I believe this is know as the naive string searching algorithm and yes it can be improved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:39:49.083",
"Id": "22033",
"Score": "0",
"body": "@ChaosPandion: Why is this considered naive, and i'd really appreciate suggestions for improvement.\n@jackwanders: I kinda want to write the algorithm that functions like `indexOf()` would use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:42:05.107",
"Id": "22035",
"Score": "1",
"body": "@W.K.S - It is called naive because that's what it is. :) I do remember the Knuth–Morris–Pratt algorithm but not the details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:47:24.433",
"Id": "22037",
"Score": "2",
"body": "Check out [Boyer-Moore](http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) or [Knuth-Morris-Pratt](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). You can find a C# implementation [here](http://www.codeproject.com/Articles/12781/Boyer-Moore-and-related-exact-string-matching-algo)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:50:54.663",
"Id": "22039",
"Score": "0",
"body": "Oh to be more clear it is called naive because it doesn't consider partial matches on the search term. This means more comparisons are necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T18:48:01.227",
"Id": "39290",
"Score": "0",
"body": "I do know the Knuth-Morris-Prat algorithm but I just wanted to write a quick search function."
}
] |
[
{
"body": "<p>I also don't code in C#, but if I'm right the following is the same in Java:</p>\n\n<pre><code>public static int find(final String term, final String text) {\n int found = -1;\n int termIndex = 0;\n\n for (int textIndex = 0; textIndex < text.length(); textIndex++) {\n if (term.charAt(termIndex) == text.charAt(textIndex)) {\n if (termIndex == term.length() - 1) {\n return found;\n }\n if (termIndex == 0) {\n found = textIndex;\n }\n termIndex++;\n } else {\n termIndex = 0;\n found = -1;\n }\n }\n return found;\n}\n</code></pre>\n\n<p>Unfortunately, it does not seem to work. Here are some test cases:</p>\n\n<pre><code>assertEquals(\"#0\", 3, find(\"de\", \"abcde\")); // OK\nassertEquals(\"#1\", 1, find(\"a\", \"ababaa\")); // fails, returns -1\nassertEquals(\"#2\", 1, find(\"ba\", \"ababaa\")); // OK\nassertEquals(\"#3\", 2, find(\"abaa\", \"ababaa\")); // fails, returns -1\nassertEquals(\"#4\", 2, find(\"abaa\", \"ababaacc\")); // fails, returns -1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T07:59:49.410",
"Id": "22049",
"Score": "1",
"body": "+1 That's right, it won't work if search term is at the beginning of the text (`found` is initialized after the `return`), or if the text contains a prefix of the term which overlaps the actual solution (because OP's code will skip the entire prefix each time)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T04:03:15.793",
"Id": "13614",
"ParentId": "13606",
"Score": "5"
}
},
{
"body": "<p>I do code in C#. I see two problems, one of which was already pointed out:</p>\n\n<pre><code>static int find(string term, string text)\n{\n int found = -1;\n int termIndex = 0;\n\n //quick check to protect the user from themselves\n if(String.IsNullOrEmpty(term) || string.IsNullOrEmpty(text))\n return -1;\n\n for (int textIndex = 0; textIndex < text.Length; textIndex++)\n {\n if (term[termIndex] == text[textIndex])\n {\n //assign the index first, then return it\n if (termIndex == 0)\n found = textIndex;\n //because we assign found to a *possible* match,\n //we must be sure that we have a real match before returning\n //so this is the ONLY place where we should return \"found\".\n termIndex++; \n if (termIndex >= term.Length)\n return found; \n }\n else\n {\n termIndex = 0;\n //If a match fails, revert to the start of the attempted match.\n //the for loop will increment it to the next character\n if(found >= 0)\n textIndex = found;\n found = -1;\n }\n }\n //if we get here, the substring was not found in its entirety,\n //regardless of the value of \"found\".\n return -1;\n}\n</code></pre>\n\n<p>The first major fix in the <code>if</code> block makes sure that <code>found</code> has the proper index in the case of a one-character match; If the first character matches the single-character substring, we'd immediately return -1 because <code>found</code> was never initialized. However, if we do this, then we run the risk of finding a possible match at the end of the string, running out of characters, and incorrectly returning the index of the partial match. For example, <code>find(\"aaa\", \"aabaa\")</code> would return index 3 when <code>term</code> doesn't actually exist, because it looked like a match until we ran out of characters. So, we must change the default return value to -1, and must only return the index of a possible match once we confirm that it really is a match, because if we run out of characters in <code>text</code> before we successfully reach the end of <code>term</code>, then <code>term</code> doesn't exist in <code>text</code>.</p>\n\n<p>The second fix in the <code>else</code> block makes sure that multi-character substrings aren't overlooked in cases where one substring seems to match but then doesn't, but the substring starting on the very next character of <code>text</code> would match. For instance, <code>find(\"aabaa\", \"aaabaa\")</code> would fail with your initial implementation, because after the algorithm found the first two 'a's, it would search for 'b' and not find it, discard that match, but then continue at index 3, when the substring starting at index 1 would have matched. Now, this does change the index of the counter variable in the for loop, which some might say is a no-no, but I see no problem with it; it's exactly the behavior that the algorithm should exhibit.</p>\n\n<p>Finally, up at the very top, if <code>term</code> or <code>text</code> had been null, the function would have thrown a NullReferenceException. If <code>term</code> had been empty, same thing. <code>text</code> being empty would have worked (<code>text.Length</code> would be zero and so we'd never enter the loop), but it's easy with String.INOE() to check both at once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:02:14.197",
"Id": "13633",
"ParentId": "13606",
"Score": "5"
}
},
{
"body": "<p>As already pointed out you need to backtrack when match fails<br>\nYou don't need to preemptively save the found position<br>\nI think this is much simpler approach </p>\n\n<pre><code>public static int? StringInString2(string stringToSearch, string stringToFind)\n{\n int M = stringToFind.Count();\n int N = stringToSearch.Count();\n\n /* A loop to slide pat[] one by one */\n for (int i = 0; i <= N - M; i++)\n {\n int j;\n\n /* For current index i, check for pattern match */\n for (j = 0; j < M; j++)\n if (stringToSearch[i + j] != stringToFind[j])\n break;\n\n if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]\n return i;\n }\n return null;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T19:23:29.430",
"Id": "155785",
"ParentId": "13606",
"Score": "1"
}
},
{
"body": "<p>Besides fixing the bug, you can make the following improvements...</p>\n\n<ul>\n<li>I find it's more natural if the <code>text</code> is the first parameter and <code>term</code> the second one for a simple reason, you could make it an extension so then the <code>text</code> would go first.</li>\n<li>You don't need any of the helper variables, you can put them all inside the <code>for</code> declaration.</li>\n<li>Use a constant for the <code>-1</code>.</li>\n<li>Few years later and you can use local functions (C# 7) so you can put them inside the loop to encapsulate the logic and make it much easier to understand.</li>\n<li>Additionaly you could add an option for case sensitivity.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>public static int find7(this string text, string term)\n{\n const int indexOutOfRange = -1;\n\n for (int i = 0, j = 0, index = indexOutOfRange; i < text.Length; i++)\n {\n if (IsMatch())\n {\n if (IsFirstMatch()) index = i;\n if (IsSuccess()) return index;\n j++;\n }\n else\n {\n Backtrack();\n Reset();\n }\n\n bool IsMatch() => text[i] == term[j];\n bool IsSuccess() => j == term.Length - 1;\n bool IsFirstMatch() => j == 0;\n void Backtrack()\n {\n if (IsPartialMatch()) RestartAfterFirstMatch();\n\n bool IsPartialMatch() => index > indexOutOfRange;\n void RestartAfterFirstMatch() => i = index;\n }\n void Reset()\n {\n j = 0;\n index = indexOutOfRange;\n }\n }\n\n return indexOutOfRange;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>\"foo bar baz\".find7(\"u\"); // -1\n\"foo bar baz\".find7(\"b\"); // 4\n\"foo bar baz\".find7(\"bar\"); // 4\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T21:06:14.633",
"Id": "294899",
"Score": "1",
"body": "Are you sure this backtracks? Please try \"aabaa\", \"aaabaa\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T21:07:33.203",
"Id": "294900",
"Score": "1",
"body": "@Paparazzi, admittedly, I didn't think of that, I'll need to take a look. thx."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T21:25:22.933",
"Id": "294901",
"Score": "1",
"body": "@Paparazzi I think I got it right this time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T21:27:05.413",
"Id": "294902",
"Score": "1",
"body": "I like the way my code goes about it better"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T21:35:34.870",
"Id": "294903",
"Score": "1",
"body": "@Paparazzi maybe, but unfortunatelly it's quite hard to read and understand (so are the other solutions) and I couldn't understand it without actually debugging it (reading the lengthy comments), that's why I love the new local functions, they make it super easy to write comprehensible code. Anyway, thx for your comment, it was a nice exercise ;-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-19T20:07:31.377",
"Id": "155788",
"ParentId": "13606",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13633",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T20:17:41.117",
"Id": "13606",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"strings"
],
"Title": "Algorithm to find substring in a string"
}
|
13606
|
<p>I'm new to LINQ, but I have some background in T-SQL. I know there are probably 100 different ways to design a T-SQL statement that would run this much more efficiently, but I'm not sure how I would do it in LINQ and I would like to stick with LINQ. </p>
<p>This works perfectly well, I just hate the way it looks and am unsure of how to fix it. </p>
<p>I am using MVC3, C#, LINQ, Entity Framework 4.3</p>
<pre><code>public class CollectionRepository : ICollectionRepository {
private CollectionEntities db = new CollectionEntities();
public IEnumerable<Collection> GetCollectionByUid(long id) {
var _collection = (from c in db.UserCollections
where c.uid == id
orderby c.CreateDate descending
select new Collection {
Name = c.CollectionName,
Type = (from t in db.CollectionTypes
where t.ctypeid == c.Type
select t.CollectionTypeName).FirstOrDefault(),
Created = c.CreateDate,
Count = (from f in db.Figures
where f.CollectionID == c.cid
select f).Count()
}).ToList();
return _collection;
}
}
</code></pre>
<p>The constructors it points to:</p>
<pre><code>public class Collection {
public string Name { get; set; }
public string Type { get; set; }
public DateTime Created { get; set; }
public int Count { get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>As this is EF code, assuming you have all the associations set up correctly, you should be able to write it something like this:</p>\n\n<pre><code>public IEnumerable<Collection> GetCollectionByUid(long uid) {\n var result =\n (from collection in db.UserCollections\n where collection.uid == uid\n orderby collection.CreateDate descending\n select new Collection {\n Name = collection.CollectionName,\n Type = collection.CollectionType.CollectionTypeName,\n Created = collection.CreateDate,\n Count = collection.Figures.Count(),\n }).ToList();\n return result;\n}\n</code></pre>\n\n<p>My only real criticism is the variable names.</p>\n\n<p>Local variables or parameters should not be prefixed with an underscore. IMHO, it should only be allowed for private instance fields. So rather than using <code>_collection</code>, it would be better off as <code>collection</code> (though I used <code>result</code> for the name here instead).</p>\n\n<p>Parameter names are very much part of the documentation as well (especially so in C# and .NET in general). The method is called <code>GetCollectionByUid</code> which suggests you provide a <code>uid</code>. The parameter name should reflect that. Call it <code>uid</code> since that's what it is.</p>\n\n<p>Personal preference but I also prefer to write out the full/reasonable-length variable names in queries. I reserve significantly shortened variable names (i.e., one character variable names) in lambda expressions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T01:31:52.887",
"Id": "22043",
"Score": "0",
"body": "Great! Thanks. I was wondering how I could better use those associations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T07:51:06.530",
"Id": "22048",
"Score": "0",
"body": "+1 But I would also ditch the \"Collection\" prefix out of every property which belongs to a `Collection` class. `Collection.Name` and `Collection.Type` should be enough. On the other hand, the class itself should probably be renamed to `FigureCollection` (if that's what it's used for) or something similar which would explain what data it contains."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T13:34:06.157",
"Id": "22066",
"Score": "0",
"body": "@Groo: You know, I didn't even notice the names of those properties on the entities. I definitely agree with that. Though it'd be moot if they can't be renamed in the DB. Even though the names of the entities and their properties doesn't necessarily have to match that of in the DB, they should always match IMHO."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T00:56:39.017",
"Id": "13612",
"ParentId": "13611",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "13612",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T00:29:21.983",
"Id": "13611",
"Score": "5",
"Tags": [
"c#",
"linq",
"asp.net-mvc-3"
],
"Title": "This LINQ Model Query seems extremely inefficient"
}
|
13611
|
<p>I have written a templated singleton class in C++ but I am afraid that it is not properly destroyed. Can you advise me on that ? </p>
<p>my singleton.h</p>
<pre><code>#ifndef SINGLETON_H
#define SINGLETON_H
template <typename T>
class Singleton
{
public:
static T& Instance();
protected:
virtual ~Singleton();
inline explicit Singleton();
private:
static T* _instance;
static T* CreateInstance();
};
template<typename T>
T* Singleton<T>::_instance = 0;
#endif // SINGLETON_H
</code></pre>
<p>singleton.cpp</p>
<pre><code>#include "singleton.h"
#include <cstdlib>
template <typename T>
Singleton<T>::Singleton()
{
assert(Singleton::_instance == 0);
Singleton::_instance = static_cast<T*>(this);
}
template<typename T>
T& Singleton<T>::Instance()
{
if (Singleton::_instance == 0)
{
Singleton::_instance = CreateInstance();
}
return *(Singleton::_instance);
}
template<typename T>
inline T* Singleton<T>::CreateInstance()
{
return new T();
}
template<typename T>
Singleton<T>::~Singleton()
{
if(Singleton::_instance != 0)
{
delete Singleton::_instance;
}
Singleton::_instance = 0;
}
</code></pre>
<p>and that's how I call it (with normal - not templated or anything - class <code>Game</code> )
<code>Singleton<Game>::Instance().run();</code></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T13:07:42.703",
"Id": "22064",
"Score": "0",
"body": "Why are you using pointers? Don’t, then the problems go away. But this code has other problems anyway, such as its non-thread-safe initialisation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T14:40:52.667",
"Id": "22069",
"Score": "0",
"body": "Look here: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289"
}
] |
[
{
"body": "<p>A classic singleton looks like this (in C++):</p>\n\n<pre><code>class S\n{\n public:\n static S& getInstance()\n {\n static S instance; // Guaranteed to be destroyed.\n // Instantiated on first use.\n return instance;\n }\n private:\n S();\n // Dont forget to declare these two. You want to make sure they\n // are unaccessable otherwise you may accidently get copies of\n // your singleton appearing.\n S(S const&); // Don't Implement\n void operator=(S const&); // Don't implement\n};\n</code></pre>\n\n<p>It is simple enough that template-ing it is redundant.<br>\nAlso making it a template start to have other issues that require you to have a very good linker. SO it is worth just doing it explicitly for each object you want to make a singleton.</p>\n\n<p>It is worth noting that it is probably a mistake to use a singleton. The use cases were they actually work well are very limited. Best to create the object in main and pass it as a parameter to everything that needs it.</p>\n\n<p>This <a href=\"https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289\">article</a> covers a lot of info.</p>\n\n<p>Looking at your code the thing that sticks out is:</p>\n\n<pre><code>template<typename T>\nSingleton<T>::~Singleton()\n{\n if(Singleton::_instance != 0)\n {\n delete Singleton::_instance;\n }\n Singleton::_instance = 0;\n}\n</code></pre>\n\n<p>You are already in the destructor of the only object. Thus calling delete on _instance is calling delete on yourself (and that must already have been done otherwise you would not be in the destructor).</p>\n\n<p>As you have deduced the problem is that the object is not automatically destroyed. There are several ways of solving this in your code. The best would be to make <code>_instance</code> a std::auto_ptr (std::unique_ptr in C++11). This will mean as a static storage duration object that it will be destroyed at the end of the program (which will call the destructor for you).</p>\n\n<p>That aside C++ code where you have pointers strewn about the place is not real C++ code. You may be using the C++ syntax but you are writing C. There is a very different style attached to C++. You should barely ever see pointers. This is because there is no ownership semantics associated with pointers and one of the big things in C++ is expressing ownership of dynamic storage duration objects.</p>\n\n<p>About the only place you see pointers are in the implementation of containers and smart pointers. As a user you should be using smart pointers or containers (depending on situation) instead of pointers. Where you <code>passing be reference</code> using a pointer (aka C) you should use references (aka C++).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T14:42:56.253",
"Id": "13631",
"ParentId": "13615",
"Score": "3"
}
},
{
"body": "<p>You should not delete singleton object in destructor as it may possible another object is referring to it once first object scope ends.</p>\n\n<p>Add another static function to destruct the object. It need to call explicitly to destruct the object. Also, Add reference counting to decide whether Singleton object need to be deleted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T16:50:37.040",
"Id": "22419",
"Score": "0",
"body": "Manually doing your suggestions leads to possibility of leaking it. Write the code so that it is all done automatically by the compiler. We already have a reference counted smart pointer (`std::shared_ptr`) that will do all you suggest. Alternatively never give the user the opportunity by returning a reference and automatically destroy at the end of the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T06:03:14.443",
"Id": "22483",
"Score": "0",
"body": "@LokiAstari : Agree. shared_ptr will be alternate solution. But You can also add your own logic to destructing objects which will be done by shared_ptr. I don't agree that manually doing will possibility of leaking it if you do it carefully."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T22:37:18.810",
"Id": "22557",
"Score": "0",
"body": "You can't do it manually no matter how carefully you are because you have no way of imposing ownership semantics onto the situations. Secondly relying on sobody to do something is the **WRONG** way to write C++. You should be using RAII to make sure the correct thing is always done. Otherwise you are writing bad C++."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:50:03.183",
"Id": "13711",
"ParentId": "13615",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T06:55:28.490",
"Id": "13615",
"Score": "3",
"Tags": [
"c++",
"singleton",
"template"
],
"Title": "C++ templated singleton class - properly destroyed?"
}
|
13615
|
<p>I'm new in PHP, MySQL and OOP, so I tried to write a small project to learn things better. The Pponebook should contains contacts which can be edited, deleted, added, sorted and it has pagination, too. Search is also available. This is my first project in PHP and I am using OOP for the first time, so I am sure that my code is complete mess.</p>
<p><strong><code>Contact</code>:</strong></p>
<pre><code><?php
class Contact
{
private $name;
private $phone ;
private $address;
private $notes ;
private function isValid($var, $min_limit)
{
if(strlen(trim($var))>=$min_limit)
{
return true;
}
return false;
}
public function __construct($name, $phone, $address='', $notes='')
{
if($this->isValid($name, 3)&& $this->isValid($phone, 3))
{
$this->name = addslashes(trim($name));
$this->phone = addslashes(trim($phone));
$this->address = addslashes(trim($address));
$this->notes = addslashes(trim($notes));
}
else if (!$this->isValid($name, 3))
{
throw new Exception('The name is too short.');
}
else if (!$this->isValid($phone, 3))
{
throw new Exception('The phone number is too short.');
}
}
public function getName()
{
return $this->name;
}
public function getPhone()
{
return $this->phone;
}
public function getAddress()
{
return $this->address;
}
public function getNotes()
{
return $this->notes;
}
public static function printTable($sql)
{
$temp= DataBaseActions::run_q($sql);
while($row = mysql_fetch_assoc($temp))
{
$tmp='<tr class="content"><td>'.$row['name'].'</td><td>'.$row['phone'].'</td>
<td>'.$row['address'].'</td><td>'.$row['notes'].'</td>
<td class="try"><a href="index.php?mode=edit&id='.$row['contact_id'].'">Edit</a></td>
<td class="try"><a href="index.php?mode=delete&id='.$row['contact_id'].'">Delete</a></td></tr>';
echo $tmp;
}
}
}
</code></pre>
<p><strong><code>Database</code>:</strong></p>
<pre><code><?php
class DataBaseActions
{
private $db_name='phonebook';
private $db_username='Emanuela';
private $db_host='localhost';
public function connect()
{
mysql_connect($this->db_host, $this->db_username) or die('Error with the database.');
mysql_select_db($this->db_name) or die ('Error with the database.');
}
public static function run_q($sql)
{
mysql_query('SET NAMES utf8');
return mysql_query($sql);
}
public function insert($obj)
{
DataBaseActions::run_q('INSERT INTO contacts (name, address, phone, notes)
VALUES ("'.addslashes($obj->getName()).'", "'.addslashes($obj->getAddress()).'",
"'.addslashes($obj->getPhone()).'", "'.addslashes($obj->getNotes()).'")');
}
public function update($obj, $id)
{
DataBaseActions::run_q('UPDATE contacts SET name="'.$obj->getName().'",
address="'.$obj->getAddress().'", phone="'.$obj->getPhone().'",
notes="'.$obj->getNotes().'" WHERE contact_id='.$id);
}
public function delete($id)
{
DataBaseActions::run_q('DELETE FROM contacts WHERE contact_id='.$id);
}
public function sortTable($field, $mode)
{
$sql='SELECT * FROM contacts ORDER BY `'.$field.'`'.$mode;
return $sql;
}
public function search($field, $value)
{
$keywords = explode(' ',$value);
$query = 'SELECT * FROM contacts WHERE';
foreach ($keywords as $key)
{
$query .= ' `'.$field.'` LIKE "%'.$key.'%" AND';
}
$query = rtrim($query,' AND');
return $query;
}
}
</code></pre>
<p><strong><code>Pagination</code>:</strong></p>
<pre><code><?php
include 'DataBaseActions.php';
class Pagination
{
private $limit;
private static $all=0;
private $last_page;
private $page;
public function __construct($limit=5, $page=0)
{
$this->limit = $limit;
$this->page = $page;
$this->last_page = ceil(Pagination::$all/$this->limit);
}
public function setAll($sql)
{
$temp= DataBaseActions::run_q($sql);
Pagination::$all= mysql_num_rows($temp);
$this->last_page = ceil(Pagination::$all/$this->limit);
}
public function setPage($page)
{
$this->page = $page;
}
public function pageQuery($sql)
{
$newsql =$sql.' LIMIT '.$this->page*$this->limit.','.$this->limit;
return $newsql;
}
public function printPages()
{
if($this->page>0)
{
echo '<a href="index.php?page='.($this->page).'">Previous</a>';
}
echo ' | ';
for($i=0; $i<$this->last_page; $i++)
{
if($i==$this->page)
{
echo ($i+1);
}
else
{
echo '<a href="index.php?page='.($i+1).'">'.($i+1).' </a>';
}
echo ' | ';
}
if($this->page<($this->last_page-1))
{
echo '<a href="index.php?page='.($this->page+2).'"> Next</a><br>';
}
}
}
</code></pre>
<p>And the index file which is the worst of all. There are so many <code>if</code>s and the HTML and PHP code are so messy.</p>
<pre><code><?php
error_reporting(0);
include 'Contact.php';
include 'Pagination.php';
session_start();
$db=new DataBaseActions();
$db->connect();
if($_GET['mode']=='normal')
{
$flag=0;
$_SESSION['mode']='normal';
}
if($_GET['mode']=='delete')
{
$id = addslashes($_GET['id']);
$id = htmlspecialchars(stripslashes($id));
$id = mysql_escape_string($id);
$db->delete($id);
header('Location: index.php');
}
if ($_GET['mode'] == 'edit' && $_GET['id'] > 0)
{
$id = (int) $_GET['id'];
$rs = DataBaseActions::run_q('SELECT * FROM contacts WHERE contact_id=' . $id);
$info = mysql_fetch_assoc($rs);
}
if($_GET['mode']=='ASC')
{
$flag=1;
$field=$_GET['field'];
$mode='ASC';
$_SESSION['mode']='ASC';
$_SESSION['field']=$field;
}
if($_GET['mode']=='DESC')
{
$flag=1;
$field=$_GET['field'];
$mode='DESC';
$_SESSION['mode']='DESC';
$_SESSION['field']=$field;
}
if($_POST['name']==1)
{
$s_name=$_POST['search_name'];
$flag=2;
$_SESSION['mode']='sname';
}
if($_POST['phone']==1)
{
$s_phone=$_POST['search_phone'];
$flag=3;
$_SESSION['mode']='sphone';
}
if($_POST['address']==1)
{
$s_address=$_POST['search_address'];
$flag=4;
$_SESSION['mode']='saddress';
}
if($_POST['notes']==1)
{
$s_notes=$_POST['search_notes'];
$flag=5;
$_SESSION['mode']='snotes';
}
if($_POST['form_submit']==1)
{
$flag=0;
$name=$_POST['name'];
$phone=$_POST['phone'];
$address=$_POST['address'];
$notes=$_POST['notes'];
$_SESSION['mode']='normal';
try
{
$a=new Contact($name, $phone, $address, $notes);
$id=(int)$_POST['edit_value'];
$temp=DataBaseActions::run_q('SELECT * FROM contacts WHERE phone='.$a->getPhone().' AND contact_id!='.$id);
if(mysql_num_rows($temp)==0)
{
if($id>0)
{
$db->update($a, $id);
echo 'Successful update.';
}
else
{
$db->insert($a);
echo 'The contact was successfully added to the Phone Book!';
}
}
else
{
echo 'This phone number is already in the Phone Book.';
}
}
catch(Exception $exc)
{
echo $exc->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Phone Book</title>
</head>
<body>
<center>
<h3>Phone Book</h3><br />
<form method="post" action="index.php">
<table border="0">
<tr><td>Name:</td><td> <input type="text" name="name" value="<?php echo $info['name'];?>"/></td></tr>
<tr><td>Phone number:</td><td> <input type="text" name="phone" value="<?php echo $info['phone'];?>"/></td></tr>
<tr><td>Address:</td><td> <input type="text" name="address" value="<?php echo $info['address'];?>"/></td></tr>
<tr><td>Notes: </td><td><input type="textarea" name="notes" value="<?php echo $info['notes'];?>"/></td></tr>
</table>
<input type="hidden" name="form_submit" value="1" /><br />
<input type="submit" value="Submit" /><br /><br />
<?php
if($_GET['mode']=='edit')
{
echo '<input type="hidden" name="edit_value" value="'.$_GET['id'].'" /><br />';
}
?>
</form>
<table border="3" style="border-collapse:collapse; border-color: gray; padding: 2px;">
<tr class="header">
<td>Name</td>
<td>Phone number</td>
<td>Address</td>
<td>Notes</td>
<td></td>
<td></td>
</tr>
<?php
$p=new Pagination();
if((int)$_GET['page']>0)
{
$p->setPage((int)$_GET['page']-1);
}
if($_SESSION['mode']=='normal')
{
$flag=0;
}
if($_SESSION['mode']=='ASC' || $_SESSION['mode']=='DESC')
{
$flag=1;
$field=$_SESSION['field'];
$mode=$_SESSION['mode'];
}
if($_SESSION['mode']=='sname')
{
$flag=2;
}
if($_SESSION['mode']=='sphone')
{
$flag=3;
}
if($_SESSION['mode']=='saddress')
{
$flag=4;
}
if($_SESSION['mode']=='snotes')
{
$flag=5;
}
switch($flag)
{
case 0:
$sql='SELECT * FROM contacts';
$p->setAll($sql);
Contact::printTable($p->pageQuery($sql));
break;
case 1:
echo'<a href="index.php?mode=normal"> Go back to unsorted table<br></a>';
$p->setAll($db->sortTable($field, $mode));
Contact::printTable($p->pageQuery($db->sortTable($field, $mode)));
break;
case 2:
echo'<a href="index.php?mode=normal">Go back to all contacts<br></a>';
$p->setAll($db->search('name', $s_name));
Contact::printTable($p->pageQuery($db->search('name', $s_name)));
break;
case 3:
echo'<a href="index.php?mode=normal">Go back to all contacts<br></a>';
$p->setAll($db->search('phone', $s_phone));
Contact::printTable($p->pageQuery($db->search('phone', $s_phone)));
break;
case 4:
echo'<a href="index.php?mode=normal">Go back to all contacts<br></a>';
$p->setAll($db->search('address', $s_address));
Contact::printTable($p->pageQuery($db->search('address', $s_address)));
break;
case 5:
echo'<a href="index.php?mode=normal">Go back to all contacts<br></a>';
$p->setAll($db->search('notes', $s_notes));
Contact::printTable($p->pageQuery($db->search('notes', $s_notes)));
break;
}
?>
<tr class="content">
<td><form method="post" action="index.php"><input type="text" name="search_name">
<input type="submit" value=">"><input type="hidden" name="name" value="1"></form></td>
<td><form method="post" action="index.php"><input type="text" name="search_phone">
<input type="submit" value=">"><input type="hidden" name="phone" value="1"></form></td>
<td><form method="post" action="index.php"><input type="text" name="search_address">
<input type="submit" value=">"><input type="hidden" name="address" value="1"></form></td>
<td><form method="post" action="index.php"><input type="text" name="search_notes">
<input type="submit" value=">"><input type="hidden" name="notes" value="1"></form></td>
<td></td>
<td></td>
</tr>
<tr class="content">
<td><a href="index.php?mode=ASC&field=name">Sort ASC</a></td>
<td><a href="index.php?mode=ASC&field=phone">Sort ASC</a></td>
<td><a href="index.php?mode=ASC&field=address">Sort ASC</a></td>
<td><a href="index.php?mode=ASC&field=notes">Sort ASC</a></td>
<td></td>
<td></td>
</tr>
<tr class="content">
<td><a href="index.php?mode=DESC&field=name">Sort DESC</a></td>
<td><a href="index.php?mode=DESC&field=phone">Sort DESC</a></td>
<td><a href="index.php?mode=DESC&field=address">Sort DESC</a></td>
<td><a href="index.php?mode=DESC&field=notes">Sort DESC</a></td>
<td></td>
<td></td>
</tr>
</table>
<br>
<?php
$p->printPages();
?>
</div>
</center>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T08:05:05.597",
"Id": "22050",
"Score": "0",
"body": "personally I don't like having HTML strings inside PHP script, I prefer to separate server by client. So client ajax calls a server php functions which echoes something like json_encode($row) that is a JSON representation of the $row array. Then on client side you get the datas and put them in your DOM as you like. This way if you want to change user interface you'll just have to edit the client script, also you can make any changes to the server script but as long as the output data format is the same it will still work fine."
}
] |
[
{
"body": "<p>Don't know if this is just poor question formatting, or your style, but please indent properly, this isn't really good:</p>\n\n<pre><code>class Contact\n{\nprivate $name;\nprivate $phone ;\nprivate $address;\nprivate $notes ;\n}\n</code></pre>\n\n<p>This would be better:</p>\n\n<pre><code>class Contact\n{\n private $name;\n private $phone ;\n private $address;\n private $notes ;\n}\n</code></pre>\n\n<p>I'd rewrite <code>Contact::__construct</code> as: </p>\n\n<pre><code>if (!$this->isValid($name, 3)) throw new Exception('The name is too short.'); \nif (!$this->isValid($phone, 3)) throw new Exception('The phone number is too short.');\n\n// at this point both checks have succeeded, no point in rechecking \n$this->name = addslashes(trim($name));\n$this->phone = addslashes(trim($phone));\n$this->address = addslashes(trim($address));\n$this->notes = addslashes(trim($notes)); \n</code></pre>\n\n<p>for brevity, readability and to not have redundant checks. <code>Contact::isValid</code> is not that expensive, still no point in calling it more times than necessary. </p>\n\n<p>I'd advice against having HTML in your classes, as you do in <code>Contact::printTable</code>. Simplest solution would be to create an array of your database results, return the array and construct the table when it's absolutely necessary - at the script you actually show it.</p>\n\n<p>Moving on to <code>DataBaseActions</code>, <code>mysql_query('SET NAMES utf8');</code> is called every time <code>DataBaseActions::run_q</code> is called, and that's absolutely unnecessary. Not really an expensive database call, still redundant, you can safely move it into <code>DataBaseActions::connect</code>, it's a call that only needs be done once, just after you connect.</p>\n\n<p>In general, avoid <code>mysql_*</code> functions, they are essentially obsolete, kept around only for legacy reasons. <a href=\"http://www.php.net/manual/en/intro.mysql.php\">Their use is discouraged in the manual</a>:</p>\n\n<blockquote>\n <p>This extension is not recommended for writing new code. Instead, either the mysqli or PDO_MySQL extension should be used. </p>\n</blockquote>\n\n<p><a href=\"http://www.php.net/manual/en/book.mysqli.php\">mysqli</a> is a drop in replacement, all you need to do is add that extra <strong>i</strong> to all your functions (yes, it's that easy ;), but I'd strongly advice exploring <a href=\"http://www.php.net/manual/en/book.pdo.php\">PDO</a>. You don't do any kind of validation on the stuff you throw at the database, your code is vulnerable to all sorts of trouble, the scariest one being <a href=\"http://php.net/manual/en/security.database.sql-injection.php\">SQL injection</a>, and the simplest solution would be to use <a href=\"http://www.php.net/manual/en/pdo.prepared-statements.php\">prepared statements</a>. For example, how can you be certain <code>$id</code> is an integer when you call <code>delete($id)</code>?</p>\n\n<p>In <code>Pagination</code> you also have some HTML, ideally you should move it out of the class, still given the class' nature, don't make it a top priority. As is, your class isn't reusable, if you want to have a different looking pagination somewhere you'd have to change the HTML in the class (and then your first pagination would look weird ;). Read up on <a href=\"http://en.wikipedia.org/wiki/Separation_of_presentation_and_content\">separation of presentation and content</a>.</p>\n\n<p>Architecturally, there's a bit of a mess with <code>DataBaseActions::run_q</code>, as it's declared static when it's <em>not really static</em>, as it depends on <code>DataBaseActions</code> having been instantiated (for the database connection to be established). That's more PHP's fault than your own, the way <code>mysql_*</code> utilizes the global namespace always made me chuckle a bit. Now, since it's not really static, there's no point in declaring it as such, just make it a normal public function and feed your <code>DataBaseActions</code> object where it's needed. Read up on <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\">dependency injection</a> and try to avoid static functions if they are not absolutely necessary. You could just pass the object as a parameter in <code>Contact::__construct</code> and <code>Pagination::_construct</code>, and replace <code>DataBaseActions::run_q</code> with <code>$this->databaseActions->run_q</code>.</p>\n\n<p>Your index file is indeed messy. Start by breaking it up into smaller files, <a href=\"http://php.net/manual/en/function.include.php\"><code>include</code></a> as appropriate. And... good luck ;) Overall, your code is good for a starter, you're in a good path. If you significantly alter your code, don't forget to post another question here, there's always room for improvement, that's just the nature of code reviews (but don't over-engineer, done is better than perfect ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T10:22:51.930",
"Id": "13619",
"ParentId": "13616",
"Score": "6"
}
},
{
"body": "<p>An important OOP principle is the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>: a class should have only one responsibility. Input validation and output (such as is handled by <code>Contact::printTable</code>) should be in separate classes. You can create a <a href=\"https://stackoverflow.com/a/8423720/\">table view</a> that will work with arbitrary data classes to handle output; the key is to use a combination of self-description on the part of data classes (a.k.a. models) and a limited amount of <a href=\"http://tw.php.net/manual/en/book.reflection.php\" rel=\"nofollow noreferrer\">reflection</a> (reflection generally isn't very efficient, so its use should be limited; you can use it for default implementations in parents to speed up development and override it in children for efficiency once you've got it working): data classes would include methods that return information (names, types &c.) about their fields. Read up on the other <a href=\"http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">SOLID principles</a>, the <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">MVC architecture pattern</a> and <a href=\"http://en.wikipedia.org/wiki/Multitier_architecture\" rel=\"nofollow noreferrer\">multi-tier architectures</a> for more (links follow at the end).</p>\n\n<p><code>DataBaseActions</code> is the beginning of the <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">data mapper</a> pattern. Run with it: separate out anything specific to contacts into a child class. That way, you can use <code>DataBaseActions</code> as the basis for other database access classes.</p>\n\n<p><code>Exception</code> is a little too generic to instantiate and throw; better to use an exception of a type that's specific to the exceptional situation. Often, you can use (possibly extending) one of the <a href=\"http://tw.php.net/manual/en/spl.exceptions.php\" rel=\"nofollow noreferrer\">SPL exceptions</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/q/534742/\"><code>addslashes</code></a> shouldn't be used to escape data destined for an SQL statement. If you use prepared statements, it's a moot point, but you otherwise should use the escape function provided by the database extension. You also shouldn't escape data before you're getting it ready to pass it on to another system, so don't use <code>addslashes</code> as you do in <code>Contact::__construct</code>, and the whole:</p>\n\n<pre><code>$id = addslashes($_GET['id']);\n$id = htmlspecialchars(stripslashes($id));\n$id = mysql_escape_string($id);\n</code></pre>\n\n<p>sequence in index.php is a combination of busy work (the <code>addslashes</code>/<code>stripslashes</code> calls) and inappropriate escaping (the call to <code>htmlspecialchars</code>). The SQL escaping should be left to the database access layer (DAL).</p>\n\n<p>The HTML uses some presentational markup (e.g. <code><center></code>), and uses some elements non-<a href=\"http://webstyleguide.com/wsg3/5-site-structure/2-semantic-markup.html\" rel=\"nofollow noreferrer\">semantically</a> (e.g. <a href=\"http://brainstormsandraves.com/articles/semantics/structure/#br\" rel=\"nofollow noreferrer\"><code><br>/</code></a> and the table used to format the form inputs). HTML is a document structuring language, not a formatting language. Use CSS for presentation. You can set the bottom margin of the <code><h3></code> element if you want extra space after it. Input label text should be placed in <a href=\"http://www.w3.org/wiki/HTML/Elements/label\" rel=\"nofollow noreferrer\"><code><label></code></a> elements (this is particularly important for screen readers and other aids to disabled users). You can then style labels and inputs to get the same presentation as you do with tables, or put the labels and inputs in some other semantically appropriate (such as a definition list) and style that.</p>\n\n<p><a href=\"http://www.w3.org/wiki/HTML/Elements/textarea\" rel=\"nofollow noreferrer\">Textareas</a> are separate elements, rather than being a type of <code><input></code>. The default value is specified by the content of the element, rather than as the value of its <code>value</code> attribute.</p>\n\n<p>To prevent HTML injection vulnerabilities (such as <a href=\"https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29\" rel=\"nofollow noreferrer\">cross-site scripting (XSS)</a>), data that shouldn't be allowed to contain HTML should be escaped using (e.g.) <a href=\"http://php.net/htmlspecialchars\" rel=\"nofollow noreferrer\"><code>htmlspecialchars</code></a>. The content of a <code><textarea></code> is one of the few exceptions, as it won't be interpreted as HTML.</p>\n\n<pre><code><style type=\"text/css\">\n label {\n float: left;\n min-width: 6em;\n margin-right: 0.5em;\n }\n input, textarea {\n display: block;\n }\n</style>\n\n<form method=\"post\" action=\"...\">\n <fieldset>\n <legend>Search</legend>\n <label for=\"name\">Name:</label>\n <input name=\"name\" id=\"name\" value=\"<?php echo htmlspecialchars($info['name']) ?>\"/>\n\n <label for=\"phone\">Phone number:</label>\n <input name=\"phone\" id=\"phone\" value=\"<?php echo htmlspecialchars($info['phone']) ?>\"/>\n\n <label for=\"address\">Address:</label>\n <input name=\"address\" id=\"address\" value=\"<?php echo htmlspecialchars($info['address']) ?>\"/>\n\n <label for=\"notes\">Notes:</label>\n <textarea name=\"notes\" id=\"notes\"><?php echo $info['notes']; ?></textarea>\n\n <input type=\"submit\" value=\"Submit\" />\n </fieldset>\n</form>\n</code></pre>\n\n<p>Instead of a canned form for contacts, you could create a form view that would work with arbitrary models.</p>\n\n<p>If a variable or array index might not be set, use <a href=\"http://php.net/isset\" rel=\"nofollow noreferrer\"><code>isset</code></a> to test it. That way your code will work when <a href=\"http://php.net/error_reporting\" rel=\"nofollow noreferrer\">error reporting</a> is set to include <a href=\"http://www.php.net/manual/en/errorfunc.constants.php\" rel=\"nofollow noreferrer\"><code>E_NOTICE</code></a> (which you should do on your development server to catch typos). You can also make use of <code>isset</code> to test for (e.g.) <code>$_POST['name']</code> and do away with the \"form_submit\" input.</p>\n\n<p>One big advantage to PDO (and mysqli in PHP 5.4 and greater) is they support the <a href=\"http://php.net/Traversable\" rel=\"nofollow noreferrer\"><code>Traversable</code></a> interface for database results, meaning you can loop over the results using <code>foreach</code> rather than relying on any method from the DB class API. This helps with decoupling database access and output.</p>\n\n<pre><code># DB access (in production code, would be part of various methods)\ntry {\n $contactQuery = $db->prepare('SELECT name, phone, address, notes FROM contacts WHERE ...');\n $contacts = $contactQuery->execute(array(...));\n /* without PDO::FETCH_PROPS_LATE, the constructor will overwrite the \n * property values fetched from the database. Note this shows a good\n * reason not to perform validation in Contact: though the constructor \n * arguments result in an invalid contact, it's immediately corrected\n * after the constructor call.\n */\n $contactQuery->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, \n 'Contact', array(NULL, NULL));\n $fields = array();\n for ($i=0; $i < $contactQuery->columnCount(); ++$i) {\n $columnInfo = $contactQuery->getColumnMeta($i);\n $fields[] = $columnInfo['name'];\n }\n} catch (PDOException $exc) {\n ...\n}\n\n$rows = $contacts;\n\n/* Output. Note the only requirements are that:\n * + $fields is an array\n * + the elements of $fields can be cast to strings\n * + $rows is traversable \n * + the elements of $rows are objects with properties named in $fields\n *\n * In particular, $rows could be an array, a PDOStatement, a mysqli_result\n * or something else entirely\n */\n?>\n<table>\n <thead><th><?php echo implode('</th><th>', array_map('ucfirst', $fields)) ?></th></thead>\n <tbody>\n <?php foreach ($rows as $i => $row) { ?>\n <tr>\n <?php foreach ($fields as $field) { ?>\n <td><?php echo $row->$field ?></td>\n <?php } ?>\n </tr>\n <?php } ?>\n </tbody>\n</table>\n</code></pre>\n\n<h3>Further Reading</h3>\n\n<ul>\n<li><a href=\"http://oreilly.com/php/archive/mvc-intro.html\" rel=\"nofollow noreferrer\">Understanding MVC in PHP</a></li>\n<li><a href=\"http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/\" rel=\"nofollow noreferrer\">Write your own PHP MVC Framework (Part 1)</a></li>\n<li><a href=\"http://www.phpro.org/tutorials/Model-View-Controller-MVC.html\" rel=\"nofollow noreferrer\">Model View Controller</a></li>\n<li><a href=\"http://www.webopedia.com/quick_ref/app.arch.asp\" rel=\"nofollow noreferrer\">N-Tier Application Architecture</a> (in brief)</li>\n<li><a href=\"http://giorgiosironi.blogspot.com/2009/08/10-orm-patterns-components-of-object.html\" rel=\"nofollow noreferrer\">10 orm patterns: components of a object-relational mapper</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:58:34.440",
"Id": "13627",
"ParentId": "13616",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "13619",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T06:57:51.833",
"Id": "13616",
"Score": "4",
"Tags": [
"php",
"beginner",
"object-oriented"
],
"Title": "Phonebook - a small PHP project"
}
|
13616
|
<p>I'm hoping that you kind people could cast an eye over my code and let me know what you think... Have I missed something obvious? Are there any possible race conditions? Is there an entirely different and/or better way to do this? Good and bad, everything is appreciated!</p>
<p>So, I have to produce and consume lots of <em>something</em>, however the producers are extremely slow and the consumption of the items extremely fast. <strong>slow producers, fast consumer</strong></p>
<p>Thankfully my current problem can have the production of items parallelized to some extent, so I have written a class that implements <code>IEnumerable<T></code>, takes a bunch of <code>IEnumerable<T></code>s in it's constructor and exposes their combined output. The idea being that I am breaking the problem into parallelizable chunks, and feeding each in to be (behind-the-scenes) enumerated in parallel.</p>
<p>The code is probably more instructive than my babbling sentences above:</p>
<pre class="lang-cs prettyprint-override"><code>// The ability to limit the number of cached items is in case we have the unexpected
// case of producing items faster than we can consume
class ParallelProducer<T> : IEnumerable<T>
{
#region Fields
private readonly IEnumerable<T>[] enumerables;
private readonly int maxItemsToCache;
#endregion
#region Constructors
private ParallelProducer(int maxItemsToCache, IEnumerable<T>[] enumerables)
{
this.maxItemsToCache = maxItemsToCache;
this.enumerables = enumerables;
}
#endregion
#region Properties
#endregion
#region Methods
public IEnumerator<T> GetEnumerator()
{
return new ParallelProducerEnumerator<T>(this.maxItemsToCache, this.enumerables);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Nested types
private class ParallelProducerEnumerator<U> : IEnumerator<U>
{
#region Fields
private readonly List<Thread> producerThreads;
int threadsStillEnumerating;
private bool producersStarted = false;
private readonly BlockingCollection<U> cachedItems;
private U currentItem;
#endregion
#region Constructors
public ParallelProducerEnumerator(int maxItemsToCache, IEnumerable<U>[] slowEnumerables)
{
this.cachedItems = new BlockingCollection<U>(maxItemsToCache);
this.producerThreads = new List<Thread>();
this.threadsStillEnumerating = slowEnumerables.Length;
// this variable will be captured by all of the thread methods
foreach (var slowEnumerable in slowEnumerables)
{
// to avoid a reference to the iterator variable being captured
var enumerableToCapture = slowEnumerable;
var thread = new Thread(() => ProducerMethod(enumerableToCapture));
this.producerThreads.Add(thread);
}
}
#endregion
#region Properties
public U Current
{
get { return this.currentItem; }
}
object System.Collections.IEnumerator.Current
{
get { return this.Current; }
}
#endregion
#region Methods
private void ProducerMethod(IEnumerable<U> enumerable)
{
foreach (var item in enumerable)
{
this.cachedItems.Add(item);
}
int postDecrementValue = Interlocked.Decrement(ref this.threadsStillEnumerating);
if (postDecrementValue == 0)
{
cachedItems.CompleteAdding();
}
}
public bool MoveNext()
{
if (!producersStarted)
{
producersStarted = true;
foreach (var thread in producerThreads)
{
thread.Start();
}
}
if (!cachedItems.TryTake(out this.currentItem, Timeout.Infinite))
return false;
return true;
}
public void Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
#endregion
}
#endregion
}
</code></pre>
<p>And a little example usage for good measure...</p>
<pre class="lang-cs prettyprint-override"><code>// a slow producer...
static IEnumerable<int> SlowGetNumbers(int start, int end)
{
for (int i = start; i < end; i++)
{
Thread.Sleep(100);
yield return i;
}
}
// a fast consumer
static void Consume(IEnumerable<int> enumerable)
{
foreach (var item in enumerable)
{
Console.WriteLine(item);
}
}
var vanillaProducer = SlowGetNumbers(1, 30);
var parallelProducer = new ParallelProducer<int>(
SlowGetNumbers(1, 10),
SlowGetNumbers(10, 20),
SlowGetNumbers(20, 30));
// This will take 3 seconds
Consume(vanillaProducer);
// This will take ~1 second
Consume(parallelProducer);
</code></pre>
<h3>Edit</h3>
<p>On svick's advice, I'm just creating a <code>IEnumerator<T></code>-returning method, and it's far simpler and has far less boilerplate... </p>
<pre class="lang-cs prettyprint-override"><code>static class ParallelProducer
{
public static IEnumerable<T> Create<T>(int maxItemsToCache, params IEnumerable<T>[] enumerables)
{
BlockingCollection<T> cachedItems = new BlockingCollection<T>(maxItemsToCache);
int threadsStillEnumerating = enumerables.Length;
foreach (var slowEnumerable in enumerables)
{
// to avoid a reference to the iterator variable being captured
var enumerableToCapture = slowEnumerable;
var thread = new Thread(() =>
{
foreach (var item in enumerableToCapture)
{
cachedItems.Add(item);
}
int postDecrementValue = Interlocked.Decrement(ref threadsStillEnumerating);
if (postDecrementValue == 0)
{
cachedItems.CompleteAdding();
}
});
thread.Start();
}
return cachedItems.GetConsumingEnumerable();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T10:32:58.973",
"Id": "22056",
"Score": "0",
"body": "If you can use .Net 4.5, problems like this can be solved very easily using TPL Dataflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-22T10:54:08.670",
"Id": "24240",
"Score": "0",
"body": "@svick any good sample using TPL Dataflow ?"
}
] |
[
{
"body": "<p>Your code seems fine and thread-safe to me. Few things to think about:</p>\n\n<ol>\n<li>You're using lots of threads that could block in the unlikely case when the consumer is slow. Doing things asynchronously could help you there, but it's most likely not worth it, because it would be quite complicated (unless you could use C# 5).</li>\n<li>I would usually prefer <code>Task</code>s to <code>Thread</code>s, but in your case that doesn't give you much. So I think using <code>Thread</code>s here directly is fine.</li>\n<li>If your producers are slow, why do you wait until you start them until the call to <code>MoveNext()</code>? I think starting them in the constructor would make more sense here.</li>\n<li>You could avoid all of the boilerplate <code>IEnumerator<T></code> code by using <a href=\"http://msdn.microsoft.com/en-us/library/dd287186.aspx\" rel=\"nofollow\"><code>GetConsumingEnumerable()</code></a> (in that case, you would probably change your constructor to an <code>IEnumerator<T></code>-returning method). This has the added benefit that you could more easily modify your code for multiple consumer threads in the future.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:08:38.547",
"Id": "22062",
"Score": "0",
"body": "For 3, I didn't feel quite right kicking it all off in the constructor (I never like doing too much in there), but I think you might be right. As for 4, that's perfect, a failure to read the docs thoroughly enough on my part... All good food for thought though, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T10:59:02.297",
"Id": "13620",
"ParentId": "13618",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "13620",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T10:03:08.163",
"Id": "13618",
"Score": "2",
"Tags": [
"c#",
"multithreading"
],
"Title": "Slow-producer, fast-consumer IEnumerable wrapper"
}
|
13618
|
<p>I've decided to do this by writing a simple word counter. The app gets all the params and outputs all the unique words, each one with a counter:</p>
<p>"Hello world Hello" would return "Hello: 2", "world: 1"</p>
<p>(not taking in consideration the actual output structure)</p>
<p>This program is the Python equivalent of:</p>
<pre><code>import sys
from collections import defaultdict
def main():
results = defaultdict(int)
for word in sys.argv[1:]:
results[word] += 1
print results
</code></pre>
<p>Writing it in C is a bit different. I feel like I'm getting something utterly wrong with pointers, arrays of pointers and all that stuff.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
// This is what a key-value pair: <int, string>
typedef struct {
int counter;
unsigned char* word;
} hashmap;
// Checks if inside the array of results, hashmap->word is equals to word paramter
hashmap* get_word_from_results(hashmap* results[], int count, const char* word) {
int i;
hashmap* result;
for (i = 0; i < count; i++) {
result = results[i];
if (result->word == (unsigned char *)word)
return result;
}
return NULL;
}
int main(int argc, const char *argv[])
{
hashmap* results;
int results_counter = 0;
int i;
const char* word;
for (i = 1; i < argc; i++) {
word = argv[i];
hashmap* result = get_word_from_results(&results, results_counter, word);
// If result is NULL, means word is not inserted yet, let's create a new hashmap and insert it inside the array
if (result == NULL) {
hashmap h;
h.counter = 1;
h.word = (unsigned char *)word;
results = realloc(NULL, (results_counter + 1) * sizeof(hashmap) );
// NOTE: potential memory leak? would h be deallocated?
results[results_counter] = h;
results_counter++;
printf("NEW\n");
} else {
// The word already exists in the hashmap array, let's increase it by 1
result->counter++;
printf("INCREMENTED\n");
}
}
return 0;
}
</code></pre>
<ol>
<li>Can anyone give me some advice?</li>
<li>What am I doing wrong here?</li>
<li>Are my pointers okay? I also think I've spotted a memory leak (see comments).</li>
<li>Would anyone like to submit their version?</li>
</ol>
|
[] |
[
{
"body": "<p>I am new to programming so there is chance to be completely wrong, but isn't this line a problem?</p>\n\n<pre><code>if (result->word == (unsigned char *)word)\n</code></pre>\n\n<p>I think that you should compare strings using strcmp()</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:05:49.687",
"Id": "22061",
"Score": "0",
"body": "yes, thanks for the answer. strcmp is the way to go"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T11:39:47.167",
"Id": "13622",
"ParentId": "13621",
"Score": "4"
}
},
{
"body": "<p>Well, firstly, your hashmap isn't a hash map. If that's what you want, it'd be better to go and implement one first. Remember, just because C doesn't have direct support for OO, doesn't mean you can't write real containers, or use real abstractions.</p>\n\n<p>Try implementing the hash map in isolation first, then you can test the implementation, and then write your app on top.</p>\n\n<p>Alternatively, if you want to focus on the app logic first,and then drill down into the implementation, either find an existing hashmap you can use, or switch to C++ and just use <code>std::unordered_map<std::string, int></code></p>\n\n<hr>\n\n<p>OK, and a review of the actual code:</p>\n\n<ul>\n<li>you're switching between <code>char *</code> and <code>unsigned char *</code> for no reason. Stick with <code>char *</code> for text strings</li>\n<li><p>you're using <code>realloc</code> wrongly; you need to pass the current value of <code>results</code> as the first argument if you want to grow the existing array (and have the existing values copied over)</p>\n\n<ul>\n<li>eg. <code>results = realloc(NULL, n)</code> just discards (and leaks) the old array and allocates a new, bigger one</li>\n<li><p>but <code>results = realloc(results, n)</code> moves the existing contents to a new, bigger block</p>\n\n<ul>\n<li><p>unless the re-allocation fails, in which case you've leaked the old block. This may be an unrecoverable error anyway, but Loki Astari's comment shows the correct approach:</p>\n\n<pre><code>hashmap *tmp = realloc(results, n);\nif (tmp)\n results = tmp; // reallocation succeeded\nelse {\n // handle failure somehow?\n}\n</code></pre></li>\n</ul></li>\n</ul></li>\n<li><p>the <code>hashmap* results[]</code> argument to <code>get_word_from_results</code> is the wrong type. You're passing <code>hashmap*</code>, and that's what it should take. The fact you're using it as an array doesn't mean you have to throw in random <code>[]</code></p></li>\n<li>you can't compare string values using <code>if (result->word == word)</code>, that just checks whether they have the same <em>address</em>. It's exactly equivalent to <code>if id(result.word) == id(word)</code> in Python. Use <code>strcmp</code> to compare the contents of the string (or, go with C++ and use std::string references, which you can compare with <code>==</code>)</li>\n</ul>\n\n<hr>\n\n<p>For example, the public interface in <code>hashmap.h</code> might look like:</p>\n\n<pre><code>#ifndef HASHMAP_H\n#define HASHMAP_H\n/* nobody needs to see the contents except the implementation */\nstruct hashmap;\n\nstruct hashmap* create_hashmap();\n\nvoid *lookup_hashmap(struct hashmap*, const char *key);\n/* return NULL if not found? */\n\nint insert_hashmap(struct hashmap*, const char *key, void *value);\n/* return zero on success, -1 on collision? */\n#endif\n</code></pre>\n\n<p>and the implementation file <code>hashmap.c</code></p>\n\n<pre><code>#include \"hashmap.h\"\n\nstruct bucket\n{\n const char *key;\n void *value;\n};\n\nstruct hashmap\n{\n int used; /* to calculate load factor */\n int n_buckets;\n struct bucket *buckets;\n}\n\nstruct hashmap* create_hashmap() { /* allocate and initialize */ }\n\nvoid *lookup_hashmap(struct hashmap *map, const char *key)\n{\n /* hash key, find bucket, return value */\n}\n\nint insert_hashmap(struct hashmap *map, const char *key, void *value)\n{\n /* hash key, find bucket, return -1 if it's in use?\n otherwise store value and return 0\n factor out bucket lookup from insert_ and lookup_?\n ...\n */\n}\n</code></pre>\n\n<hr>\n\n<p>For reference, here's a simple C++11 implementation, which is (hopefully) much closer to Python than you can get in C:</p>\n\n<pre><code>#include <string>\n#include <unordered_map>\n#include <iostream>\n\nint main(int argc, char *argv[]) {\n // std::unordered_map is similar to dict\n std::unordered_map<std::string, int> results;\n for (int i=1; i<argc; ++i) {\n std::string word = argv[i];\n results[word] += 1;\n }\n // the main complexity is that C++ library types don't have a\n // built-in way to print themselves\n std::cout << \"results = {\";\n for (auto i:results) {\n std::cout << i.first << ':' << i.second << ' ';\n }\n std::cout << \"}\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:05:23.603",
"Id": "22060",
"Score": "0",
"body": "Thanks for the time spent in answering this question! I'll check this straigt away! @Useless"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:53:47.710",
"Id": "22083",
"Score": "0",
"body": "Your comment about realloc() is correct your solution is just as bad. The pattern **must** be `tmp = realloc(result, /*STUFF*/); if (tmp != NULL) {result = tmp;}` Otherwise if realloc fails and returns NULL you leak memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T09:20:20.917",
"Id": "22104",
"Score": "0",
"body": "Good point - I intentionally omitted error handling, but that's actually misleading"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:02:11.780",
"Id": "13623",
"ParentId": "13621",
"Score": "6"
}
},
{
"body": "<p>1) As Faery says, you should be using strcmp() to compare strings. What you're doing is comparing the address of the string, which is always going to be different (in your program), even if it's the same word.</p>\n\n<p>2) You have got a bit confused with your pointers! Should <code>results</code> hold an array of hashmaps or pointers to hashmaps. I'd guess that you meant the former - in which case, the function prototype should be <em>either</em>:</p>\n\n<pre><code>hashmap* get_word_from_results(hashmap* results, int count, const char* word)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>hashmap* get_word_from_results(hashmap results[], int count, const char* word)\n</code></pre>\n\n<p>and various lines should be:</p>\n\n<pre><code>result = &results[i];\n</code></pre>\n\n<p>and in main:</p>\n\n<pre><code>hashmap* result = get_word_from_results(results, results_counter, word);\n</code></pre>\n\n<p>3) Keep using <code>char*</code> rather than <code>unsigned char*</code>.</p>\n\n<p>4) When you realloc with NULL as the first parameter, you're throwing away what you originally had. You need to initialise <code>results = NULL;</code> and then use results as that first parameter.</p>\n\n<p>5) As an aside - don't reallocate every time through the loop. In this case, you know the maximum number of words possible, so allocate that before the start of the loop.</p>\n\n<p>6) Your assignment of h is OK. You're performing a shallow copy rather than anything involving memory allocations.</p>\n\n<p>7) Don't forget to <code>free</code> your results (preferably after printing them out)!!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:15:40.807",
"Id": "13624",
"ParentId": "13621",
"Score": "2"
}
},
{
"body": "<p>Declarations must be located at the start of the scope ({}). For example, <code>hashmap* result</code> in the loop is not at the start of the loop body.</p>\n\n<p>As two other answers have stated, use strcmp() to compare strings. For example <code>(strcmp(x,y) == 0)</code> is true if <code>x</code> and <code>y</code> are equal. You'll have to add <code>#include <string.h></code>.</p>\n\n<p><code>if(result == NULL)</code> is easy to get wrong because C will sap you of your will. Always make sure the lhs of a condition expression is not a l-value. For example, <code>if(NULL == x)</code> or <code>if(x + 0 == y)</code>.</p>\n\n<p>Just don't use realloc(). It is six functions in one. Just do the following...</p>\n\n<pre><code>{\n hashmap* temp;\n temp = (pair_p) malloc((results_counter + 1) * sizeof(hashmap));\n memmove(temp, results, (results_counter + 1) * sizeof(hashmap));\n free(results);\n results = temp;\n}\n</code></pre>\n\n<p>Comments in C are <code>/* */</code> not <code>//</code>.</p>\n\n<p>Get rid of <code>unsigned</code> qualifier for the strings, as another person said.</p>\n\n<p>Rename <code>hashmap</code> to <code>pair</code>. For instance,</p>\n\n<pre><code>typedef struct {\n int counter;\n char * word;\n} pair, * pair_p;\n</code></pre>\n\n<p>Replacing <code>pair_p</code> for <code>hashmap*</code> ...</p>\n\n<pre><code>pair_p get_word_from_results(pair_p results[], int count, char* word)\n</code></pre>\n\n<p>Notice that the first parameter is the wrong type. It reads as <code>results</code> is an array of pointers of type <code>pair</code>. But it should read as <code>results</code> is a pointer of type <code>pair</code>. (Yes, I know it is a sequence but trust me on this.) Removing the square brackets will fix it.</p>\n\n<p>As to your memory leak comment. It is wrong. <code>h</code> would not be leaked because it is stored on the <em>stack</em> and not on the <em>heap</em>. But <code>results</code> would leak from the prior line. Grr!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T12:34:59.313",
"Id": "13625",
"ParentId": "13621",
"Score": "1"
}
},
{
"body": "<p>Never trust a hand written hashing algorithm.<br>\nPeople have an advanced feeling of superiority if they do and they always botch it up resulting in a pretty shitty hash. Writing a good hash is actually quite hard; something you should leave to the experts or specifically study up on. <strong>DO NOT</strong> write your own and expect a good result.</p>\n\n<p>The most common hash you see people write is</p>\n\n<pre><code>// DO NOT USE THIS.\n// Its bad for ENGLISH worse for URLS\nval = <SEED>;\nfor(int loop = 0;loop < len;++loop)\n{ val = val * <MULT> + str[loop];\n}\n</code></pre>\n\n<p>No matter what you choose for SEED/MULT this always pretty bad. English means the input values are nor evenly distributed and overflow of the val is usually the next thing that happens meaning you are really only generating the hash with the last 4-8 characters of the string.</p>\n\n<p>C++ gives you the power of C but the express-ability of python.</p>\n\n<pre><code>#include <unordered_map>\n#include <vector>\n#include <iterator>\n#include <iostream>\n#include <sstream>\n\nint main(int argc, char* argv[])\n{\n std::vector<std::string> args(argv+1, argv+argc);\n std::unordered_map<std::string, int> result;\n\n for(auto loop = args.begin(); loop != args.end(); ++loop)\n { \n ++result[word];\n } \n for(auto loop = result.begin();loop != result.end();++loop)\n { \n std::cout << loop->first << \": \" << loop->second << \"\\n\";\n } \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T14:19:35.907",
"Id": "13629",
"ParentId": "13621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T11:06:20.883",
"Id": "13621",
"Score": "10",
"Tags": [
"c",
"algorithm",
"hash-map",
"pointers"
],
"Title": "Simple word counter"
}
|
13621
|
<p>I have my own PHP MVC framework that I'm iteratively developing (i.e. adding a feature when I have the time). I'm trying to keep it to the best practices I can, while still adding the most in terms of functionality.</p>
<p>The latest addition I've implemented is lazy loading for my model properties. I've gone, you could say, off the beaten path a bit and decided to make a general <code>Lazy</code> class. It would hold reference to what needs to be instantiated, which is then replaced, on access, but not definition, by its evaluation.</p>
<pre><code>class Lazy extends Object
{
private $_source;
private $_class;
private $_target;
private $_params;
function evaluate() {
if (empty($this->_source)) {
if (empty($this->_target))
if (empty($this->_params))
return $this->_class->newInstance();
else return $this->_class->newInstanceArgs($this->_params);
else {
if (empty($this->_params))
return $this->_target->invoke(null);
else return $this->_target->invokeArgs(null, $this->_params);
}
} else {
if (empty($this->_target))
return $this->_source;
else {
if (empty($this->_params))
return $this->_target->invoke($this->_source);
else return $this->_target->invokeArgs($this->_source, $this->_params);
}
}
}
function __construct($source, $target = null, $params = null)
{
parent::__construct();
if (is_object($source))
$this->_source =& $source;
$this->_class = new ReflectionClass($source);
if (!empty($target))
$this->_target = $this->_class->getMethod($target);
$this->_params = is_array($params) ? $params : array($params);
}
function __destruct()
{
parent::__destruct();
}
}
</code></pre>
<p>The 'loading' functionality is serviced by the parent class of the models:</p>
<pre><code>function mapLazy($name, $source, $target = null, $params = null) {
if (is_array($target)) {
$params = $target;
$target = null;
}
$this->_lazy[$name] = new Lazy($source, $target, $params);
}
function __get($name)
{
if (!isset($this->_lazy[$name]))
throw new Exception_InvalidProperty("No such property found.", 1);
if ($this->_lazy[$name] instanceof Lazy)
$this->_lazy[$name] = $this->_lazy[$name]->evaluate();
return $this->_lazy[$name];
}
</code></pre>
<p>Used as such:</p>
<pre><code>$this->mapLazy('Pictures', $this, 'getPictures');
$this->mapLazy('Gallery', 'CMS_Gallery', array(&$this->_gallery_id));
</code></pre>
<p>Basically, <code>mapLazy</code> takes a property name to map and creates a hidden instance of a <code>Lazy</code> object and storing the information neccessary for execution in it. Internally, <code>Lazy</code> converts the parameters to the appropriate <code>Reflection</code> children so it can later execute the commands. The reason for all the code in <code>mapLazy</code> and <code>Lazy::ctor</code> is that <code>mapLazy</code> can take a whole lot of parameter forms (which is either a downside or upside of PHP, depends on how you look at it; for this example, overloading would probably work better).</p>
<pre><code>mapLazy('<property>', '<name of class>', '<method / parameters [OPTIONAL]>', '<parameters [OPTIONAL]>');
</code></pre>
<p>is the "static" call. <code>Lazy</code> will either instantiate a class (if no second parameter or array of them given), or it will bind to <code>property</code> the result of whatever method was passed in <code>method</code>, possibly with parameters in <code>parameters</code>.</p>
<p>The second major form takes an object instead of class name (<code>ReflectionClass::ctor</code> gracefully doesn't care) and does the same, just on the provided object reference.</p>
<p>After all of that, my question would be one for comments on this implementation of lazy loading and whether or not I'm missing an important flaw or possible improvement. The entire framework can also be found on <a href="https://bitbucket.org/Naltharial/ouroboros/src" rel="nofollow">BitBucket</a>, if desired. Do keep in mind it's mostly an "educational exercise" (although it's used in production on a site), but I'd like to make the best of it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T10:58:48.523",
"Id": "22151",
"Score": "0",
"body": "Your evaluate() method is going to be a nightmare to debug, it's got really high nPath complexity. Also, evaluate() isn't a great method name, as it tells you very little about what the method actually does."
}
] |
[
{
"body": "<p><code>Lazy::evaluate</code> has a lot of logic in it that may be better implemented using inheritance. There seem to be several possibilities:</p>\n\n<ul>\n<li>Instantiate a class with or without arguments.</li>\n<li>Call a function or static method with or without arguments.</li>\n<li>Call an instance method with or without arguments.</li>\n<li>Return the <code>$_source</code> value, i.e., not lazy.</li>\n</ul>\n\n<p>I would create multiple subclasses of the abstract class (or interface) <code>Lazy</code> to handle the disparate cases above. As well, I agree that you should define several versions of <code>mapLazy</code> with different names and appropriate type hints. This will provide a nicer API for the developers that must use it.</p>\n\n<p>I don't see an example of when <code>$target</code> is a method. Do you pass in the method's name or its <code>ReflectionMethod</code>? What about functions? Here's where named factory methods would be helpful since they could look up the reflection objects or defer to the lazy subclass.</p>\n\n<p>Remove all those <code>empty</code>s. The following are equivalent to <code>false</code> in a boolean context:</p>\n\n<ul>\n<li><code>false</code></li>\n<li><code>null</code></li>\n<li>Empty string</li>\n<li>Empty array</li>\n<li>Zero (<code>0</code> and <code>0.0</code>)</li>\n</ul>\n\n<p>In PHP 5.0+, <a href=\"http://php.net/manual/en/language.oop5.references.php\" rel=\"nofollow\">variables that hold objects are actually identifiers for looking up the object</a>. Only assign using the reference operator <code>&</code> if you truly need to bind those two variables together. Assigning normally will only copy the identifier and not the original object.</p>\n\n<p>Do you need a destructor that calls the parent's? I suspect that you only need to override it when you want to augment its behavior just like normal methods. However, I admit I've never needed a destructor in PHP and could be mistaken.</p>\n\n<p>This comes down to coding style, but I am not a big fan of leaving off braces for single-line blocks. I used to be, but once I got used to putting them on every time I became a convert. I can't count how many times I've added a second line and forgot to add the braces and wasted time trying to figure out why it was executing the second statement when the block wasn't entered.</p>\n\n<p>Finally, I'd add an explicit <code>public</code> for those methods. I believe this will eventually be required for all methods (no more default) in PHP.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T17:40:04.730",
"Id": "36432",
"Score": "0",
"body": "Whoah, this took me way too long to get back to. Talk about a busy ... year? :)\nI ended up taking your advice and breaking it into three methods (Instance, Invoke and Static) and refactoring it a bit (incl. removing the `&`s, heh). I think the API is now indeed much clearer. Thanks for the comments!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T00:08:24.530",
"Id": "53873",
"Score": "1",
"body": "Hey @Naltharial - Would be great if you could post your ultimate solution for others to learn from?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T01:59:42.847",
"Id": "13671",
"ParentId": "13630",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13671",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T14:21:06.427",
"Id": "13630",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"php5",
"reflection",
"lazy"
],
"Title": "Lazy loading with __get"
}
|
13630
|
<p>The below code is real and in use, but I've modified it to simplify the process/make it easier to explain.</p>
<p>The purpose of this code is to combine data from multiple data sources. All sources are .xls files, but the names will vary based on the date of creation, and the formatting can vary based on the user. </p>
<p>Because the names are variable, I have opted to prompt the
user to select each of the necessary files, rather than try to code in an auto-selection.
Also, since the end-users like to have things as simple as possible, I've condensed this
process into one function (there are multiple extra functions, all wrapped in this main
function) as opposed to having to manually begin multiple processing steps. Since there
are a number of files involved, I have designed this to have the user pre-open each
of the necessary files (which all live in different locations on a network) before
beginning this process. As a result, I have multiple <code>If</code> checks to verify that a user
has not cancelled mid-way (say, they forgot to open one of the files earlier and didn't
realize until they were prompted for it).</p>
<p><strong>Is there a better way to collect all the files that are needed for processing while allowing the user to cancel at any step in the process?</strong>
There is nothing wrong for me to have such deep nesting, but I feel like this may be bad
form. I believe I can put each check all on one line with <code>And</code>, but that I think would
also become unwieldy/harder to debug if there was an issue.</p>
<p>I have added comments to the code to explain what may be missing from the example, but feel free to ask if I've missed anything.</p>
<p><em>Update:</em> I've made it a little nicer by putting all the workbook/sheet assignments after the last if.</p>
<pre><code>Option Explicit
Sub Example()
Dim Book0 As Workbook
Dim Sheet0 As Worksheet
Dim Book1 As Workbook
Dim Book2 As Workbook
Dim Sheet2 As Worksheet
Dim Book3 As Workbook
Dim Sheet3 As Worksheet
Dim Book4 As Workbook
Dim Sheet4 As Worksheet
Dim Book5 As Workbook
Dim Sheet5 As Worksheet
If MsgBox("Before beginning, please make sure you have each of the following files open:" & vbCr & vbCr & vbTab & _
"Book1" & vbCr & vbTab & "Book2" & vbCr & vbTab & _
"Book3" & vbCr & vbTab & "Book4" & vbCr & vbTab & _
"Book5" & vbCr & vbTab & "Book6" & vbCr & vbCr & _
"If these files are ready, then please click 'OK' (or 'Cancel' to cancel and try again).", _
vbOKCancel, "All files ready?") = vbOK Then
' sListing is a 2d array of strings, holding the names of workbooks/sheets.
' sListing(0, 0) is the name of the first workbook in a selection.
' sListing(0, 1) is the name of the (optionally selected) worksheet within sListing(0, 0).
' sListing(1, 0) is the name of the second workbook in a selection. (And so on...)
' Reset_sListing assigns all values within the array to a null string.
Reset_sListing
' GetBook is a function that finds all open workbooks within an instance of Excel.
' The function displays a list of all workbooks on a form and prompts the user to select one.
' If only one string argument is passed, then is searches only for a workbook.
' The name of the selected workbook is then added to sListing at position (n, 0),
' where n is the number passed as the third argument to GetBook. If two string arguments
' are passed, then the function will do the same as above, but for a sheet within the
' selected workbook, passing the value to sListing at position (n, 1). The function will
' return true if the user made a proper selection on the form(s), false if there was
' an error or the user cancels.
If GetBook("Please select the Book0.", "Please select a sheet within Book0.", 0) Then
If GetBook("Please select the Book1.", , 1) Then
If GetBook("Please select the Book2.", "Please select a sheet within Book2.", 2) Then
If GetBook("Please select the Book3.", "Please select a sheet within Book3.", 3) Then
If GetBook("Please select the Book4.", "Please select a sheet within Book4.", 4) Then
If GetBook("Please select the Book5.", "Please select a sheet within Book5.", 5) Then
If GetBook("Please select the Book6.", "Please select a sheet within Book6.", 6) Then
Set Book0 = Workbooks(sListing(0, 0))
Set Sheet0 = Book0.Sheets(sListing(0, 1))
Set Book1 = Workbooks(sListing(1, 0))
Set Book2 = Workbooks(sListing(2, 0))
Set Sheet2 = Book2.Sheets(sListing(2, 1))
Set Book3 = Workbooks(sListing(3, 0))
Set Sheet3 = Book3.Sheets(sListing(3, 1))
Set Book4 = Workbooks(sListing(4, 0))
Set Sheet4 = Book4.Sheets(sListing(4, 1))
Set Book5 = Workbooks(sListing(5, 0))
Set Sheet5 = Book5.Sheets(sListing(5, 1))
Set Book6 = Workbooks(sListing(6, 0))
Set Sheet6 = Book6.Sheets(sListing(6, 1))
'Do stuff with books/sheets.
MsgBox "Process complete!"
End If
End If
End If
End If
End If
End If
End If
End If
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>You can replace all of the Getbook nested ifs with the following. Place this first:</p>\n\n<pre><code>Dim i As Long\nFor i = 0 To 6\n If Not Getbook(\"Please select the Book\" & i & \".\", \"Please select a sheet within Book\" & i & \".\", i) Then\n Exit Sub\n End If\nNext i\n</code></pre>\n\n<p>Then below that list what you want to happen:</p>\n\n<pre><code>Set Book0 = Workbooks(sListing(0, 0))\nSet Sheet0 = Book0.Sheets(sListing(0, 1))\nSet Book1 = Workbooks(sListing(1, 0))\nSet Book2 = Workbooks(sListing(2, 0))\nSet Sheet2 = Book2.Sheets(sListing(2, 1))\nSet Book3 = Workbooks(sListing(3, 0))\nSet Sheet3 = Book3.Sheets(sListing(3, 1))\nSet Book4 = Workbooks(sListing(4, 0))\nSet Sheet4 = Book4.Sheets(sListing(4, 1))\nSet Book5 = Workbooks(sListing(5, 0))\nSet Sheet5 = Book5.Sheets(sListing(5, 1))\nSet Book6 = Workbooks(sListing(6, 0))\nSet Sheet6 = Book6.Sheets(sListing(6, 1))\n'Do stuff with books/sheets.\n\nMsgBox \"Process complete!\"\n</code></pre>\n\n<p>This replaces the huge amount of ifs with a loop that has the same result. I.E. Operation continues only if every if statement returns true, and if any return false the sub exits.</p>\n\n<p>Edit:\nIt should also be possible to standardize your Set Book0 Set Sheet0 sections as well by using arrays.</p>\n\n<p>To do that you would do something like this...:</p>\n\n<pre><code>Dim workbooks(6) As Workbook\nDim sheets(6) As Worksheet\nDim i As Long\nFor i = 0 To 6\n If Not Getbook(\"Please select the Book\" & i & \".\", \"Please select a sheet within Book\" & i & \".\", i) Then\n Exit Sub\n Else\n Set workbooks(i) = workbooks(slisting(i, 0))\n Set sheets(i) = workbooks(i).sheets(slisting(i, 1))\n End If\nNext i\n'Do stuff with books/sheets.\n\nMsgBox \"Process complete!\"\n</code></pre>\n\n<p>This way once the loop is done all the workbooks have been assigned to the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:59:18.817",
"Id": "22084",
"Score": "0",
"body": "I like this idea a lot. (kicking myself for not doing it already...) When I started reading, I was thinking 'no, that's not going to work' because the specific prompt for the workbooks will vary by workbook. However, you're absolutely right that I can use arrays. I can also use arrays to hold the prompt strings! I will try an implement and see what I come up with. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:08:55.370",
"Id": "22085",
"Score": "0",
"body": "And for the record, VBA assigns arrays with a 1 base, instead of 0, so those have to be `sheets(0 to 6) As Worksheet`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:19:54.140",
"Id": "22087",
"Score": "0",
"body": "That works beautifully and is much easier to read/look at! Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:38:15.100",
"Id": "22088",
"Score": "0",
"body": "Check your locals window. When I created the arrays, they were 0 based. This is the default behavior. (http://msdn.microsoft.com/en-us/library/aa266179(v=vs.60).aspx) But if you want to be certain you can indeed specify. It would probably be a good practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:41:49.030",
"Id": "22089",
"Score": "0",
"body": "You are right. I think I was getting confused with VBA `array(n)` is 0 to n (n+1 total items), whereas in many others, `array(n)` is 0 to n-1 (n total items). Either way, this was extremely helpful."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:38:38.927",
"Id": "13644",
"ParentId": "13632",
"Score": "6"
}
},
{
"body": "<p>In your case, I think @DanielCook's example of using a for-loop is your best option. But I wanted to share a trick I use when you can't really viably use a for-loop. In this example, if any of the calls to <code>GetBook()</code> return <code>False</code> then <code>Result</code> will be <code>False</code>. As I said though, this isn't as good as a for-loop, but when your conditions are something that can't easily be iterated, this works well.</p>\n\n<pre><code>Dim Result As Boolean: Result = True\nResult = Result And GetBook(\"Please select the Book0.\", \"Please select a sheet within Book0.\", 0)\nResult = Result And GetBook(\"Please select the Book1.\", , 1)\nResult = Result And GetBook(\"Please select the Book2.\", \"Please select a sheet within Book2.\", 2)\nResult = Result And GetBook(\"Please select the Book3.\", \"Please select a sheet within Book3.\", 3)\nResult = Result And GetBook(\"Please select the Book4.\", \"Please select a sheet within Book4.\", 4)\nResult = Result And GetBook(\"Please select the Book5.\", \"Please select a sheet within Book5.\", 5)\nResult = Result And GetBook(\"Please select the Book6.\", \"Please select a sheet within Book6.\", 6)\nIf Result Then\n Set Book0 = Workbooks(sListing(0, 0))\n Set Sheet0 = Book0.Sheets(sListing(0, 1))\n Set Book1 = Workbooks(sListing(1, 0))\n Set Book2 = Workbooks(sListing(2, 0))\n Set Sheet2 = Book2.Sheets(sListing(2, 1))\n Set Book3 = Workbooks(sListing(3, 0))\n Set Sheet3 = Book3.Sheets(sListing(3, 1))\n Set Book4 = Workbooks(sListing(4, 0))\n Set Sheet4 = Book4.Sheets(sListing(4, 1))\n Set Book5 = Workbooks(sListing(5, 0))\n Set Sheet5 = Book5.Sheets(sListing(5, 1))\n Set Book6 = Workbooks(sListing(6, 0))\n Set Sheet6 = Book6.Sheets(sListing(6, 1))\n\n 'Do stuff with books/sheets.\n\n MsgBox \"Process complete!\"\nEnd If\n</code></pre>\n\n<p><br />\n<strong>EDIT</strong> <br />\nI realized that in @DanielCook's example, if you want the \"Process complete!\" message box to show up regardless of whether <code>GetBook()</code> ever returns <code>False</code> then a combination of his example and mine would be better.. </p>\n\n<pre><code>Dim Workbooks(6) As Workbook\nDim Sheets(6) As Worksheet\nDim Result As Boolean: Result = True\n\nDim i As Long\nFor i = 0 to 6\n Result = Result And GetBook(\"Please select the Book\" & i & \".\", \"Please select a sheet within Book\" & i & \".\", 1)\n If Result Then\n Set Workbooks(i) = Workbooks(sListing(i,0))\n Set Sheets(i) = Workbooks(i).sheets(sListing(i, 1))\n End If\nNext\n\n' Some code you want to run regardless of the result\nMsgBox \"Process complete!\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T15:22:56.837",
"Id": "22109",
"Score": "0",
"body": "Yeah, that's not quite as simple, but still better than my original. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:23:06.630",
"Id": "32220",
"Score": "0",
"body": "This is a bit late of a comment, but in response to your edit, you could also achieve the same results by replacing my line that says `Exit Sub` with `Exit For`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T03:26:52.383",
"Id": "32238",
"Score": "0",
"body": "True. However, mine has the luxury of not having to use an `Exit` call of any kind."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T14:55:55.830",
"Id": "13662",
"ParentId": "13632",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13644",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T15:44:50.917",
"Id": "13632",
"Score": "6",
"Tags": [
"vba",
"user-interface"
],
"Title": "Multiple nested If checks in VBA"
}
|
13632
|
<p>Help me make it better. Requirement: support arbitrary number of factors, not just 3 & 5. </p>
<pre><code>(ns fizzbuzz.core
(:use [clojure.contrib.string :only (join)]))
(def targets (sorted-map 3 "fizz" 5 "buzz" 7 "baz"))
;; match any applicable factors
(defn match [n, factors]
(filter #(= 0 (mod n %)) factors))
(defn fizzbuzz [n]
(let [factors (keys targets)
matches (match n factors)]
(if (= 0 (count matches))
(str n)
(reduce str (map targets matches)))))
(join ", " (map fizzbuzz (range 1 20)))
</code></pre>
|
[] |
[
{
"body": "<p>I tried keeping your approach, although I would've made it an infinite lazy sequence. Yours is probably a better idea, since you still have the infinite sequence (mapping to range as you did) and you can map it to other non-linear sequences too.</p>\n\n<pre><code>(def targets ;; This is more readable for me\n (sorted-map\n 3 \"fizz\",\n 5 \"buzz\",\n 7 \"baz\"))\n\n(defn fizzbuzz [targets n] ;; Pass the targets here! Commas aren't very common in args lists\n (let [matches (keep (fn [[f w]] ;; Destructuring is nice :P\n (when (zero? (mod n f)) w)) ;; Got rid of your helper function\n targets)] ;; ^ Use 'zero?' instead of '(= 0 ...)'\n (if (empty? matches) ;; Use 'empty?' instead of '(= 0 (count ...))'\n (str n)\n (apply str matches)))) ;; I prefer apply here, but seen both\n\n;;;;; EXAMPLE\n(map (partial fizzbuzz targets) (range 1 20))\n => (\"1\" \"2\" \"fizz\" \"4\" \"buzz\" \"fizz\" \"baz\" \"8\" \"fizz\" \"buzz\" \"11\" \"fizz\" \"13\" \"baz\" \"fizzbuzz\" \"16\" \"17\" \"fizz\" \"19\" \"buzz\")\n</code></pre>\n\n<p>There's an even more idiomatic way to rewrite the <code>(if (empty? matches)...)</code> bit:</p>\n\n<pre><code>(if matches\n (apply str matches)\n (str n))\n</code></pre>\n\n<p>Lazy sequence style. Consider <em>fizzbuzz</em> and <em>targets</em> are already defined:</p>\n\n<pre><code>(defn lazy-fizzbuzz\n ([targets n]\n (lazy-seq\n (cons (fizzbuzz targets n)\n (lazy-fizzbuzz targets (inc n)))))\n ([targets]\n (lazy-fizzbuzz targets 1)))\n\n;;;;; EXAMPLES\n(take 20 (lazy-fizzbuzz targets))\n => (\"1\" \"2\" \"fizz\" \"4\" \"buzz\" \"fizz\" \"baz\" \"8\" \"fizz\" \"buzz\" \"11\" \"fizz\" \"13\" \"baz\" \"fizzbuzz\" \"16\" \"17\" \"fizz\" \"19\" \"buzz\")\n\n;; You can also specify an initial n\n(take 20 (lazy-fizzbuzz targets 20))\n => (\"buzz\" \"fizzbaz\" \"22\" \"23\" \"fizz\" \"buzz\" \"26\" \"fizz\" \"baz\" \"29\" \"fizzbuzz\" \"31\" \"32\" \"fizz\" \"34\" \"buzzbaz\" \"fizz\" \"37\" \"38\" \"fizz\")\n\n;; which is the same as...\n(take 20 (drop 19 (lazy-fizzbuzz targets)))\n => (\"buzz\" \"fizzbaz\" \"22\" \"23\" \"fizz\" \"buzz\" \"26\" \"fizz\" \"baz\" \"29\" \"fizzbuzz\" \"31\" \"32\" \"fizz\" \"34\" \"buzzbaz\" \"fizz\" \"37\" \"38\" \"fizz\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T22:23:58.620",
"Id": "13654",
"ParentId": "13634",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:09:02.257",
"Id": "13634",
"Score": "4",
"Tags": [
"clojure",
"fizzbuzz"
],
"Title": "Higher-order FizzBuzz in Clojure"
}
|
13634
|
<p>I built my code according to the algorithm provided in <a href="http://www.youtube.com/watch?v=y_G9BkAm6B8" rel="nofollow">this YouTube video</a>. Please review it and help me find any problems. It definitely takes a lot longer than the <code>qsort()</code> function in C++. But the algorithm I use should be just as fast. Can anyone find problems?</p>
<pre><code>#include <iostream>
#include <time.h>
using namespace std;
void randomize( int* array, int size );
void qsort( int* array, int leftbound , int rightbound );
void swap( int &a, int &b );
void output( int* array, int size );
int main()
{
//declare array
int array[100];
//get size of the array
int size = sizeof(array)/sizeof(int);
//randomize value
randomize(array, size);
//start the quicksort algorithm
qsort(array, 0, size-1 );
//output the array
output(array, size);
return 0;
}
void randomize( int* array, int size )
{
srand((int)(time(0)));
for ( int i = 0 ; i < size ; i++ ) {
array[i] = rand();
}
}
void output( int* array, int size )
{
for ( int i = 0 ; i < size ; i++ ) {
cout << array[i] << endl;
}
}
void qsort( int* array, int leftbound , int rightbound )
{
if (rightbound > leftbound) {
int pivot = array[leftbound + (rand() % (rightbound - leftbound + 1))];
int leftposition = leftbound;
int rightposition = rightbound;
while ( leftposition != rightposition ) {
while ( array[leftposition] < pivot ) {
leftposition++;
}
while ( array[rightposition] > pivot ) {
rightposition--;
}
swap ( array[leftposition], array[rightposition] );
}
qsort( array, 0, leftposition - 1 );
qsort( array, leftposition + 1, rightbound );
}
}
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
</code></pre>
|
[] |
[
{
"body": "<p>The first major problem I see is that you're not considering <code>rightposition</code> when incrementing <code>leftposition</code> and vice versa. This can cause L and R to cross, which will cause additional unnecessary swaps:</p>\n\n<pre><code>pivot value 7\n\n4,7,3,9,6,2,8,1\n L R \n4,7,3,9,6,2,8,1\n L R //<--this is the last swap that should happen, but L < R\n4,1,3,9,6,2,8,7\n L //...so L moves to the next value greater than the pivot\n4,1,3,2,6,9,8,7\n R L //...and R moves to the next value less than the pivot\n4,1,3,2,6,9,8,7\n R L //...which are swapped incorrectly\n4,1,3,2,9,6,8,7\n</code></pre>\n\n<p>I'm going to assume that the != in the main pivoting loop is a typo, because combined with the lack of checking that the positions don't cross, the positions would be incremented beyond the ends of the array and the whole thing would error out.</p>\n\n<p><code>leftposition</code> and <code>rightposition</code> should NEVER cross. In addition, even if they don't and you miraculously end up with both leftpos and rightpos on the same element (which would have to be the pivot), you swap that element with itself unnecessarily; don't do that.</p>\n\n<p>Finally, in your code the \"left half\" call always starts at index zero; that means that the left-half call that branches from all right-half calls will scan through the entire left-hand side of the array, not just of the half it should have been given. Because the left half is sorted first, there should be no swaps, but it still has to scan through all those elements, which makes the right-hand half of the algorithm approach <em>O</em>(N<sup>2</sup>) complexity.</p>\n\n<p>Try this:</p>\n\n<pre><code>void qsort( int* array, int leftbound, int rightbound )\n{\n if (rightbound <= leftbound) return; //reduce nesting\n\n int pivotIndex = leftbound + (rand() % (rightbound - leftbound + 1);\n int pivot = array[pivotIndex];\n\n //move the pivot value out of the way; we will discover where it goes\n swap(array[pivotIndex], array[rightbound]);\n\n int leftposition = leftbound;\n int rightposition = rightbound-1;\n\n //you could use the != here if you really wanted, WITH the changes inside the loop\n while ( leftposition < rightposition ) \n {\n //don't move leftpos past rightpos\n while ( array[leftposition] < pivot && leftposition < rightposition) \n leftposition++;\n\n //ditto\n while ( array[rightposition] > pivot && rightposition > leftposition )\n rightposition--;\n\n //don't swap if the two positions have merged\n if(leftposition < rightposition)\n swap ( array[leftposition], array[rightposition] );\n }\n\n //now, swap the pivot element back in; leftposition is its proper location.\n swap(array[rightbound], array[leftposition]);\n\n //No matter what, leftposition (and rightposition) will be at an element \n //that should be to the right of the pivot, so the swap works. \n //Trace it out yourself if you don't believe me.\n\n //here's your main inefficiency; you were always starting from index 0 \n //on the left side, meaning that the call for the \"left half\" of all \n //\"right half\" calls scans most of the array redundantly.\n qsort( array, leftbound, leftposition - 1 );\n qsort( array, leftposition + 1, rightbound); \n}\n</code></pre>\n\n<p>I'm sure there are some additional micro-optimizations that could be made here:</p>\n\n<ul>\n<li>since we're making the leftpos vs rightpos check in all the right places, we could use != instead of < everywhere which would probably be faster.</li>\n<li>The prefix increment operation is performed assuming that the existing value isn't needed for any further operation, and so it just happens, making it faster than the postfix increment.</li>\n</ul>\n\n<p>However, the algorithm above will perform correctly which is the primary goal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:18:42.713",
"Id": "13641",
"ParentId": "13635",
"Score": "2"
}
},
{
"body": "<p>Please stop using:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It may seem like a time saver. But for anything that isn't a toy program, it causes problems with collisions. So, it is a bad habit to get into. Stop before it becomes a habit.</p>\n\n<p>You have alternatives.<br>\nYou can selectively bring stuff into the current scope:</p>\n\n<pre><code>using std::cout;\nusing std::vector;\n</code></pre>\n\n<p>Alternatively (my preference) you prefix stuff in the the standard library with <code>std::</code>. The name std was chosen so it was short enough that people would not be hampered with typing it.</p>\n\n<p>Prefer to use the C++ version of the headers:</p>\n\n<pre><code>#include <time.h>\n// Prefer\n#include <ctime>\n</code></pre>\n\n<p>Note: This also puts the functions in the standard namespace.</p>\n\n<p>This is correct:</p>\n\n<pre><code>int size = sizeof(array)/sizeof(int);\n</code></pre>\n\n<p>But it makes the code brittle. If you change the type of the array. You also need to remember to change type here in the size expression. It is best to let the compiler deduce this so use:</p>\n\n<pre><code>int size = sizeof(array)/sizeof(array[0]);\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>qsort(array, 0, size-1 );\n</code></pre>\n\n<p>Here you are making right bound point at the rightmost item. In C++ it is so common that the end points one past the end of the data it may make the code slightly harder to grok. I would stick with the standard convention of pointing one past the end. This means there will be some adjustment in your qsort but not that much and it makes it easier for C++ users to read.</p>\n\n<p>Prefer pre-increment:</p>\n\n<pre><code>++leftposition; // rather than leftposition++;\n</code></pre>\n\n<p>Though it makes no difference in this situation. There are situations where it can. So it one of those habits you should get into. Then when the types of objects are changed you do not need to search your code to make sure you are using the efficient version you know you used the efficient version automatically.</p>\n\n<p>Your test for a sortable array is not aggressive enough:</p>\n\n<pre><code>if (rightbound > leftbound) {\n</code></pre>\n\n<p>You only don't sort if the array is zero length. Which may potentially lead to long recursion as you randomly choose a pivot point that always dives stuff to one side (luckily your non standard code below saved you by always leaving the pivot off subsequent sorts).</p>\n\n<p>The real answer is you only need to sort arrays that have a size >= 2. (size zero and one are already sorted).</p>\n\n<pre><code>if ((rightbound - leftbound /* +1 depending on if you rightbound is one past or not*/ ) >= 2)\n</code></pre>\n\n<p>Small difference from a standard implementation here:<br>\nWhich can potentially give you an infinite loop.</p>\n\n<pre><code> while ( array[leftposition] < pivot ) {\n leftposition++;\n }\n while ( array[rightposition] > pivot ) {\n rightposition--;\n }\n</code></pre>\n\n<p>What happens if the value is equal to the pivot.\nIn that case it will go to a random side. Also if both left and right side hit a value that is equal to pivot then you will swap them and restart the loop which will do nothing swap them and restart the loop (etc)</p>\n\n<pre><code> while ( array[leftposition] <= pivot ) {\n leftposition++;\n }\n while ( array[rightposition] > pivot ) {\n rightposition--;\n }\n</code></pre>\n\n<p>Your left bound of the first recursive call is wrong.</p>\n\n<pre><code> qsort( array, 0, leftposition - 1 );\n qsort( array, leftposition + 1, rightbound );\n</code></pre>\n\n<p>Should be leftbound.</p>\n\n<pre><code> qsort( array, leftbound, leftposition - 1 );\n qsort( array, leftposition + 1, rightbound );\n</code></pre>\n\n<p>Since there can potentially be more than one value equal to pivot. Maybe you can remove the all from the side you put them in.</p>\n\n<p>You need to look at the standard libs.</p>\n\n<p>We have a std::swap()</p>\n\n<pre><code>void swap(int &a, int &b)\n\n// use \nstd::swap(val1, val2)\n</code></pre>\n\n<p>We have a way to print stuff:</p>\n\n<pre><code>void output( int* array, int size )\n\n// use\nstd::copy(std::begin(array), std::end(array), std::ostream_iterator<int>(std::cout, \"\\n\")); \n</code></pre>\n\n<p>We have a way to generate values:</p>\n\n<pre><code>void randomize( int* array, int size )\n\n// use\ngenerate(std::begin(array), std::end(array), ::rand);\n</code></pre>\n\n<p>This is what I got:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <ctime>\n\nvoid qsort( int* array, int leftbound , int rightbound );\n\nint main()\n{ \n //declare array\n int array[100];\n\n //get size of the array\n int size = sizeof(array)/sizeof(array[0]);\n\n //randomize value\n std::srand(std::time(NULL));\n std::generate(std::begin(array), std::end(array), std::rand);\n\n //start the quicksort algorithm\n qsort(array, 0, size);\n\n //output the array\n std::copy(std::begin(array), std::end(array), std::ostream_iterator<int>(std::cout, \"\\n\"));\n}\n\nvoid qsort( int* array, int leftbound , int rightbound )\n{\n if ((rightbound - leftbound) >= 2)\n { \n int pivot = array[leftbound + (rand() % (rightbound - leftbound))];\n int leftposition = leftbound;\n int rightposition = rightbound - 1;\n\n while ( leftposition < rightposition )\n { \n while ((array[leftposition] <= pivot) && (leftposition < rightposition))\n { ++leftposition;\n } \n while ((array[rightposition] > pivot ) && (leftposition < rightposition))\n { --rightposition;\n } \n std::swap(array[leftposition], array[rightposition]);\n }\n // At least the pivot point will be on the left hand side.\n // This will also be the largest value. So move the leftposition back\n // to remove all the pivot points.\n while(((leftposition-1) > leftbound) && (array[leftposition-1] == pivot))\n { --leftposition;\n }\n qsort(array, leftbound, leftposition-1); // leftposition is one past the end of the left\n qsort(array, rightposition+1, rightbound); // Thus at the start of the right.\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T21:23:25.877",
"Id": "22091",
"Score": "0",
"body": "+1 but omitting elements equal to the pivot is not only common but actually *required* for strong runtime guarantees, if I recall correctly from the Bentley & McIlroy paper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T00:30:38.240",
"Id": "22096",
"Score": "0",
"body": "@KonradRudolph: Yep you are correct. With a badly chosen pivot each time it could potentially recurce forever if you don't take the pivot values. Have changed the above to correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T10:06:14.960",
"Id": "195580",
"Score": "0",
"body": "Why prefer `<ctime>` over `<time.h>`? The first puts the symbols into namespace std and maybe also in global scope, the latter the other way around. I'm missing any advantage at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T10:16:18.133",
"Id": "195583",
"Score": "0",
"body": "Also, we have neither `std::begin` nor `std::end` for pointers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T15:08:41.840",
"Id": "195677",
"Score": "0",
"body": "@Deduplicator: Putting things in a namespace is an advantage unto itself. So making sure they are in `std` is useful. Also consistency across C++ programs. Why not use the C++ version of the library."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T15:10:14.743",
"Id": "195678",
"Score": "0",
"body": "@Deduplicator: In the context where `std::begin()` and `std::end()` are used `array` is not a pointer but an array. The OP uses function where the array decays into a pointer (and thus looses type information; we want to avoid decay into pointers)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T16:07:02.083",
"Id": "195688",
"Score": "0",
"body": "@Loki: Sure, in the context it's actually *used* later it's an array, but that's somewhat divorced from the place you introduce it, so might merit clarification. And regarding having the symbols in the namespace, I would certainly concurr iff they wouldn't haphazardly also appear without."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:20:40.453",
"Id": "13646",
"ParentId": "13635",
"Score": "10"
}
},
{
"body": "<p>similar to the last one below is a list of differences</p>\n\n<ul>\n<li><p>Accounted for the condition where both left and right point to the pivot in this case you have the code keep swapping endlessly, this would happen in the case of an array 100 100 5 4 3 100 where say value 100 is the pivot at slot 1, then slot zero and slot 5 would never move since you are checking just operator < so you need to move one of the pointers</p></li>\n<li><p>Also removed the additional 2 swaps to move the pivot out and back into the list as this is not needed.</p></li>\n<li><p>Additionally, I am not using c++11 so I did this using c++98 removing the c++11 references in the other version</p></li>\n<li><p>Kept the same syntax of allowing the end of the function to be one more than the end of the data to be consistent with other stl like calls.</p></li>\n<li><p>Finally just added some logging so that someone can follow what is happening when running the code.</p></li>\n</ul>\n\n<p>Hope you like this version, enjoy splitting lists, moving pointers, and recursing. </p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <ctime>\n\nvoid quicksort ( int array[], int start, int end);\nvoid printArray ( int array[], size_t N, const int p = -1);\nvoid randomize (int array[], size_t N);\n\nint main ( int argc, char *argv[])\n{\n const int SIZE = 6;\n int x[SIZE];\n std::cout << \"Starting Quick Sort\" <<std::endl;\n randomize(x, SIZE);\n std::cout << \"Array before quick sort\" << std::endl;\n printArray(x,SIZE);\n quicksort(x,0,SIZE);\n std::cout << \"Array after quick sort\" << std::endl;\n printArray(x,SIZE);\n}\n\n\nvoid quicksort (int array[], int start, int end )\n{\n static unsigned int calls = 0;\n std::cout << \"QuickSort Call #: \" << ++calls << std::endl;\n\n //function allows one past the end to be consistent with most function calls\n // but we normalize to left and rightbounds that point to the data\n\n int leftbound = start;\n int rightbound = end - 1;\n\n if (rightbound <= leftbound )\n return;\n\n int pivotIndex = leftbound + (rand() % (end - leftbound));\n int pivot = array[pivotIndex];\n\n std::cout << \" Pivot: \" << \"[\" << pivotIndex << \"] \" << pivot << std::endl;\n printArray (array,end,pivot);\n\n int leftposition = leftbound;\n int rightposition = rightbound; // accounting for pivot that was moved out\n\n while ( leftposition < rightposition )\n {\n while ( leftposition < rightposition && array[leftposition] < pivot )\n ++leftposition;\n\n while ( rightposition > leftposition && array[rightposition] > pivot )\n --rightposition;\n\n if(leftposition < rightposition)\n {\n if (array[leftposition] != array[rightposition])\n {\n std::swap(array[leftposition],array[rightposition]);\n std::cout << \" Swapping RightPosition: \" << rightposition << \" and LeftPosition: \" << leftposition << std::endl;\n printArray (array,end,pivot);\n }\n else\n ++leftposition;\n }\n }\n std::cout << \"Array at the end of QuickSort Call #: \" << calls << std::endl;\n printArray (array,end,pivot);\n\n // sort leaving the pivot out\n quicksort (array,leftbound, leftposition); // leftposition is at the pivot which is one past the data\n quicksort (array,leftposition + 1,end); // leftposition + 1 is past the pivot till the end\n}\n\n\nvoid printArray ( int array[], size_t N, const int p)\n{\n//output the array\n for ( unsigned int i = 0; i < N; ++i)\n {\n if (array[i] == p)\n {\n std::cout << \" [\" << i << \"] *\" << array[i] << \"*\";\n }\n else\n {\n std::cout << \" [\" << i << \"] \" << array[i];\n }\n }\n std::cout << std::endl;\n}\n\nvoid randomize (int array[], size_t N)\n{\n static const unsigned int RANDSIZE = 100;\n srand(time(0));\n for ( unsigned int i = 0; i < N; ++i)\n {\n array[i]=rand() % RANDSIZE + 1;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:06:29.360",
"Id": "27376",
"ParentId": "13635",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:11:25.227",
"Id": "13635",
"Score": "6",
"Tags": [
"c++",
"sorting",
"quick-sort"
],
"Title": "My version of C++ quicksort"
}
|
13635
|
<p>Our company uses an old version of JAXB so it does not allow generics. Other than that, I am using recursive calls because <code>Rows</code> can have subrows and I want to find out if any of the rows for the given column id <code>i</code> has any values. </p>
<p>I am interested to know if I got the recursion right. </p>
<pre><code>private static boolean anyCellHasValue(CommonRowType row, int i) {
CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);
if(!CELL_EMPTY.equals(cell.getType())) {
return true ;
}
if (row.getChildren() != null && row.getChildren().getRowData() != null &&
!row.getChildren().getRowData().isEmpty()) {
for (int k = 0; k < row.getChildren().getRowData().size(); k++) {
if(anyCellHasValue((CommonRowType) row.getChildren().getRowData().get(k), i)) {
return true;
}
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>This site is more about the readability and structure of code rather than actual correctness. I will comment on that and maybe a more readable program will help you find any potential errors?</p>\n\n<p>I would recommend that you:</p>\n\n<ul>\n<li>Extract complex if statements to their own methods describing the test</li>\n<li>Use the new style java iteration instead of the old for loop</li>\n<li>Reduce the block nesting level by returning early when you know you have a negative match</li>\n<li>Use good naming for all variables. In this case the variable i desperately needs a better name!</li>\n</ul>\n\n<p>This should produce (sans renaming of i) code that look something like this: (not compiled or tested in any way :))</p>\n\n<pre><code>private static boolean anyCellHasValue(CommonRowType row, int i) {\n if (isNonEmptyCellType(row, i)) {\n return true;\n }\n\n if (!hasChildren(row)) {\n return false;\n }\n\n for (CommonRowType childRow : row.getChildren().getRowData()) {\n if (anyCellHasValue(childRow, i)) {\n return true;\n }\n }\n\n return false;\n}\n\nprivate static boolean isNonEmptyCellType(CommonRowType row, int i) {\n CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);\n return !CELL_EMPTY.equals(cell.getType()));\n}\n\nprivate static boolean hasChildren(CommonRowType row) {\n return row.getChildren() != null \n && row.getChildren().getRowData() != null \n && !row.getChildren().getRowData().isEmpty();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T19:04:01.863",
"Id": "13649",
"ParentId": "13636",
"Score": "4"
}
},
{
"body": "<p>I'd improve <em>@kyck-ling</em>'s <code>hasChildren</code> method a little bit:</p>\n\n<pre><code>private static boolean hasChildren(CommonRowType row) {\n final Children children = row.getChildren();\n if (children == null) {\n return false;\n }\n\n final RowData rowData = children.getRowData();\n if (rowData == null) {\n return false;\n }\n if (rowData.isEmpty()) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Now it uses <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clauses</a> and a few local variables to remove some duplication like <code>row.getChildren().getRowData()</code>.\nAnyway, it still violates <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">the Law of Demeter</a>. A better solution is to create a <code>hasChildren</code> method in the <code>Children</code> class. See also: <a href=\"http://c2.com/cgi/wiki?FeatureEnvySmell\" rel=\"nofollow\">Feature envy smell</a>.</p>\n\n<p>Another interesting point that that it seems that the <code>children.getRowData()</code> returns a collection which could be <code>null</code>. It reminds me the <em>Item 43: Return empty arrays or collections, not nulls</em> chapter of <em>Effective Java, 2nd Edition</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T21:26:14.963",
"Id": "22092",
"Score": "0",
"body": "maybe replace the last two if-clauses with return rowData != null && !rowData.isEmpty();"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T22:59:06.063",
"Id": "22095",
"Score": "1",
"body": "@kyck-ling I'm not sure about replacing those. I tend to find double negatives quite hard to follow without doing a double take. Perhaps !(rowData == null || rowData.isEmpty()) or put it into it's own method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T06:35:37.893",
"Id": "22100",
"Score": "0",
"body": "@dreza its not a double negative but sure, there are other ways to write it. My main point was that seven rows of code could be one row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T23:09:45.943",
"Id": "22121",
"Score": "0",
"body": "@kyck-ling: Source code storage costs almost nothing but developer time is expensive, so I'd choose the cheaper one, which is easier to understand, therefore easier (cheaper) to maintain and less error-prone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T00:13:18.753",
"Id": "22122",
"Score": "0",
"body": "@palacsint I'm not talking about storage but readability (and thus developer time) same as you. But I guess this boils down to personal choice more than anything else."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T20:49:36.650",
"Id": "13651",
"ParentId": "13636",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:21:03.003",
"Id": "13636",
"Score": "2",
"Tags": [
"java",
"recursion",
"jaxb"
],
"Title": "Finding if value exists in any column recursively"
}
|
13636
|
<p>I am at a loss as to how to simplify the following two functions that <strong>share variables without polluting the global namespace</strong>. (Partial code for a carousel). I would like to streamline it.</p>
<p>Note:
snapshotCheck(); is called once on window load.
snapshotScroll(); is called on click events.</p>
<pre><code>//FIRST FUNCTION
function snapshotScroll(amount, refresh) {
var imageSum = snapshots.total_entries; //Inner Box
var dl = $j('#snapshots')[0]; //Outer Box
var c = $j('#photo-carousel')[0];
var l = ((dl.style.left) ? parseInt(dl.style.left) : 0);
var pos = l + parseInt(amount);
var pos0 = pos;
var viewport = $j('#photo-carousel')[0];
var inView = Math.floor(viewport.clientWidth / snapshotWidth); //How many snapshots in view
var maxPos = (imageSum * -snapshotWidth);
if(pos > 0) { // prevent left side from going too far right
pos = 0;
} else if(pos < c.clientWidth - dl.clientWidth) {
pos = c.clientWidth - dl.clientWidth;
if(pos == 8) { // To account for 8px variation, set position to initial pos0 for animation.
pos = pos0;
}
}
$j(dl).animate({"left" : pos}, 1200); // Animate scroll
// Toggle "filter" class (reduces opacity) depending on position.
// if position is max, toggleClass of #next.
// if position is 0, toggleClass of #prev.
$j('#next').toggleClass('filter', (pos - maxPos) == (c.clientWidth))
$j('#prev').toggleClass('filter', (pos >= 0))
if(imageSum > inView) {
dl.style.width = maxPos * -1 + "px";
}
} // end snapshotScroll();
//SECOND FUNCTION
function snapshotCheck(){ // Check if snapshot is in view
var c = $j('#photo-carousel')[0]; // #snapshots parent container
var dl = $j('#snapshots')[0]; // ol container holding snapshots
var imageSum = snapshots.total_entries;
var l = ((dl.style.left) ? parseInt(dl.style.left) : 0);
var maxPos = (imageSum * -snapshotWidth);
var setWidth;
var viewport = $j('#photo-carousel')[0]
var inView = Math.floor(viewport.clientWidth / snapshotWidth); // # of snapshots in view
(setWidth = function(){ // set initial width in order to retrieve position of currentSnapshot
if(imageSum > inView) {
dl.style.width = maxPos * -1 + "px";
}
})();
if(typeof currentSnapshot != 'undefined') {
var aSnapshot = $j('#' + currentSnapshot.snapshot.id + '_slide'); // jQuery object, array
var theSnapshot = $j('#' + currentSnapshot.snapshot.id + '_slide')[0]; // first DOM element
var pos = -aSnapshot.position().left; // a negative value, set to first position carousel (in view)
$j(dl).animate({"left" : pos}, 1200); // Animate scroll
}
$j('#next').toggleClass('filter', (pos - maxPos) == (c.clientWidth))
$j('#prev').toggleClass('filter', (pos >= 0))
} // end snapshotCheck();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:55:43.950",
"Id": "22073",
"Score": "0",
"body": "This code doesn't look complete enough to review. [Here are some tips you can use to make it better though.](http://codereview.stackexchange.com/questions/11233/optimizing-and-consolidating-a-big-jquery-function/11235#11235)"
}
] |
[
{
"body": "<p>If those variables are constant (ie, they don't change between invocations of of the functions), you can put the functions and variables into a closure:</p>\n\n<pre><code>(function() {\n //FIRST FUNCTION\n var imageSum = snapshots.total_entries; //Inner Box\n var dl = $j('#snapshots')[0]; //Outer Box\n ...\n window.snapshotScroll = function (amount, refresh) {\n ...\n } // end snapshotScroll();\n\n //SECOND FUNCTION\n window.snapshotCheck = function (){ // Check if snapshot is in view\n ...\n } // end snapshotCheck();\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T08:55:26.247",
"Id": "22072",
"Score": "1",
"body": "Actually this would work quite fine even if the functions change the variables."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T06:43:05.810",
"Id": "13638",
"ParentId": "13637",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13638",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T06:32:40.973",
"Id": "13637",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Shorten JavaScript Code due to duplicate variables without polluting global namespace"
}
|
13637
|
<p>I'm VERY new to PHP and have begun writing a basic login for a website that uses data from a Microsoft SQL server to display information on the web. Below are 3 snippets of code (two functions from the same file and one controller file that calls them.)</p>
<h1>Connect to MSSQL to validate user (from phplib)</h1>
<p>With this, I take the login credentials stored in a MySQL database, and use them to connect to a MSSQL database. (As seen in the "createUser" case of the controller).</p>
<pre><code>function PDOConn(&$IPAddress, &$userAdmin, &$passAdmin, &$Database, $sess_client)
{
global $host,
$username,
$password,
$db_name,
$tbl_name_client;
try {
$conn = new PDO("mysql:host=$host; dbname=$db_name", $username, $password);
$stmt = $conn -> prepare("SELECT stuff
FROM $tbl_name_client
WHERE client = :clientId");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute(array('clientId' => $sess_client));
$result = $stmt->fetchAll();
if ( count($result) == 1 )
{
foreach($result as $row)
{
$IPAddress = $row['IP'];
$userAdmin = $row['Username'];
$passAdmin = $row['Password'];
$Database = $row['database'];
}
}
else if (count($result) > 1)//Primative error handling
{
exit( "<h1>There are multiple rows in the clients table with the same clientID, which is really strange...</h1>");
}
else
{
exit( "<h1>ID isn't in the table. No rows returned. Sorry bro...");
}
}
catch(PDOException $e)
{
echo 'ERROR: '. $e->getMessage();
}
}
</code></pre>
<h1>Check Function (from phplib)</h1>
<p>This is the function that get called from the main login screen.
function PDOCheckLogin($myusername, $mypassword)
{
global $host,
$username,
$password,
$db_name,
$tbl_name;</p>
<pre><code> try {
$conn = new PDO("mysql:host=$host; dbname=$db_name", $username, $password);
$stmt = $conn->prepare("SELECT * FROM $tbl_name WHERE username = :myusername");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute(array('myusername' => $myusername));
$result = $stmt->fetchAll();
if ( count($result) == 1 )
{
foreach($result as $row)
{
$validpass = $row['password'];
$hashsalt = substr($validpass, 0, 128); //get the salt from the front of the hash
$testhash = hash('sha512', $hashsalt.$mypassword);
$testhash = $hashsalt.$testhash;
if($testhash === $validpass)
{
$sess_empno = $row['employeeno'];
$sess_client = $row['ClientId'];
$sess_username = $row['username'];
$_SESSION['sess_empno'] = $sess_empno;
$_SESSION['sess_client'] = $sess_client;
$_SESSION['sess_username'] = $sess_username;
header("location:../index.php");
}
else
{
exit("<h1>WRONG PASSWORD >:(</h1>");
}
}
}
else if (count($result) > 1)
{
exit( "<h1>There are multiple users with that username in the database...Whoops...</h1>");
}
else
{
exit( "<h1>That's not a username...</h1>");
}
}
catch(PDOException $e) {
echo 'ERROR: '. $e->getMessage();
}
}
</code></pre>
<h1>My...Well Whatever this is...Controller I guess.</h1>
<p>This receives posts from various forms and then calls the correct functions.</p>
<pre><code><?php
ob_start();
include_once('../phplib.php');
session_start();
$form = $_POST['form'];
switch ($form) {
case 'login': //When the User Logs in
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
PDOCheckLogin($myusername, $mypassword);//Do this function
break;
case 'createUser': //MSSQL verification for the user for user creation
$client=$_POST['clientId'];
$email=$_POST['email'];
PDOConn($IPAddress, $userAdmin, $passAdmin, $Database, $client);//Get the login credentials from the database
$Login = $userAdmin;
$Password = $passAdmin;
$conn=mssql_connect($IPAddress,$Login,$Password); //Connect to the database
if (!$conn )
{
die( print_r("Unable to connect to server", true));
}
mssql_select_db($Database, $conn);
$sql="SELECT stuff FROM table WHERE email = '$email'"; //Make sure your email is in the MSSQL database
$rs=mssql_query($sql);
$count=mssql_num_rows($rs);
if ($count == 0 || $count > 1)
{
echo("Email Not Found or Valid");//You liar...
}
else{
while ($row = mssql_fetch_array($rs))
{
$EmpNo = $row['employee_number'];
}
}
PDONewUser($EmpNo, $email, $client, $tempSess);
break;
default:
# code...
break;
}
ob_end_flush();
?>
</code></pre>
<p>I'm not thrilled with the state of my mssql_connect() code but I really don't know the alternative as the PDO drivers are extremely complicated and, from what I gather, experimental.</p>
<p>I salt my passwords (so I'm ahead of LinkedIn) but that's about it. I'm looking into measures to stop Brute force and XSS but I want to make sure this isn't completely broken first. </p>
<p>Is this secure? Is there a better way to be doing thing? OOP probably would be a smart move but I really do struggle with the concepts. I wrote my first line of HTML code in February of this year and had no real computer experience prior to that.</p>
<p>My Controller file currently points to 5 different cases (better than my old approach of five files point to different functions, which in turn was better than 5 files that didn't even have functions, they just ran procedural code and then redirected as necessary.) Is that bad coding?</p>
<p>Any suggestions would be great. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:39:20.487",
"Id": "29848",
"Score": "0",
"body": "Minor formatting issue -- hit enter after the line \"This is the function that get called from the main login screen.\""
}
] |
[
{
"body": "<p>First off, welcome to Code Review. Answers here may be a while in coming. Usually I'm better about getting to these questions but I've been extremely busy the last week and so missed this. Hopefully you're still watching this.</p>\n\n<p>Learning MySQL is a great way to get comfortable with the idea of SQL, but PDO or MySQLi are the ways to go. MySQL is soon to be deprecated. So heads up. To the best of my knowledge, PDO is not expiramental, but then again, my knowledge is limited when it comes to SQL. That's not to say that my answer won't be full of good information, only that I can't help you with specifics in this regard. I've helped people with PDO and MySQLi code on here before without needing to know how it works. I do normally suggest they seek further opinions, but that's a general disclaimer about anything seen on the internet.</p>\n\n<p>Anyways, without further ado...</p>\n\n<p><strong>Globals and Security</strong></p>\n\n<p>Are bad. If you want a piece of information to be available across scripts, then either pass it through POST, GET, SESSION, or COOKIE. Which depends on the type of information being passed. For instance, anything private should only be passed via post, and is usually done via customer to server and you will have no control over it. Anything public can be passed with get, and saved with cookies. Anything session specific to a customer should be passed with sessions.</p>\n\n<p>So your comment about being ahead of the game compared to LinkedIn was wrong. Your passwords are freely available on the default global environment, unsalted and unprotected. Besides, I think the specific instance with LinkedIn was not that they weren't salting their passwords, it was that they were using SHA to do it. Though I may be misremembering my facts here. I am by no means a security expect, so, if you'll pardon the pun, take my advice with a grain of salt.</p>\n\n<p><strong>Functions and OOP</strong></p>\n\n<p>Functions should be specialized. In other words they should do only one thing, and do it well. So <code>PDOConn()</code> should only be worried about connecting to the database. A separate function should be concerned with preparing and executing statements. This is the first step to learning OOP, a subject that baffles many. Once you are familiar with this concept, and the DRY principle, then you might be ready for OOP.</p>\n\n<p>Naming conventions say that only the first letter in every word should be capitalized and only on interior words. At least when using camelcase. So your function should actually be <code>pdoConn()</code>. Only classes should capitalize the first letter in the first word, and even then it would only be <code>PdoConn()</code>. Think of it like this. A class is an object, or noun, a function is an action, or verb. You capitalize nouns, you don't capitalize verbs.</p>\n\n<p><strong>Exiting a Script</strong></p>\n\n<p>Exit is used to tell PHP to cancel a script. If you want to set some output, you should do so before calling exit, usually with echo, though some people prefer print. While the way you are doing it is technically OK, it is usually better to separate the tasks.</p>\n\n<p><strong>Storing and Retrieving Passwords</strong></p>\n\n<p>I can't imagine a reason to have a password stored on every row of a table unless that table was the user credentials table. In which case you should not be traversing the entire table to get a single login, you should instead retrieve the row specific to your user and compare their information to that single row. Besides, on the off chance that two customers share a password, you will be faced with the real possibility of a user getting the wrong account credentials.</p>\n\n<p><strong>Breaking the Loop</strong></p>\n\n<p>When you have found what you were looking for in a loop, you should break from it to prevent further iterations. This saves processing power. Now, before you say, \"But I did, look at that <code>header()</code>!\", know that you did not. In order to properly terminate a script after calling a header with the location flag, you must also call the <code>exit()</code> function immediately afterwards, else the script will continue to run. Additionally, when using a header, it is proper to use an absolute path instead of the relative one.</p>\n\n<p><strong>Output Buffering</strong></p>\n\n<p>Asides from you calling an include before the <code>session_start()</code> I see no reason for this. You are not processing the information buffered, you are simply dumping it. I'd remove this buffer and just move the include to below the session.</p>\n\n<p><strong>Another Security Concern</strong></p>\n\n<p>You are using direct user input without validating or sanitizing it. This is a concern for XSS. If you have PHP version >= 5.2 you can use PHP's <code>filter_input()</code> function, for example:</p>\n\n<pre><code>$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_EMAIL );\n</code></pre>\n\n<p><strong>Controllers</strong></p>\n\n<p>I'm assuming you are talking about the OOP approach MVC here. A controller, normally, only focuses on one view (case). However, I can see that using the same controller for similar views, such as adding/removing a user, is understandable and I don't really see anything wrong with it. But I would limit that as much as possible. If the controllers start getting too large or difficult to follow, then you'll know you should start separating them. I wouldn't really worry about this yet, at least not until you have everything else sorted out. If this part works, leave it for now and come back to it when the rest does.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T20:57:31.763",
"Id": "22337",
"Score": "0",
"body": "I see what you're saying about a lot of this, but one thing that I can tell you didn't understand is that my MYSQL is used to store credentials for MICROSOFT SQL SERVER (Which I should probably stop referring to as MSSQL, my apologies.) I don't ever use mysql functions, but I am forced to use MSSQL functions (the PDO drivers for which I believe are experimental). One question is, for the MySQL connection credentials (as in, connecting to the servers DB), if I shouldn't use globals, what should I use instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:15:48.247",
"Id": "22340",
"Score": "0",
"body": "Ah, my bad, my dyslexia kicked in, that and I'm so used to seeing MySQL. Completely missed the difference. Thought it odd that you mentioned that then used PDO as well. No, MSSQL is the proper term for it, that was my mistake."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T20:48:26.580",
"Id": "13854",
"ParentId": "13639",
"Score": "2"
}
},
{
"body": "<h2>CSRF</h2>\n<p>Interesting fact: If I can get somebody to navigate to a webpage I control, then I can use their browser to mass-create users. I think they might be able to brute-force logins, but I'm not sure how to detect a successful login.</p>\n<p><a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)\" rel=\"nofollow noreferrer\">OWASP guide to CSRF</a></p>\n<h2>Salting</h2>\n<p>These days, site-specific salts are pretty much pointless. If somebody attacks the hashes for your site, it will be with a GPU, not a rainbow table. On the other hand, user specific salts still very much have a point - it means that if somebody wants to attack your passwords, they have to do it one account at a time.</p>\n<p>I can't tell if you use random per-user salts or not, because I don't see any code for producing that salt in the first place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-17T05:47:40.670",
"Id": "18728",
"ParentId": "13639",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T16:47:50.653",
"Id": "13639",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"security",
"sql-server"
],
"Title": "PHP Login/User Creation Validation Function"
}
|
13639
|
<p>My project has a central concept of a <code>Callback<T></code> which is defined very simply:</p>
<pre><code>public interface Callback<T> {
void call(T item) throws Exception;
}
</code></pre>
<p>This is used to enforce correct resource management (e.g. database connections, HTTP sessions) while still allowing the data to be streamed through.</p>
<p>This works very well for code that is written with it in mind, but occasionally we'll come to a point where we want to hook it into an external API that takes an Iterator rather than a Callback. This seems roughly analogous to an in-process UNIX pipe (with objects rather than bytes), so I'm referring to the operation as piping.</p>
<p>Unfortunately, the code required to implement it isn't very simple:</p>
<pre><code>/**
* Limited adapter from a {@link Callback} to an {@link Iterator}. Performs roughly the inverse operation of
* {@link #stream(Callback, Iterable)}. Requires two callbacks. The first is passed a Callback
* which is the 'source' end of the pipe. The second is passed an Iterator, the 'consuming' end of the pipe.
* Every element pushed into the source Callback will come out at the consuming Iterator. Due to the push-pull
* nature of this operation, the use of an auxiliary thread is required.
*
* <p>While in general we encourage writing all API producers and consumers to use Callbacks directly,
* it is occasionally desirable to interface with an Iterator-based API that is either mandated externally
* or is inconvenient to change.
*
* <p>The somewhat inconvenient method call signature (with everything wrapped again in Callbacks) is
* required to ensure correct resource management.
*
* <p>If the either thread is interrupted, the main thread terminates with an exception
* and the worker thread dies.
*
* @param fromSource invoked with the source Callback
* @param intoCallback invoked with the destination Iterator
* @param pipeName the name of the auxiliary thread
*/
@Beta
public static <T> void pipeToIterator(
final Callback<Callback<T>> fromSource,
final Callback<Iterator<T>> intoCallback,
final String pipeName)
throws InterruptedException
{
final SynchronousQueue<T> queue = new SynchronousQueue<T>();
@SuppressWarnings("unchecked") // Used only for == checks
final T poisonPill = (T) new Object();
final ExecutorService pipe = com.mogwee.executors.Executors.newSingleThreadExecutor(pipeName);
// Set when the child thread exits
final AtomicBoolean childThreadAborted = new AtomicBoolean();
// Thrown as a marker from the callback if the child thread unexpectedly exits
final Exception childTerminated = new Exception();
try {
pipe.submit(new Callable<Void>() {
@Override
public Void call() throws Exception
{
try {
// Read items off of the queue until we see the poison pill
QueueIterator<T> iterator = new QueueIterator<T>(queue, poisonPill);
intoCallback.call(iterator);
Iterators.getLast(iterator); // Consume the rest of the iterator, in case the callback returns early
return null;
} finally
{
childThreadAborted.set(true);
}
}
});
} finally { // Ensure we always shutdown the service so that we never leak threads
pipe.shutdown();
}
try {
// Offer items from the callback into the queue
fromSource.call(new Callback<T>() {
@Override
public void call(T item) throws Exception
{
// Check periodically if the child thread is dead, and give up
while (!queue.offer(item, CHILD_DEATH_POLL_INTERVAL_MS, TimeUnit.MILLISECONDS))
{
if (childThreadAborted.get())
{
throw childTerminated;
}
}
}
});
} catch (InterruptedException e) {
// Give up, let the finally block kill the worker
Thread.currentThread().interrupt();
throw e;
} catch (Exception e) {
if (e == childTerminated) { // The child thread died unexpectedly
throw new IllegalStateException("worker thread interrupted");
}
throw Throwables.propagate(e);
} finally {
try
{
if (!childThreadAborted.get())
{
queue.offer(poisonPill, POISON_PILL_GIVEUP_MS, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
} finally
{
pipe.shutdownNow();
}
}
}
/**
* Consume elements from a queue until a given poison pill is found.
*/
private static class QueueIterator<T> implements Iterator<T>
{
private SynchronousQueue<T> queue;
private T element;
private T poisonPill;
QueueIterator(SynchronousQueue<T> queue, T poisonPill)
{
this.queue = queue;
this.poisonPill = poisonPill;
}
@Override
public boolean hasNext()
{
ensureNext();
return element != poisonPill;
}
@Override
public T next()
{
ensureNext();
if (element == poisonPill)
{
throw new NoSuchElementException();
}
try {
return element;
}
finally {
element = null;
}
}
private void ensureNext()
{
if (element == null)
{
try
{
element = queue.take();
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
}
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
</code></pre>
<p>(the code, along with some unit tests, is also <a href="https://github.com/NessComputing/components-ness-core/pull/7/files" rel="noreferrer">on GitHub</a>, in case that's easier)</p>
<p>This is a lot of intricate threaded code. I'm generally pretty wary of writing code like this, but I've been unable to come up with much of a better approach. My question is twofold: Is there a better way to handle this, or perhaps a nicer way of writing the code? Failing that, I'm pretty sure that there's at least a few race conditions / errors hiding in here, so some code review would be much appreciated :-)</p>
<p>In case an example of how this is used helps:</p>
<pre><code>Callbacks.pipeToIterator(new Callback<Callback<UserAccount>>() {
@Override
public void call(Callback<UserAccount> callback) throws Exception
{
userClient.doQuery(Queries.<UserAccount>allItems(), callback);
}
}, new Callback<Iterator<UserAccount>>() {
@Override
public void call(Iterator<UserAccount> iter) throws Exception
{
searchService.updateIndex(iter);
}
}, "user-search-index-updater");
</code></pre>
|
[] |
[
{
"body": "<p>The code looks fine. Here are some small notes and questions which you may find useful.</p>\n\n<ol>\n<li><p>The code seems as a custom implementation of actor-based concurrency. It has some implementations (Akka is, for example) which you should check if you haven't seen them already. (In Venkat Subramaniam's book, <em>Programming Concurrency on the JVM: Mastering Synchronization, STM, and Actors</em>, there is a good introduction to Akka.)</p></li>\n<li><p>Have you considered using a queue which is not a <code>SynchronousQueue</code>? It might improve the throughput.</p></li>\n<li><p>I'd rename <code>childThreadAborted</code> to <code>childThreadFinished</code> since it will be <code>true</code> when it simply finishes.</p></li>\n<li><p>Do you instantiate the <code>childTerminated</code> exception early for the <code>e == childTerminated</code> check only? If that's the only reason I'd check the <code>childThreadFinished</code> boolean in the <code>catch</code> block and create the exception in the <code>while</code> loop with the proper stacktrace. It would help debugging if the exception contains a real stacktrace.</p></li>\n<li><p>Instead of the <code>childThreadFinished</code> flag you could check the <code>isDone()</code> method of the <code>Future</code> which is returned from the <code>pipe.submit</code> call.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T18:43:07.897",
"Id": "22778",
"Score": "1",
"body": "Thanks for the pointer to Akka, that looks very interesting! I'll probably not adopt it for this, but might use it in my next project..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T15:17:24.257",
"Id": "13889",
"ParentId": "13642",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13889",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:24:06.880",
"Id": "13642",
"Score": "5",
"Tags": [
"java",
"multithreading",
"callback"
],
"Title": "\"Piping\" from a callback to an Iterator"
}
|
13642
|
<p>I promise that I've done my reading on this topic. I've seen many suggestions and critiques, but I haven't seen the argument below critiqued. I'm not trying to beat a dead horse, but I don't think anyone's offered this one up yet:</p>
<p><code>x ||= y</code><br>
is functionally equivalent to<br>
<code>x = y unless x</code></p>
<p>The code below has been through 5 years of feature additions; hence the difference in coding style. An evaluation is a survey questionnaire. To determine which questions to present, first see if an evaluation ID is specified in the URL, then fall back on the evaluation the user should see (if any), then fall back on the evaluation configured for this site (if any).</p>
<pre><code>evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation ||= Evaluation.find(@user.id_of_required_evaluation)
evaluation = Evaluation.find(@site.id_of_required_evaluation) unless evaluation
</code></pre>
<p>This doesn't flow well visually. I'm at the point where I can use <code>||=</code> or <code>unless</code> and don't believe there to be any difference between the two.</p>
<p>Therefore, my question is: <i>Is there any reason to choose one of the below blocks over the other?</i></p>
<p>Option 1</p>
<pre><code>evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation ||= Evaluation.find(@user.id_of_required_evaluation)
evaluation ||= Evaluation.find(@site.id_of_required_evaluation)
</code></pre>
<p>Option 2</p>
<pre><code>evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation = Evaluation.find(@user.id_of_required_evaluation) unless evaluation
evaluation = Evaluation.find(@site.id_of_required_evaluation) unless evaluation
</code></pre>
<p>My apologies to the dead horse who again finds himself being beaten and to those who have to watch. If this is a stupid question, please consider the horse and beat me instead.</p>
|
[] |
[
{
"body": "<p>I think it really just comes down to opinion.</p>\n\n<p>I think using <code>||=</code> is better in this case, it's easier to glance at the code and see what it's intent is. When using the inline <code>if</code> or <code>unless</code>, I have to scan the whole line to know what is going on.</p>\n\n<pre><code>evaluation ||= Evaluation.find(@user.id_of_required_evaluation)\n</code></pre>\n\n<p>That said, I do like the inline <code>if</code> and <code>unless</code> with returns, since it reads nicely.</p>\n\n<pre><code>return false unless isSelected\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:30:58.880",
"Id": "22266",
"Score": "0",
"body": "I agree that `||=` reads better because, as a future developer debugging a problem, you can simply stop reading when you reach `||=` but you'd have to bounce all over the line to find and understand the `unless`. I've read the stuff that says \"there's no functional equivalent of ||=\" but I think I stumbled across it above and thought I'd post it here. And yeah, `return false unless isSelected` reads nicely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-05T04:54:23.383",
"Id": "208783",
"Score": "0",
"body": "Good answer. Just want to add that using `unless` the way OP suggests is very quirky. It only works 100% of the time in the inline form (because of the way Ruby defines variables). You would get a big surprise later if you would refactor it to the normal (condition first) way and `!defined?(evaluation)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T18:55:37.160",
"Id": "13648",
"ParentId": "13643",
"Score": "8"
}
},
{
"body": "<p>Well, it is subjective. :) so this is my understanding of the situation.\nUse the particular operator depending on what you want the user to understand immediately, that is try to be as specific as possible. </p>\n\n<p>In this case, what you want a reader to notice is that the value of <code>evaluation</code> is updated only if the previous attempt failed to return a value. So I would go for <code>||=</code> which is explicit about the value on the left.</p>\n\n<p>The operators <code>x if y</code> and <code>x unless y</code> have a different purpose. They are used if the normal execution always goes through <code>x</code> however, for some reason (which is checked by a boolean expression <code>y</code>) you make an exception to this current flow and do not execute <code>x</code>. I do not think that your above workflow is suited for this from this point of view.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T19:54:43.767",
"Id": "13650",
"ParentId": "13643",
"Score": "0"
}
},
{
"body": "<p>I would use neither of the proposed blocks and refactor it into into something like</p>\n\n<pre><code>class Evaluation\n # Determines and returns the effective evaluation. If an evaluation id\n # was passed in the url, that evaluation is returned. Otherwise, the\n # default evaluation for the +user+ or, if none, the +site+ is returned.\n #\n # @return [Evaluation] The effective evaluation for the parameters\n def find_evaluation(id_from_url, user, site)\n return find(id_from_url) if id_from_url\n find(@user.id_of_required_evaluation) || find(@site.id_of_required_evaluation)\n end\nend\n</code></pre>\n\n<p>to be called as</p>\n\n<p>evaluation = Evaluation.find_evaluation(params[:evaluation], @user, @site)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T18:04:03.010",
"Id": "13666",
"ParentId": "13643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T17:26:43.617",
"Id": "13643",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Another ||= question"
}
|
13643
|
<p>I have a class library in which I'm using generics as below. I'm not sure if it's an improper use or not. So aside from the fact that it works and everything "depends", id like some specific critique on how this usage might fall apart. In particular In wondering about the shadowing of non generic properties with generic counterparts. Is this an accepted practice?</p>
<pre><code> public interface IPickOrder
{
IPickOrderHeader Header { get; }
ERPListBase<IPickOrderLine> Lines { get; }
}
public interface IPickOrder<TPickOrderHeader, TPickOrderLine> : IPickOrder
where TPickOrderHeader : class, IPickOrderHeader
where TPickOrderLine : class, IPickOrderLine
{
new TPickOrderHeader Header { get; }
new ERPListBase<TPickOrderLine> Lines { get; }
}
public class PickOrder : IPickOrder
{
public IPickOrderHeader Header { get; protected set; }
public ERPListBase<IPickOrderLine> Lines { get; protected set; }
public PickOrder() { }
}
public class PickOrder<TPickOrderHeader, TPickOrderLine> : PickOrder, IPickOrder<TPickOrderHeader, TPickOrderLine>
where TPickOrderHeader : class, IPickOrderHeader, new()
where TPickOrderLine : class, IPickOrderLine, new()
{
public new TPickOrderHeader Header
{
get { return base.Header as TPickOrderHeader; }
protected set { base.Header = value; }
}
public new ERPListBase<TPickOrderLine> Lines { get; protected set; }
/// <summary>
///
/// </summary>
public PickOrder() : base() { }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T08:07:21.903",
"Id": "22079",
"Score": "1",
"body": "As you say, it \"depends\" - in this case, it depends on the purpose of these types. Why do you need to have both generic and non-generic `IPickOrder` and `PickOrder`? Perhaps try to write more about what are you trying to achieve with these types - how are they going to be used?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T08:14:12.697",
"Id": "22080",
"Score": "0",
"body": "My reasons are more due to preference than need. Non generic means I can sling very simple types around in the core of the program re: work flow and routing. Then also having the generic types means at the periphery I can have strongly type objects so i do not have to recast everywhere i need more specific functionality... which at the periphery is often tho in the core assembly almost never... just a simple type interface will do. I also find that if i leave out a non generic type at the core, I can often get \"type trapped\" at the periphery. So at the core i like a very simple model."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T08:43:49.757",
"Id": "22081",
"Score": "4",
"body": "just a quick note - when I see myself using \"new\" to hide members from a base class I take a step back and rethink the approach..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T09:25:51.753",
"Id": "22082",
"Score": "0",
"body": "If you have only instances of the `PickOrder<T>` class, then you only use the non-generic `PickOrder` as a conceptual 'interface' class. In that case, make `PickOrder` an abstract class."
}
] |
[
{
"body": "<p>I feel you on the \"My reasons are more due to preference than need.\" comment but the inheritance from PickOrder and <code>public new ERPListBase<TPickOrderLine> Lines { get; protected set; }</code> will confuse somebody best case and really mess things up worst case. While it may still give you that feeling of impending doom here are some suggestions to make this safer while keeping the look and feel you prefer.</p>\n\n<p>Consider implementing the property like so (also for Header)</p>\n\n<pre><code>public new ERPListBase<TPickOrderLine> Lines {\n get {\n // note that you can't control base.Lines so some values may not be of TPickOrderLine\n return new ERPListBase<TPickOrderLine>(base.Lines.OfType<TPickOrderLine>());\n }\n protected set { base.Lines = new new ERPListBase<IPickOrderLine>(value.Cast<IPickOrderLine>()); }\n}\n</code></pre>\n\n<p>Consider not reusing the base class and using explicit interface implementation:</p>\n\n<pre><code>public class PickOrder<TPickOrderHeader, TPickOrderLine> :\n IPickOrder<TPickOrderHeader, TPickOrderLine>\n where TPickOrderHeader : class, IPickOrderHeader, new()\n where TPickOrderLine : class, IPickOrderLine, new()\n{\n public TPickOrderHeader Header { get; protected set; }\n\n IPickOrderHeader IPickOrder.Header { get { return Header; } }\n\n public ERPListBase<TPickOrderLine> Lines { get; protected set; }\n\n ERPListBase<IPickOrderLine> IPickOrder.Lines { get { return new ERPListBase<IPickOrderLine>(Lines.Cast<IPickOrderLine>()); } }\n}\n</code></pre>\n\n<p>Whatever you do, avoid storing the same data twice as you may be doing (depending on use) in your current code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-25T18:32:00.803",
"Id": "37556",
"Score": "0",
"body": "Also be careful not to confuse `new` with `override`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-26T21:36:54.733",
"Id": "37668",
"Score": "0",
"body": "All great points especially re: not reusing the base class. 9 months later now and I hate that code *my*. I've been doing alot more TDD and if nothing else that will teach one the merits of simplicity *composition over inheritance* etc. The comments now re: if I have to new / shadow I should rethink the architecture are also very valid. Why have a base class if I have to shadow the thing so much it's not even the same class? I think i kinda latched onto to something new (for me) and then proceeded to overuse it everywhere. Each tool is just a tool and each tool has a time & place for it's use."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-25T18:28:57.493",
"Id": "24355",
"ParentId": "13645",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24355",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T08:02:03.157",
"Id": "13645",
"Score": "2",
"Tags": [
"c#",
".net",
"generics"
],
"Title": "Generics: Is this improper use?"
}
|
13645
|
<p>I'm trying to create a doubly linked list using the null object design pattern. I've implemented four classes: a <code>node</code> abstract class, <code>nullnode</code> and <code>datanode</code> classes for the null node object and the <code>linkedlist</code> class, for the linked list implementation. I'm not sure if I've done this correctly.</p>
<p>Can anyone tell me if I am correctly using the null object design pattern and if not, how I can fix it?</p>
<pre><code>/* Node abstract class */
class node{
public:
node();
node(int el) { element = el; }
/* Return pointer to next node */
node* getNext() { return next; }
/* Set pointer to next node */
void setNext(node* n) { next = n; }
/* Return pointer to prev node */
node* getPrev(){ return prev; }
/* Set pointer to prev node */
void setPrev(node* n) { prev = n; }
/* Return element stored in node */
int getElement() { return element; }
/* Set element stored in node */
void setElement(int e) { element = e; }
node* self();
private:
// pointer to next node
node* next;
// pointer to prev node
node* prev;
// element stored in node
int element;
};
/* Null node class */
class NullNode : public node{
public:
/* Return pointer to next node */
node* getNext() { return NULL; }
/* Set pointer to next node */
void setNext(node* n){ /* Do Nothing */ }
/* Return pointer to prev node */
node* getPrev() { return NULL; }
/* Set pointer to prev node */
void setPrev(node* n){ /* Do Nothing */ }
/* Return element stored in node */
int getElement() { return -1; }
/* Set element stored in node */
void setElement(int e){ /* Do Nothing */ }
node* self(){ return NULL; }
};
/* datanode class */
class dataNode : public node{
public:
dataNode(int ele) { node::node(); }
// Return pointer to next node
node* getNext() { return node::getNext(); }
// Set pointer to next node
void setNext(node* n){ node::setNext(n); }
// Return pointer to prev node
node* getPrev() { return node::getPrev(); }
// Set pointer to prev node
void setPrev(node* n){ node::setPrev(n); }
// Return element stored in node
int getElement() { return node::getElement(); }
// Set element stored in node
void setElement(int e){ node::setElement(e); }
node* self(){ return this; }
};
/* linked list class */
class linkedlist{
public:
linkedlist(){
container.setNext(&container);
container.setPrev(&container);
}
~linkedlist();
// Insert an element at the beginning of the list
dataNode* insertHead(int element);
// Return pointer to first node in list
dataNode* getHead() { return (container.getNext())->self(); }
// Return pointer to last node in list
dataNode* getTail() { return (container.getPrev())->self(); }
void insertBefore(dataNode* n, int e);
void insertAfter(dataNode* n, int e);
// Remove specified node
void remove(dataNode* n);
private:
// Pointer to first node in list
NullNode container;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T07:22:20.057",
"Id": "22101",
"Score": "1",
"body": "I'm sorry, but you don't appear to actually have working code here. That is a prerequisite for asking for a code review."
}
] |
[
{
"body": "<p>The question's classes are <code>node</code>, <code>NullNode</code>, <code>dataNode</code>, and <code>linkedlist</code>. Notice that the naming scheme appears not to be case-aware. It is best to fix this. Let's use camel case and capitalize the first letter. So we'll use <code>Node</code>, <code>NullNode</code>, <code>DataNode</code>, and <code>LinkedList</code>.</p>\n\n<p>A problem is the type of <code>LinkedList::container</code> is <code>NullNode</code>. This means that <code>LinkedList</code> cannot contain <code>DataNode</code> objects!</p>\n\n<p><code>DataNode</code> -> <code>Node</code> (-> means implies)</p>\n\n<p><code>NullNode</code> -> <code>Node</code></p>\n\n<p>Also, the null object design pattern is not properly used for linked lists. For example, <code>NullNode::setNode()</code> does not set the node. What does this mean? If the caller wants to store a value in a <code>LinkedList</code> object and it only contains a <code>NullNode</code> should the method do nothing?</p>\n\n<p>What if the result of <code>NullNode::getNext()</code> is invoked? For instance,</p>\n\n<pre><code>NullNode x = ...;\nNullNode w = x.getNext();\nw.getNext(); // Grr, error!\n</code></pre>\n\n<p>In terms of rewriting this, I'm not sure abstracting nodes (with the null object pattern) is useful for doubly (or singly) linked lists. My gut leads me to believe that using the null object pattern for abstracting the data or elements of the list may work well.</p>\n\n<pre><code>class Data\n{\n // interface for getter and setter\n};\nclass BlankData : public Data\n{\n // returns 0 for summing, 1 for multiplying, etc.\n};\nclass IntegerData : public Data\n{\n // returns value\n};\nclass Node\n{\n // typical pointer handling code\n Data element;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T00:40:32.583",
"Id": "13656",
"ParentId": "13655",
"Score": "1"
}
},
{
"body": "<p>I am not much aware of NULL Object pattern. But, I think NullNode should be a <code>singleton</code> as multiple object doesn't have any significance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:52:11.997",
"Id": "13709",
"ParentId": "13655",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T23:00:56.787",
"Id": "13655",
"Score": "0",
"Tags": [
"c++",
"design-patterns",
"linked-list",
"null"
],
"Title": "Null object design pattern in a linked list"
}
|
13655
|
<p>This code (<a href="http://jsbin.com/isexez/3/edit" rel="nofollow">http://jsbin.com/isexez/5/edit</a>) functions as expected:
(1) it displays the page selected; and
(2) it highlights the number of the selected page.</p>
<p>I would appreciate help in improving it. </p>
<p>I am in the process of writing an ebook (<a href="http://www.keepcount.net/ebook/01-09/02_tricks.html" rel="nofollow">http://www.keepcount.net/ebook/01-09/02_tricks.html</a>) and need to improve this code before I get back to my writing.</p>
<p><em><strong></em>* Here's my jQuery code as suggested by @Gisborne <em>*</em></strong><br>
See also jsbin.com/iduxol/2/edit</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- Need to add http: to link in following line -->
<script class="jsbin" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> -->
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
.nodisp { display:none; }
.highlight { background:yellow; }
</style>
</head>
<body>
<!-- When page numbers (p1 & p2) are clicked, page's text is displayed and page number remains highlighted -->
<span class="pageNumbers">
<a id="1"> p1 </a>
<a id="2"> p2 </a>
</span>
<!-- Show page 1 initially -->
<div id="pg1" class="page">
text on page 1
</div>
<!-- Hide page 2 initially -->
<div id="pg2" class="page nodisp">
quiz on page 2
</div>
<script>
$("span.pageNumbers a").click(function () {
// Remove all highlighting
$("span.pageNumbers a").removeClass("highlight");
// Add highlighting to clicked page number
$(this).addClass("highlight");
// Hide all text
$("div.page").hide();
// Show text corresponding to clicked page number
$("#pg"+ $(this).attr('id')).show();
});
</script>
</body>
</html>
</code></pre>
<hr>
|
[] |
[
{
"body": "<p>Here are some ideas:</p>\n\n<ul>\n<li>Use either tab or, preferably, 4-spaces for indention consistently. Right now the indention is all screwy on JSBin.</li>\n<li>Put <em>all</em> your variable declarations at the top, even if you don't define them yet. This'll prevent any confusion from <a href=\"https://stackoverflow.com/questions/3725546/variable-hoisting\">variable hoisting</a>.</li>\n<li>Since <code>null</code> is a falsy value, you can change <code>document.getElementById(...) !== null</code> to <code>document.getElementById(...)</code> to check for the existence of an element in you <code>if</code> statements.</li>\n<li>Space out your <code>if</code> statements (so <code>if (...)</code> instead of <code>if(...)</code>.)</li>\n<li>Maybe think about using jQuery? It'll make working with events and elements much easier than using the DOM directly. So for example, hiding all the pages could be written as easy as: <code>$('div').hide()</code>.</li>\n</ul>\n\n<p>That's all I have time for now!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T16:18:58.950",
"Id": "13663",
"ParentId": "13659",
"Score": "3"
}
},
{
"body": "<p>I came up with several changes, however most of these require the latest jQuery as well as making use of HTML5. Here's why. </p>\n\n<p>First of all, in HTML5 you have a data attribute that is easily accessible via jQuery .data(). This means you can store massive amounts of element related data on each specific element and recall it as needed. Which is why I rewrote your HTML as follow:</p>\n\n<blockquote>\n <p>HTML </p>\n</blockquote>\n\n<pre><code><!-- When page numbers (p1 & p2) are clicked, page's text is displayed and page number remains highlighted.\n Here I replaced the id attribute with a data attribute that contains each pages exact id\n You may also noticed the change in ID's simply to help better represent what pg they correlate too. \n This will be used later to make dynamic call on load to start things off on the right foot -->\n<span class=\"pageNumbers\">\n <a id=\"a-1\" data-page=\"#pg1\" href=\"javascript:void(0)\"> p1 </a>\n <a id=\"a-2\" data-page=\"#pg2\" href=\"javascript:void(0)\"> p2 </a>\n</span>\n\n<!-- Show page 1 initially --> \n<div id=\"pg1\" class=\"page\">\n text on page 1\n</div>\n\n<!-- Hide page 2 initially -->\n<div id=\"pg2\" class=\"page nodisp\">\n quiz on page 2\n</div>\n</code></pre>\n\n<p>Secondly, one of the main purposes of jQuery is to \"Do more, write less\", thus they have many different ways to initiate an action, but the idea is to find the least amount of code to do it in. Thus I make use of the sibling function in order to write less and do more. See the following:</p>\n\n<blockquote>\n <p>Script</p>\n</blockquote>\n\n<pre><code>$(function() {\n $(\".pageNumbers a\").on(\"click\", function(e) {\n // Add highlight to the element clicked and remove highlighting from its siblings\n $(this).addClass(\"highlight\").siblings().removeClass(\"highlight\");\n // Make use of our data attribute to show the correct page and hide the siblings\n $($(this).data('page')).show().siblings(\".page\").hide();\n });\n\n // Finally, dynamically click first page to start things off for the user and provide proper highlighting and showing of text\n $(\"#a-1\").click();\n});\n</code></pre>\n\n<p>See working jsFiddle <a href=\"http://jsfiddle.net/SpYk3/SkwfT/\" rel=\"nofollow\"><h1>HERE</h1></a>\nMore instruction found on script section there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T05:46:54.703",
"Id": "22356",
"Score": "0",
"body": "Thanks @spYk3HH. I guess it will makes things easier in the long run to learn jQuery."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T16:18:31.700",
"Id": "13687",
"ParentId": "13659",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13687",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T12:57:59.157",
"Id": "13659",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Improve this javascript code: It displays hidden text and highlights the selected page number"
}
|
13659
|
<p>I have just implemented a quick test of the visitor design pattern in C++ and have a few questions regarding the code.</p>
<h2>main.cpp</h2>
<pre><code>#include <iostream>
#include "Base.h"
#include "Derived.h"
#include "Visitor.h"
int main() {
Base base;
std::cout << "hello\n";
Base * derived = new Derived();
Visitor v;
base.acceptvisitor(v);
derived->acceptvisitor(v);
}
</code></pre>
<h2>IVisitable.h</h2>
<pre><code>#ifndef IVISITABLE_H
#define IVISITABLE_H
class Visitor;
class IVisitable {
virtual void acceptvisitor(Visitor v) = 0;
};
#endif
</code></pre>
<h2>Base.h</h2>
<pre><code>#ifndef BASE_H
#define BASE_H
#include <string>
#include "IVisitable.h"
class Base : public IVisitable {
public:
void acceptvisitor(Visitor v);
};
#endif
</code></pre>
<h2>Base.cpp</h2>
<pre><code>#include "Base.h"
#include "Visitor.h"
void Base::acceptvisitor(Visitor v) {
v.visit(*this);
}
</code></pre>
<h2>Derived.h</h2>
<pre><code>#include "Base.h"
class Derived : public Base {
public:
void acceptvisitor(Visitor v);
};
</code></pre>
<h2>Derived.cpp</h2>
<pre><code>#include "Derived.h"
#include "Visitor.h"
void Derived::acceptvisitor(Visitor v) {
v.visit(*this);
}
</code></pre>
<h2>Visitor.h</h2>
<pre><code>#ifndef VISITOR_H
#define VISITOR_H
class Base;
class Derived;
class Visitor {
public:
void visit(Base b);
void visit(Derived d);
};
#endif
</code></pre>
<h2>Visitor.cpp</h2>
<pre><code>#include "Visitor.h"
#include <iostream>
#include "Base.h"
#include "Derived.h"
void Visitor::visit(Base b) {
std::cout << "Visiting Base\n";
}
void Visitor::visit(Derived d) {
std::cout << "Visiting Derived\n";
}
</code></pre>
<p>And here are some questions, of course I am interested in all remarks you may have not just answers to these.</p>
<ol>
<li><p>How do you keep track of includes? Even in this short example I now have includes that are not needed anymore.</p></li>
<li><p>Is this <code>#ifndef</code> treatment of header files still normal? I picked it up somewhere but have never actually seen anybody else do it.</p></li>
<li><p>Is there any way to treat an object as a superclass without a pointer? I.e. can I do something like this: <code>Base d = Derived();</code></p></li>
<li><p>When can I use a forward declaration like <code>class Visitor;</code> and when do I need to include the actual header file? Or when should I?</p></li>
<li><p>Should I make implementations of abstract functions virtual? It seems not to matter.</p></li>
</ol>
|
[] |
[
{
"body": "<p>Your implementation looks mostly good, however I'm not sure if I'd recommend passing your parameters by value. It may be what you're looking for, but generally I'd consider passing by reference or const-reference - it avoids the need for one or more copies, and means you shouldn't get any object slicing as I mention in answer to question 3 below. Unless of course you wanted the copies and/or slicing to occur, in which case your implementation is fine.</p>\n\n<p>Now, to try and answer your questions:</p>\n\n<ol>\n<li><p>I try to just keep an eye on the <code>#includes</code> and remove any that I don't think are required anymore. If I remove one that was actually required I can always add it back in again. I also tend to make a point of removing #includes whenever I have made changes to a file that I know mean I no longer require a header. It's more art & experience than science though, so I'm not sure I can give much good advice here.</p></li>\n<li><p>Using <code>#ifndef</code> etc. to protect your include files from being included more than once is definitely still a good idea. Some compilers support <code>#pragma once</code> that does a similar thing, but as this isn't universally supported I'd stick with <code>#ifndef</code> protection.</p></li>\n<li><p>You could use references for that, which act very similarly to pointers. Allow me to demonstrate:</p>\n\n<p><code>Base b = Derived(); // Here b will be an instance of base</code></p>\n\n<p><code>Base& b = Derived(); // In this case b will be an instance of Derived.</code></p>\n\n<p>In the first case, the derived that is created will be \"sliced\" into an instance of <code>Base</code>, meaning that any members that are in <code>Derived</code> but not in <code>Base</code> will be dropped, and b will just be a normal instance of <code>Base</code>. For more information on object slicing, you could read <a href=\"http://en.wikipedia.org/wiki/Object_slicing\" rel=\"nofollow\">this wikipedia article</a></p>\n\n<p>In the second case, you're creating a reference to an instance of <code>Derived</code>. This will act much like a pointer would - you can only directly access members exposed by <code>Base</code>, but the underlying instance is a <code>Derived</code>. </p>\n\n<p>To answer your comment below, <code>Base& b = Derived()</code> isn't actually valid c++, because the <code>Derived()</code> call creates a temporary, and you can't point a reference at a temporary. The code was just to illustrate a point, rather than as a proper suggestion. What you can do however, is</p>\n\n<p><code>Derived d; Base& b = d;</code></p></li>\n<li><p>You should include the actual header file for a class whenever the compiler actually needs some information about it's members - for example if you're calling functions on the class, or if you're declaring a value type of the class.</p>\n\n<p>If you're just passing around pointers or references to a class without actually using it you can usually get away with just a forward declaration.</p>\n\n<p>My general rule of thumb is to forward declare anything that is needed in a header file, then #include the headers required in the .cpp file. Except when the full declerations are actually required in the header file. This seems to be roughly what you're doing, so I think you've got the right idea.</p></li>\n<li><p>I'm assuming you're asking whether you should specifically state that <code>void acceptvisitor(Visitor v);</code> in Derived is virtual. This isn't strictly neccesary - as the function is declared as virtual in the <code>IVisitable</code> class then it will be virtual in <code>Derived</code> as well.</p>\n\n<p>However, you may want to mark it as virtual anyway - this might make it more obvious to anyone reading the code that the function is actually virtual, rather than a normal method.</p></li>\n</ol>\n\n<p>Hopefully I've been clear enough here, but feel free to leave a comment if you have any further questions or want some clarificaiton.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T14:12:10.637",
"Id": "22106",
"Score": "0",
"body": "The objects have to know about the visitor because the vtable of the objects is used to make sure the right function is called. To make sure, I tried your changes and as expected I got \"Visiting Base\" twice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T14:14:39.587",
"Id": "22107",
"Score": "0",
"body": "This: Base& b = Derived(); gives me main.cpp:10:29: error: invalid initialization of non-const reference of type ‘Base&’ from an rvalue of type ‘Derived’ -- What am I doing wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T14:52:40.773",
"Id": "22108",
"Score": "0",
"body": "@CorporalTouchy Ah, sorry. I obviously didn't think my first suggestion through! I've removed it and added a bit of clarification on the error you're getting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T20:30:00.347",
"Id": "22116",
"Score": "0",
"body": "The code is broken, not “mostly good”. See Loki’s answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T20:47:31.527",
"Id": "22120",
"Score": "0",
"body": "@KonradRudolph Care to elaborate? I don't see anything *actually* broken. There's object slicing going on and a bit of excess copying, which I mention. Can't see anything critical mentioned in Loki's answer either, though I've mostly just skimmed it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T13:52:12.660",
"Id": "13661",
"ParentId": "13660",
"Score": "0"
}
},
{
"body": "<p>Well your code is all broken.<br />\nBut we will get to that as we answer your questions:</p>\n<h3>Answers to Questions</h3>\n<blockquote>\n<p>How do you keep track of includes? Even in this short example I now have includes that are not needed anymore.</p>\n</blockquote>\n<ul>\n<li>Only include a header file if you need the class definition.</li>\n<li>Forward declare <strong>everything</strong> else</li>\n</ul>\n<p>Using this rule it is easy to only include files you need. In your header files only include other header files if you need them. You only need them if the object you are defining has a member of that type or is derived from that type (or takes a parameter to a method by value).</p>\n<p>In all other situations forward declare.<br />\nThis reduces the header count considerably.</p>\n<p>In the source file you include all the header files of object you use to implement your code (that your header files have not included).</p>\n<pre><code>#ifndef BASE_H\n#define BASE_H\n\n#include <string> // There is no need for this.\n // There are no members that use string\n // You are not deriving from string (who would)\n // You are not passing a string as a parameter\n // Remove this.\n\n#include "IVisitable.h"\n\nclass Base : public IVisitable {\npublic:\n void acceptvisitor(Visitor v); // By the way this is probably wrong.\n // You are passing by value and thus will\n // Make a copy.\n // Here you (if you really\n // wanted to pass by value) you should have\n // include "Visitor.h".\n //\n // But you don't want to pass by value you want\n // to pass by reference. So you just need to \n // forward declare.\n};\n\n#endif\n</code></pre>\n<blockquote>\n<p>Is this #ifndef treatment of header files still normal? I picked it up somewhere but have never actually seen anybody else do it.</p>\n</blockquote>\n<p>Yes you should always place include guards around header files to protect from multiple inclusion.</p>\n<blockquote>\n<p>Is there any way to treat an object as a superclass without a pointer? I.e. can I do something like this: Base d = Derived();</p>\n</blockquote>\n<p>Well actually what you have written will compile:<br />\nUnfortunately it does not do what you expect. Here you have object slicing. The Base part of the object you created is sliced out and copied into d. What you need is a pointer (or a reference).</p>\n<p>It looks like you are used to languages like Java. Where all objects are dynamically allocated. C++ has a much superior mechanism that allows us to accurately control the lifetime of the object. The disadvantage is that it adds complexity to the language.</p>\n<p>What is called a pointer in C/C++ (to distinguish it from C++ references) would in most other languages be called a reference. C++ has both local objects (automatic storage duration object) and dynamically allocated objects (dynamic storage duration objects) thus we need a convention that allows access to both types of object, hence we use <code>*</code> to refer to objects that are dynamically allocated (to distinguish them from local objects).</p>\n<p><strong>BUT</strong> it is unusual to use pointers directly in C++ (unless you are implementing some real low level stuff). Most of the time when you dynamically allocate objects you will use a smart pointer that defines the lifespan of the object (much like other languages with garbage collection (but better)). <code>std::shared_ptr<T></code> would be the equivalent of <code>T</code> in Java.</p>\n<pre><code>std::shared_ptr<Base> d = new Derived(); // dynamically allocated object\n // That will be correctly destroyed\n // when there are no more references.\n</code></pre>\n<blockquote>\n<p>When can I use a forward declaration like "class Visitor;" and when do I need to include the actual header file. Or when should I?</p>\n</blockquote>\n<p>As described above.<br />\nIn the header file (were there is only declaration) only include another header if the header file defines a type that is a member or is used as a parent or used to pass a parameter by value (parameters are infrequent as they are normally passed by reference). In all other cases in a header file you should use forward declaration. In the source file include the header files that define types that you use (ie call methods on).</p>\n<p>Note: You only need a forward declaration for objects that are pointers or references.</p>\n<blockquote>\n<p>Should I make implementations of abstract functions virtual? It seems not to matter.</p>\n</blockquote>\n<p>Only virtual methods can be abstract.<br />\nIf you forget to define a method the compiler will not complain (as you may define it in another compilation unit). The linker will only complain if somebody tries to call the method and can't find a definition. So if you don't call it then there will be no error (but if you don't call it then it does not matter).</p>\n<p>When you implement a virtual function in a derived class it is probably best to mark it as virtual to show a subsequent maintainer that it is virtual function (but it is not required by the language).</p>\n<p>You should also note that C++11 introduces they keyword <code>override</code>. Which is an indicator that this method overrides a virtual method in a base class. If there is not such method in the base class it is a compilation error.</p>\n<h3>Other Notes</h3>\n<p>Your code passes all parameters by value. This is probably not what you want (as a copy will be made). If it is a derived type the base parameter type will be sliced out and passed to the method. So pass by reference.</p>\n<pre><code>class IVisitable {\n virtual void acceptvisitor(Visitor& v) = 0;\n}; // ^^^ pass by reference\n</code></pre>\n<p>Also note that you can have more than one class defined in a file. Thus personally I would have put the <code>IVisitable</code> and <code>Visitor</code> patterns in the same file (they are tightly coupled anyway).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T19:38:37.257",
"Id": "22112",
"Score": "0",
"body": "Wow, another answer. Again I have follow-up questions. :) Above you said if I pass by value I should include the header file but it wasn't necessary, should I have done it anyway? Also what are the different kinds of smart pointers? I have seen at least shared_ptr and auto_ptr."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T19:44:23.600",
"Id": "22113",
"Score": "0",
"body": "Did I understand correctly that object slicing is used when passing by copy but not when passing by reference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T20:44:10.790",
"Id": "22117",
"Score": "0",
"body": "If you pass by reference you only need to use a forward declare (so don't include header file)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T20:45:36.203",
"Id": "22118",
"Score": "0",
"body": "Types of smart pointers: http://stackoverflow.com/a/8706254/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T20:47:24.017",
"Id": "22119",
"Score": "1",
"body": "Slicing is a side affect. Few people `use` it intentionally. Object slicing happens when you pass a derived object to a base class object and the copy constructor (or assignment) gets invoked (so passing a parameter by value is one of those places). It **will not** happen when passing by reference or pointer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T16:33:16.517",
"Id": "13665",
"ParentId": "13660",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "13665",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-14T13:10:01.453",
"Id": "13660",
"Score": "13",
"Tags": [
"c++",
"visitor-pattern"
],
"Title": "Visitor pattern in C++"
}
|
13660
|
<p>I have written a class which I will use as a base class, allowing other classes to extend this class.</p>
<p>How can I improve this? Am I breaking any conventions or styling?</p>
<pre><code>import requests
import feedparser
from BeautifulSoup import BeautifulSoup
class BaseCrawler(object):
''' Base Class will be extended by other classes'''
def __init__(self, url):
self.url = url
def test(self):
return self.url
def get_feed(self):
feed = feedparser.parse(self.url)
return feed
def post_request(self):
res = requests.post(self.url, self.data)
return res
def get_request(self):
res = requests.get(self.url)
self.raw = res.content
return self.raw
def build_entity(self):
raise NotImplementedError("Subclasses should implement this!")
def process(self):
return NotImplementedError("Subclasses should implement this!")
def build_query(self):
return NotImplementedError("Subclasses should implement this!")
</code></pre>
|
[] |
[
{
"body": "<p>I'm not sure what you're intending to do with this class so I can only offer some general tips.</p>\n\n<ol>\n<li><p>Make private variables private:</p>\n\n<pre><code>def __init__(self, url):\n self._url = url\n</code></pre></li>\n<li><p>Use properties instead of <code>get_</code> methods. For example:</p>\n\n<pre><code>@property\ndef request(self):\n return self._requests.get(self._url)\n\n# to make it writeable:\n@request.setter\ndef request(self, value):\n self._requests.set(value)\n</code></pre></li>\n<li><p>If you're using Python 3, have a look at abc.ABCMeta for better solution for abstract base classes with abstract methods.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T00:52:59.013",
"Id": "13670",
"ParentId": "13664",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T16:22:03.267",
"Id": "13664",
"Score": "2",
"Tags": [
"python"
],
"Title": "Base class for feed-parsing"
}
|
13664
|
<p>When reigstering a user I request two reads from the database to see if there is a username and email and then I write if the checks pass.. Can anyone tell me if this code will block other users?</p>
<p>I am using node with express.js and mongojs.</p>
<p>I know I am saving passwords in plaintext.. This will be changed.</p>
<pre><code>app.post('/register', function(req, res) {
var checked = 0;
var errors = [];
var finishedCheck = function() {
checked++;
register();
}
var register = function() {
if(checked === 2){
if(errors.length > 0) {
console.log('errors', errors);
res.statusCode = 409;
res.send(errors);
} else {
var newuser = {
username: req.body.username,
uppercase: req.body.username.toUpperCase(),
password:req.body.password,
email: req.body.email.toLowerCase(),
userLevel: 0,
createdOn: new Date()
};
db.users.save(newuser, function(err, val){
if(!err) {
req.session.userid = val['_id'];
res.end();
} else {
res.statusCode = 406;
res.end(['Something went wrong', err]);
}
});
}
}
}
var check = function(username, email) {
console.log('chekc');
db.users.ensureIndex({email:1},{unique:true});
db.users.ensureIndex({uppercase:1},{unique:true});
if(!username.match(/^[A-Za-z0-9_]*$/)) {
errors.push('Username is invalid');
finishedCheck();
} else {
db.users.findOne({uppercase: username}, function(err, val) {
if(val) {
errors.push('Username Taken');
}
finishedCheck();
});
}
//check if the is a valid email address if so then check to see if its already registered
if(!email.match(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i)) {
errors.push('Email is invalid');
finishedCheck();
} else {
db.users.findOne({email: email}, function(err, val) {
if(val) {
errors.push('Email is already in the database');
}
finishedCheck();
});
}
};
check(req.body.username.toUpperCase(), req.body.email.toLowerCase());
});
</code></pre>
|
[] |
[
{
"body": "<p>The answer is NO.</p>\n\n<p>The reason is that the calls to db are asynchronous, that's why you pass a function object as a callback.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T22:46:46.240",
"Id": "13669",
"ParentId": "13667",
"Score": "1"
}
},
{
"body": "<p><strong>No</strong></p>\n\n<pre><code>app.post('/register'...\n</code></pre>\n\n<p>Has a callback and is non-blocking within Node</p>\n\n<pre><code>db.users.save(...\n</code></pre>\n\n<p>Has a callback and is non-blocking within Node (but will block on your database level, which is normal)</p>\n\n<pre><code>db.users.findOne(...\n</code></pre>\n\n<p>Has a callback and is non-blocking within Node (but will block on your database level, which is normal)</p>\n\n<p>Your code looks pretty normal. MongoDB has a global lock across an entire mongoDB server daemon, so this is the only level that your current code will block. It will not block on your Node.js level for your concurrent users.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T03:07:39.850",
"Id": "13672",
"ParentId": "13667",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13672",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T22:21:55.823",
"Id": "13667",
"Score": "1",
"Tags": [
"node.js"
],
"Title": "Will this code block in node.js"
}
|
13667
|
<p>My code listens for a number of events, and calls the Google Analytics event tracking function when they fire.</p>
<p>Each event uses a similar pattern. Can I achieve the same functionality without repeating myself?</p>
<pre><code>/*jslint debug:true, browser:true, devel:true nomen:true */
/*global _gaq:true, jquery:true, $:true */
function trackEvent(c, a, l) {
'use strict'; // JSLint
//console.log(c, a, l); // Dev only
_gaq.push(['_trackEvent', c, a, l]);
}
$(function () {
'use strict'; // JSLint
var alert, carousel, collapse, modal, tab, tooltip, download, external, mailto;
// Alerts event handler
alert = function () {
var alertButton = $(this),
category = 'Alerts',
action = alertButton.next().text(),
label;
trackEvent(category, action, label);
};
$('body').on('click.alert.data-api', '[data-dismiss="alert"]', alert);
// Carousel event handler
carousel = function () {
var carouselButton = $(this),
category = 'Carousels',
action = carouselButton.attr('data-slide'),
label;
trackEvent(category, action, label);
};
$('body').on('click.carousel.data-api', '[data-slide]', carousel);
// Collapse event handler
collapse = function () {
var category = 'Collapses',
action = $(this).text(),
label;
trackEvent(category, action, label);
};
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', collapse);
// Modal event handler
modal = function () {
var category = 'Modals', action, label, activeModal;
activeModal = $(this).attr('href');
action = $(activeModal).find('h3').text();
trackEvent(category, action, label);
};
$('body').on('click.modal.data-api', '[data-toggle="modal"]', modal);
// Tab event handler
tab = function () {
var category = "Tabs",
action = $(this).text(),
label;
trackEvent(category, action, label);
};
$('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', tab);
// Tooltip event handler
tooltip = function () {
var category = "Tooltips",
action = $(this).text(),
label;
trackEvent(category, action, label);
};
$('body').on('mouseenter', '[rel="tooltip"], [rel="popover"]', tooltip);
// Download link event handler
download = function () {
var category = "Downloads",
action = $(this).attr('href'),
label;
trackEvent(category, action, label);
};
$('body').on('click', 'a[href$="pdf"], a[href$="doc"], a[href$="docx"], a[href$="rtf"], a[href$="ppt"], a[href$="zip"]', download);
// Mailto event handler
mailto = function () {
var category = 'Mailto',
action = $(this).attr('href'),
label;
trackEvent(category, action, label);
};
$('body').on('click', 'a[href^="mailto"]', mailto);
// External link event handler
$.expr[':'].external = function (a) {
var PATTERN_FOR_EXTERNAL_URLS = /^\w+:\/\//,
href = $(a).attr('href');
return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
};
external = function () {
var category = 'External links',
action = $(this).attr('href'),
label;
trackEvent(category, action, label);
};
$('body').on('click', 'a:external', external);
});
</code></pre>
|
[] |
[
{
"body": "<p>Id suggest something like:</p>\n\n<pre><code>$('body').on('click.alert.data-api', '[data-dismiss=\"alert\"]', function () {\n trackEvent('Alerts', $(this).next().text());\n});\n</code></pre>\n\n<p>instead of the whole <code>alert</code> code, and similar things for the other items.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:06:23.463",
"Id": "22155",
"Score": "0",
"body": "I can see how your code is easier to read. Thanks for the suggestion Inkbug."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T10:04:18.870",
"Id": "13678",
"ParentId": "13675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T07:05:57.023",
"Id": "13675",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Stop repeating myself: Similar pattern used on multiple event handlers"
}
|
13675
|
<p>I'm playing around with JMock and trying to understand whether I understand the idea correctly.</p>
<p>There's an interface <code>Printer</code> aimed to print integers somewhere. There's an interface <code>Calculator</code> aimed to perform math. There's a class <code>CalculatingMachine</code> aimed to connect <code>Calculator</code> and <code>Printer</code>: first, it calculates the result with <code>Calculator</code> and then this result is passed to <code>Printer</code>. Here's the code</p>
<pre><code>public class CalculatingMachine {
private final Printer printer;
private final Calculator calculator;
public CalculatingMachine(Printer printer, Calculator calculator) {
this.printer = printer;
this.calculator = calculator;
}
public void processAdd(int x, int y) {
int result = calculator.add(x, y);
printer.print(result);
}
public static interface Printer {
void print(int x);
}
public static interface Calculator {
int add(int x, int y);
}
}
</code></pre>
<p>As far as I understand <code>CalculatingMachine</code> only requires one test: we need to make sure IT USES calculator to do the math and then we need to make sure IT USES printer to print the result. So, here's my test:</p>
<pre><code>public class CalculatingMachineTest {
@Test
public void testCalculatingMachine() {
Mockery context = new JUnit4Mockery();
final Printer printer = context.mock(Printer.class);
final Calculator calculator = context.mock(Calculator.class);
context.checking(new Expectations() {{
oneOf(calculator).add(1, 2);
will(returnValue(3));
oneOf(printer).print(3);
}});
CalculatingMachine machine = new CalculatingMachine(printer, calculator);
machine.processAdd(1, 2);
context.assertIsSatisfied();
}
}
</code></pre>
<p>Pretty straightforward and does what it supposed to do. There are 2 points I'm curious about:</p>
<ol>
<li>Is it the right approach even though CodePro says that <code>CalculatingMachine</code> itself has 19 lines of code, though test for it is 23 lines of code? I'm just not sure: is it normal to write more tests then code that does something?</li>
<li>Is there any other way to test all the same but with less code?</li>
</ol>
|
[] |
[
{
"body": "<p>This is technically correct code, whether it's right depends... </p>\n\n<p>This might be the first test for an object that will become more complicated. It's reasonable to start small and work your way up. </p>\n\n<p>If the Calculator is a self-contained implementation that doesn't pull in other dependencies, it might be better to just use a real one. In this case, it looks more like a function.</p>\n\n<p>In the end, there might well be more test than production code because you want to exercise all the paths. These days, I find myself writing unit tests with mocks at a slightly higher level, around a small cluster of objects.</p>\n\n<p>If the call to the Calculator doesn't change the state of the world outside the Machine, I'd probably use an allowing clause, we \"Stub Queries, Expect Actions\"</p>\n\n<pre><code>allowing(calculator).add(1,2); will(returnValue(3));\n</code></pre>\n\n<p>it's the same implementation underneath but expresses the intent more clearly.</p>\n\n<p>You might try the JUnitRuleMockery with JUnit's @Rule. It takes care of the assertion housekeeping at the right time.</p>\n\n<p>And before someone jumps in with their favourite alternative mocking framework, I'm not sure that's really the point. We can shave a few lines off here and there, but it's more important to understand the design issues. And everything will change with Java 8.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T10:19:46.043",
"Id": "13680",
"ParentId": "13676",
"Score": "3"
}
},
{
"body": "<p>It's completely normal to have more test code than production code. See:</p>\n\n<ul>\n<li><a href=\"http://c2.com/cgi/wiki?ProductionCodeVsUnitTestsRatio\" rel=\"nofollow\">Production Code Vs Unit Tests Ratio</a></li>\n</ul>\n\n<p>You can make it a little bit shorted if you use the <code>@RunWith(JMock.class)</code> annotation and move the fixture to class fields:</p>\n\n<pre><code>import org.jmock.Expectations;\nimport org.jmock.Mockery;\nimport org.jmock.integration.junit4.JMock;\nimport org.jmock.integration.junit4.JUnit4Mockery;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n@RunWith(JMock.class)\npublic class CalculatingMachineJMockTest {\n\n private final Mockery context = new JUnit4Mockery();\n\n private final Printer printer = context.mock(Printer.class);\n private final Calculator calculator = context.mock(Calculator.class);\n\n @Test\n public void testCalculatingMachine() {\n context.checking(new Expectations() {\n {\n oneOf(calculator).add(1, 2);\n will(returnValue(3));\n\n oneOf(printer).print(3);\n }\n });\n\n final CalculatingMachine machine = new CalculatingMachine(printer, calculator);\n machine.processAdd(1, 2);\n }\n\n}\n</code></pre>\n\n<p>It helps more if you have more than one test method.</p>\n\n<hr>\n\n<p>Another note: does it make sense to create a <code>CalculatingMachine</code> with <code>null</code> <code>printer</code> or <code>calculator</code>? I'd check these <code>null</code>s in the constructor. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow\">checkNotNull from Guava</a> is a great choice for this.</p>\n\n<pre><code> public CalculatingMachine(final Printer printer, final Calculator calculator) {\n this.printer = checkNotNull(printer, \"printer cannot be null\");\n this.calculator = checkNotNull(calculator, \"calculator cannot be null\");\n }\n</code></pre>\n\n<p>And here are two test:</p>\n\n<pre><code> @Test(expected = NullPointerException.class)\n public void testNullPrinter() throws Exception {\n new CalculatingMachine(null, calculator);\n }\n\n @Test(expected = NullPointerException.class)\n public void testNullCalculator() throws Exception {\n new CalculatingMachine(printer, null);\n }\n</code></pre>\n\n<p>(See: <em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:26:30.143",
"Id": "13682",
"ParentId": "13676",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13680",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T07:52:46.230",
"Id": "13676",
"Score": "2",
"Tags": [
"java",
"unit-testing",
"junit"
],
"Title": "Tesing a simple calculator class with JUnit/JMock"
}
|
13676
|
<p>This is a solver for Sudoku using backtracking. How can I make it more optimized and clean?</p>
<pre><code>#include <stdio.h>
int isAvailable(int sudoku[][9], int row, int col, int num)
{
int i, j;
for(i=0; i<9; ++i)
if( (sudoku[row][i] == num) || ( sudoku[i][col] == num ) )//checking in row and col
return 0;
//checking in the grid
int rowStart = (row/3) * 3;
int colStart = (col/3) * 3;
for(i=rowStart; i<(rowStart+3); ++i)
{
for(j=colStart; j<(colStart+3); ++j)
{
if( sudoku[i][j] == num )
return 0;
}
}
return 1;
}
int fillsudoku(int sudoku[][9], int row, int col)
{
int i;
if( row<9 && col<9 )
{
if( sudoku[row][col] != 0 )//pre filled
{
if( (col+1)<9 )
return fillsudoku(sudoku, row, col+1);
else if( (row+1)<9 )
return fillsudoku(sudoku, row+1, 0);
else
return 1;
}
else
{
for(i=0; i<9; ++i)
{
if( isAvailable(sudoku, row, col, i+1) )
{
sudoku[row][col] = i+1;
if( (col+1)<9 )
{
if( fillsudoku(sudoku, row, col +1) )
return 1;
else
sudoku[row][col] = 0;
}
else if( (row+1)<9 )
{
if( fillsudoku(sudoku, row+1, 0) )
return 1;
else
sudoku[row][col] = 0;
}
else
return 1;
}
}
}
return 0;
}
else
{
return 1;
}
}
int main()
{
int i, j;
int sudoku[9][9]={{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
if( fillsudoku(sudoku, 0, 0) )
{
for(i=0; i<9; ++i)
{
for(j=0; j<9; ++j)
printf("%d ", sudoku[i][j]);
printf("\n");
}
}
else
{
printf("\n\nNO SOLUTION\n\n");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Very nice:</p>\n\n<p>Few minor changes I would make.</p>\n\n<p>In <code>isAvailable()</code> I would check row/col/box all at the same time.</p>\n\n<pre><code>int isAvailable(int sudoku[][9], int row, int col, int num)\n{\n //checking in the grid\n int rowStart = (row/3) * 3;\n int colStart = (col/3) * 3;\n\n int i, j;\n for(i=0; i<9; ++i)\n {\n if (sudoku[row][i] == num) return 0;\n if (sudoku[i][col] == num) return 0;\n if (sudoku[rowStart + (i%3)][colStart + (i/3)] == num) return 0;\n }\n\n return 1;\n} \n</code></pre>\n\n<p>Which brings my to my first comment:<br>\nI prefer to have sub statments of while/for/if inside block quotes.</p>\n\n<pre><code>if( sudoku[i][j] == num )\n return 0;\n\n// I prefer this:\nif( sudoku[i][j] == num )\n{ return 0;\n}\n</code></pre>\n\n<p>This way there is not chance of accidentally putting a macro that expands and is not all executed.</p>\n\n<p>Your code for moving to the next square is in multiple places in the code:</p>\n\n<pre><code> if( (col+1)<9 )\n STUFF(row, col+1);\n else if( (row+1)<9 )\n STUFF(row+1, 0);\n else\n WIN\n</code></pre>\n\n<p>Because it is multiple places you have redundancy. I would move this check to one location. The easiest way to do that is move it to the first few lines of code in the function. Then you always make a recursive call like this <code>fillsudoku(sudoku, row, col+1)</code>.</p>\n\n<pre><code>int fillsudoku(int sudoku[][9], int row, int col)\n{\n if (col >= 9)\n {\n col = 0;\n ++row;\n if (row >= 9)\n {\n return 1;\n }\n }\n\n // Original code.\n // When doing a recursive call use ` fillsudoku(sudoku, row, col+1)`\n // You know the start of the code will test it.\n</code></pre>\n\n<p>Next I would exit early rather than have nested code.<br>\nThis is a debatable point on style but I don;t think having to scroll down a long way to see a one lineer for failure helps in readability. And since you already exit early that is not a problem.</p>\n\n<pre><code> if( sudoku[row][col] != 0) //pre filled \n {\n return fillsudoku(sudoku, row, col+1);\n }\n else\n {\n for(i=0; i<9; ++i)\n {\n if( isAvailable(sudoku, row, col, i+1) )\n {\n sudoku[row][col] = i+1;\n\n int good = fillsudoku(sudoku, row, col +1);\n if (good)\n { return 1;\n }\n sudoku[row][col] = 0;\n }\n }\n }\n return 0;\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T17:41:19.830",
"Id": "13688",
"ParentId": "13677",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "13688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T08:57:12.143",
"Id": "13677",
"Score": "10",
"Tags": [
"optimization",
"c",
"sudoku",
"backtracking"
],
"Title": "Solving Sudoku using backtracking"
}
|
13677
|
<p>I want to validate a list of objects for example strings. and if one of the objects fails to pass the condition return false as validation result . this is the code I use :</p>
<pre><code> public static bool AreValid(string[] strs)
{
foreach (string str in strs)
{
if (str != condition )
{
return false; // does this breaks the for loop ?
// break; // no need to this
}
}
return true;
}
</code></pre>
<p>is this a correct approach ?</p>
|
[] |
[
{
"body": "<p>Yes, <code>return</code> immediately* returns from the method, no matter where in the method you are. You don't need the <code>break</code>.</p>\n\n<p>But there is even easier way to write this code, using the LINQ method <a href=\"http://msdn.microsoft.com/en-us/library/bb548541.aspx\"><code>All()</code></a>:</p>\n\n<pre><code>strs.All(str => str == condition)\n</code></pre>\n\n<p>This also returns as soon as single non-matching element is found and is more readable.</p>\n\n<hr>\n\n<p>* Actually, <code>finally</code> blocks run before you actually return from the method, but that's not relevant here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T10:29:20.557",
"Id": "13681",
"ParentId": "13679",
"Score": "15"
}
},
{
"body": "<p>Any would be a bit faster than All</p>\n\n<pre><code>return !strs.Any(str => str != condition);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-14T07:21:10.190",
"Id": "270573",
"Score": "0",
"body": "[Enumerable.All](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,be4bfd025bd2724c) returns as soon as the condition does not match. Therefore there is no difference in performance but Enumerable.All is more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-14T07:22:47.323",
"Id": "270574",
"Score": "0",
"body": "Hmm.. in that case both will have similar performance"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-14T07:04:36.997",
"Id": "144201",
"ParentId": "13679",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "13681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T10:19:41.260",
"Id": "13679",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Validating that all strings in an array match a condition"
}
|
13679
|
<p>I have a simple script that will take a list of hosts and ping each host (there's about 200) a single time before moving on. This is not the most effecient method I am sure, as it is very linear. And it takes a few minutes to complete. I would ideally like to run this script every minute (so each IP address is checked every minute (the actual running of the script is controlled externally).</p>
<p>I was looking for some pointers on potentially making the script more effecient/dynamic.</p>
<pre><code>import sys
import os
import platform
import subprocess
plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir, 'hosts.txt')
hostsFile = open(hosts, "r")
lines = hostsFile.readlines()
if plat == "Windows":
for line in lines:
line = line.strip( )
ping = subprocess.Popen(
["ping", "-n", "1", "-l", "1", "-w", "100", line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
if plat == "Linux":
for line in lines:
line = line.strip( )
ping = subprocess.Popen(
["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1", line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
hostsFile.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T11:41:53.960",
"Id": "22127",
"Score": "0",
"body": "I think it may be the way I'm reading a file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T13:14:11.567",
"Id": "22131",
"Score": "0",
"body": "Might want to take a look at [Nagios's](http://www.nagios.org/) scheduler code to get some ideas."
}
] |
[
{
"body": "<p>Why not using threads ? You could run your pings simultaneously. </p>\n\n<p>This works quite well :</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\nimport threading\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\nhostsFile = open(hosts, \"r\")\nlines = hostsFile.readlines()\n\ndef ping(ip):\n if plat == \"Windows\":\n ping = subprocess.Popen(\n [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\", ip],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n\n if plat == \"Linux\":\n ping = subprocess.Popen(\n [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\", ip],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n\n out, error = ping.communicate()\n print out\n print error\n\nfor ip in lines:\n threading.Thread(target=ping, args=(ip,)).run()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:07:39.933",
"Id": "22128",
"Score": "0",
"body": "When I run this, I get the following error...\n `OSError: [Errno 24] Too many open files`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T13:16:58.070",
"Id": "22132",
"Score": "0",
"body": "seems like you exceeded your file-quota. either you raise your limit or limit the amount of threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T15:13:22.683",
"Id": "22135",
"Score": "0",
"body": "How would I do that then?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-08T09:57:02.477",
"Id": "309409",
"Score": "0",
"body": "In the above code the file is being open, but never close that's why you are getting this error.."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T11:44:10.760",
"Id": "13684",
"ParentId": "13683",
"Score": "0"
}
},
{
"body": "<p>It's not a complete answer, but your code would be more clear (and easy to maintain) if you won't duplicate code:</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\nhostsFile = open(hosts, \"r\")\nlines = hostsFile.readlines()\nfor line in lines:\n line = line.strip( )\n if plat == \"Windows\":\n args = [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\", line]\n\n elif plat == \"Linux\":\n args = [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\", line]\n\n ping = subprocess.Popen(\n args,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n out, error = ping.communicate()\n print out\n print error\n\nhostsFile.close()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:04:04.330",
"Id": "13685",
"ParentId": "13683",
"Score": "4"
}
},
{
"body": "<p>i would look into the python-nmap <a href=\"http://pypi.python.org/pypi/python-nmap/\" rel=\"nofollow\">package</a>.</p>\n\n<p>why reinvent the wheel if there is already one free to use?\nYou will be much more productive and flexible this way.</p>\n\n<p>to check for hosts active in an ipv4 network you would usually do a:</p>\n\n<pre><code>nmap -sP 192.168.100.0/24 \n</code></pre>\n\n<p>which basically does a ping and takes in most cicumstances 2-5 sec.</p>\n\n<p>nmap is also avaiable for <a href=\"http://nmap.org/download.html#windows\" rel=\"nofollow\">windows</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:10:26.517",
"Id": "22129",
"Score": "0",
"body": "nmap is frowned upon in the network :/ . Plus we only want to check specific hosts not network ranges."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:14:40.370",
"Id": "22130",
"Score": "0",
"body": "frowned? why? thats like a chirurg using a scalpel being frowned on not using a dull spoon."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T12:04:20.180",
"Id": "13686",
"ParentId": "13683",
"Score": "0"
}
},
{
"body": "<p>Here's a solution using threads:</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\nimport Queue\nimport threading\n\ndef worker_func(pingArgs, pending, done):\n try:\n while True:\n # Get the next address to ping.\n address = pending.get_nowait()\n\n ping = subprocess.Popen(ping_args + [address],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n out, error = ping.communicate()\n\n # Output the result to the 'done' queue.\n done.put((out, error))\n except Queue.Empty:\n # No more addresses.\n pass\n finally:\n # Tell the main thread that a worker is about to terminate.\n done.put(None)\n\n# The number of workers.\nNUM_WORKERS = 4\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\n\n# The arguments for the 'ping', excluding the address.\nif plat == \"Windows\":\n pingArgs = [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\"]\nelif plat == \"Linux\":\n pingArgs = [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\"]\nelse:\n raise ValueError(\"Unknown platform\")\n\n# The queue of addresses to ping.\npending = Queue.Queue()\n\n# The queue of results.\ndone = Queue.Queue()\n\n# Create all the workers.\nworkers = []\nfor _ in range(NUM_WORKERS):\n workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))\n\n# Put all the addresses into the 'pending' queue.\nwith open(hosts, \"r\") as hostsFile:\n for line in hostsFile:\n pending.put(line.strip())\n\n# Start all the workers.\nfor w in workers:\n w.daemon = True\n w.start()\n\n# Print out the results as they arrive.\nnumTerminated = 0\nwhile numTerminated < NUM_WORKERS:\n result = done.get()\n if result is None:\n # A worker is about to terminate.\n numTerminated += 1\n else:\n print result[0] # out\n print result[1] # error\n\n# Wait for all the workers to terminate.\nfor w in workers:\n w.join()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T09:52:03.693",
"Id": "26177",
"Score": "0",
"body": "sorry for the delayed response this part of my project has to take a massive \"side-step\". Couple of questions... NUM_WORKERS... I assume this is the amount of pings done in one cycle, for exaample you have \"4\" this would mean 4 hosts would be pinged in one go. Also am I right in assuming I would feed my ip addresses in as `pending`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-02T18:01:57.607",
"Id": "26210",
"Score": "0",
"body": "Each worker gets a host from the pending queue, sends a ping, and puts the reply in the done queue, repeating until the pending queue is empty. There are NUM_WORKERS workers, so there are at most concurrent pings. Note that it fills the pending queue before starting the workers. Another way of doing it is to replace \"pending.get_nowait()\" with \"pending.get()\" and put a sentinel such as None in the pending queue at the end to say that there'll be no more hosts; when a worker sees that sentinel, it puts it back into the pending queue for the other workers to see, and then breaks out of its loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T07:42:33.910",
"Id": "26241",
"Score": "0",
"body": "Ha! I didn't actually scroll down on the code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-03T08:40:41.630",
"Id": "26242",
"Score": "0",
"body": "This is amazing! How many threads is too many? Is there a any calculations that I can perform to (i.e. using CPU and memory, etc) work out what the optimal number of threads is? - I have tried a few, and got the script to finish the list in about 13 seconds (it was in minutes before)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T13:46:10.253",
"Id": "26360",
"Score": "0",
"body": "The optimal number of threads depends on several factors, including the ping response time, so you'll just need to test it with differing numbers of threads. I expect that increasing the number of threads will decrease the run time, but with diminishing returns, so just pick a (non-excessive) number of threads which gives you a reasonable run time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T15:37:47.033",
"Id": "26366",
"Score": "0",
"body": "okay cool... one more thing, occasionally the script hangs once it has reached the end of the hosts file. I'm guessing this is an issue the threads not closing... is there a way to time then out, say after 30seconds?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-04T19:29:55.277",
"Id": "26381",
"Score": "0",
"body": "Try adding a `finally` clause to the `try` and put the `done.put(None)` line in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T10:01:15.127",
"Id": "26396",
"Score": "0",
"body": "Thanks, I still see it hang occasionally... if I put a timeout in the `join()` call, will that do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-05T17:56:15.467",
"Id": "26407",
"Score": "0",
"body": "I don't know. Why did you try it? :-) I also suggest making the threads 'daemon' threads. I've edited the code to do that."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T19:31:28.377",
"Id": "13691",
"ParentId": "13683",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "13691",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T11:41:14.833",
"Id": "13683",
"Score": "6",
"Tags": [
"python",
"performance",
"networking",
"status-monitoring"
],
"Title": "Pinging a list of hosts"
}
|
13683
|
<p>Any suggestions/improvements for the following custom thread-pool code?</p>
<pre><code>import threading
from Queue import Queue
class Worker(threading.Thread):
def __init__(self, function, in_queue, out_queue):
self.function = function
self.in_queue, self.out_queue = in_queue, out_queue
super(Worker, self).__init__()
def run(self):
while True:
if self.in_queue.empty(): break
data = in_queue.get()
result = self.function(*data)
self.out_queue.put(result)
self.in_queue.task_done()
def process(data, function, num_workers=1):
in_queue = Queue()
for item in data:
in_queue.put(item)
out_queue = Queue(maxsize=in_queue.qsize())
workers = [Worker(function, in_queue, out_queue) for i in xrange(num_workers)]
for worker in workers:
worker.start()
in_queue.join()
while not out_queue.empty():
yield out_queue.get()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T21:03:07.577",
"Id": "221086",
"Score": "0",
"body": "I recommend looking into the `multiprocessing.pool.ThreadPool` object, also explained [here](http://stackoverflow.com/questions/3033952/python-thread-pool-similar-to-the-multiprocessing-pool)."
}
] |
[
{
"body": "<ol>\n<li><p>The function <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map\" rel=\"nofollow\"><code>concurrent.futures.ThreadPoolExecutor.map</code></a> is built into Python 3 and does almost the same thing as the code in the post. If you're still using Python 2, then there's a <a href=\"https://pypi.python.org/pypi/futures/3.0.5\" rel=\"nofollow\">backport of the <code>concurrent.futures</code> package</a> on PyPI.</p></li>\n<li><p>But considered as an exercise, the code here seems basically fine (apart from the lack of documentation), and the remaining comments are minor issues.</p></li>\n<li><p><code>Worker.run</code> could be simplified slightly by writing the loop condition like this:</p>\n\n<pre><code>while not self.in_queue.empty():\n # ...\n</code></pre></li>\n<li><p>There's no need to pass a <code>maxsize</code> argument to the <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue\" rel=\"nofollow\"><code>Queue</code></a> constructor—the default is that the queue is unbounded, which is fine.</p></li>\n<li><p>The only use of the <code>workers</code> list is to start the workers. But it would be easier to start each one as you create it:</p>\n\n<pre><code>for _ in range(num_workers):\n Worker(function, in_queue, out_queue).start()\n</code></pre></li>\n<li><p>The results come out in random(-ish) order because threads are nondeterministic. But for many use cases you would like to know which input corresponds to which output, and so you'd like the outputs to be in the same order as the inputs (as they are in the case of <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map\" rel=\"nofollow\"><code>concurrent.futures.ThreadPoolExecutor.map</code></a>).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-26T14:07:52.500",
"Id": "142503",
"ParentId": "13690",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-15T18:56:53.000",
"Id": "13690",
"Score": "2",
"Tags": [
"python",
"multithreading"
],
"Title": "Custom thread-pooling"
}
|
13690
|
<p>When I read some code,I think the usage of Event is not necessary,is it right?</p>
<pre><code># start server
while True:
# accept a request here
queue.put(info)
event.set() # notify all the threads?
# pass queue and event here to a Thread constructor
</code></pre>
<p>other place there are more than 10 threads running,</p>
<pre><code># inside a Thread class
def __init__(self, queue, event):
threading.Thread.__init__(self)
self.queue, self.event = queue, event
def run(self):
while True:
self.event.wait() # <- block here, I think this can be removed
info = self.queue.get() # <- block here again, only one thread can get job to do?
# do something
self.queue.task_done()
self.event.clear() #
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T01:49:19.680",
"Id": "22198",
"Score": "0",
"body": "In the small snippets of code that you posted, it does indeed seem that `event` is unnecessary. Furthermore, it seems as if event is global, which is probably not a good idea either, if it is to be used, event should be stored as an instance variable of the thread class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T07:42:00.363",
"Id": "22200",
"Score": "0",
"body": "They are not global,I have updated the snippet."
}
] |
[
{
"body": "<p>As long as <code>queue</code> is actually <code>Queue.Queue</code> (or another collection with its own blocking mechanic), the event object is not required in the code you posted. <del>I'd even say that it's used incorrectly. There is a racing condition when the server calls <code>event.set()</code> and a thread is just done with its current task, calling <code>event.clear()</code>. This leaves all threads waiting on the event, even though there's an item in the queue. </del></p>\n\n<p>Edit: Bollocks, didn't think that one through. <code>event.set()</code> wakes up all threads that are hanging on <code>event.wait()</code>, causing them to continue waiting at <code>queue.get()</code>. One thread will fetch the item and process it. So, no racing condition. Just redundancy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T17:04:12.263",
"Id": "22213",
"Score": "0",
"body": "IOW `Queue.Queue` is thread-safe."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T08:14:10.837",
"Id": "13741",
"ParentId": "13693",
"Score": "2"
}
},
{
"body": "<p>The Queue module has implemented multi-producer, multi-consumer queues, which is thread-safe.So you can remove event object.The queue.get() will block there and wait something to happen that you expected.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T08:21:55.783",
"Id": "13775",
"ParentId": "13693",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13741",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T03:42:09.247",
"Id": "13693",
"Score": "3",
"Tags": [
"python",
"multithreading"
],
"Title": "Is Event.wait necessary here?"
}
|
13693
|
<p>I am new to Groovy and I am having a little problem with constructors of subclasses. Basically, I have a base abstract class like</p>
<pre><code>class BaseClass {
def BaseClass(Map options) {
// Does something with options,
// mainly initialization.
}
// More methods
}
</code></pre>
<p>and a bunch of derived classes like</p>
<pre><code>class AnotherClass extends BaseClass {
// Does stuff
}
</code></pre>
<p>I would like to be able to create instances like</p>
<pre><code>def someObject = new AnotherClass(foo: 1, bar: 2)
</code></pre>
<p>Unfortunately, Groovy creates automatically all sorts of constructors for <code>AnotherClass</code>, with various signatures - based on the properties of <code>AnotherClass</code> - but will not allow me to just reuse the constructor in <code>BaseClass</code>. I have to manually create one like</p>
<pre><code>class AnotherClass extends BaseClass {
def AnotherClass(options) {
super(options)
}
// Does stuff
}
</code></pre>
<p>It feels repetitive doing so for each subclass, and it is probably the wrong way.</p>
<p>What would be the Groovy way to share some logic in the constructor?</p>
|
[] |
[
{
"body": "<p><code>@InheritConstructors</code> is probably what you are looking for:</p>\n\n<pre><code>@InheritConstructors\nclass AnotherClass extends BaseClass {}\n</code></pre>\n\n<p>will create the constructors corresponding to the superclass constructors for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T08:01:08.090",
"Id": "22144",
"Score": "2",
"body": "Thank you very much, this is exactly what I was looking for! By the way, for possible future readers, `InheritConstructors` lives in the package `groovy.transform`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T07:39:38.137",
"Id": "13697",
"ParentId": "13696",
"Score": "19"
}
}
] |
{
"AcceptedAnswerId": "13697",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T07:28:32.593",
"Id": "13696",
"Score": "12",
"Tags": [
"constructor",
"groovy"
],
"Title": "Constructors and inheritance in Groovy"
}
|
13696
|
<p>I am writing code for a very basic jQuery slider with the following features:</p>
<ol>
<li>Slide the content left or right on click of next/previous links till there is no more content on the clicked side.</li>
<li>If any content is added dynamically, the entire content should slide.</li>
</ol>
<p>While there are still many additions and modifications necessary, I would like to know if my approach is correct and the code that I am writing is going the correct way.</p>
<p>I am planning to write a plugin for this later.</p>
<p><a href="http://jsfiddle.net/gentrobot/RY3TH/2/" rel="nofollow noreferrer">jsFiddle</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $('#next').click(function(){
//slide a div only if there is a next element
if($('.currentRight').length >0)
{
$('.current').animate({left:'-100px'}).removeClass('current').addClass('currentLeft').next().animate({left:'0px'}).removeClass('currentRight').addClass('current');
}
});
$('#previous').click(function(){
//slide a div only if there is a previous element
if($('.currentLeft').length >0)
{
$('.current').animate({left:'100px'}).removeClass('current').addClass('currentRight').prev().animate({left:'0px'}).removeClass('currentLeft').addClass('current');
}
});
$('#add').click(function(){
//it is used for simplicity's sake. I intend to use append()/prepend() to add more content
var cont = $('.current').html()+'More<br/>';
$('.current').html(cont);
var ht = $('.current').css('height');
$('#container').css('height',ht);
}); </code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> /*the main div that contains all the sliding div*/
#container{
width:100px;
border:1px solid #000;
height:20px;
position: relative;
overflow:hidden;
}
/*there are 3 different classes
* current - div that is presently visible
* currentLeft - div that should slide from left on pressing previous
* currentRight - div that should slide from right on pressing next
*/
.current{
width:99px;
height:auto;
position: absolute;
float: left;
left:0px;
}
.currentLeft{
width:99px;
height:auto;
position: absolute;
left:-100px;
float:left;
}
.currentRight{
width:99px;
height:auto;
position: absolute;
left:100px;
float:left;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="currentLeft">
First Div
</div>
<div class="current">
Second Div
</div>
<div class="currentRight">
Third Div
</div>
</div>
<a href="#" id="previous">Previous</a>
<a href="#" id="next">Next</a>
<a href="#" id="add">Add content</a>
</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T09:50:26.860",
"Id": "22146",
"Score": "1",
"body": "On code review one is supposed to include at least part of one's code in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T10:05:07.970",
"Id": "22147",
"Score": "0",
"body": "The link for the fiddle has the entire code. I thought it would be easier to review the code at the fiddle since the jQuery, CSS and HTML are separated and also are working."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T10:10:09.850",
"Id": "22148",
"Score": "0",
"body": "@Inkbug: Included the code. Thanks for improvement suggestions :)"
}
] |
[
{
"body": "<p><a href=\"http://jsfiddle.net/RY3TH/3/\" rel=\"nofollow\">JsFiddle</a></p>\n\n<p>Not writing this as a plugin here are some suggestions:</p>\n\n<ol>\n<li>instead of <code>removeClass('a').addClass('b')</code> use <code>toggleClass('a b')</code></li>\n<li>instead of searching the entire DOM for <code>.current</code> you should constrain it to the children of <code>#container</code></li>\n<li>instead of <code>css('height')</code> use <code>height()</code></li>\n<li>you should set the container height to the maximum height of all child elements, not just the height of the current visible one</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T14:17:06.253",
"Id": "13713",
"ParentId": "13698",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13713",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T08:46:17.257",
"Id": "13698",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Basic jQuery slider"
}
|
13698
|
<p>I have written a JS library (think, jQuery, but with much much less features, and targeted for newer browsers on mobile). This library provides an extension mechanism. One of the ways the extension can be defined is:</p>
<pre><code>$.extension("extname", function(options) {
this.forEach(function(elem) {
// do something
});
return this; // for chaining.
});
</code></pre>
<p>This can be later used like so:</p>
<pre><code>$("#myId").extname({various: "options"});
</code></pre>
<p>Using this mechanism I've written UI widgets (as extensions). <strong>For UI widgets that have state I don't want to have chaining like jQuery does.</strong> I want widget objects with various methods. I am aware (although I'm not too sure) that jQuery UI uses a different
pattern for UI widgets.</p>
<p>e.g. In jQuery, if you have an accordion widget, then you have to use it like so (example only, not actual widget):</p>
<pre><code>$("#acc").accordion({various: "options"}).accordion(
"collapse", 0).accordion("expand", 1); //etc.
</code></pre>
<p>Although I like chaining and use it in various cases, I am not particularly a fan of this style when it comes to stateful widgets.</p>
<p>I would like widgets to be used like so:</p>
<pre><code>var acc = $("#acc").accordion(options);
acc.collapse(0).expand(1);
acc.getExpanded(); // etc.
</code></pre>
<p>I've written a data list widget using the extension mechanism above in the following way:</p>
<pre><code>(function($, undefined) {
var defaults = {
// various defaults for list widget
},
extend = $.extend,
other, variables;
// these functions don't depend or modify any state of the widget
function thoseNotDependingOnState() {
}
$.extension("datalist", function(options) {
var opts = extend({}, defaults, options),
data = [], // data for this list
self = this,
widget,
privateVars_maintaining_state;
// these functions work on private state of the widget
function someFunctionDependingOnPrivateState() {}
widget = {
getItems: function() {},
selectItemAt: function(index) {},
addItem: function(itm) {}
// etc.
};
return widget;
});
})(h5);
</code></pre>
<p>Since there's a chance that some widgets will be used a lot, resulting the call of the extension function, re-defining functions (private) everytime a new widget is created does not make sense(?), so I'm planning to do this in the following way. Here the bulk of the behaviour is defined in the prototype. The wrapper is only a lightweight object that delegates all the calls to the underlying widget and exposes only the widget's public API. <strong>The convention followed here is that all the private members of the widgets have names starting with an '_' character.</strong></p>
<pre><code>(function($, undefined) {
var defaults = {
// various defaults for list widget
},
extend = $.extend,
other, variables,
widgetProto; // This is the prototype object
// from which all the list widgets inherit.
function thoseNotDependingOnState() {
}
widgetProto = {
/* ----------------- Private variables ---------------------- */
_data: [],
_element: null, // ui element associated with this list
_allItems: [],
/* ----------------- Private functions ---------------------- */
/* Initialize the list from options passed to factory */
_init: function(element, options) {
},
_createListItem: function() {},
// other private functions
/* -------------------- Public Api --------------------------- */
getItems: function() {},
getItemAt: function(i) {},
addItem: function() {}
// other public functions
};
$.extension("datalist", function(options) {
var widget = Object.create(widgetProto), widgetWrapper = {};
// initialize the widget, passing the dom wrapper
widget._init(this, $.extend({}, defaults, options));
// prepare the wrapper
$.forEach(widget, function(val, prop) {
var property;
// expose only public API, i.e all properties
// not starting with an '_'
if(prop.indexOf("_") !== 0) {
if(typeof val === "function") {
widgetWrapper[prop] = function() {
return val.apply(widget, arguments);
}
}else {
property = capitalize(prop);
widgetWrapper["get" + property] = function() {
return widget[prop];
};
widgetWrapper["set" + property] = function(v) {
widget[prop] = v;
};
}
}
});
return widgetWrapper;
});
})(h5);
</code></pre>
<p>With all this, I have two questions:</p>
<ol>
<li><p>Do you think its a good idea to do away with chaining pattern for widgets?</p></li>
<li><p>Of the above two approaches, does the second one provide any advantages in terms of performance (memory or otherwise)?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-15T16:14:20.077",
"Id": "23891",
"Score": "0",
"body": "You say you want to do away with chaining, but your example, `acc.collapse(0).expand(1);` uses chaining. Also, you may want to read this part of Addy Osmani's book about JavaScript Patterns: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T15:36:59.120",
"Id": "29574",
"Score": "0",
"body": "@Mike, what I meant was, I didn't want to have jQuery-like chaining e.g. $.accordion(\"expand\", 1).accordion(\"collapse\", 3), etc. But I'm okay with chaining where it makes sense in method calls, like $(\"selector\").accordion({}).expand(1).collapse(3). Btw Thanks for the book link :)"
}
] |
[
{
"body": "<p>Are you aware that <a href=\"http://wiki.jqueryui.com/w/page/12138135/Widget-factory\" rel=\"nofollow\">you can use JQueryUI widgets like this</a>:</p>\n\n<pre><code>var acc = $('#acc').accordion(options).data('accordion');\nacc.collapse(0);\nacc.expand(1);\nacc.getExpanded(); // etc.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T15:36:17.257",
"Id": "22170",
"Score": "0",
"body": "Yes Bill, but doesn't the accordion object 'acc' has all the private properties and functions too? I think we can call `acc._insertItem()`. This is what I don't want."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:09:14.373",
"Id": "13710",
"ParentId": "13699",
"Score": "0"
}
},
{
"body": "<p>@naikus, Bill Barry's point is rather accurate -- chainable methods are for convenience rather than convention. You can structure your method calls either way, though the chaining helps with expressiveness in your code (readability is up to the developer.)</p>\n\n<p>So, no--I wouldn't do away with chaining unless you absolutely want or need to for some reason.</p>\n\n<p>As for your second question, I'd be in favour of your first approach for a couple reasons:</p>\n\n<ol>\n<li>Legibility -- far easier to read, and honestly, far more flexible.</li>\n<li>Maintainability -- the pattern can be extended to make use of a factory if you want, and still have the benefits of being legible and maintainable.</li>\n</ol>\n\n<p>As for your actual widgets, I think you might need to spend a little more time looking at implementations of the JS Design patterns you're using--and not because what you have is wrong, but I found it really cumbersome to follow. Here's a couple sources that really helped me when I was developing my own system:</p>\n\n<ol>\n<li><a href=\"http://www.klauskomenda.com/code/javascript-programming-patterns/#module\" rel=\"nofollow\">http://www.klauskomenda.com/code/javascript-programming-patterns/#module</a></li>\n<li><a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow\">http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth</a></li>\n</ol>\n\n<p>jQuery's plugin system is quite flexible. It's use of a module pattern gives developers the ability to declare public and private members/methods. My own module system is heavily inspired by it:</p>\n\n<pre><code>(function( o ){\n\n // +------------------------------------------------------------------------+\n // MEMBERS (PRIVATE)\n // +------------------------------------------------------------------------+\n var parent = this;\n var $ = {};\n\n // +------------------------------------------------------------------------+\n // METHODS (PRIVATE)\n // +------------------------------------------------------------------------+\n // Inject dependencies\n function init( jQuery, ModuleNamespace )\n {\n $ = jQuery;\n parent = ModuleNamespace;\n\n console.log( 'READY: BaseModule::init()', $, parent ); \n\n }\n\n function __notify( strEvent, objData )\n {\n switch( strEvent )\n {\n case 'onReady' :\n case 'onModuleReady' :\n init( objData.jQuery, objData.ModuleNamespace );\n break;\n default :\n break;\n }\n }\n\n // +------------------------------------------------------------------------+\n // METHODS (PRIVATE)\n // +------------------------------------------------------------------------+\n\n // +------------------------------------------------------------------------+\n // METHODS (PUBLIC)\n // +------------------------------------------------------------------------+\n o.notify = __notify; // Expose private methods\n\n // Broadcast when this module is loaded\n ModuleNamespace.EventDispatcher.notify( 'onModuleReady', o );\n\n return o;\n\n})( window.ModuleNamespace.BaseModule = window.ModuleNamespace.BaseModule || {} );\n</code></pre>\n\n<p>This base module is my starting point for my plugins. <code>ModuleNamespace</code> is a reference to a parent object, e.g. <code>window.ModuleNamespace</code> to keep things as self contained as possible. The example module illustrates dependency injection (<code>jQuery</code> and the <code>ModuleNamespace</code> objects), which I fall back to when dependencies like <code>jQuery</code> are already a mainstay in the project; however, you could limit this to simply, <code>ModuleNamespace</code>. I also make use of an <code>EventDispatcher</code> module (observer pattern) to deal global state handling, but bubbling up events through callbacks etc, is still possible. </p>\n\n<p>It's easy enough to create a <code>Factory</code> method or object similar to jQuery UI's widget factory, or to go the common plugin route and extend. </p>\n\n<p>All this to say, I would favour a simpler approach to encapsulation and extendability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-15T00:41:00.603",
"Id": "17540",
"ParentId": "13699",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T09:03:02.307",
"Id": "13699",
"Score": "2",
"Tags": [
"javascript",
"library",
"plugin"
],
"Title": "Library providing an extension mechanism"
}
|
13699
|
A plug-in (or plugin) is a set of software components that adds specific abilities to a larger software application. If supported, plug-ins enable customizing the functionality of an application.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T09:47:50.717",
"Id": "13702",
"Score": "0",
"Tags": null,
"Title": null
}
|
13702
|
<p>This is sort of a follow up question on <a href="https://stackoverflow.com/questions/754661/httpruntime-cache-best-practices/11431198">https://stackoverflow.com/questions/754661/httpruntime-cache-best-practices/11431198</a> where a reply from frankadelic contains this quote and code sample from <a href="http://msdn.microsoft.com/en-us/magazine/cc500561.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc500561.aspx</a>:</p>
<blockquote>
<p>The problem is that if you've got a query that takes 30 seconds and you're executing the page every second, in the time it takes to populate the cache item, 29 other requests will come in, all of which will attempt to populate the cache item with their own queries to the database. To solve this problem, you can add a thread lock to stop the other page executions from requesting the data from the database.</p>
</blockquote>
<pre><code>// check for cached results
object cachedResults = ctx.Cache["PersonList"];
ArrayList results = new ArrayList();
if (cachedResults == null)
{
// lock this section of the code
// while we populate the list
lock(lockObject)
{
// only populate if list was not populated by
// another thread while this thread was waiting
if (cachedResults == null)
{
...
}
}
}
</code></pre>
<p>In my opinion this code sample would have benefitted from showing the actual cache assign/get logic as well. My assumption also is that the <code>cachedResults</code> reference in the sample above should be a static reference, otherwise different threads wont access the same instance.</p>
<p>Is this correct and would the following be a correct implementation of a property where you want to lazy-load data through the cache?</p>
<pre><code>private static object _someDataCacheLock = new object();
private static object _cachedResults;
public List<object> SomeData
{
get
{
HttpContext ctx = HttpContext.Current;
_cachedResults = ctx.Cache["SomeData"] as List<object>;
if (_cachedResults == null)
{
// lock this section of the code
// while we populate the list
lock (_someDataCacheLock)
{
// only populate if list was not populated by
// another thread while this thread was waiting
if (_cachedResults== null)
{
_cachedResults= GetSomeData(); //db access inside GetSomeData()
ctx.Cache.Insert("SomeData",
_cachedResults,
null, DateTime.Now.AddMinutes(10),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
}
return _cachedResults;
}
}
</code></pre>
<hr>
<p>Ok, so I'm going ahead with this code instead, where I've added one row that in my opinion must have been missing from the MSDN sample... Any feedback on this?</p>
<pre><code>private static object _someDataCacheLock = new object();
public List<object> SomeData
{
get
{
HttpContext ctx = HttpContext.Current;
List<object> cachedResults = ctx.Cache["SomeData"] as List<object>;
if (cachedResults == null)
{
// lock this section of the code
// while we populate the list
lock (_someDataCacheLock)
{
//This row was missing in the MSDN sample, I believe...
cachedResults = ctx.Cache["SomeData"] as List<object>;
// only populate if list was not populated by
// another thread while this thread was waiting
if (cachedResults == null)
{
cachedResults = GetSomeData(); //db access inside GetSomeData()
ctx.Cache.Insert("SomeData",
cachedResults,
null, DateTime.Now.AddMinutes(10),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
}
return cachedResults;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:23:46.130",
"Id": "22157",
"Score": "0",
"body": "Did you mean to write `_cachedResults` instead of `_cachedResults`? And what is the type of the object, `List<object>` or `PageDataCollection`?"
}
] |
[
{
"body": "<p>First, I think your code doesn't make much sense. The only reason why <code>Cache</code> can be useful is if you want the cached data to expire after some time or if the memory is low. But you're preventing the memory to be freed by using the field <code>_cachedResults</code>, which will hold the data even after they are removed from the cache. This field is of no use for you, <code>_cachedResults</code> should be a local variable instead.</p>\n\n<p>Second, your code is not reliably thread-safe, because of the way you're assigning to <code>_cachedResults</code>. What could happen is if <code>GetSomeData()</code> creates the result using <code>new</code>, an uninitialized object could be first assigned to <code>_cachedResults</code> and only then would be the constructor called. Such reordering could happen, because it's safe from the point of view of a single thread.</p>\n\n<p>Normally, you would solve this by using a volatile write. But in your case, simply using a local variable instead of a field will be enough.</p>\n\n<p>For more details, see <em>The Famous Double-Check Locking Technique</em> in Chapter 29 of Jeffrey Richter's <em>CLR via C#</em>, or <a href=\"http://en.wikipedia.org/wiki/Double-checked_locking\" rel=\"nofollow\">the Wikipedia article <em>Double-checked locking</em></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T02:37:27.353",
"Id": "22199",
"Score": "0",
"body": "Ah, you're right about that. But how can the second null check be of much use then? Shouldn't I try to get the data from the cache again before that?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:34:42.447",
"Id": "13706",
"ParentId": "13704",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T11:38:52.117",
"Id": "13704",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"cache"
],
"Title": "How to correctly use lock when adding/renewing cached data in asp.net cache?"
}
|
13704
|
<p>We have an in-house time-tracking application at the office.</p>
<p>We, the employees, can view an overview of our hours on a web page. This web page renders a table, with worked hours per day in table cells, which is styled as a monthly calendar. I wrote a small script which I can copy-paste in my console to get a total of hours worked too much for that month.</p>
<p>A relevant snippet of the HTML.</p>
<pre><code><td height="17" align="right" >
<font size="1">10</font>
<b><font size="2">&nbsp;</font></b>
<a href="/something/a" class="link">
<b><font size="2" color=black>08:33 </font></b>
</a>
</td>
<td height="17" align="right" ><font size="1">11</font>
<b><font size="2">&nbsp;</font></b>
<a href="/something/b" class="link">
<b><font size="2" color=black>08:25 </font></b>
</a>
</td>
</code></pre>
<p>The JavaScript snippet.</p>
<pre><code>var elementsToParse = $(".link").find("font:not(:empty)");
var totalMinutes = 0;
$.each(elementsToParse, function(index, element) {
var text = $(element).text();
var hours = parseInt(text.substr(1, 2));
var minutes = parseInt(text.substr(3, 2));
var elementTotal = ((hours * 60) + minutes) - 480;
totalMinutes += elementTotal;
});
alert('Overtime so far: ' + totalMinutes + ' minutes');
</code></pre>
<p>Any thoughts on how to make the script more compact or elegant, while maybe improving readability?</p>
|
[] |
[
{
"body": "<p>Well, you only need to pass parameters to <code>each</code> if you need the index.</p>\n\n<pre><code>$.each(elementsToParse, function() {\n var text = $(this).text();\n</code></pre>\n\n<p>Also, a more elegant way than <code>substr</code> is just using <code>split</code>. You can <code>trim</code> the text before that.</p>\n\n<pre><code>var text = $.trim( $(this).text() ).split(':'),\n hours = parseInt( text[0], 10 ),\n minutes = parseInt( text[1], 10 );\n</code></pre>\n\n<p>Don't forget the second parameter of <code>parseInt</code> :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:57:43.763",
"Id": "22158",
"Score": "0",
"body": "How could I forget the second parseInt argument!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:04:07.687",
"Id": "22159",
"Score": "1",
"body": "Use `+x` instead of `parseInt(x,10)`. It is [faster](http://jsperf.com/str2intbench/4), shorter and doesn't lose any conveyed meaning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:10:57.593",
"Id": "22160",
"Score": "0",
"body": "Is it more readable, though? (rhetorical question)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:48:18.020",
"Id": "22162",
"Score": "1",
"body": "If you're not a js regular, it might not be very explicit, not to say plain obscure. But hey, learn the good parts, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T14:55:45.113",
"Id": "22169",
"Score": "2",
"body": "Yes +x is faster, but be careful as it will not have the same results as parseInt(x, 10) if x is not a number. If x = '10px', parseInt(x, 10) will return 10 where +x will return NaN."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:40:50.127",
"Id": "13707",
"ParentId": "13705",
"Score": "1"
}
},
{
"body": "<p>I would make it less compact to improve readability. Leave it up to your build process (minifier) to make things compact. Your goal should be to make things understandable.</p>\n\n<p><strong>Use regular expressions</strong></p>\n\n<p>In cases like this, where you have a strict format, I <em>love</em> using regular expressions:</p>\n\n<pre><code>/** @const */\nvar TIME_FORMAT = /(\\d{2}):(\\d{2})/;\n...\n\"10:30\".match(TIME_FORMAT) // == [\"10:30\", \"10\", \"30\"]\n</code></pre>\n\n<p>This makes it clear that you expect a date to consist of two digits a colon, and two more digits. As a bonus, let everyone know it's a constant with JSDoc and common coding conventions.</p>\n\n<p><strong>Define functions</strong></p>\n\n<p>Short modular code is easy to read:</p>\n\n<pre><code>/**\n * Parses a time string and returns the hours and minutes.\n */\nfunction parseTime(text) {\n var match = String(text).match(TIME_FORMAT);\n\n if (match === null) {\n throw new Error('Time \"' + text + '\" could not be parsed.');\n }\n\n return {\n hours: Number(match[1]),\n minutes: Number(match[2])\n };\n}\n\n/**\n * Gets the total minutes of overtime based on time worked and number of working hours\n * in a day.\n */\nfunction calculateOvertime(parsedTime, workingHours) {\n var minutesWorked = parsedTime.hours * 60 + parsedTime.minutes;\n var minutesRequired = workingHours * 60;\n return minutesWorked - minutesRequired;\n}\n</code></pre>\n\n<p>Here, the <code>parseTime</code> parses the time, returning an object, and <code>calculateOvertime</code> calculates the overtime.</p>\n\n<p><strong>Put it all together</strong></p>\n\n<p>Putting it together, your actual function does become more compact and more readable because tangental functions are extracted:</p>\n\n<pre><code>/**\n * Gets the total minutes of overtime from a tracking table.\n *\n * @param selector A CSS2.1 selector, DOM element or jQuery object pointing to the\n * tracking table.\n */\nfunction getOvertimeFromTable(selector, dailyWorkingHours) {\n var totalMinutesOfOvertime = 0;\n var $dailyTimes = $(selector).find(\"font:not(:empty)\");\n\n $dailyTimes.each(function () {\n var parsedTime = parseTime($(this).text());\n var minutesOfOvertime = calculateOvertime(parsedTime, dailyWorkingHours);\n\n totalMinutesOfOvertime += minutesOfOvertime;\n });\n}\n\nalert('Overtime so far: ' + getOvertimeFromTable('.links', 8) + ' minutes');\n</code></pre>\n\n<p><strong>Protecting global, enabling compilation</strong></p>\n\n<p>Right now we are exposing a variety of variables and functions on the global object. This means that anyone could call <code>parseTime</code> or read a similar function. It also means a minifier can't rename the function to a shorter name. Wrapping everything in a closure will be the final step for making sure your output code is more compact and your source needn't be:</p>\n\n<pre><code>/**\n * Alerts the number of hours of overtime you have accumulated so far in this pay cycle,\n * assuming a standard 8-hour day.\n */\n(function () {\n /* Your code here */\n}());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:04:50.163",
"Id": "13723",
"ParentId": "13705",
"Score": "3"
}
},
{
"body": "<p>As Inkbug mentions, you could run <code>each()</code> straight on the query. <code>split()</code> is definitely an elegant means to retrieve minutes and hours. For style reasons, you probably should have 1 <code>var</code> inside the the <code>each()</code> function. You could split up <code>480</code> into <code>60 * 8</code>, this makes it clear you are supposed to work 8 hours a day. Finally, if you put the code inside a self executing function, you will not mess up the global namespace, and you can then store the code as a bookmarklet.</p>\n\n<p>This should work:</p>\n\n<pre><code>void((function () {\n var totalMinutes = 0;\n $(\".link\").find(\"font:not(:empty)\").each(function () {\n var time = $(this).text().split(\":\"),\n hours = +time[0],\n minutes = +time[1],\n overtime = ((hours * 60) + minutes) - (8 * 60);\n\n totalMinutes += overtime;\n });\n\n alert('Overtime so far: ' + totalMinutes + ' minutes');\n})());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:04:11.863",
"Id": "37307",
"ParentId": "13705",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:32:55.243",
"Id": "13705",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"portability"
],
"Title": "Optimizing a JavaScript snippet for portability and readability"
}
|
13705
|
<p>I am filtering a List (childList) based on the contents of another List (parentList).</p>
<p>The parentList can contain 0-n entities where items of the childList are referenced by an ID (btw. ID is in this case a string, you could also call it "Name" or whatever you like). I want to filter the childList in a way that the result is all elements that have at least one entry in the parentList.</p>
<p>The obvious solution is:</p>
<pre><code>List<childItem> resultList = new List<childItem>();
foreach(var childItem in childList){
foreach(var parentItem in parentList){
if(childItem.ID.Equals(parentItem.ChildID,StringComparison.InvariantCultureIgnoreCase){
resultList.Add(childItem); //found entity
break; // search for next childItem
}
}
</code></pre>
<p>What I have done by now is:</p>
<pre><code>// Group by childID and create List with all relevant IDs
var groupedParentList = parentList.AsParallel().GroupBy(p => p.ChildID).Select(group => group.First()).ToList();
// Filter childList on groupedParentList
var result = childList.AsParallel().Where(child => groupedParentList.AsParallel().Count(parent => parent.childID.Equals(child.ID, StringComparison.InvariantCultureIgnoreCase)) > 0).ToList();
</code></pre>
<p>But it's lasting rather long. The parentList contains about 75k entries and the childList about 4.5k entries. I just can't believe it actually takes time - imo this should be done in almost no time?</p>
<p>Maybe I am on the wrong track or am I missing some obvious performance-stopper?</p>
<p>Btw.: I have chosen the names parent- and childList just as an example. It's actaully no parent-child-relation. </p>
<p><strong>Additional Question:</strong> Could it be faster to direcly check if the parentList contains the childList-Item? Something a lá:</p>
<pre><code>var test = childList.RemoveWhere(child => !parentList.Contains(item => item.childID.Equals(child.ID));
</code></pre>
<p>So I would just skip the grouping? Any suggestions/ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T13:50:47.673",
"Id": "22163",
"Score": "0",
"body": "Can't you change the entities so that they don't use IDs, but direct references?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T14:02:53.303",
"Id": "22164",
"Score": "0",
"body": "Unluckily - no. Let's say I have no access to the structure itself."
}
] |
[
{
"body": "<p>First red flag; you're using <code>Count(predicate) > 0</code>. The Count() overload that takes a predicate must iterate over all elements of the parent enumerable to determine the correct count, and you're telling it to do so for each element of the child list. You simply want to know if at least one of those elements matches; for that, the Any() overload which accepts the same parameter will be faster, because it will quit as soon as it finds the first element that matches (unfortunately the worst-case of a match not existing will still require a full scan of the enumerable).</p>\n\n<p>You're also parallelizing parallelization. While parallel is good, threads waiting on threads waiting on threads can easily result in an algorithm that is bound by the ThreadPool's ability to spin up new threads (the default is a 250ms wait for each new thread after a predetermined number of \"readily-available\" threads have been scheduled). So, after creating, let's say 10 threads for this algorithm, most of which will be waiting on sub-threads, the ThreadPool will only create four new threads per second. Let's say the TPL begind the PLinq library thinks that one thread per 100 elements of both collections is necessary. On a collection of 4500 elements, for each of which a comparison of 4500 more elements is necessary, the ThreadPool could schedule two thousand worker threads to execute. After 10 of them are created near-instantaneously, only four more per second will be created as long as at least 10 are running, meaning this algorithm will take up to 500 seconds just to schedule all the necessary threads. The more \"instantaneous\" threads you tell the ThreadPool to spin up before queueing them, the more cache-thrashing you'll do forcing the CPU to juggle all these threads.</p>\n\n<p>First step to improving this: Instead of grouping, select a list of distinct child IDs from the parent list. This process will produce strings instead of groups of larger ParentItems, which should hopefully reduce the amount of \"heap-thrashing\" required to generate the groups only to reduce it down to a much smaller collection. You only ever need the child IDs from the parent list anyway.</p>\n\n<pre><code>// Group by childID and create List with all relevant IDs\nvar childrenOfParents = parentList.AsParallel()\n .Select(p => p.childId)\n .Distinct()\n .OrderBy(x=>x)\n .ToList();\n</code></pre>\n\n<p>Then, filter the child list based on the ID being in the derived list of child IDs:</p>\n\n<pre><code>// Filter childList on groupedParentList\nvar result = childList.AsParallel()\n .Where(child => childrenOfParents\n .Any(cid=>cid.Equals(child.ID, StringComparison.InvariantCultureIgnoreCase)))\n .ToList();\n</code></pre>\n\n<p>I do not know about the culture-specific comparison behavior, but if it's at all possible to compare the strings verbatim (even ToLower()ed), it would likely be preferable performance-wise.</p>\n\n<p>Other things that may help include building custom extension methods that make certain assumptions:</p>\n\n<ul>\n<li><p>Naive grouping or deduping (Distinct()) of an enumerable is an N<sup>2</sup>-complexity operation (compare each element to a list of already-processed elements and remove if it exists). This is the least efficient part of the first query. Deduping of a list sorted by the same projection that must be de-duped is linear (compare each element to the previous one and remove if equal). You will be able to dedupe the list of child IDs more efficiently than PLinq's default implementation if you know the list is sorted by the same projection (in this case the identity projection) that you must dedupe.</p>\n\n<pre><code>public IEnumerable<TObj> SortAndDedupe<TObj, TProj>(this IEnumerable<TObj> input, Func<TObj, TProj> projection)\n{\n sortedInput = input.OrderBy(projection);\n\n TProj last;\n var init = false; //default(T) might be valid\n foreach(var element in sortedInput)\n {\n if(!init || !projection(element).Equals(last))\n {\n init = true;\n last = projection(element);\n yield return element;\n }\n }\n}\n\n...\n\n// Your first query is now an NlogN operation\nvar childrenOfParents = parentList.AsParallel()\n .Select(p => p.childId)\n .SortAndDedupe(s=>s)\n .ToList();\n</code></pre></li>\n<li><p>Naive searching for elements that match a predicate is linear, which makes the second query N<sup>2</sup>-complexity. In your case, with a sorted list of childID strings being searched for a value that is equal to a passed projection, you can use a logarithmic binary search:</p>\n\n<pre><code>public bool IsInSortedList(this T toFind, List<T> collection)\n where T: IComparable<T>\n{\n var max = collection.Count - 1;\n var min = 0;\n var idx = (max-min)/2;\n\n while(max >= min)\n {\n if(collection[idx].CompareTo(toFind) == 0) return true;\n else if(collection[idx].CompareTo(toFind) < 0) //search right\n min = idx+1;\n else if(collection[idx].CompareTo(toFind) > 0) //search left\n max = idx-1;\n\n idx = (max-min)/2 + min; \n }\n\n return false; \n}\n\n...\n\n//This query is now an NlogN as well\nvar result = childList.AsParallel()\n .Where(child => child.IsInSortedList(childrenOfParents)\n .ToList();\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T07:49:07.500",
"Id": "22201",
"Score": "0",
"body": "Thanks for this awesome answer, it really taught me, to read and learn more about datastructures and algorithms.\n\nA few Questions: In SortAndDedupe(..), I needed to initialize the TProj last with default(T) and I had to reverse your if() in the while(). By doing this I removed the init-bool. (Otherwise I always got only one result back).\nDid I implement it wrong, or was it just a typo? (I just want to make sure, I did it right! :) )\nBtw. your solution is great (I will use it), but it also takes 3 sec. - the same as my initial try :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T14:32:57.210",
"Id": "22208",
"Score": "1",
"body": "The condition that the current element must equal the last should actually be that the current element does *not* equal the last one. Use of default(TProj) to initialize `last`, thus doing away with `init`, is OK as long as you don't use this in a situation where the default value of a value type (e.g. zero for numeric types) is valid. In your specific case, you're using string IDs, but if they were numbers, you could see a problem. Another way to solve it is to yield return the first element (setting it to `last`) before entering the loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:03:07.110",
"Id": "13721",
"ParentId": "13708",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13721",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T12:44:34.087",
"Id": "13708",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Performance Optimization of n:1-mapping"
}
|
13708
|
<p>The following is a symmetric encryption/decryption routine using AES in GCM mode. This code operates in the application layer, and is meant to receive user specific and confidential information and encrypt it, after which it is stored in a separate database server. It also is called upon to decrypt encrypted information from the database. </p>
<p>I am looking for a review of the code with respect to its level of security, which in this case refers primarily to the correct implementation of the class called AuthenticatedAesCng found here:</p>
<p><a href="http://clrsecurity.codeplex.com/" rel="nofollow">http://clrsecurity.codeplex.com/</a> </p>
<p>My encryption/decryption routines are based on the code found here:</p>
<p><a href="http://clrsecurity.codeplex.com/wikipage?title=Security.Cryptography.AuthenticatedAesCng" rel="nofollow">source 1</a></p>
<p>Any comments or advice is very much appreciated.</p>
<p>Here is the code:</p>
<p> </p>
<pre><code>class encryptionHelper
{
// Do not change.
private static int IV_LENGTH = 12;
private static int TAG_LENGTH = 16;
// EncryptString - encrypts a string
// Pre: passed a non-empty string
// Post: returns the encrypted string in the format [IV]-[TAG]-[DATA]
public static string EncryptString(string str)
{
if (String.IsNullOrEmpty(str))
{
throw new ArgumentNullException("encryption string invalid");
}
using (AuthenticatedAesCng aes = new AuthenticatedAesCng())
{
byte[] message = Encoding.UTF8.GetBytes(str); // Convert to bytes.
aes.Key = getEncryptionKey(); // Retrieve Key.
aes.IV = generateIV(); // Generate nonce.
aes.CngMode = CngChainingMode.Gcm; // Set Cryptographic Mode.
aes.AuthenticatedData = getAdditionalAuthenticationData(); // Set Authentication Data.
using (MemoryStream ms = new MemoryStream())
{
using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// Write through and retrieve encrypted data.
cs.Write(message, 0, message.Length);
cs.FlushFinalBlock();
byte[] cipherText = ms.ToArray();
// Retrieve tag and create array to hold encrypted data.
byte[] authenticationTag = encryptor.GetTag();
byte[] encrypted = new byte[cipherText.Length + aes.IV.Length + authenticationTag.Length];
// Set needed data in byte array.
aes.IV.CopyTo(encrypted, 0);
authenticationTag.CopyTo(encrypted, IV_LENGTH);
cipherText.CopyTo(encrypted, IV_LENGTH + TAG_LENGTH);
// Store encrypted value in base 64.
return Convert.ToBase64String(encrypted);
}
}
}
}
}
// DecryptString - decrypts a string
// Pre: passed the base 64 string from the database to be decrypted
// Post: returns the decrypted string
public static string DecryptString(string str)
{
if (String.IsNullOrEmpty(str))
{
throw new ArgumentNullException("decryption string invalid");
}
using (AuthenticatedAesCng aes = new AuthenticatedAesCng())
{
byte[] encrypted = Convert.FromBase64String(str); // Convert string to bytes.
aes.Key = getEncryptionKey(); // Retrieve Key.
aes.IV = getIV(encrypted); // Parse IV from encrypted text.
aes.Tag = getTag(encrypted); // Parse Tag from encrypted text.
encrypted = removeTagAndIV(encrypted); // Remove Tag and IV for proper decryption.
aes.CngMode = CngChainingMode.Gcm; // Set Cryptographic Mode.
aes.AuthenticatedData = getAdditionalAuthenticationData(); // Set Authentication Data.
using (MemoryStream ms = new MemoryStream())
{
using (ICryptoTransform decryptor = aes.CreateDecryptor())
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
// Decrypt through stream.
cs.Write(encrypted, 0, encrypted.Length);
cs.FlushFinalBlock();
// Remove from stream and convert to string.
byte[] decrypted = ms.ToArray();
return Encoding.UTF8.GetString(decrypted);
}
}
}
}
}
// getEncryptionKey - retrieves encryption key from somewhere close to Saturn.
// Pre: nada.
// Post: Don't worry bout it
private static byte[] getEncryptionKey()
{
// Normally some magic to retrieve the key.
// For now just hard code it.
byte[] key = { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 };
return key;
}
// generateIV - generates a random 12 byte IV.
// Pre: none.
// Post: returns the random nonce.
private static byte[] generateIV()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] nonce = new byte[IV_LENGTH];
rng.GetBytes(nonce);
return nonce;
}
}
// getAdditionalAuthenticationData - retrieves authentication data.
// Pre: none;.
// Post: returns the AAD as a byte array.
private static byte[] getAdditionalAuthenticationData()
{
// hardcode for now
string str_1 = "A promise that I know the key";
return Encoding.UTF8.GetBytes(str_1);
}
// getTag - parses authentication tag from the ciphertext.
// Pre: passed the byte array.
// Post: returns the tag as a byte array.
private static byte[] getTag(byte[] arr)
{
byte[] tag = new byte[TAG_LENGTH];
Array.Copy(arr, IV_LENGTH, tag, 0, TAG_LENGTH);
return tag;
}
// getIV - parses IV from ciphertext.
// Pre: Passed the ciphertext byte array.
// Post: Returns byte array containing the IV.
private static byte[] getIV(byte[] arr)
{
byte[] IV = new byte[IV_LENGTH];
Array.Copy(arr, 0, IV, 0, IV_LENGTH);
return IV;
}
// removeTagAndIV - removes the tag and IV from the byte array so it may be decrypted.
// Pre: Passed the ciphertext byte array.
// Post: Peturns a byte array consisting of only encrypted data.
private static byte[] removeTagAndIV(byte[] arr)
{
byte[] enc = new byte[arr.Length - TAG_LENGTH - IV_LENGTH];
Array.Copy(arr, IV_LENGTH + TAG_LENGTH, enc, 0, arr.Length - IV_LENGTH - TAG_LENGTH);
return enc;
}
}
</code></pre>
<p></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T16:29:49.587",
"Id": "22172",
"Score": "4",
"body": "There are specific style guides that Microsoft publishes regarding [C# documentation comments](http://msdn.microsoft.com/en-us/library/b2s063f7%28VS.80%29.aspx) and [capitalization conventions](http://msdn.microsoft.com/en-us/library/ms229043.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T20:06:05.580",
"Id": "22184",
"Score": "0",
"body": "I'm used to writing c++ comments and sometimes forget formatting, sorry"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T19:23:30.780",
"Id": "25024",
"Score": "1",
"body": "It's not **Authentication Data**, but **Authenticated Data**, often referred to as **Additional Authenticated Data**. The idea is that you can have data that doesn't need to be encrypted and needs to be included with the cipher text. You still need it to be authenticated for integrity -- so that you know that this additional unencrypted data hasn't been tampered with. It is also *optional* you don't need to use it."
}
] |
[
{
"body": "<ol>\n<li>C# uses PascalCase naming convention for method names.</li>\n<li><p>It is accepted practice to reduce indent with multiple <code>using</code> blocks like this (in cases where no additional statements have to be executed in the outer using block):</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())\nusing (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))\n{ \n</code></pre></li>\n<li><p>You have some methods to copy individual elements out of the array containing the encrypted data (<code>getIV</code>, <code>getTag</code>) but you manually fill it in in the encryption method. Also you have delete the IV and tag to get just the data. I would encapsulate this in a <code>EncryptedMessage</code> class where you can set these properties individually and it deals with the layout of it. Something along these lines:</p>\n\n<pre><code>public class EncryptedMessage\n{\n public byte[] IV { get; set; }\n public byte[] Tag { get; set; }\n public byte[] Data { get; set; }\n\n private EncryptedMessage(byte[] iv, byte[] tag, byte[] data)\n {\n IV = iv;\n Tag = tag;\n Data = data;\n }\n\n public static EncryptedMessage FromBase64String(string input)\n {\n ...\n }\n\n public string ToBase64String()\n {\n ....\n }\n}\n</code></pre></li>\n<li>I would not make this class a static class. If you have a few places where you want to use this then make it non-static and give it an interface like <code>IStringEncrypter</code> which you pass around. This will ease unit testing and remove an implicit dependency on the static helper class.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T09:24:35.273",
"Id": "35970",
"ParentId": "13714",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T14:31:31.257",
"Id": "13714",
"Score": "5",
"Tags": [
"c#",
"security",
"aes"
],
"Title": "Symmetric encryption/decryption routine using AES"
}
|
13714
|
<p>I have this function which returns the time that a Tweet was created based on the <code>created_at</code> value that comes when a timeline is pulled. I also check whether or not the tweet was created more than 2 hours ago, and if it was, have an action execute. I was wondering, is there a way that this code could be shortened down because it currently feels very long. I thought about using a switch statement instead of all the <code>if</code>s, but it didn't really shorten the function down at all.</p>
<pre><code>
function timeAgo(dateString) {
var rightNow = new Date();
var then = new Date(dateString);
if ($.browser.msie) {
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
}
var diff = rightNow - then;
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
if (isNaN(diff) || diff < 0) {
return "";
}
if (diff < second * 2) {
return {tAgo: "right now", timeCheck: false};
}
if (diff < minute) {
return {tAgo: Math.floor(diff / second) + " seconds ago", timeCheck: false};
}
if (diff < minute * 2) {
return {tAgo: "about 1 minute ago", timeCheck: false};
}
if (diff < hour) {
return {tAgo: Math.floor(diff / minute) + " minutes ago", timeCheck: false};
}
if (diff < hour * 2) {
return {tAgo: "about 1 hour ago", timeCheck: false};
}
if (diff < day) {
return {tAgo: Math.floor(diff / hour) + " hours ago", timeCheck: true};
}
if (diff > day && diff < day * 2) {
return {tAgo: "yesterday", timeCheck: true};
}
if (diff < day * 365) {
return {tAgo: Math.floor(diff / day) + " days ago", timeCheck: true};
}
else {
return {tAgo: "over a year ago", timeCheck: true};
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T13:38:36.967",
"Id": "22255",
"Score": "0",
"body": "`$.browser` is deprecated - is there someway to do that with bug-detection?"
}
] |
[
{
"body": "<p>This doesn't really shorten it, but I think it reads better if you get rid of the diff variable and instead calculate the diff in terms of seconds, minutes, hours and days:</p>\n\n<pre><code>function timeAgo(dateString) {\n var rightNow = new Date(), then = new Date(dateString), seconds, minutes, hours, days;\n if ($.browser.msie) {\n then = Date.parse(dateString.replace(/( \\+)/, ' UTC$1'));\n }\n seconds = (rightNow - then) / 1000;\n if (isNaN(seconds) || seconds < 0) {\n return \"\";\n }\n if (seconds < 2) {\n return {tAgo: \"right now\", timeCheck: false};\n }\n if (seconds < 60) {\n return {tAgo: Math.floor(seconds) + \" seconds ago\", timeCheck: false};\n }\n\n minutes = seconds / 60;\n if (minutes < 2) {\n return {tAgo: \"about 1 minute ago\", timeCheck: false};\n }\n if (minutes < 60) {\n return {tAgo: Math.floor(minutes) + \" minutes ago\", timeCheck: false};\n }\n\n hours = minutes / 60;\n if (hours < 2) {\n return {tAgo: \"about 1 hour ago\", timeCheck: false};\n }\n if (hours < 24) {\n return {tAgo: Math.floor(hours) + \" hours ago\", timeCheck: true};\n }\n\n days = hours * 24;\n if (days < 2) {\n return {tAgo: \"yesterday\", timeCheck: true};\n }\n if (days < 365) {\n return {tAgo: Math.floor(days) + \" days ago\", timeCheck: true};\n }\n\n return {tAgo: \"over a year ago\", timeCheck: true};\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T16:18:58.087",
"Id": "13718",
"ParentId": "13717",
"Score": "1"
}
},
{
"body": "<p>Taking what Bill Barry wrote - I then cleaned up the function a bit, got rid of a few declarations and returns, added error checking for future dates and a couple of test cases. Hope this is something along the lines of what you were looking for. </p>\n\n<pre><code>function timeAgo(dateString) {\n /* removed rightNow, replaced with function call in seconds declaration */\n /* removed seconds, minutes, hours, days declarations, declared below on set */\n /* added new returnVal variable to remove all returns below with 1 return */\n var returnVal, then = new Date(dateString);\n\n /* left alone */\n if($.browser.msie) then = Date.parse(dateString.replace(/( \\+)/, ' UTC$1'));\n\n /* replaced rightNow in seconds declare with new Date() */\n /* declared variables in place instead of above */\n var seconds = (new Date() - then) / 1000;\n var minutes = seconds / 60;\n var hours = minutes / 60;\n var days = hours * 24;\n\n /* Check for negative value of seconds (negative indicates a future date) */\n if(seconds < 0) return \"\";\n\n /* replaced if statements with ternary operations - might not save much performance wise, but looks cleaner */\n seconds < 2 ? returnVal = {tAgo: \"right now\", timeCheck: false} :\n seconds < 60 ? returnVal = {tAgo: Math.floor(seconds) + \" seconds ago\", timeCheck: false} :\n returnVal = \"\";\n\n minutes < 2 ? returnVal = {tAgo: \"about 1 minute ago\", timeCheck: false} : \n minutes < 60 ? returnVal = {tAgo: Math.floor(minutes) + \" minutes ago\", timeCheck: false} : \n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n hours < 2 ? returnVal = {tAgo: \"about 1 hour ago\", timeCheck: false} :\n hours < 24 ? returnVal = {tAgo: Math.floor(hours) + \" hours ago\", timeCheck: true} :\n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n days < 2 ? returnVal = {tAgo: \"yesterday\", timeCheck: true} :\n days < 365 ? returnVal = {tAgo: Math.floor(days) + \" days ago\", timeCheck: true} :\n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n /* Remove JSON.stringify() if you want to return an object */\n return JSON.stringify(returnVal);\n}\n\nfunction testTimeAgo(){\n document.write(\"For ~Tue Apr 07 22:52:51 +0000 2009~:: \" + timeAgo(\"Tue Apr 07 22:52:51 +0000 2009\") + \"<br>\");\n document.write(\"For ~Tue July 16 22:52:51 +0000 2012~:: \" + timeAgo(\"Tue July 16 22:52:51 +0000 2012\") + \"<br>\");\n document.write(\"For ~Tue Apr 07 22:52:51 +0000 2013~:: \" + timeAgo(\"Tue Apr 07 22:52:51 +0000 2013\") + \"<br>\");\n document.write(\"For ~Tue June 07 22:52:51 +0000 2012~:: \" + timeAgo(\"Tue June 07 22:52:51 +0000 2012\") + \"<br>\");\n}\n\n/* Run a few tests */\ntestTimeAgo();\n</code></pre>\n\n<p>Without comments or test case, and a couple more improvements: </p>\n\n<pre><code>function timeAgo(dateString) {\n var returnVal, then;\n\n $.browser.msie ? then = Date.parse(dateString.replace(/( \\+)/, ' UTC$1')) : then = new Date(dateString);\n\n var seconds = new Date() - then) / 1000;\n var minutes = seconds / 60;\n var hours = minutes / 60;\n var days = hours * 24;\n\n if(seconds < 0) return \"\";\n\n seconds < 2 ? returnVal = {tAgo: \"right now\", timeCheck: false} :\n seconds < 60 ? returnVal = {tAgo: Math.floor(seconds) + \" seconds ago\", timeCheck: false} :\n returnVal = \"\";\n\n minutes < 2 ? returnVal = {tAgo: \"about 1 minute ago\", timeCheck: false} : \n minutes < 60 ? returnVal = {tAgo: Math.floor(minutes) + \" minutes ago\", timeCheck: false} : \n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n hours < 2 ? returnVal = {tAgo: \"about 1 hour ago\", timeCheck: false} :\n hours < 24 ? returnVal = {tAgo: Math.floor(hours) + \" hours ago\", timeCheck: true} :\n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n days < 2 ? returnVal = {tAgo: \"yesterday\", timeCheck: true} :\n days < 365 ? returnVal = {tAgo: Math.floor(days) + \" days ago\", timeCheck: true} :\n returnVal = {tAgo: \"over a year ago\", timeCheck: true};\n\n return returnVal;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:24:42.027",
"Id": "22180",
"Score": "0",
"body": "Could I initially define `returnVal` as `{tAgo: \"over a year ago\", timeCheck: true};` so that I don't have it repeat three times as an `else` return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:55:20.417",
"Id": "22182",
"Score": "0",
"body": "You could initially define it as well, and just replace the definitions in else as an empty string (: \"\";) - remember not to reassign."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T18:08:29.417",
"Id": "13720",
"ParentId": "13717",
"Score": "1"
}
},
{
"body": "<p>Two words: Use functions.</p>\n\n<pre><code>/** @const */\nvar ONE_SECOND = 1000;\n/** @const */\nvar ONE_MINUTE = ONE_SECOND * 60;\n/** @const */\nvar ONE_HOUR = ONE_MINUTE * 60;\n/** @const */\nvar ONE_DAY = ONE_HOUR * 24;\n/** @const */\nvar ONE_WEEK = ONE_DAY * 7;\n/** @const */\nvar ONE_YEAR = ONE_DAY * 365;\n\nfunction createSingularOrPlural(singular, plural, value, divisor) {\n value = Math.floor(value / divisor);\n\n return value < 2 ? singular : plural.replace('?', value);\n}\n\nfunction getPrettyTimeAgo(timeAgo) {\n\n if (timeAgo >= ONE_YEAR) {\n return \"over a year ago\";\n }\n\n if (timeAgo >= ONE_DAY) {\n return createSingularOrPlural(\"yesterday\", \"? days ago\", timeAgo, ONE_DAY);\n }\n\n if (timeAgo >= ONE_HOUR) {\n return createSingularOrPlural(\"about 1 hour ago\", \"? hours ago\", timeAgo, ONE_HOUR);\n }\n\n if (timeAgo >= ONE_MINUTE) {\n return createSingularOrPlural(\"about 1 minute ago\", \"? minutes ago\", timeAgo, ONE_MINUTE);\n }\n\n return createSingularOrPlural(\"right now\", \"? seconds ago\", timeAgo, ONE_SECOND);\n}\n\nfunction getMillisecondsSinceDate(dateString) {\n var rightNow = new Date();\n var then = new Date(dateString);\n\n // If we're using jQuery, check if we're using IE to perform a defect fix. \n if (window.$ && window.$.browser && window.$.browser.msie) {\n then = Date.parse(dateString.replace(/( \\+)/, ' UTC$1'));\n }\n\n return rightNow - then;\n}\n\nfunction timeAgo(dateString) {\n\n var timeDifference = getMillisecondsSinceDate(dateString);\n\n if (isNaN(timeDifference) || timeDifference < 0) {\n return \"\";\n }\n\n return {\n tAgo: getPrettyTimeAgo(timeDifference),\n timeCheck: timeDifference >= 2 * ONE_HOUR\n };\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:36:20.857",
"Id": "13724",
"ParentId": "13717",
"Score": "0"
}
},
{
"body": "<p>Here is how i'd approach it</p>\n\n<pre><code>// Make all those units constants\nvar SECOND = 1000;\nvar MINUTE = SECOND * 60;\nvar HOUR = MINUTE * 60;\nvar DAY = HOUR * 24;\nvar YEAR = DAY * 365;\n\n// store the string variations in a table, seperate from the code\nTIMES = [\n {min: 0, text: \"right now\", unit: SECOND},\n {min: 2 * SECOND, text: \"@ seconds ago\", unit: SECOND},\n {min: MINUTE, text: \"about 1 minute ago\", unit: MINUTE},\n {min: 2 * MINUTE, text: \"@ minutes ago\", unit: MINUTE},\n {min: HOUR, text: \"about 1 hour ago\", unit: HOUR},\n {min: 2 * HOUR, text: \"@ hours ago\", unit: HOUR},\n {min: DAY, text: \"yesterday\", unit: DAY},\n {min: 2 * DAY, text: \"@ days ago\", unit: DAY},\n {min: YEAR, text: \"over a year ago\", unit: YEAR}\n];\n\n// use the table to generate the date\nfunction timeAgoText(diff) {\n var use;\n for(var index = 0, length = TIMES.length; index < length; index++)\n {\n if( TIMES[index].min < diff )\n {\n use = TIMES[index];\n }\n }\n units = Math.floor(diff / use.unit)\n return use.text.replace(\"@\", units)\n}\n\nfunction timeAgo(dateText)\n{\n var then = new Date(dateString);\n if ($.browser.msie) {\n then = Date.parse(dateString.replace(/( \\+)/, ' UTC$1'));\n }\n var diff = new Date() - then;\n if( isNaN(diff) || diff < 0 )\n {\n return \"\"\n }\n else\n {\n // seperate the time check and the text generation\n return {\n tAgo: timeAgoText(diff),\n timeCheck: diff > HOUR * 2 \n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T18:59:27.340",
"Id": "22218",
"Score": "0",
"body": "+1, Indeed, this calls out for a table based lookup method. Much simpler to understand and modify then a switch (if/else) based approach. Code complete has further examples of this coding style."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T20:02:41.887",
"Id": "13729",
"ParentId": "13717",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13729",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T15:08:16.960",
"Id": "13717",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Shorten Time Return Function"
}
|
13717
|
<p>I have created a class intended to average the previous few data points submitted. It is able to change in size and has a feature to bypass the average without affecting the data contained therein. Are there any improvements I could make, or any exceptions thrown in certain situations that I haven't thought of?</p>
<pre><code>public class RollingAverage {
private double[] data;
private boolean bypass = false;
public RollingAverage(int size) {
if (size == 1) {
bypass = true;
}
data = new double[size];
Arrays.fill(data, Integer.MIN_VALUE);
}
/**
* Adds a data point to the rolling average
*
* @param newData
* @return the new average
*/
public double addData(double newData) {
if (bypass) {
return newData;
}
boolean full = true;
for (double point : data) {
if (point == Integer.MIN_VALUE) {
full = false;
break;
}
}
if (full) {
int j = 0;
while (j < data.length - 1) {
data[j++] = data[j];
}
data[0] = newData;
int sum = 0;
for (double point : data) {
sum += point;
}
return sum / data.length;
} else {
double sum = newData;
int j = 0;
while (data[j] != Integer.MIN_VALUE) {
sum += data[j++];
}
data[j] = newData;
return sum / (j + 1);
}
}
public void changeSize(int size) {
if (size == data.length) {
return;
}
if (size == 1) {
bypass = true;
}
double[] oldData = data;
data = new double[size];
for (int i = 0; i < size; i++) {
if (i < oldData.length) {
data[i] = oldData[i];
} else {
data[i] = Integer.MIN_VALUE;
}
}
}
public void setBypass(boolean bypass) {
this.bypass = bypass;
}
public void clear() {
Arrays.fill(data, Integer.MIN_VALUE);
}
public int getAverage() {
return (int) getAverageDouble();
}
public double getAverageDouble() {
int sum = 0;
int count = 0;
for (double point : data) {
if (point != Integer.MIN_VALUE) {
sum += point;
count++;
} else {
break;
}
}
return sum / count;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T18:56:33.373",
"Id": "22179",
"Score": "0",
"body": "Are you aware of java.util.ArrayList, or are you required to use an array?"
}
] |
[
{
"body": "<ol>\n<li><p>On <code>new RollingAverage(-1)</code> it throws a <code>NegativeArraySizeException</code>. An <code>IllegalArgumentException</code> with a proper message would be better here since clients should not know that you are using arrays in the implementation.</p></li>\n<li><p>On <code>new RollingAverageImpl(1).getAverage()</code> it throws an <code>ArithmeticExpression</code>. What about an <code>IllegalStateException</code> here?</p></li>\n<li><p>If you are using <code>Integer.MIN_VALUE</code> as a special marker value the <code>addData</code> method should not accept it. Just throw an <code>IllegalArgumentException</code>. (I'd consider using <code>Double.NaN</code> here as a named constant, like <code>EMPTY_DATA</code> or just <code>EMPTY</code>.)</p></li>\n<li><p>Comparing doubles with integers (like <code>point == Integer.MIN_VALUE</code>) might not be precise. See: <a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a></p></li>\n<li><p>If you calculate the new average after every <code>addData</code> call maybe you should cache it and use the cached value in the <code>getAverageDouble</code> method.</p></li>\n<li><p>Actually, I'd cache the <code>sum</code> too, and in the <code>addData</code> subtract the old value from the <code>sum</code> (if the array is full) and add the <code>newData</code> to it, then divide it by the number of elements. Maybe there are better algorithms.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:03:11.743",
"Id": "13722",
"ParentId": "13719",
"Score": "5"
}
},
{
"body": "<p>My thoughts:</p>\n\n<ul>\n<li>IllegalArgumentException when entering size < 1 (point made by palacsint)</li>\n<li>Somehow remedy the situation when no data exists (either IllegalStateException or return 0?)</li>\n<li>You are using an int to calculate the sum of longs in getAverageDouble(), this will cause precisions errors and potentially completely wrong results if sum wraps</li>\n</ul>\n\n<p>Overall though I think you should consider using a different, queue-like, data structure (i.e. LinkedList) to hold your data. This should really reduce the complexity of the code. It could actually <em>increase</em> performance as you no longer have to shift elements when the array is full or determine whether the array is full or not at each add (though I would worry about readability first and performance only if needed). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:58:08.107",
"Id": "13728",
"ParentId": "13719",
"Score": "3"
}
},
{
"body": "<p>When using double, Double.NaN is probably a better flag than Integer.MIN_VALUE.</p>\n\n<p>If you really want to use an array based structure, you would probably be better off with a <a href=\"http://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow\">Circular Buffer</a></p>\n\n<p>I would cache the <code>sum</code>, as @palacsint suggested. This will reduce recalculating the new average to a constant time operation. It might not matter when the size is small, but as the size gets larger or the sample rate increases (or both), this could become important.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T17:32:05.077",
"Id": "13757",
"ParentId": "13719",
"Score": "1"
}
},
{
"body": "<p>Future readers of this post, this is what I ended up with:</p>\n\n<pre><code>import java.util.LinkedList;\n\n/**\n * @author gobernador\n */\npublic class RollingAverage {\n\n private LinkedList<Double> data;\n private double average = 0;\n public static final double EMPTY = Double.NaN;\n\n public RollingAverage(int size) {\n if (size < 1) {\n throw new IllegalArgumentException(Integer.toString(size));\n }\n\n data = new LinkedList<Double>();\n for (int i = 0; i < size; i++) {\n data.add(EMPTY);\n }\n }\n\n /**\n * Adds a data point to the rolling average\n *\n * @param newData\n * @return the new average\n */\n public double addData(double newData) {\n if (newData == EMPTY) {\n throw new IllegalArgumentException(Double.toString(EMPTY));\n }\n\n if (data.contains(EMPTY)) {\n data.set(data.indexOf(EMPTY), newData);\n } else {\n data.removeFirst();\n data.addLast(newData);\n }\n\n fireUpdated();\n return average;\n }\n\n public void changeSize(int size) {\n if (size == data.size()) {\n return;\n }\n\n if (size < 1) {\n throw new IllegalArgumentException(Integer.toString(size));\n }\n\n while (size < data.size()) {\n data.removeFirst();\n }\n\n while (size > data.size()) {\n data.addLast(EMPTY);\n }\n\n fireUpdated();\n }\n\n protected void fireUpdated() {\n double sum = 0;\n for (double point : data) {\n if (point != EMPTY) {\n sum += point;\n }\n }\n\n if (data.contains(EMPTY)) {\n average = sum / data.indexOf(EMPTY);\n } else {\n average = sum / data.size();\n }\n }\n\n public double getAverage() {\n return average;\n }\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:45:36.990",
"Id": "13811",
"ParentId": "13719",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13728",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T17:47:57.177",
"Id": "13719",
"Score": "3",
"Tags": [
"java"
],
"Title": "Rolling Average improvements"
}
|
13719
|
<p>I have 3 car rental agencies. Each agency requires the data in XML, but in a different format, for example:</p>
<p>Agency 1</p>
<pre><code><Rental>
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
<Pickup date="07/20/2012"/>
<Dropoff date="07/25/2012"/>
<Deposit cost="100"/>
</Rental>
</code></pre>
<p>Agency 2</p>
<pre><code><Rental>
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
<Pickup>07/20/2012</Pickup>
<Dropoff>07/25/2012</Dropoff>
<Deposit>100</Deposit>
</Rental>
</code></pre>
<p>Agency 3</p>
<pre><code><Rental pickup="07/20/2012" dropoff="07/25/2012" deposit="100">
<Customer>
<FirstName>test</FirstName>
<LastName>test</LastName>
</Customer>
</Rental>
</code></pre>
<p>As you can see from above, all 3 basically contain the same information, altough this doesn't have to be the case (some can contain more or less information), but it is structured different, so the way I access it is different. What is the best approach to take so I can write the most minimum code, but be able to adapt to new rental agencies that come along with a different structure?</p>
<p>Right now, I am doing something like this:</p>
<pre><code>public class Agency1
{
SubmitRental()
{
//Parse XML for Agency 1
}
//Other methods for agency 1
}
public class Agency2
{
SubmitRental()
{
//Parse XML for Agency 2
}
//Other methods for agency 2
}
public class Agency3
{
SubmitRental()
{
//Parse XML for Agency 3
}
//Other methods for agency 3
}
</code></pre>
<p>In the above, the classes contain the same methods, but the way they are implemented is different. There are some methods, properties, etc that are in some classes, but not in others. Are interfaces the best way to approach this? If so, should everything be made an interface?</p>
<p>In the XML samples above, the data was the same, but the format was different, which led some to bring up mapping the all the different formats to a set of common classes, but what about the scenario where not only is the format different, but the data is different as well?</p>
<p>For example:</p>
<p>Agency 4</p>
<pre><code><Rental start="07/20/12" end="07/25/12">
<Name>John Doe</Name>
<DriverLicenseNumber>193048204820</DriverLicenseNumber>
<DOB>3/4/64</DOB>
<Rental>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T21:02:34.560",
"Id": "22222",
"Score": "0",
"body": "There's a date/time type in XML, which should at least help _some_ with stuff in respect to that datatype. I wouldn't be surprised if there's a money-related one too."
}
] |
[
{
"body": "<p>Assuming all three companies require the same information, create a base class \"CarRentalInformation.\" This information will store/transmit all pertinent information.</p>\n\n<p>Create serializer/deserializer classes for all types of can rentals you need. <a href=\"http://www.oodesign.com/factory-pattern.html\" rel=\"nofollow\">You could probably use the factory pattern</a> effectively here even if you need specialized information for each type you need. </p>\n\n<p>The logic could then be written as</p>\n\n<pre><code>public List<CarRentalInformation> GetCarRentalInformation(string XML)\n{\n CarRentalXmlType xmlType = this.DetectCarRentalXmlFormat(XML);\n ICarRentalFactory deserializer = this.GetCarRentalFactory(xmlType);\n\n return deserializer.Deserialize(XML);\n}\n\npublic string GetCarRentalXML(List<CarRentalInformation> rentalInfo, CarRentalXmlType xmlType)\n{\n ICarRentalFactory serializer = this.GetCarRentalFactory(xmlType);\n return serializer.Serialize(rentalInfo);\n}\n\nprivate CarRentalXmlType DetectCarRentalXmlFormat(string XML)\n{\n //do some magic detectivework, and return appropriate type\n return CarRentalXmlType.Budget;\n}\n\nprivate ICarRentalFactory GetCarRentalFactory(CarRentalXmlType xmlType)\n{\n switch(xmlType)\n {\n case CarRentalXmlType.Budget:\n return new BudgetCarRentalFactory();\n case CarRentalXmlType.Dollar:\n return new DollarCarRentalFactory();\n default\n return null;\n }\n}\n\npublic interface ICarRentalFactory\n{\n public List<CarRentalInformation> Deserialize(string XML);\n public string Serialize(List<CarRentalInformation> rentalInfo);\n}\n\npublic class BudgetCarRentalFacotry : ICarRentalFactory\n{\n //contains code to serialize/deserialize XML into CarRentalInformation objects\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T20:18:43.457",
"Id": "22188",
"Score": "0",
"body": "In my example, all the agencies had the same data, but in most cases, the data will be different(some will have more and some will have less and some may call the elements/attributes something else) and it will be in different formats, so does this rule having some a mapping class out or is it still plausible?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T13:39:46.453",
"Id": "22204",
"Score": "0",
"body": "This would definitely make a candidate for a builder pattern with dependency injection, as you could use one central engine to process the requests, but pull the information appropriately. Having the mapping classes will definitely work for multiple formats, but if the data contents are wildly different, the benefit does start to break down as you handle one-offs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T13:42:09.570",
"Id": "22205",
"Score": "0",
"body": "J Torres - If you have the time, would you mind showing an example with the builder pattern with dependency injection? Thanks for your patience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T15:25:27.503",
"Id": "22210",
"Score": "0",
"body": "I still think this basic idea is the best conceptually, even if the data required in each XML is almost totally different; have one main \"domain\" class with the information, that can then be digested by one or more serializers chosen by strategy pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T19:05:26.247",
"Id": "22219",
"Score": "0",
"body": "-1. Factory is the right idea, but the implementation here makes no sense. All those methods should be inside the factory class. The factory figures out what kind of serializer to build, builds one and holds onto it. The client should make 3 calls, passing stuff to the factory as needed. 1) initial factory creation, 2)convert XML to a rental car list, 3)convert a rental car list to XML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T19:09:21.093",
"Id": "22220",
"Score": "0",
"body": "@radarbob My original intent (based on a possibly invalid assumption) was that the presentation was being obfuscated, not the model objects themselves. With the additional information provided by OP, you are correct that further abstraction makes more sense. However, in the future, rather than downvoting a valid answer to OP, perhaps you could provide your work in the form of an answer as there is nothing incorrect with the answer provided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T20:40:55.980",
"Id": "22221",
"Score": "0",
"body": "@radarbob - I second J Torres. It would be nice to see an answer from you."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T20:08:41.443",
"Id": "13730",
"ParentId": "13726",
"Score": "3"
}
},
{
"body": "<p>This is a factory pattern because the client uses a class (the factory) to build the Rental car information list.</p>\n\n<p>It strikes me that this is <em>almost</em> the builder pattern. The Builder is simply an object that encapsulates the building of a more complex object. IF, along with building a particular <code>ISerializerFactory</code> we had to build a custom version of the <code>RentalCar</code> to go along with it - well then <code>RentalCarBuilder</code>'s class diagram would look like a <a href=\"http://www.oodesign.com/builder-pattern.html\" rel=\"nofollow\">builder pattern</a> I believe.</p>\n\n<p>So it occurs to me that perhaps a Builder (pattern) is simply an encapsulation for a more complex Factory (pattern).</p>\n\n<pre class=\"lang-cs prettyprint-override\"> \n// client code\nXDocument rentals = ReadTheXML();\nRentalCarBuilder rentalData = new RentalCarBuilder(rentals);\nList myRentals = rentalData.RentalList();\nRentalDealerForm RentalCompany = rentalData.theDealerForm;\n\n// the details\n\npublic class RentalCarBuilder() {\n protected ISerializerFactory mySerializer;\n protected XDocument rentalXml;\n protected RentalDealerForm theDealerForm;\n\n public void Create (XDocument rentalCarXml) {\n rentalXml = rentalCarXml;\n mySerializer = BuildSerializer(rentalCarXml);\n }\n\n public List RentalList () {\n return mySerializer.CreateRentalList(rentalXml);\n }\n\n protected void BuildSerializer (XDocument rentalCarXml) {\n // magic to figure out what form of the xml we're dealing with\n // for fun, i'm going to assume we figure it out and capture that\n // with an enumeration.\n theDealerForm = WhatDealerIsThis(rentalXml);\n mySerializer = new RentalCarSerializerFactory(theDealerForm);\n }\n\n protected RentalDealerForm WhatDealerIsThis(XDocument rentalXml) {\n RentalDealerForm who;\n // more magic\n\n return who;\n }\n}\n\npublic class RentalCarSerializerFactory {\n // methods to build the appropriate class below\n}\n\npublic class BudgetSerializer : ISerializerFactory () {}\npublic class RentAWreckSerializer : ISerializerFactory() {}\npublic class EnterpriseSerializer : ISerializerFactory() {}\n\n\npublic enum RentalDealerForm {\n Budget\n ,Enterprise\n ,RentAWreck\n}\n\npublic class RentalCar {\n public Customer renter {get; set;}\n public DateTime Pickup {get; set;}\n public DateTime Dropoff {get; set;}\n public double Deposit {get; set;}\n\n}\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T13:50:35.803",
"Id": "22256",
"Score": "0",
"body": "You make some great points, but I am confused on certain things because I am not too good with design patterns. I will add a comment with some questions, but I want to give you an idea of one scenario I run into: Each agency can update their car inventory by passing xml to a specific `web-service`, so for example, `agency one` will pass `inventoryupdate.xml` to `service a` and agency two will pass `inventoryupdate.xml` to `service b`. Each service (a and b) have their own set of classes, but I don't like this because a lot of the code is the same and I would like to share and reduce code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T13:53:32.930",
"Id": "22257",
"Score": "0",
"body": "Is `ReadTheXml` just the same as `XDocument.Load`? I don't see a constructor for `RentalCarBuilder`? What is it supposed to do with the `rentals` argument? What is `RentalList()` supposed to do? and why return a list? What if I am just dealing with one rental? I am confused on what `RentalDealerForm` is supposed to be? What should the defenition of `ISerializerFactory` be?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T20:49:37.043",
"Id": "13765",
"ParentId": "13726",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "13730",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T19:49:24.430",
"Id": "13726",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"object-oriented"
],
"Title": "How can I use object oriented principles in the following scenario?"
}
|
13726
|
<p>I've been doing some parsing with regular expression named capture groups and decided it might make sense to write an extension to handle this. </p>
<p>The code below will create an instance of a specified type and attempt to match the property names to the capture group names and then set the values. It also attempts to cast between compatible types.</p>
<p>Any suggestions for improving this code? Is it ok as an extension?</p>
<pre><code> public static class RegularExpressionExtension
{
public static T CreateType<T>(this Regex regEx, string matchString) where T : new()
{
MatchCollection matchCollection = regEx.Matches(matchString);
T obj = new T();
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
IEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0
if (matchCollection.Count >= 1)
{
SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, matchCollection[0].Groups, properties);
}
return obj;
}
public static IEnumerable<T> CreateTypeCollection<T>(this Regex regEx, string matchString) where T : new()
{
MatchCollection matchCollection = regEx.Matches(matchString);
IEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
foreach (Match match in matchCollection)
{
T obj = new T();
SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, match.Groups, properties);
yield return obj;
}
}
private static void SetPropertyValuesFromGroupMatches<T>(IEnumerable<string> groupNames, Regex regEx, T typeToPopulate, GroupCollection groupCollection, PropertyInfo[] properties)
{
Type type = typeof(T);
foreach (string group in groupNames)
{
var foundProperty = properties.SingleOrDefault(p => p.Name.Equals(group,StringComparison.CurrentCultureIgnoreCase));
if (foundProperty != null)
{
var matchValue = groupCollection[group].Value;
object convertedValue = System.ComponentModel.TypeDescriptor.GetConverter(foundProperty.PropertyType).ConvertFrom(matchValue);
foundProperty.SetValue(typeToPopulate, convertedValue, null);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T15:21:41.813",
"Id": "22209",
"Score": "0",
"body": "Overloads that just take the match pattern and instantiate their own Regex (or just use the static methods) might be called for. The code also requires using only mutable properties for all data members; you can't have any get-only properties, and you can't use fields (readonly or otherwise) which may hurt you if you want to use this down the road for a class with calculated or WORM properties."
}
] |
[
{
"body": "<p>If you are doing reflection magics the caller of your method may be as well. If that person already has a <code>Type</code> it can be a bit of a pain in the butt to call your generic method. Since you are already working against a <code>Type</code> offering an overload for it should not be too much work. Perhaps extracting the following code into its own method may help:</p>\n\n<pre><code>PropertyInfo[] properties = type.GetProperties();\nIEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0\nif (matchCollection.Count >= 1) {\n SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, matchCollection[0].Groups, properties);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-22T22:29:36.460",
"Id": "24263",
"ParentId": "13731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:28:37.387",
"Id": "13731",
"Score": "3",
"Tags": [
"c#",
"regex"
],
"Title": "Extension Method for Creating Types from Regular Expression Match Groups"
}
|
13731
|
<p>I currently have the following jQuery code, which does work, but I know there is a better way of doing it without having to repeat myself so much:</p>
<pre><code><script>
$(document).ready(function() {
$('.container').hide();
$('#btn-post').click(function() {
$('.container').hide();
});
$('#btn-game').click(function() {
$('.container').hide();
$('#game_container').show();
});
$('#btn-video').click(function() {
$('.container').hide();
$('#video_container').show();
});
$('#btn-giveaway').click(function() {
$('.container').hide();
$('#giveaway_container').show();
});
});
</script>
</code></pre>
<p>Basically, when a button is clicked, I need to show the additional div for that content type and hide the rest. If it's just a Post, then all of the divs are hidden as there is no specific div for the post type.</p>
<p>The HTML looks like this:</p>
<pre><code><div class="btn-group" data-toggle="buttons-radio">
<button id="btn-post" class="btn btn btn-primary active" type="button">Post</button>
<button id="btn-game" class="btn btn btn-primary" type="button">Game</button>
<button id="btn-video" class="btn btn btn-primary" type="button">Video</button>
<button id="btn-giveaway" class="btn btn btn-primary" type="button">Giveaway</button>
</div>
<div class="container" id="game_container">
game stuff
</div>
<div class="container" id="video_container">
video stuff
</div>
<div class="container" id="giveaway_container">
giveaway stuff
</div>
</code></pre>
<p>What's the more efficient way of writing that jQuery?</p>
|
[] |
[
{
"body": "<p>Try this:</p>\n<h2><em><a href=\"http://jsbin.com/iniqaj/edit#javascript,html,live\" rel=\"nofollow noreferrer\">jsBin demo</a></em></h2>\n<pre><code>$('.container').hide();\n\n$('.btn').click(function() {\n \n $('.container').hide();\n $('#'+this.id.split('-')[1]+'_container').show();\n\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:48:32.593",
"Id": "13734",
"ParentId": "13733",
"Score": "2"
}
},
{
"body": "<p>I'd suggest:</p>\n\n<pre><code>$('button[id^=btn]').click(\n function() {\n var affects = this.id.split('-')[1];\n $('.container').hide();\n $('#' + affects + '_container').show();\n });\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/davidThomas/cdwc9/\" rel=\"nofollow\">JS Fiddle demo</a>.</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/attribute-starts-with-selector\" rel=\"nofollow\">attribute-starts-with <code>[attribute^=\"value\"]</code> selector</a>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:49:44.823",
"Id": "22189",
"Score": "0",
"body": "this is already answered"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:51:00.890",
"Id": "22190",
"Score": "0",
"body": "Darn; took a longer time than I thought to register the new account...sigh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:51:47.643",
"Id": "22191",
"Score": "1",
"body": ";) ..... hehe funny to see 3 Overflowers in here all with (starting) 101 score :) trying to help :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:52:23.680",
"Id": "22192",
"Score": "0",
"body": "It was a fun, though frankly obvious (I must concede) question to resolve =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:53:58.607",
"Id": "22193",
"Score": "2",
"body": "still dunno why this kind of qhestion should come here to CR ... easily answerable, but none from CR hurried to answer. Overflowers (we) eat for breakfast such Q :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:55:11.453",
"Id": "22194",
"Score": "0",
"body": "Upvote for the effort! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:57:00.337",
"Id": "22195",
"Score": "0",
"body": "@roXon: agreed, and I really wouldn't have migrated this one. Yes, the 'natural home' is Code Review, but...I'm sure I read that the preferred course of action with questions is that if they're not *explicitly* off-topic they should be answered where they're posted; and this question seemed more about learning jQuery, and JavaScript, than refactoring working code (though obviously that was definitely a major part of the question). So, yeah: I'm not impressed by the immediate migration."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:49:22.107",
"Id": "13735",
"ParentId": "13733",
"Score": "2"
}
},
{
"body": "<p>Try this:</p>\n\n<p><a href=\"http://jsfiddle.net/VYSXn/\" rel=\"nofollow\">http://jsfiddle.net/VYSXn/</a></p>\n\n<p>Change your HTML to (note the data attributes):</p>\n\n<pre><code><div class=\"btn-group\" data-toggle=\"buttons-radio\">\n <button id=\"btn-post\" class=\"btn btn btn-primary active\" type=\"button\">Post</button>\n <button id=\"btn-game\" data-target=\"game_container\" class=\"btn btn btn-primary\" type=\"button\">Game</button>\n <button id=\"btn-video\" data-target=\"video_container\" class=\"btn btn btn-primary\" type=\"button\">Video</button>\n <button id=\"btn-giveaway\" data-target=\"giveaway_container\" class=\"btn btn btn-primary\" type=\"button\">Giveaway</button>\n</div>\n<div class=\"container\" id=\"game_container\">\ngame stuff\n</div>\n\n<div class=\"container\" id=\"video_container\">\nvideo stuff\n</div>\n\n<div class=\"container\" id=\"giveaway_container\">\ngiveaway stuff\n</div>\n</code></pre>\n\n<p>and now your javascript can just be:</p>\n\n<pre><code>$(document).ready(function() {\n\n $('.container').hide();\n $('.btn-group button').click(function(){\n var target = \"#\" + $(this).data(\"target\");\n $(\".container\").not(target).hide();\n $(target).show();\n });\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:13:43.050",
"Id": "22525",
"Score": "0",
"body": "Try using .addClass('hidden')/.removeClass('hidden'); where the selector .hidden is defined as { display:none }. This will help to avoid inline style and a possible CSS inheritance conflict."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:49:36.630",
"Id": "13736",
"ParentId": "13733",
"Score": "7"
}
},
{
"body": "<p>First off, your model looks a lot like many implementations of a tab-based interface. Using one of the existing frameworks for that will make your life a lot easier and avoid you re-writing boilerplate. Some people are partial to JQuery-UI's tabs, but I much prefer <a href=\"http://twitter.github.com/bootstrap/javascript.html#tabs\" rel=\"nofollow\">Bootstrap's</a>. (Your syntax actually suggests you might be using Bootstrap's Button Groups already...) In addition to the obvious function that fires when you click on a tab, you can also just use <code>$(#id_for_tab_you_want).tab('show')</code> for programmatic access to hide/show the tabs. Much easier than showing and hiding everything manually. (Also, note that you don't need to actually show the tab UI in order to use the logic. You can hide either the whole list of tabs, or just the ones you don't want to see. The functions still work well.)</p>\n\n<p>But if you want a plain-old JQuery option, chaining and the <code>siblings()</code> function can boil it down into one line for you inside your listener function: </p>\n\n<pre><code>$(\"#\" + $(this).data(\"target\")).show().siblings('.container').hide()\n</code></pre>\n\n<p>What you're doing is locating your target <div>, showing it, then immediately finding any siblings it has with the class <code>.container</code>, and hiding those. Here's an updated <a href=\"http://jsfiddle.net/xmlilley/VYSXn/1/\" rel=\"nofollow\">Fiddle</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T16:47:43.090",
"Id": "13754",
"ParentId": "13733",
"Score": "1"
}
},
{
"body": "<p>Better solution with only one line of JS/Jquery, as demoed here: <a href=\"http://jsfiddle.net/krY56/13/\" rel=\"nofollow\">http://jsfiddle.net/krY56/13/</a></p>\n\n<p>This leverages the .Toggle functionality, which is perfect for this</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-24T12:47:28.723",
"Id": "206008",
"Score": "1",
"body": "Welcome to Code Review! Please include the code in your post as the link may break or disappear, leaving vital information out of your post."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-24T12:43:07.970",
"Id": "111694",
"ParentId": "13733",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "13736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:40:07.007",
"Id": "13733",
"Score": "7",
"Tags": [
"javascript",
"jquery"
],
"Title": "More efficient way of doing this hide()/show() jQuery"
}
|
13733
|
<p>This is the dashboard controller code in PHP Symfony 2. It collects some aggregate data and points for charts, but i don't like it very much. Do you think that <em>this code belongs to what a controller should do in a MVC patter</em>? How can i refactor it?</p>
<pre><code>public function dashboardAction()
{
$bag = array();
// Helpers from service container
$messaging = $this->get('messaging.helper');
$charting = $this->get('charting.helper');
// Current logged user, subscription and message inhibitor
$loggedUser = $this->getSecurityContext()->getToken()->getUser();
$subscription = $messaging->createSubscriptionFromUser($loggedUser);
$usage = $messaging->createUsageFromSubscription($subscription);
$bag['subscription'] = $subscription;
$bag['usage'] = $usage;
$bag['inhibitor'] = $messaging->createInhibitor($usage, $subscription);
// Get charts from usage raw data
$rawData = $usage->getRawData();
$start = $usage->getStartDate();
$end = $usage->getEndDate();
$bag['line_chart'] = $charting->createMessagesLineChart($rawData, $start, $end);
$bag['pie_chart'] = $charting->createMessagesPieChart($rawData);
// Customers and latest 5 added
$customers = $loggedUser->getCustomers();
$bag['customers_count'] = $customers->count();
$bag['latest_customers'] = $customers->slice(0, 5);
// Tags/keywords counts and latest 5 meta
$metas = $loggedUser->getMeta();
$getTags = function($m) { return $m instanceof Tag; };
$getKeywords = function($m) { return $m instanceof Keyword; };
$bag['tags_count'] = $metas->filter($getTags)->count();
$bag['keywords_count'] = $metas->filter($getKeywords)->count();
$bag['latest_meta'] = $metas->slice(0, 5);
// SMS and newsletter counts
$outgoingMessages = $loggedUser->getOutgoingMessages();
$getSms = function($m) { return $m instanceof SmallTextMessage; };
$getNewsletters = function($m) { return $m instanceof Newsletter; };
$bag['sms_count'] = $outgoingMessages->filter($getSms)->count();
$bag['newsletter_count'] = $outgoingMessages->filter($getNewsletters)->count();
return $bag;
}
</code></pre>
|
[] |
[
{
"body": "<p>Without knowing anything about sympony's details:</p>\n\n<ul>\n<li>I'd refactor most of the code into your view. I prefer to pass the required objects to the view and let the view pull the information it needs from the object(s) </li>\n<li>Rename the variable <code>bag</code> </li>\n<li>Move the subscription data into your user-model</li>\n<li>Make the helpers available to your views (especially the charting helper)</li>\n</ul>\n\n<p>This decouples the controller from the display logic. The controller just determines the user to display the dashboard for and the view determines which data to display and how to display it (e.g. you could have to different dashboards (views)).</p>\n\n<pre><code>public function dashboardAction()\n{\n return array('user' => $this->getSecurityContext()->getToken()->getUser());\n}\n</code></pre>\n\n<p>In your view (not knowing how views are done in symphony):</p>\n\n<pre><code>// Helpers from service container\n$messaging = $this->get('messaging.helper');\n$charting = $this->get('charting.helper');\n\n// Current logged user, subscription and message inhibitor\n$loggedUser = $this->get('user);\n$subscription = $messaging->createSubscriptionFromUser($loggedUser);\n$usage = $messaging->createUsageFromSubscription($subscription);\n\n// Display charts from usage raw data\n$rawData = $usage->getRawData();\n$start = $usage->getStartDate();\n$end = $usage->getEndDate();\n\necho $charting->createMessagesLineChart($rawData, $start, $end);\necho $charting->createMessagesPieChart($rawData);\n\n// Display the 5 newest customers\n$customers = $loggedUser->getCustomers();\n\necho $customers->count();\necho $customers->slice(0, 5);\n\n// Display the 5 latest Tags/keywords & total count\n$metas = $loggedUser->getMeta();\n$getTags = function($m) { return $m instanceof Tag; };\n$getKeywords = function($m) { return $m instanceof Keyword; };\n\necho $metas->filter($getTags)->count();\necho $metas->filter($getKeywords)->count();\necho implode(\",\", $metas->slice(0, 5));\n\n// Display SMS and newsletter counts\n$outgoingMessages = $loggedUser->getOutgoingMessages();\n$getSms = function($m) { return $m instanceof SmallTextMessage; };\n$getNewsletters = function($m) { return $m instanceof Newsletter; };\n\necho $outgoingMessages->filter($getSms)->count();\necho $outgoingMessages->filter($getNewsletters)->count();\n</code></pre>\n\n<p>Another view of the same dashboardAction just might decide to display only a welcome message, other information, or even be customizable by the user without changing the controller every time (possibly passing the superset of all variables required by any view to each view). </p>\n\n<p>Going further you might want to move some <code>get</code> logic (which you're doing by filtering) into your model: <code>$getTags = $loggedUser->getMeta()->getTags();</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T16:57:33.237",
"Id": "22324",
"Score": "3",
"body": "This is not a very good example of a view. In fact, its a poor one. Views are supposed to be sparse in PHP code and be primarily HTML. You are combining all three here. Controllers are supposed to get data from the model and pass it to the view in an easy to use manner so that the view does not need to know anything about the controller or model."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:37:33.480",
"Id": "22331",
"Score": "0",
"body": "@showerhead: And it's not the controller's job to decide how the data is going to be displayed (e.g. as a chart). Sure we can argue if we pass an array to the view containing the content of the model or the model directly - resulting in the same result... (forgetting about what happens if we change the model). It's just accessing the data by either array-key or method-call. Ultimately some of the logic should be in the models (see last paragraph) or in view helpers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:49:08.843",
"Id": "22332",
"Score": "0",
"body": "No, its not the controller's job, its the view's. The view will request the chart from the controller, which will then request it from the model. The view should only have to say `$chart` to get a chart. The controller is responsible for calling the proper methods from the model to create that chart and then declare it as a variable before including the view. This way the only thing you have to change if the model changes is the controller. Which, if done correctly, may not need to be changed either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T22:49:54.567",
"Id": "22345",
"Score": "0",
"body": "@showerhead: So far we're both talking about the same idea - mine as a 'lightweight' variant of viewmodels - your's as an array. Beside the chart you're almost returning the same data as I do - letting the view decide which data to display and how. If you want complete decoupling my solution would require complete viewmodels bloating the code for small applications. However using objects would enable lazy- loading/calculating stuff like graphs instead of pre-calculating the superset of required variables. (In my opinion creating charts is the view's task as they are about \"displaying stuff\".)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T22:56:11.267",
"Id": "22346",
"Score": "0",
"body": "@showerhead: Guess we'll just come to the same result as this discussion here: http://stackoverflow.com/questions/1371119/mvc-pass-model-model-data-to-a-view-from-a-controller"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T13:02:36.653",
"Id": "13836",
"ParentId": "13742",
"Score": "-1"
}
},
{
"body": "<p>A controller? No. A model? Sure. Not sure if Symfony defines a controller differently, but this is not what I think of as a controller.</p>\n\n<p>As for refactoring, the easiest way would be to break it up into smaller methods. For instance, right off the bat I see at least 6 different potential methods here. You could create a bunch of smaller methods that returns a part of the bag (messaging, charting, etc...) and then merge them all together. In fact, that's the only real improvement I can see. I feel bad leaving such a short answer, so here's an example of a couple of those smaller methods, which is actually about half that code.</p>\n\n<pre><code>private function getUsageCharts ( $usage ) {\n $rawData = $usage->getRawData();\n $start = $usage->getStartDate();\n $end = $usage->getEndDate();\n\n $line_chart = $charting->createMessagesLineChart($rawData, $start, $end);\n $pie_chart = $charting->createMessagesPieChart($rawData);\n\n return compact( 'usage', 'line_chart', 'pie_chart' );\n}\n\nprivate function getMessagingFields( $loggedUser ) {\n $messaging = $this->get('messaging.helper');\n\n $subscription = $messaging->createSubscriptionFromUser($loggedUser);\n $usage = $messaging->createUsageFromSubscription($subscription);\n $inhibitor = $messaging->createInhibitor($usage, $subscription);\n\n extract( $this->getUsageCharts( $usage ) );//$line_chart, $pie_chart\n return compact( 'subscription', 'usage', 'inhibitor', 'line_chard', 'pie_chart' );\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T07:55:29.197",
"Id": "22490",
"Score": "0",
"body": "To make it more clean, all data is used to render widgets on my dashboard. Would be better to create - say - statsWidgetAction, chartWidgetAction ans so on, letting the view render each widget as as single item?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T14:51:42.647",
"Id": "22506",
"Score": "0",
"body": "@Gremo: If they are indeed different and are manipulated independently, then yes, I would believe separating them might be better. But at the same time I believe the redundancy introduced from doing so might be a bit much for such similar tasks. There's also the issue of unsynchonized data should your data be updated in real time. If each of the widgets are refreshed at the same time there might only be slight differences between them based on load time, or none at all. So there are a number of things to look at before deciding. In the end its up to you and your allowance for fault tolerance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T16:53:49.370",
"Id": "13844",
"ParentId": "13742",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T09:27:28.113",
"Id": "13742",
"Score": "4",
"Tags": [
"php",
"mvc",
"php5",
"controller"
],
"Title": "PHP MVC controller code needs diet?"
}
|
13742
|
<p><img src="https://i.stack.imgur.com/0xufA.png" alt="Google Logotype"></p>
<h1>About</h1>
<p><strong>Google, the search engine</strong><br>
Google is the world's foremost search engine and most visited domain that crawls the web and provides users with a list of links relevant to their search.</p>
<p><strong>Google Inc.</strong><br>
Is an American multinational corporation which provides Internet-related products and services, including Internet search, cloud computing, software and advertising technologies.</p>
<hr>
<h1>History</h1>
<p><strong>1996</strong><br>
Google began in January 1996 as a research project by Larry Page and Sergey Brin when they were both PhD students at Stanford University in California.</p>
<p><strong>1997</strong><br>
The domain name for Google was registered on September 15, 1997,[38] and the company was incorporated on September 4, 1998. It was based in a friend's garage in Menlo Park, California. Craig Silverstein, a fellow PhD student at Stanford, was hired as the first employee.</p>
<p><strong>2011</strong><br>
In May 2011, the number of monthly unique visitors to Google surpassed 1 billion for the first time, an 8.4 percent increase from May 2010 (931 million).</p>
<hr>
<h1>Products and services</h1>
<p>Google provides a wide variety of services that are mostly accessed with a web browser, hardware and development tools for the masses:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Search_tools" rel="nofollow noreferrer">Search tools</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Advertising_services" rel="nofollow noreferrer">Advertising services</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Communication_and_publishing_tools" rel="nofollow noreferrer">Communication and publishing tools</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Development_resources" rel="nofollow noreferrer">Development resources</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Map-related_products" rel="nofollow noreferrer">Map-related products</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Statistical_tools" rel="nofollow noreferrer">Statistical tools</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Operating_systems" rel="nofollow noreferrer">Operating systems</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Desktop_applications" rel="nofollow noreferrer">Desktop applications</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Mobile_web_applications" rel="nofollow noreferrer">Mobile web applications</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Mobile_standalone_applications" rel="nofollow noreferrer">Mobile standalone applications</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Hardware" rel="nofollow noreferrer">Hardware</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/List_of_Google_products#Services" rel="nofollow noreferrer">Services</a></p></li>
</ul>
<p>And there's also a useful list of <a href="http://en.wikipedia.org/wiki/List_of_Google_products#Discontinued_products_and_services" rel="nofollow noreferrer">Discontinued products and services</a>.</p>
<p>See all at Wikipedia :: <a href="http://en.wikipedia.org/wiki/List_of_Google_products" rel="nofollow noreferrer">List of Google products</a>.</p>
<hr>
<h1>Available APIs</h1>
<ul>
<li>Ad Exchange Buyer API</li>
<li>Ad Exchange Seller API</li>
<li>Admin Reports API</li>
<li>AdSense Host API</li>
<li>AdSense Management API</li>
<li>APIs Discovery Service</li>
<li>BigQuery API</li>
<li>Blogger API</li>
<li>Books API</li>
<li>Calendar API</li>
<li>Cloud SQL Administration API</li>
<li>Cloud Storage API</li>
<li>Compute Engine API</li>
<li>CustomSearch API</li>
<li>DFA Reporting API</li>
<li>DoubleClick Bid Manager API</li>
<li>Drive API</li>
<li>Enterprise Apps Reseller API</li>
<li>Enterprise Audit API</li>
<li>Enterprise License Manager API</li>
<li>External API For Ads DoubleClick Search</li>
<li>Freebase Search</li>
<li>Fusion Tables API</li>
<li>Google Affiliate Network API</li>
<li>Google Analytics API</li>
<li>Google App State API</li>
<li>Google Apps Reseller API</li>
<li>Google Civic Information API</li>
<li>Google Cloud Datastore API</li>
<li>Google Fonts Developer API</li>
<li>Google Identity Toolkit API</li>
<li>Google Maps Coordinate API</li>
<li>Google OAuth2 API</li>
<li>Google Play Android Developer API</li>
<li>Google Play Game Services API</li>
<li>Google Play Game Services Management API</li>
<li>Google Site Verification API</li>
<li>Google+ API</li>
<li>Google+ Domains API</li>
<li>Groups Settings API</li>
<li>Orkut API</li>
<li>PageSpeed Insights API</li>
<li>Prediction API</li>
<li>Search API For Shopping</li>
<li>TaskQueue API</li>
<li>Tasks API</li>
<li>Translate API</li>
<li>URL Shortener API</li>
<li>YouTube Analytics API</li>
<li>YouTube Data API</li>
</ul>
<hr>
<h1>Useful Links</h1>
<ul>
<li><p>Google <a href="https://www.google.com/" rel="nofollow noreferrer">Website</a></p></li>
<li><p>Google on <a href="http://en.wikipedia.org/wiki/Google" rel="nofollow noreferrer">Wikipedia</a></p></li>
<li><p>Google - <a href="https://www.google.pt/intl/en/about/" rel="nofollow noreferrer">About Google</a></p></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T12:00:00.450",
"Id": "13744",
"Score": "0",
"Tags": null,
"Title": null
}
|
13744
|
Google offers a variety of APIs, mostly web APIs for web developers. The APIs are based on popular Google consumer products, including Google Maps, Google Earth, AdSense, Adwords, Google Apps and YouTube.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T12:00:00.450",
"Id": "13745",
"Score": "0",
"Tags": null,
"Title": null
}
|
13745
|
<p>Here is an ant script for generating TeX code and documentation for one LaTeX class and one LaTeX package. It is my first larger ant script: I welcome suggestions for improvements.</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project name="customer TeX code" default="main">
<description>Buildscript for the LaTeX classes and packages</description>
<property name="foo" value="foo" />
<property name="bar" value="bar" />
<!-- target: init -->
<target name="init" description="initialize properties">
<condition property="foo.uptodate">
<and>
<available file="${foo}.cls" />
<available file="${foo}.drv" />
<available file="${foo}.pdf" />
<uptodate property="foo.cls.uptodate" targetfile="${foo}.cls">
<srcfiles file="${foo}.dtx" />
<srcfiles file="${foo}.ins" />
</uptodate>
<uptodate property="foo.drv.uptodate" targetfile="${foo}.drv">
<srcfiles file="${foo}.dtx" />
<srcfiles file="${foo}.ins" />
</uptodate>
<uptodate property="foo.pdf.uptodate" targetfile="${foo}.pdf">
<srcfiles file="${foo}.dtx" />
<srcfiles file="${foo}.ins" />
</uptodate>
</and>
</condition>
<condition property="bar.uptodate">
<and>
<available file="${bar}.sty" />
<available file="${bar}.drv" />
<available file="${bar}.pdf" />
<uptodate property="bar.sty.uptodate" targetfile="${bar}.sty">
<srcfiles file="${bar}.dtx" />
<srcfiles file="${bar}.ins" />
</uptodate>
<uptodate property="bar.drv.uptodate" targetfile="${bar}.drv">
<srcfiles file="${bar}.dtx" />
<srcfiles file="${bar}.ins" />
</uptodate>
<uptodate property="bar.pdf.uptodate" targetfile="${bar}.pdf">
<srcfiles file="${bar}.dtx" />
<srcfiles file="${bar}.ins" />
</uptodate>
</and>
</condition>
</target>
<!-- target: foo -->
<target name="foo" unless="foo.uptodate" depends="init" description="builds all files for the foo class">
<exec executable="latex" failonerror="true">
<arg value="${foo}.ins" />
</exec>
<exec executable="lualatex" failonerror="true">
<arg value="-draftmode" />
<arg value="${foo}.drv" />
</exec>
<parallel>
<exec executable="makeindex" failonerror="true">
<arg value="-s" />
<arg value="gind.ist" />
<arg value="-t" />
<arg value="${foo}.ind.ilg" />
<arg value="${foo}.idx" />
</exec>
<exec executable="makeindex" failonerror="true">
<arg value="-s" />
<arg value="gglo.ist" />
<arg value="-t" />
<arg value="${foo}.gls.ilg" />
<arg value="-o" />
<arg value="${foo}.gls" />
<arg value="${foo}.glo" />
</exec>
</parallel>
<exec executable="lualatex" failonerror="true">
<arg value="-draftmode" />
<arg value="${foo}.drv" />
</exec>
<exec executable="lualatex" failonerror="true">
<arg value="${foo}.drv" />
</exec>
</target>
<!-- target: bar -->
<target name="bar" unless="bar.uptodate" depends="init" description="builds all files for the bar package">
<exec executable="latex" failonerror="true">
<arg value="${bar}.ins" />
</exec>
<exec executable="lualatex" failonerror="true">
<arg value="-draftmode" />
<arg value="${bar}.drv" />
</exec>
<parallel>
<exec executable="makeindex" failonerror="true">
<arg value="-s" />
<arg value="gind.ist" />
<arg value="-t" />
<arg value="${bar}.ind.ilg" />
<arg value="${bar}.idx" />
</exec>
<exec executable="makeindex" failonerror="true">
<arg value="-s" />
<arg value="gglo.ist" />
<arg value="-t" />
<arg value="${bar}.gls.ilg" />
<arg value="-o" />
<arg value="${bar}.gls" />
<arg value="${bar}.glo" />
</exec>
</parallel>
<exec executable="lualatex" failonerror="true">
<arg value="-draftmode" />
<arg value="${bar}.drv" />
</exec>
<exec executable="lualatex" failonerror="true">
<arg value="${bar}.drv" />
</exec>
</target>
<!-- target: main -->
<target name="main" depends="foo, bar" description="default target" />
</project>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:11:32.123",
"Id": "22329",
"Score": "0",
"body": "Can’t comment specifically on the ant file but it seems like a lot of effort. Are you aware of the existence of `latexmk` which ships with all modern TeX distributions and which is a versatile build tool for TeX (requiring in most cases *zero* configuration)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T20:17:55.597",
"Id": "22334",
"Score": "0",
"body": "@KonradRudolph: Yes. But I need it on Windows, MacOS and Linux. And I fear that the configuration latexmk needs for _this_ build process and the dependencies is also quite non-trivial. And I wanted to learn ant. `:-)`"
}
] |
[
{
"body": "<p>The <code>bar</code> and <code>foo</code> targets (as well as the conditions on <code>foo.uptodate</code> and <code>bar.uptodate</code>) seems really similar to each other. I'd try to remove this duplication with a <a href=\"http://ant.apache.org/manual/Tasks/presetdef.html\" rel=\"nofollow noreferrer\"><code>presetdef</code></a> or a <a href=\"http://ant.apache.org/manual/Tasks/macrodef.html\" rel=\"nofollow noreferrer\"><code>macrodef</code></a></p>\n\n<p><em>Reply for the edit</em>:</p>\n\n<p>Nice to see that the <code>macrodef</code> works :-). A few other ideas:</p>\n\n<ol>\n<li>\n\n<pre><code><attribute name=\"basename\" default=\"unknown\" />\n</code></pre>\n\n<p>Are you sure that you need the <code>default</code> attribute here? The <code>macrodef</code> documentation says the following:</p>\n\n<blockquote>\n <p>The attributes will be required attributes unless a default value has been set. </p>\n</blockquote></li>\n<li><p>I'd create a list for</p>\n\n<pre><code><srcfiles file=\"@{basename}.dtx\" />\n<srcfiles file=\"@{basename}.ins\" />\n</code></pre>\n\n<p>Here is an example: <a href=\"https://stackoverflow.com/a/4565492/843804\">Ant: using Filelist as Fileset in Uptodate?</a></p></li>\n<li><p>After this I guess the three <code>uptodate</code> tag could be replaced with only one which uses a composite or a chained mapper but I'm not too familiar with these.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:41:57.003",
"Id": "22260",
"Score": "1",
"body": "Thanks; I've added a new version with `macrodef` to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T18:20:08.020",
"Id": "22276",
"Score": "0",
"body": "@MartinSchröder: Thanks for the feedback! I've updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:05:04.473",
"Id": "22311",
"Score": "0",
"body": "Thanks. I've updated the question with a new version with `union` and `srcresources`. That seems to be an area that's severly underdocumented in the online manual. `:-(`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T17:57:31.807",
"Id": "13758",
"ParentId": "13749",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13758",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T14:27:22.410",
"Id": "13749",
"Score": "2",
"Tags": [
"java",
"tex",
"ant"
],
"Title": "ant file for TeX compilation"
}
|
13749
|
<p>I am primarily a java programmer and for the first time working in C++.</p>
<p>I have implemented a Factory design pattern in C++.</p>
<pre><code> class TaskFactory
{
public:
typedef Task* (*create_callback)(map<string, string> vMap);
static void register_task(const string& type, create_callback cb); // function for registering the classes with Factory
static void unregister_task(const string& type); // function for unregistering the classess with factory
static Task* create_task(const string& type,map<string, string> vMap); // function for creating instance of Tasks classes on the basis of class type
private:
static map<string, create_callback> mTasks; // map to store class types along with callback
};
</code></pre>
<p>Following is the factory implementation.</p>
<pre><code> map<string, TaskFactory::create_callback> TaskFactory::mTasks;
//registers the task with the factory
void TaskFactory::register_task(const string& type, TaskFactory::create_callback cb){
mTasks[type]= cb;
}
//unregisters the task with the factory
void TaskFactory::unregister_task(const string& type){
mTasks.erase(type);
}
//creates instance of Task subclasses on the basis of task
Task* TaskFactory::create_task(const std::string& type, map<string, string> vMap){
map<string, TaskFactory::create_callback>::iterator it=mTasks.find(type);
if(it==mTasks.end()){
return NULL;
}else{
return mTasks[type](vMap);
}
}
</code></pre>
<p>And my base Task class is below:</p>
<pre><code> class Task{
private:
map<string, string> vMap;
Task(map<string, string>);
public:
static Task* create(map<string, string>); // funtion is used for creating instance of the Task
};
</code></pre>
<p>In code review I was told that Factory implementation is not doing its intended job. But in my opinion its working very well.
Is any thing wrong with this implementation?</p>
|
[] |
[
{
"body": "<p>Few small problems with the factory.</p>\n\n<h3>You are using a pointer to a method.</h3>\n\n<pre><code> typedef Task* (*create_callback)(map<string, string> vMap); \n</code></pre>\n\n<p>As the way of creating your object. This is very C like. It also introduces the possibilities of passing a NULL pointer (which is not good).</p>\n\n<p>The more idiomatic way to to declare a functor:</p>\n\n<pre><code>struct TaskCreator\n{\n // Leaving Task* for similarities to current code (I will get back to it).\n Task* operator()(std::map<std::string, std::string> vMap) const\n {\n return build(vMap);\n }\n private:\n virtual Task* build(std::map<std::string, std::string> vMap) const = 0;\n};\n</code></pre>\n\n<h3>Register objects</h3>\n\n<p>Now you should register objects derived from this class with the factory. This will prevent you accidentally passing NULL as a callback.</p>\n\n<pre><code>// This looks incant because there are no `*` here\n// But there is a hidden '*' in create_callback \nstatic void register_task(const string& type, create_callback cb);\n\n// I would change this too:\n// Notice I am not using `static` here. I will get to that in a second.\nvoid register_task(const string& type, TaskCreator& cb);\n // ^^^ That is important.\n// Alternatively you can register via smart pointers.\n// But I prefer to pass references. Then make the `TaskCreator` automatically\n// Register themselves in their constructor.\n</code></pre>\n\n<h3>Order of construction</h3>\n\n<p>You also have another invisible problem in the order of construction across compilation units. Remember that the order of construction of <code>static storage duration</code> objects is undefined across compilation units.</p>\n\n<pre><code>static map<string, create_callback> mTasks;\n</code></pre>\n\n<p>This object is constructed before main() is called. The problem is you do not know exactly when. As a result if you call <code>register_task()</code> before main() you don't know if it will work because the storage <code>mTasks</code> may not have been created yet.</p>\n\n<p>There are a couple of ways of solving this. The easiest to use a static member of a function as the storage.</p>\n\n<pre><code>static map<string, create_callback>& getTaskStorage()\n{\n static map<string, create_callback> mTasks;\n return mTasks;\n}\n</code></pre>\n\n<p>But I would go the other way. And use a factory object pattern.</p>\n\n<h3>Factory object</h3>\n\n<p>You are using a set of static methods as your factory. I would swing this around and actually create a factory object. The problem with static functions is that it is hard to use test code with them. It is much easier to mock an object than static API.</p>\n\n<h3>Ownership</h3>\n\n<p>Last. You are not expressing ownership semantics for the created object.</p>\n\n<pre><code>static Task* create_task(const string& type,map<string, string> vMap);\n</code></pre>\n\n<p>A pointer <code>Task*</code> is totally useless in this situation as you have no idea if the ownership is being retained by the factory (and it will destroy it) or if ownership is being returned to the caller so he can destroy it.</p>\n\n<p>Here you have two options:</p>\n\n<ul>\n<li>Return a reference.\n<ul>\n<li>This indicates that the factory is retaining ownership of the created object. This means the object will be destroyed when the factory is destroyed (This implies a factory object).</li>\n</ul></li>\n<li>Return a smart pointer\n<ul>\n<li>By returning a smart pointer you are indicating somthing else has ownership. The type of ownersip depends on the type of smart pointer (unique_ptr: ownership is returned to the caller, shared_ptr: ownership is shared and the loss of the last reference will delelte it).</li>\n</ul></li>\n</ul>\n\n<h3>Further Advice.</h3>\n\n<p>I would suggest some more specific recommendations. But unfortunately you do not provide the expected usage semantics of your factory. Thus I may write something that is tially usless. If you can write some more details on how you think the factory is going to be used I can give you some more concrete information.</p>\n\n<h3>Errors in the code:</h3>\n\n<pre><code>class Task\n{\n static Task* create(map<string, string>);\n};\n</code></pre>\n\n<p>If you take this address it does not match:</p>\n\n<pre><code>typedef Task* (*create_callback)(map<string, string> vMap); \n</code></pre>\n\n<p>There is nothing in the standard that guarantees that the calling convention of a normal function matches the calling convention of static methods. It just happens to work on your compiler but it is non portable.</p>\n\n<p>As stated above: What happens of somebody registers a NULL function.</p>\n\n<pre><code>return mTasks[type](vMap);\n</code></pre>\n\n<p>This line is likely to fail. Using your method you need to validate that the pointer is not NULL wither at the point of setting or at the point were it is used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T17:06:22.343",
"Id": "13756",
"ParentId": "13751",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T16:23:52.987",
"Id": "13751",
"Score": "8",
"Tags": [
"c++",
"design-patterns"
],
"Title": "Correct implementation of Factory pattern in C++"
}
|
13751
|
<p>I tried to solve a programming contest <em><a href="https://hallg.inf.unideb.hu/progcont/exercises.html?locale=en&pid=1631">problem</a></em> in Scala, but I have a feeling, that it could be done in a more functional way. I compared it with the solution written in imperative style and it is not shorter or less complex at all. Do you have any idea how to "impove" or approach the problem in a more functional way?</p>
<p>Here is my solution:</p>
<pre><code>object Sunshine extends App {
def tanning(bedNumber:Int, part1 : List[Char], part2: List[Char], inBed: List[Char], tanned:Int, walkedAway: Int) : Int = {
val actCustomer =part2.head
val tanningTuple=(part1.indexOf(actCustomer),inBed.indexOf(actCustomer),bedNumber>inBed.length,part2.tail)
tanningTuple match {
case(_,_,_,Nil) => walkedAway
// enter,can be tanned
case (-1,-1,true,_) =>
tanning(bedNumber,actCustomer::part1,part2.tail,actCustomer::inBed,tanned,walkedAway)
// enter, can not be tanned
case (-1,-1,false,_) =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway)
//leave, not in bed
case (x ,-1,_,_) if x>=0 =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway+1)
//leave, in bed
case (x,y,_,_) if x>=0 && y>=0 =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed-actCustomer,tanned+1,walkedAway)
}
}
println(tanning(2,List(),"ABBAJJKZKZ".toList,List(),0,0))
println(tanning(3,List(),"GACCBDDBAGEE".toList,List(),0,0))
println(tanning(3,List(),"GACCBGDDBAEE".toList,List(),0,0))
println(tanning(1,List(),"ABCBCA".toList,List(),0,0))
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T15:37:26.793",
"Id": "22217",
"Score": "1",
"body": "In Scala, pattern matching is eager so the first pattern that is matched wins. It is generally a good practice to order pattern matches from most specific to least specific. Your pattern matches include a lot of wildcards. I'd suggest limiting the wildcards and trying place the pattern with more wildcards towards the end."
}
] |
[
{
"body": "<p>A good way to think about this problem is to list the different cases when a customer is encountered in the list:</p>\n\n<ol>\n<li>The person arrives and there is a bed available => the person gets a tan and the number of available bed decreases by one </li>\n<li>The person arrives and there is not a bed available => the person won't tan</li>\n<li>The person leaves and they got a tan => the number of available beds increases by one</li>\n<li>The person leaves and they didn't get a tan => nothing special happens</li>\n</ol>\n\n<p>When there are no more customers then we need to return the number of people who didn't tan.</p>\n\n<p>This is embodied by the following function:</p>\n\n<pre><code>def step(avail: Int, tanned: Set[Char], not_tanned: Set[Char], customers: List[String]): Int = {\n customers match {\n // case 3 above\n case c::cs if tanned(c) => step(avail+1, tanned, not_tanned, cs)\n // case 4 above\n case c::cs if left(c) => step(avail, tanned, not_tanned, cs)\n // case 1 above\n case c::cs if avail > 0 => step(avail-1, tanned+c, not_tanned, cs)\n // case 2 above\n case c::cs if avail == 0 => step(avail, tanned, not_tanned+c, cs)\n // exit condition, no more customers\n case Nil => not_tanned.size\n }\n}\n</code></pre>\n\n<p>Since the problem statement says that no customer visits more than once and everyone who doesn't get a tan leaves before the people getting tans do it isn't necessary to remove people from the sets or maintain a list of waiting customers in case a bed opens up.</p>\n\n<p>The step function above needs to be called with an initial state which, assuming <code>needs</code> is the number of beds in the salon and <code>customers</code> is the string specified in the problem, is</p>\n\n<pre><code>step(needs, Set(), Set(), customers.toList)\n</code></pre>\n\n<p>It is possible to transform the <code>step</code> function into a fold which would remove the explicit list traversal, but in my opinion that would hurt the readability of the code.</p>\n\n<p>A complete version of the code is</p>\n\n<pre><code>object tanning {\n def howmanyleft(nbeds: Int, customers: String): Int = {\n def step(avail: Int, tanned: Set[Char], not_tanned: Set[Char], customers: List[Char]): Int = {\n customers match {\n case c::cs if tanned(c) => step(avail+1, tanned, not_tanned, cs)\n case c::cs if not_tanned(c) => step(avail, tanned, not_tanned, cs)\n case c::cs if avail > 0 => step(avail-1, tanned+c, not_tanned, cs)\n case c::cs if avail == 0 => step(avail, tanned, not_tanned+c, cs)\n case Nil => not_tanned.size\n }\n }\n step(nbeds, Set(), Set(), customers.toList)\n }\n def main(args: Array[String]) {\n println(howmanyleft(2, \"ABBAJJKZKZ\"))\n println(howmanyleft(3, \"GACCBDDBAGEE\"))\n println(howmanyleft(3, \"GACCBGDDBAEE\"))\n println(howmanyleft(1, \"ABCBCA\"))\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T16:00:23.707",
"Id": "13760",
"ParentId": "13759",
"Score": "6"
}
},
{
"body": "<p>Here is my solution, functional albeit using mutable collections .</p>\n\n<pre><code>import scala.collection.mutable\n\ndef tan(numBeds: Int, customersData: Seq[Char]): Int = {\n val currentCustomers = mutable.Set[Char]()\n val walkedAway = mutable.Set[Char]()\n customersData.filter {\n case c if currentCustomers.contains(c) => {\n // this customer is leaving after a tan\n currentCustomers.remove(c)\n false\n }\n case c if walkedAway.contains(c) => {\n // this customer has already walked away\n walkedAway.remove(c)\n false\n }\n case c if currentCustomers.size >= numBeds => {\n // this customer walks away\n walkedAway.add(c)\n true\n }\n case c => {\n // this customer lays for a tan\n currentCustomers.add(c)\n false\n }\n }.size\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T13:24:13.837",
"Id": "22457",
"Score": "1",
"body": "`filter {_ match {case ...}}` can be written as `filter {case ...}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T05:31:51.190",
"Id": "13770",
"ParentId": "13759",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13760",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T15:19:48.610",
"Id": "13759",
"Score": "5",
"Tags": [
"scala",
"functional-programming"
],
"Title": "Change code to use functional style"
}
|
13759
|
<p>The stored procedures must return their first resultset in the form:</p>
<pre><code>(
[index] int,
[id] varchar(50)
)
</code></pre>
<p>where </p>
<ul>
<li><code>[index]</code> is 0,1,2,3,... and </li>
<li><code>[id]</code> is the name of the struct. </li>
</ul>
<p>As long as the first resultset returns the names of the resultsets in the same order they are returned by the stored procedure the php struct will store each struct in the struct by it's name.</p>
<p>Example ResultSet 0:</p>
<pre><code>0,'resultsets'
1,'codes'
2,'listings'
3,'users'
</code></pre>
<p>Example Function Call:</p>
<pre><code>$struct = genericMultiResults('exec dbo.genericProcedure');
</code></pre>
<p>Example Results:</p>
<pre><code>$struct['resultsets'][0]; // 'resultsets'
$struct['resultsets'][1]; // 'codes'
foreach($struct['codes'] as $code) { // loop over the records of the codes resultset
...
}
foreach($struct['listings'] as $listing) { /* loop over the records of the listings resultset */
...
}
</code></pre>
<p>Implementation:</p>
<pre><code>function genericMultiResultSet($sql) {
global $conn;
// resultset holder
$resultSets = array();
// resultsets key name, can be changed by record 0 of resultset 0
$resultSetsKey = 'resultsets';
// current resultset name, only used by resultsets 1 and above, not by 0, defaults to name of 0
$resultSetKey = 'resultsets';
// execute multi-resultset procedure or sql statement
$results = sqlsrv_query($conn,$sql);
// assume we have the first resultset, loop over resultsets
do {
// loop over rows in resultset
while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)) {
// if the structure is $row['index'], $row['id'] then assume it is a resultsets key
if(isset($row['index']) && isset($row['id']) && count($row) == 2) {
// if resultsets key not created yet, create it
if(count($resultSets) == 0) {
$resultSets[$row['id']] = array();
// assume first record in resultset describes itself (the resultset, not the row)
$resultSetsKey = $row['id'];
}
// add entry to resultsets key
$resultSets[$resultSetsKey][$row['index']] = $row['id'];
// otherwise, not a resultsets key
} else {
// if no array for current $resultset create it
if(!isset($resultSets[$resultSetKey])) {
$resultSets[$resultSetKey] = array();
}
// add row to it's resultset within $resultSets
array_push($resultSets[$resultSetKey],$row);
}
}
// get next key for next resultset
if(isset($resultSets[$resultSetsKey][count($resultSets)])) {
$resultSetKey = $resultSets[$resultSetsKey][count($resultSets)];
}
// get next resultset
} while(!is_null(sqlsrv_next_result($results)));
sqlsrv_free_stmt($results);
return $resultSets;
}
</code></pre>
<p>So my implementation works perfectly, does exactly what I want, lets me edit the procedures (add remove resultsets at will) and I only have to modify my php that uses the function, I never have to touch the function.</p>
<p>So my question: Is there a more elegant implementation to get the same result, ie, reference the resultsets by name set in first resultset, rather than referencing them by the order they are returned?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T16:27:38.907",
"Id": "22323",
"Score": "0",
"body": "I'm not really sure what the code is trying to do, or what you are asking. That's probably not your fault, my brain hurts so its being rather dense. Anyways, here are some suggestions. Use `empty()` instead of comparing `count()` to zero. Declare `$resultSetsKey` before initializing `$resultSets`, then use `$resultSetsKey` instead of `$row[ 'id' ]` so that you use the same key throughout the application and don't cause confusion. Don't use `array_push()`, just append like so `$resultSets[ $resultSetKey ] [] = $row`. Assuming no other answers are forth coming I'll give this another crack later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T18:23:46.797",
"Id": "22397",
"Score": "0",
"body": "@showerhead - thanks for the feedback. I'm not really asking a question as much as I'm wanting my code reviewed as that is what I thought was meant by codereview.stackexchange.com since there are always so many different ways to do the same thing, peer review can make code that works either easier to maintain or more reliable."
}
] |
[
{
"body": "<p>In the way you formed your post it looks like you were asking for a better way to do what you are already doing, which it still apears that you are. That's fine, I just had no idea what you wanted from this code. I had to walk myself through your code step by step, so some of this is just going to be repeating what you've already said in an attempt to affirm it into my mind. I don't know why I was having difficulties before, I guess, as I said, I was just being dense.</p>\n\n<p>First of all, your example function call does not call the same function as the one you provided, though this is most likely just a typo.</p>\n\n<p>Alright, with you so far. You seem to be saying you don't like your current output and that you desire a ResultSet that uses associative indexing rather than numerical indexing, similar to:</p>\n\n<p>array(\n [ \"resultsets\" ] => array(),\n [ \"codes\" ] => array(),\n [ \"listings\" ] => array(),\n [ \"users\" ] => array()\n)</p>\n\n<p>However, the ResultSet I'm seeing does not have this problem. I do see you are using the <code>$row[ 'index' ]</code> as a key for some reason, maybe that is what you mean? You can remove those and just use automatically generated incrementals, which I'll show you below. Let's take a look at that function.</p>\n\n<p>Immediately I see a global. These are bad. Avoid globals at all costs. Globals don't exist. Forget you ever heard of them. If you need a variable to exist outside of the function in which you are using it, have it be the return value. If you need it inside a new function, have it be one of the parameters required to run it. In this case, you probably defined <code>$conn</code> just before this function is called, just pass it as a second parameter. Or rather, pass it as the first and the SQL as the second, that way it makes sense when compared to the other functions. The best way to do this would actually be to use a class and class properties, however this is beyond the scope of this review. I'd recommend becoming a little more familar with the \"Don't Repeat Yourself\" and \"Single Responsibility\" Principles, DRY and SR respectively, before attempting to learn OOP. Though SR is not usually abbreviated I will do so to save time.</p>\n\n<p>Your loop seems odd. I'm not familiar enough with SQLSRV to be 100% sure, but it looks like your code is somewhat redundant. The only reason you haven't noticed it is because the internal iterator is smart enough to know better than to reset itself. Your first loop says it will continue looping through the results while there is a next result in the array. Your second, internal loop to the first, says the same. So, because you set up your first loop as a do/while loop, it will immediately perform the first iteration without checking the condition in the first while. So, as the second while loop iterates over the same array its as if that first loop were never there. Once you exit the do statement the internal pointer on the <code>$results</code> array is already pointing to the end of the array, this means when it checks that while statement at the end of the do/while block it will see that its job is already done and proceed with the code. Unless I miss my guess completely, you should be able to remove the do/while loop and this should perform the same.</p>\n\n<p>Now, inside your loop. This is where the DRY and SR Principles begin. SR states that a function/method/class should only be concerned with a SINGLE RESPONSIBILITY. In other words its specialized to perform one task. Usually this task is repeatable, which is where the the DRY principle comes in. DRY states that you should never repeat yourself. If you find that you are performing the same task, create a function/method/class to do that task for you. So, if you want to \"fetch\" or \"get\" something, a repeatable task, you create a function that will do just that. And if there are any other smaller tasks associated with doing this one task it should be delegated to another specialized function that does just that. So this one big function you provided could actually be broken up into a few separate, more specialized, functions. So how do we separate it?</p>\n\n<p>Believe it or not, you've already got the ground work laid out for it. Because we are in a loop, anything we do can be considered a repeatable task. While this isn't the only type of \"repeatable\" task, it is the easiest to spot. Tasks are any group of related actions done to accomplish an end goal. In plain english we refer to a task such as, \"do this\". In programming we refer to them much the same, but with slightly differnt termanology, such as \"if, else, for, while, do, etc...\". Sounds pretty daunting, but it isn't. Not everything in an if statement needs to be separated into its own custom function. Usually its already done for us. For example, <code>isset()</code>, <code>count()</code>, and <code>empty()</code> are all predefined tasks that do just one thing. But sometimes we can create a larger task that uses these smaller tasks.</p>\n\n<p>Hopefully with those hints you will be able to figure out how to break this up. I don't want to do all the work for you, else you'll never learn. Now, I will show you a modified if/else statement that shows how to remove those <code>$row[ 'index' ]</code> indices and replace them with auto-incrementing indices. I'll also make a few other improvements and try explaining them below. I don't know enough about your data structure to determine if the initial if/else statement needs to be changed, but I can work with the rest.</p>\n\n<pre><code>if( isset( $row[ 'id' ] ) {\n $resultSetsKey = $row[ 'id' ];\n}\nif( ! isset( $resultSets[ $resultSetsKey ] ) ) {\n $resultSets[ $resultSetsKey ] = array();\n}\n\nif(isset($row['index']) && isset($row['id']) && count($row) == 2) {\n $resultSets[ $resultSetsKey ] [] = $row['id'];\n} else {\n $resultSets[ $resultSetKey ] [] = $row;\n}\n</code></pre>\n\n<p>So, first thing you will notice, I moved the code used to set the <code>$resultSetsKey</code> and initial value of that array index, outside of the initial if/else statement. This is to reduce the amount of DRY violations. The new if/else statement is much smaller. Now all its concerned about is which part of the arrow to set to the <code>$resultSets</code> array.</p>\n\n<p>I hope these points helped.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T04:21:15.263",
"Id": "22412",
"Score": "0",
"body": "I wish I could +1 this more than once just for \"Immediately I see a global. These are bad. Avoid globals at all costs. Globals don't exist. Forget you ever heard of them.\" :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T21:54:55.607",
"Id": "13887",
"ParentId": "13761",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T18:36:22.110",
"Id": "13761",
"Score": "2",
"Tags": [
"php",
"sql-server"
],
"Title": "Generic PHP function for making a struct out of multiple resultsets from a stored procedure call"
}
|
13761
|
Apache Ant (formerly Jakarta Ant) is a declarative, XML-based build tool for Java projects. It provides a rich set of standard tasks for performing most common build operations, such as compilation with javac, building archives and running tests. Ant's functionality can be extended through custom tasks and macros.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T19:20:41.013",
"Id": "13764",
"Score": "0",
"Tags": null,
"Title": null
}
|
13764
|
<p>Since I have little to no knowledge about native languages, I tried once more to write a simple application in C++, this time with a <a href="http://en.wikipedia.org/wiki/Brainfuck" rel="nofollow">Brainfuck</a> parser.</p>
<p>It works, kind of, verified with the <a href="http://esolangs.org/wiki/brainfuck" rel="nofollow">Hello World and Cat examples given in the Esolang wiki</a>. So...what did I just break?</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
#define INC_POINTER '>'
#define DEC_POINTER '<'
#define INC_VALUE '+'
#define DEC_VALUE '-'
#define OUTPUT_ASCII '.'
#define INPUT_ASCII ','
#define IF_ZERO '['
#define IF_NOT_ZERO ']'
int main(int argc, char* argv[]) {
if (argc <= 1) {
cout << "Input-File required..." << endl;
return 0;
}
ifstream input;
input.open(argv[1], ios::in | ios::binary | ios::ate);
ifstream::pos_type programLength = input.tellg();
char* program = new char[programLength];
input.seekg(0, ios::beg);
input.read(program, programLength);
input.close();
// I'm still thinking about a good way to pre-calculate
// the size.
char* data = new char[30000];
fill_n(data, 30000, 0);
for (int idx = 0; idx < programLength; idx++) {
if (program[idx] == INC_POINTER) {
++data;
} else if (program[idx] == DEC_POINTER) {
--data;
} else if (program[idx] == INC_VALUE) {
++*data;
} else if (program[idx] == DEC_VALUE) {
--*data;
} else if (program[idx] == OUTPUT_ASCII) {
cout << *data;
} else if (program[idx] == INPUT_ASCII) {
cin.read(data, 1);
} else if (program[idx] == IF_ZERO) {
if(*data == 0) {
while(program[idx] != IF_NOT_ZERO) {
idx++;
}
}
} else if (program[idx] == IF_NOT_ZERO) {
if(*data != 0) {
do {
idx--;
} while(program[idx] != IF_ZERO);
}
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>You don't need to read the whole program into memory.</p>\n\n<p>You use a stream to represent the program.<br>\nReading a character automatically moves you to the next location. If you need additional control of the stream you can use seekg() to move around the stream a bit more.</p>\n\n<p>Rather than multiple <code>if statements</code>. This is the perfect situation for a <code>switch</code>:</p>\n\n<p>If there is an error you should return 1 rather than 0 so that the inclosing shell notices there was an error.</p>\n\n<p>There is a small bug in your back seek:<br>\nIf you have code like this:</p>\n\n<pre><code>[XX[]XX]XXXX\n ^ \n</code></pre>\n\n<p>If you are at the point marked with ^ you will seek back to the wrong point (the second '[' in the program rather than the first.</p>\n\n<p>Here is what I would do.<br>\nJust copying and modifying your code (not reading how BF works).</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n std::vector<std::streampos> jumpPoint;\n\n if (argc <= 1) {\n cout << \"Input-File required...\" << endl;\n return 1;\n }\n\n ifstream input(argv[1], ios::in | ios::binary);\n if (!input) {\n cout << \"Failed to open: \" << argv[1] << endl;\n return 1;\n }\n\n std::vector<char> dataStore(30000, '\\0');\n char* data = &dataStore[0];\n\n unsigned char next;\n while(input >> noskipws >> next)\n {\n switch(next)\n {\n case '>': // INC_POINTER \n ++data; if (data > &dataStore[29999]) { data = &dataStore[0];}\n break;\n case '<': // DEC_POINTER\n --data; if (data < &dataStore[0]) { data = &dataStore[29999];}\n break;\n case '+': // INC_VALUE\n ++*data;\n break;\n case '-': // DEC_VALUE\n --*data;\n break;\n case '.': // OUTPUT_ASCII\n cout << *data;\n break;\n case ',': // INPUT_ASCII\n cin.read(data, 1);\n break;\n case '[': // IF_ZERO\n if(*data == 0) {\n // Seek forward to the point after ']'\n std::string ignore;\n std::getline(input, ignore, ']');\n }\n else {\n // Otherwise push the current point so we can rewind\n // if required when we hit the next ']'\n jumpPoint.push_back(input.tellg());\n }\n break;\n case ']': // IF_NOT_ZERO\n if(*data != 0) {\n // Move the read point back to the last '[' that we saved\n input.seekg(jumpPoint.back());\n }\n else {\n // Since this is a close and we did not seek back pop the last\n // saved point off the stack\n input.pop_back();\n }\n break;\n default:\n // ignore;\n break;\n }\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T22:39:53.723",
"Id": "22223",
"Score": "0",
"body": "It looks like you lost the definition of data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T19:26:40.213",
"Id": "22277",
"Score": "0",
"body": "@WinstonEwert: Thanks Fixed. You made me read the language spec. Ugg."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T22:24:44.867",
"Id": "13768",
"ParentId": "13767",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-17T21:56:08.173",
"Id": "13767",
"Score": "4",
"Tags": [
"c++",
"parsing",
"brainfuck"
],
"Title": "Brainfuck parser"
}
|
13767
|
<p>I have the following class:</p>
<pre><code>Class Core {
public $security;
public $db;
public $extra;
public function __construct() {
spl_autoload_register(array($this, 'loader'));
}
public function loader($name) {
include $name.'.php';
}
public function __get($key) {
return $this->extra[$key];
}
public function init( $extra ) {
#error_reporting(0);
$this->security = new Security();
#$this->db = new Database();
$extra = explode(",", $extra);
if(is_array($extra)) {
foreach($extra as $key) {
$key = trim($key);
$this->extra[$key] = new $key;
}
}
}
}
</code></pre>
<p>Index.php
include 'core/Core.php';</p>
<pre><code>$start = microtime(true);
$core = new Core();
$core->init('User, Control');
$core->Control->test2();
echo "<br />";
$core->User->test();
</code></pre>
<p>The purpose of this was to make it so I could load/instantiate classes only when I need them, but use the Core class on all pages. I will of course check if the file exists or not, but I wanted some feedback on whether or not this was viable. Also, is there an easier way to do what I'm trying achieve?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T06:05:23.313",
"Id": "22228",
"Score": "0",
"body": "I think you're just looking for auto loading? http://www.php.net/manual/en/language.oop5.autoload.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T09:13:07.223",
"Id": "22238",
"Score": "0",
"body": "After reading your question again, I see that you are using autoloading in a round about way. I'm not sure I understand the purpose of a registry that acts as an implicit singleton. Can you elaborate a bit more on what drove you towards this? Using autoloading already makes it so that classes are only loaded and instantiated when you need them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T10:31:49.257",
"Id": "22246",
"Score": "0",
"body": "Basically, the developer on a project before me wrote an entire CMS from scratch. The thread viewing PHP script has like 8 includes and 5 class instantiations when I know it could be cut down to way less. The idea was to only have to instantiate one class and then being able to do things like `$core->User->getUserId()`, or, `$core->Security->xss_clean($str)`.\n\nIt was just to avoid having to do `$system = new System();` , `$forum = new Forum();` etc.."
}
] |
[
{
"body": "<p>There's a lot of design oddities in this, and I don't quite see the value of it. The brevity it allows now will undoubtedly cause issues once you use this in a complex application.</p>\n\n<p>Why is:</p>\n\n<pre><code>$core = new Core();\n$core->init('User, Control');\n\n$core->Control->test2();\n\necho \"<br />\";\n\n$core->User->test();\n</code></pre>\n\n<p>Better than:</p>\n\n<pre><code>spl_autoload_register(...);\n\n$control = new Control();\n$control->test2();\n$user = new User();\n$user->test();\n</code></pre>\n\n<p>Autoloading is typically setup in some form of bootstrap. It is usually done in the same place that DB connections are made, application-wide configuration is put into place, etc.</p>\n\n<p>This mean that your main script content should never have to worry about autoloading since your bootstrapping will have already taken care of it.</p>\n\n<p>(Note that a boostrap does not need to be a huge complex process. Sometimes it can be as simple as <code>include 'boostrap.php';</code>)</p>\n\n<p>Anyway, your class has a few design problems and a a few implementation problems:</p>\n\n<p>Design:</p>\n\n<ul>\n<li>What if you want more than 1 User object in the core?</li>\n<li>What if you need to pass a parameter to a constructor</li>\n<li>init() can make the state of the object unknown.\n<ul>\n<li>if you pass a <code>Core</code> instance to some other place of code, how does that code know what properties are valid on the object</li>\n<li>This type of magic almost always ends badly since it hides state information</li>\n</ul></li>\n</ul>\n\n<p>Implementation:</p>\n\n<ul>\n<li><code>__get</code> should check if the key exists in <code>$extra</code> before blindly accessing/returning</li>\n<li>Unnecessary string processing: Why explode a string? Just use an array. It's cleaner and less error prone.</li>\n<li>If you do keep this class (which I advise that you don't), I would consider making the <code>init()</code> part of the constructor. I like to ensure that all of my instances are always in a stable, usable state. What happens if you use a <code>Core</code> instance before calling <code>init</code>?</li>\n<li>Setting up autoloading, storing objects and creating objects are three discrete responsibilities. This means that the class is likely doing too much.\n<ul>\n<li>Once again, I recommend not using the class, but if you do:</li>\n<li>Have the constructor take in an <code>Autoloader</code> instance and have that class handle loading</li>\n<li>Have the class take in instances instead of names (this decouples creation from storing -- which is good since it means you have much more control of instantiation -- but it will kill the brevity of using your class)</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T23:58:09.530",
"Id": "13817",
"ParentId": "13771",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13817",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T05:35:41.683",
"Id": "13771",
"Score": "1",
"Tags": [
"php"
],
"Title": "Dynamically instantiating classes"
}
|
13771
|
<p>I'm working on a module that downloads a file saves it then validates if the file contents are valid.</p>
<p>For simplicity lets assume that the file consists of 3 segments: Header, Body & Footer.</p>
<p>Now here is the design I thought of:</p>
<pre><code>class File{
private $header;
private $body;
private $footer;
function __construct($pathToFile){
$this->header= new Header($this->getFileHeader());
$this->body= new Header($this->getFileBody());
$this->footer= new Header($this->getFileFooter());
}
/* getFileHeader(), getFileBody(), getFileFooter() are private functions of the File class
that basically reads the contents of the corresponding segment in the file. */
function isValid(){
if(!$this->header->isValid()) return false;
if(!$this->body->isValid()) return false;
if(!$this->footer->isValid()) return false;
}
}
</code></pre>
<p>Header Segment class(I'll only show this one as the Body segment and Footer segment have similar structure)</p>
<pre><code>class Header{
private $content;
private $validators=array();
function __construct($content){
$this->content= $content;
$this->validators= array(new NotEmptyValidator($content), new AllNumbersValidator($content));
//for simplicity the validators will be only 2 and set in the constructor.
}
function isValid(){
foreach($this->validators as $validator){
if(!$validator->isValid()) return false;
}
return true;
}
}
</code></pre>
<p>Finally the Validator class:</p>
<pre><code>class NotEmptyValidator{
private $content;
function __construct($content){
$this->content= $content;
}
function isValid(){
return (empty($this->content));
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li>Overall does this look like a good object oriented design? Can it be improved?</li>
<li>The <code>Header</code> class has an array of validators. I'm not sure if this is the best approach as I borrowed this idea from Zend framework form validators. Is there a better implementation?</li>
<li>Am I <em>over delegating</em> the task of validation?</li>
</ol>
<p><strong>Update:</strong></p>
<p>I've simplified the design and striped many details to focus mainly on the validation process.</p>
<p>Another point The file I'm trying to validate is an EDI FACT file, so I suppose the file downloaded will have to be parsed first then validated.</p>
<p>Maybe reading the file contents in the File class is a bad idea and I should create a class <code>Parser</code> that takes the downloaded file and then create the <code>File</code> object itself then comes the validation.</p>
|
[] |
[
{
"body": "<p>Right off the bat, I'd consider getting the file reading for header, body, and footer out of your constructor. Not only are these potentially time-consuming operations, they're also quite likely to fail if you've got a mal-formed file. You'll want to think about whether you'd consider that a \"validation failure\" or another sort of structural failure altogether.</p>\n\n<p>Beyond that, I'd consider how you'll handle interaction among header, footer, and body. For example, you might find that you've got a footer validation that depends on a checksum derived from body fields, though there are plenty of simpler validations that you could get away with evaluating sequentially.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T22:29:57.270",
"Id": "22231",
"Score": "0",
"body": "hmmmm so you propose that I remove the File's constructor and create a public method like `loadFile()` instead that does the same job of the constructor? or should I create a `loadHeader()`, `loadBody()` & `loadFooter()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T05:07:44.737",
"Id": "22232",
"Score": "0",
"body": "Maybe a load that takes a stream of some sort -- you'd like to pass in an open file handle rather than opening and closing the same file over and over, right?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T21:01:59.973",
"Id": "13777",
"ParentId": "13776",
"Score": "0"
}
},
{
"body": "<p>That isn't OOP, that's procedural, with a thin wrapping that looks like OOP. OOP will require that your validation be done on objects that share data and behavior.</p>\n\n<p>Depending upon your file, this may or may not make sense.</p>\n\n<p>OTOH, good procedural code is definitely better than the common PHP \"just run it all together inside a single page\" that frequently gets used.</p>\n\n<p><strong>EDIT: Expanding my answer after a comment.</strong></p>\n\n<p>First off, I should be clear that I wasn't criticizing your existing code, just saying they don't make it OOP. OOP is about data and behavior not just having things called classes and constructors.</p>\n\n<p>Secondly, EDI probably means transactions of different types with well definined behavior for the various types -- that would be an opportunity to use/benefit from OOP. I would try to design a base class or interface that can be applied to all lines/transactions and then have derived classes for the header/footer and body lines.</p>\n\n<p>You need to focus on the similaririty of your data and your process for handling/validating it, your OOP implemention will come out of that. It's a little to early to be asking about OOP.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T01:17:23.373",
"Id": "22233",
"Score": "0",
"body": "Well, I'm trying to validate an EDI FACT file. Any suggestion on how to improve the classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T13:56:14.767",
"Id": "22234",
"Score": "0",
"body": "Oh! I get your point and I agree with you. It seems I wasn't clear enough in my question, but I was hoping to improve the design mainly for the validation process . Actually I striped many functions and data from the classes to make it focus on the validation process :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T15:49:44.377",
"Id": "22235",
"Score": "0",
"body": "@Songo: well the validation and parsing are pretty much the same. Your current design is, as I said procedural. You should think of the file as a collection of lines. So, no header, footer, body. Just a collection, each object having an isValid property. The type of object would be determined when the line/s is parsed (unrecognized being always invalid). So, your constructor for the file should take either a path or a stream (or database id later) and then create your collection of objects as it reads the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T20:59:05.143",
"Id": "22236",
"Score": "0",
"body": "But what if the File has a predefined structure that must contain a header segment followed by a collection of line (their number can vary) then a footer segment? I think separating them into 3 variables makes more sense IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T01:08:13.483",
"Id": "22237",
"Score": "0",
"body": "@Songo: Why would you want the header/trailer excluded from your list of objects in the file? You might want/need to have a reference to the first and last items seperate from the list, but there's no reason why they shouldn't share an interface with the other items, and be part of the same collection. You seem to be headed towards an Interface that would allow you to check the validity of the file, but you haven't made it explicit by declaring either an Interface or an Abstract class with the isValid property. Making it explicit is useful, even in duck-typing languages."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-13T01:10:14.973",
"Id": "13778",
"ParentId": "13776",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-12T19:54:02.637",
"Id": "13776",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"php5",
"validation"
],
"Title": "Is this a good object oriented design for a file validator?"
}
|
13776
|
<p>I need to do pending methods invocation in Java (Android) in my game project. A method represents actions in a scene.</p>
<p>Maybe you're familiar with <code>Context.startActivity</code> in Android, which is not suddenly starting the activity, but statements below it is still executed before starting the requested activity. I've found 3 ways, but I'm not sure which one should I choose by considering the performance and PermGen issues (actually I don't know whether Android has PermGen issue if there are so many classes). These methods will not be called very frequent, may be once in 5 seconds, but may be they will be very many (there are so many scenes).</p>
<p>Please suggest the best way of doing this, by considering memory usage (maybe PermGen too), performance, ease of coding, and bug freedom.</p>
<p><strong>Using switch-case</strong></p>
<p>I need to add each method call in switch-case.</p>
<pre><code>public class MethodContainer {
public void invoke(int index) {
switch (index) {
case 0:
method0();
break;
.
.
.
case 100:
method100();
break;
}
}
private void method0() {
...
}
.
.
.
private void method100() {
...
}
}
</code></pre>
<p><strong>Using for-loop and annotation/reflection</strong></p>
<p>Like the above, but make coding easier (except in defining constants).</p>
<pre><code>public class MethodContainer {
private static final int METHOD_0 = 0;
...
private static final int METHOD_100 = 100;
public void invoke(int index) {
for (Method m : MethodContainer.class.getMethods()) {
MyAnnotation annotation = m.getAnnotation(MyAnnotation.class);
if (annotation != null && annotation.value() == index) {
try {
m.invoke(this);
break;
} catch (...) {
...
}
}
}
}
@MyAnnotation(METHOD_0)
private void method0() {
...
}
.
.
.
@MyAnnotation(METHOD_100)
private void method100() {
...
}
}
</code></pre>
<p><strong>Using inner classes</strong></p>
<p>There's no need to declare constants and no reflection, but too many classes.</p>
<pre><code>public class MethodContainer {
public void invoke(Runnable method) {
method.run();
}
private Runnable method0 = new Runnable() {
public void run() {
...
}
};
.
.
.
private Runnable method100 = new Runnable() {
public void run() {
...
}
};
}
</code></pre>
|
[] |
[
{
"body": "<p>Your first example (switch-case) is so poorly thought of in the Object Oriented community that there is a refactoring designed specifically to replace it with your third implementation: <a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional With Polymorphism</a>.</p>\n\n<p>To be honest, I would have never thought of your second implementation. It isn't completely heinous, though I would probably use the constructor to create an array of method objects that you can index into directly - rather than run through a for loop every time you want to make a call.</p>\n\n<p>Between a revised second implementation (array with annotation/reflection) and the third implementation (inner classes) I would personally be more fond of the \"inner class\" version. I don't think that memory or performance is going to be a factor at this level and I think the third, inner class, version is much more readable (at least in Java - in other languages, you could implement something like the second approach directly).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T05:05:15.757",
"Id": "23391",
"Score": "0",
"body": "I've chosen \"inner class\" version as you've recommended. I've found it made me easier to maintain and extend the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T13:14:02.317",
"Id": "13786",
"ParentId": "13780",
"Score": "2"
}
},
{
"body": "<p>Disclaimer: I'm not too familiar with Android.</p>\n\n<p>I wouldn't optimize for permgen space unless there is a good reason for it. It seems <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimization</a>. \"<a href=\"https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation\" rel=\"nofollow noreferrer\">Permgen stores the methods of a class (including the bytecodes)</a>\" in all of your cases so I do not think that only the class definition headers would cause too much overhead.</p>\n\n<p>From the three option the third is the most OOP (+1 to Donald). If it's possible try to make these classes static inner classes (<em>Effective Java, 2nd Edition, Item 22: Favor static member classes over nonstatic</em>). If they use fields from the parent class consider passing a context object to them instead of direct access. It would result looser coupling. (<a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29#Disadvantages\" rel=\"nofollow noreferrer\">Disadvantages of coupling on Wikipedia</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:34:32.853",
"Id": "13810",
"ParentId": "13780",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "13786",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T09:43:06.663",
"Id": "13780",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Pending method invocation for a game"
}
|
13780
|
<p>Sometimes there is need to change an integer to text.
I often use the following way:</p>
<pre><code>"" + myNumber
</code></pre>
<p>But there is alternative way:</p>
<pre><code>Integer.toString(myNumber)
</code></pre>
<p>Which one is better (performance, readability, safety)?
Or are those equal?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T17:11:41.570",
"Id": "22271",
"Score": "4",
"body": "A very detailed answer to a very similar question on SO: http://stackoverflow.com/a/4105406/843804"
}
] |
[
{
"body": "<p>Integer.toString(myNumber) is the safer way because it throws a malformed exception.</p>\n\n<p>Do not worry about performance at this level. There is an expression: <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow\">Premature Optimization</a>.</p>\n\n<p><strong>EDIT after comment</strong></p>\n\n<p>\"3000000000\" <code>> Integer.MAX_VALUE</code> throw an Exception<br>\n\"-2900000000\" <code>< Integer.MIN_VALUE</code> throw an Exception<br>\n\"OO12345\" throw an exception, because it begins with two <code>O letters</code>, not zero.<br></p>\n\n<p>You can also manage radix :</p>\n\n<pre><code>String intS = \"010101\";\nSystem.out.format(\"Parsing %s gives %d, fail with \\\"010102\\\"%n\",\n intS,(Integer.parseInt(intS, 2)));\nintS = \"10CAFE8\";\nSystem.out.format(\"Parsing %s gives %d, fail with \\\"10CAGE8\\\"%n\",\n intS,(Integer.parseInt(intS, 16)));\n</code></pre>\n\n<p>Output :</p>\n\n<pre><code>Parsing 010101 gives 21, fail with \"010102\"\nParsing 10CAFE8 gives 17608680, fail with \"10CAGE8\"\n</code></pre>\n\n<p><strong>EDIT after comment 2</strong></p>\n\n<p>Look in <a href=\"http://rads.stackoverflow.com/amzn/click/0321356683\" rel=\"nofollow\">Effective Java</a> and search for <em>StringBuilder()</em> to understant how to replace '<code>+</code>' usage.</p>\n\n<p>At execution time, a '<code>+</code>' create something like this code :</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nsb.append(123);\nsb.toString();\n</code></pre>\n\n<p>This code is better :</p>\n\n<pre><code>final int a = 123;\nInteger.toString(a);\n</code></pre>\n\n<p>Look at Java code of <code>Integer.toString(a);</code><br>\nIn Eclipse : <code>CTRL+rightClick</code> on <code>toString()</code> print the Java code . Give the <code>src.zip</code> path in SDK directory if it not already done.<br>\nAnd compare with <code>StringBuilder.append(int);</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:35:07.440",
"Id": "22270",
"Score": "5",
"body": "How can an integer be malformed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T09:57:10.830",
"Id": "22309",
"Score": "0",
"body": "@FelixDombek I've edited my post to give samples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T13:05:16.703",
"Id": "22317",
"Score": "4",
"body": "Your examples are about String to Int, but the question is about Int to String."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T06:07:50.947",
"Id": "22359",
"Score": "0",
"body": "@FelixDombek Exact, I compelte my post. Sorry not to be a good english reader."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T15:50:38.773",
"Id": "22418",
"Score": "0",
"body": "@FelixDombek `Effective Java` is a reference to write good code, Is the response you needed? Many other things to know are also inside this book."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T09:52:50.087",
"Id": "13782",
"ParentId": "13781",
"Score": "11"
}
},
{
"body": "<p>I would say they were equally as good. I prefer to use</p>\n\n<pre><code>Integer.toString(myNumber)\n</code></pre>\n\n<p>as I find it explains the transition better</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T08:54:26.977",
"Id": "22365",
"Score": "0",
"body": "haha my mistake @palacsint"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:17:51.917",
"Id": "13787",
"ParentId": "13781",
"Score": "1"
}
},
{
"body": "<p>I would recommend</p>\n\n<pre><code>String.valueOf(myNumber)\n</code></pre>\n\n<p>This allows you to to change myNumber to another primitive type - or a Number - later.</p>\n\n<pre><code>\"\" + myNumber\n</code></pre>\n\n<p>should be avoided since :</p>\n\n<ul>\n<li>it produces clutter bytecode (instanciating a new StringBuffer)</li>\n<li>it does not convey what you wanted to do with myNumber</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T01:13:56.497",
"Id": "13818",
"ParentId": "13781",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "13818",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T09:45:10.033",
"Id": "13781",
"Score": "8",
"Tags": [
"java"
],
"Title": "Which way is better for converting number to string?"
}
|
13781
|
<p>I'm trying to merge two nodes. Basically, the idea is to take all children in left and new ones in right. Is there any way to get rid of <code>toAdd</code> variable and do it in a clean way?</p>
<p>I don't want to convert any <code>IEnumerable<T></code> to <code>List</code> or <code>Array</code> in this merge process.</p>
<pre><code>public IEnumerable<TChild> NodeMerge<TNode, TChild, TKey>(TNode left, TNode right,
Func<TNode, IEnumerable<TChild>> getChildren, Func<TChild, TKey> getKey)
{
var lChildren = getChildren(left);
var rChildren = getChildren(right);
IEnumerable<TChild>[] toAdd = new IEnumerable<TChild>[2];
// Common Keys between left and right
toAdd[0] = lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s)));
// new keys added to right
toAdd[1] = rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false);
return toAdd.SelectMany(s => s);
}
</code></pre>
|
[] |
[
{
"body": "<p>Little cleaner:</p>\n\n<pre><code>// Common Keys between left and right\nvar result = lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s))).ToList();\n\n// new keys added to right\nresult.AddRange(rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false));\n\nreturn result;\n</code></pre>\n\n<p>Without ToList():</p>\n\n<pre><code>public static IEnumerable<T> Merge<T>(this IEnumerable<T> first, IEnumerable<T> second)\n{\n foreach (var item in first)\n yield return item;\n\n foreach (var item in second)\n yield return item;\n}\n</code></pre>\n\n<p>In your NodeMerge method:</p>\n\n<pre><code>return lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s))).Merge(rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T11:08:34.523",
"Id": "22248",
"Score": "0",
"body": "Thanks. I should have mentioned, but in general I usually try to avoid `ToList()`, `ToArray()` operator. Will add this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T11:11:51.610",
"Id": "22250",
"Score": "0",
"body": "Why? Is there a problem with them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T11:16:53.453",
"Id": "22252",
"Score": "0",
"body": "Well I want whole function do Lazy evaluation. `ToList` will defeat that purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T11:25:11.717",
"Id": "22254",
"Score": "0",
"body": "You can make an extension method \"Merge\" that gets two enumerables and iterate both of them with yield return and use this method on your where results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:10:25.660",
"Id": "22269",
"Score": "1",
"body": "There is already an extension method that behaves exactly like your Merge method, called Concat. Neither of them will \"join\" the lists."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T11:04:10.760",
"Id": "13784",
"ParentId": "13783",
"Score": "3"
}
},
{
"body": "<pre><code>public IEnumerable<TChild> NodeMerge<TNode, TChild, TKey>(TNode left, TNode right,\n Func<TNode, IEnumerable<TChild>> getChildren,\n Func<TChild, TKey> getKey)\n{\n var lChildren = getChildren(left);\n var rChildren = getChildren(right);\n\n return lChildren\n .Intersect(rChildren, new FuncComparer<TChild, TKey>(getKey))\n .Concat(\n rChildren\n .Except(lChildren, new FuncComparer<TChild, TKey>(getKey))\n );\n}\n</code></pre>\n\n<p>With this helper class:</p>\n\n<pre><code>public class FuncComparer<T, TKey> : IEqualityComparer<T> \n{\n readonly Func<T, TKey> getKey;\n readonly EqualityComparer<TKey> comparer;\n\n public FuncComparer(Func<T, TKey> getKey) \n { \n this.getKey = getKey;\n this.comparer = EqualityComparer<TKey>.Default;\n }\n public bool Equals(T x, T y) \n {\n return comparer.Equals(getKey(x), getKey(y));\n }\n\n public int GetHashCode(T obj) \n {\n return comparer.GetHashCode(getKey(obj));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:54:07.523",
"Id": "22267",
"Score": "0",
"body": "This is matching what your code is doing, but not what your question says the code is doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T07:11:25.720",
"Id": "22302",
"Score": "0",
"body": "Is `FuncComparer` necessary? Why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T01:21:55.920",
"Id": "22348",
"Score": "0",
"body": "`FuncComparer` allows linq to optimize the comparisons via the included `GetHashCode` method. When `Intersect` runs it can build a lookup table and doesn't need to get the key to use `Equals` for every comparison."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:52:44.297",
"Id": "13796",
"ParentId": "13783",
"Score": "3"
}
},
{
"body": "<p>You can do this with vanilla Linq. The question is whether you want all keys on the left plus new keys from the right (a \"full join\") or common keys between left and right plus all keys on the right (a \"right join\"):</p>\n\n<pre><code>var lChildren = getChildren(left);\nvar rChildren = getChildren(right);\nvar lKeys = lChildren.Select(getKey);\nvar rKeys = rChildren.Select(getKey);\n\nvar fullJoin = lChildren\n .Concat(rChildren.Where(r=>!lKeys.Contains(getKey(r)));\n\nvar rightJoin = lChildren.Where(l=>!rKeys.Contains(getKey(l)))\n .Concat(rChildren.Where(r=>!lKeys.Contains(getKey(r)));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:45:05.447",
"Id": "13800",
"ParentId": "13783",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13796",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T10:48:02.087",
"Id": "13783",
"Score": "4",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Joining two IEnumerable<T>"
}
|
13783
|
<p>I have two different data inputs for the same value, I want to use the non empty one if one of them is, to return the empty string if both are empty, and to flag an error if both are not empty but differ and return one of them.</p>
<p>Empty for my criteria matches the meaning of <code>string.IsNullOrEmpty()</code>.</p>
<p>And it's okay that it's written as a property (don't worry about that part.)</p>
<p>This works but feels overly verbose. Can you think of any alternatives?</p>
<pre><code> public string Callkey
{
get
{
if (string.IsNullOrEmpty(AS_CALL_KEY) && !string.IsNullOrEmpty(CALLKEY))
{
return CALLKEY.Trim();
}
if (!string.IsNullOrEmpty(AS_CALL_KEY) && string.IsNullOrEmpty(CALLKEY))
{
return AS_CALL_KEY.Trim();
}
if (!string.IsNullOrEmpty(AS_CALL_KEY) && !string.IsNullOrEmpty(CALLKEY))
{
if (!AS_CALL_KEY.Trim().Equals(CALLKEY.Trim()))
{
_error = true;
}
return AS_CALL_KEY.Trim();
}
if (string.IsNullOrEmpty(AS_CALL_KEY) && string.IsNullOrEmpty(CALLKEY))
{
return "";
}
_error = true;
return "THISNEVERHAPPENS";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You have four cases and each of them behaves differently, so you actually need to have four different branches. But you can simplify your code by extracting the checks into variables and using nested <code>if</code>s:</p>\n\n<pre><code>public string CallKey\n{\n get\n {\n bool callKeyEmpty = string.IsNullOrEmpty(CALLKEY);\n bool asCallKeyEmpty = string.IsNullOrEmpty(AS_CALL_KEY);\n\n if (callKeyEmpty) \n {\n if (asCallKeyEmpty)\n return \"\";\n else\n return AS_CALL_KEY.Trim();\n }\n else\n {\n if (asCallKeyEmpty)\n return CALLKEY.Trim();\n else\n {\n if (AS_CALL_KEY.Trim() != CALLKEY.Trim())\n _error = true;\n return AS_CALL_KEY.Trim();\n }\n }\n }\n}\n</code></pre>\n\n<p>As an added benefit, you can now remove the “this never happens” part.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:14:53.437",
"Id": "13792",
"ParentId": "13789",
"Score": "4"
}
},
{
"body": "<p>I would check the error condition separately, then return the value you want using the \"null-coalesce\" operator and some clever extensions:</p>\n\n<pre><code>public string CallKey\n{\n get\n {\n //extension methods below\n var callKey = CALLKEY.NullIfBlank().SafeTrim();\n var asCallKey = AS_CALL_KEY.NullIfBlank().SafeTrim();\n\n //you can make this an if statement if you don't want it resetting _error\n _error = callKey != null && asCallKey != null && callKey != asCallKey;\n\n return asCallKey ?? callKey ?? String.Empty; \n }\n}\n\n...\n\n//the NullIfBlank() extension method; useful to have around\npublic static string NullIfBlank(this string input)\n{\n if (String.IsNullOrWhiteSpace(input)) return null;\n return input;\n}\n\n//and the SafeTrim() method, again useful\npublic static string SafeTrim(this string input)\n{\n return input == null ? input : input.Trim();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:09:06.257",
"Id": "22268",
"Score": "0",
"body": "This is very neat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T23:26:31.653",
"Id": "22292",
"Score": "0",
"body": "Since you are using `NullIfBlank` and `SafeTrim` together, it might make sense to have the `NullIfBlank` procedure take a `bool trim` flag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T17:25:40.540",
"Id": "22325",
"Score": "0",
"body": "That could work if this is the only usage, but conceptually those are two different operations which might have value separately elsewhere in the system, so I separated them."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:03:44.093",
"Id": "13797",
"ParentId": "13789",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13792",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:44:06.237",
"Id": "13789",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Simplify value selection"
}
|
13789
|
<p>I'm brand new to both Ruby and Rails, and while all the following works, it seems a bit messy. </p>
<p>This is on a classified model to generate WHERE/AND WHERE clauses based on whether or not the user supplies a value through a dropdown. I'm not sure if there's a more Active Recordy way of doing this:</p>
<pre><code>class Classified < ActiveRecord::Base
attr_accessible :car_id, :owner_id, :owner, :price, :condition, :description, :mileage
belongs_to :car
belongs_to :owner, :polymorphic => true
has_one :model, :through => :car
has_one :make, :through => :model
has_many :pictures
scope :filter_active_cars, lambda { |options|
filter = {}
filter[:cars] = {:year => options[:year]} unless options[:year].empty?
filter[:makes] = {:id => options[:make]} unless options[:make].empty?
filter[:models] = {:id => options[:model]} unless options[:model].empty?
joins(:car, :model, :make)
.where(filter)
.includes(:car, :model, :make)
}
</code></pre>
<p>The view has this</p>
<pre><code>=select_tag('car[year]', options_for_select(years, :selected => @selected_year))
=collection_select(:car, :make, Make.all, :id, :name, {:include_blank => '- Make -', :selected => @selected_make})
=collection_select(:car, :model, @selected_make ? Model.where(:make_id => @selected_make) : Model.all, :id, :name, {:include_blank => '- Model -', :selected => @selected_model})
</code></pre>
<p>This is the way I'm passing the "select state" on the classified view. The controller has this snippet in the index action. This is so when a user filters a result and submits the form, the corresponding select box has the same value for the form helpers above.</p>
<pre><code>if params[:car]
params[:car].each do |option, value|
next if value.empty?
eval("@selected_#{option} = #{value}")
end
end
</code></pre>
<p>On the form partial to generate and edit a classified. Obviously the chaining of &&s sucks, but it's the only way to get the default selection on new, edit, and when a user submits a new form that contains errors.</p>
<pre><code>=select_tag('car[year]', options_for_select(years, :selected => @classified.car.nil? ? nil : @classified.car.year), :prompt => "- Year -")
=collection_select(:make, :id, Make.all, :id, :name, {:prompt => '- Make -', :selected => (@classified.car && @classified.car.make && @classified.car.make.try(:id))})
=collection_select(:car, :model_id, Model.all, :id, :name, {:include_blank => '- Model -', :selected => (@classified.car && @classified.car.model && @classified.car.model.try(:id))})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:54:26.317",
"Id": "23366",
"Score": "0",
"body": "I think you'd better split your question into several"
}
] |
[
{
"body": "<p>Maybe you can convert this:</p>\n\n<pre><code>scope :filter_active_cars, lambda { |options| \n filter = {}\n filter[:cars] = {:year => options[:year]} unless options[:year].empty?\n filter[:makes] = {:id => options[:make]} unless options[:make].empty?\n filter[:models] = {:id => options[:model]} unless options[:model].empty?\n\n joins(:car, :model, :make) \n .where(filter)\n .includes(:car, :model, :make)\n }\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>scope :filter_active_cars, lambda do |options| \n with_option(:car, 'cars.year', :year).\n with_option(:make, 'makes.id', :make).\n with_option(:model, 'models.id', :model)\nend\n\nscope :with_option, lambda do |assoc, column, option|\n (options[option].present? ?\n joins(assoc).where(column => options[option]) :\n self).\n includes(assoc)\nend\n</code></pre>\n\n<p>You can reuse the <code>with_option</code> scope in other models</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T17:46:40.673",
"Id": "35285",
"Score": "0",
"body": "I would further just stop using scopes, and instead use methods. Scopes are pretty much a weird way to define a singleton method on a ActiveRecord-behaving class that MUST return an ActiveRecord::Relation & has infinite Arity. Better to have a real method with real Arity that can return anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T07:11:49.680",
"Id": "41794",
"Score": "0",
"body": "the fact that a scope MUST return a relation is the reason we use scopes. I'm not a big fan of those, but at least when you use one you know what to expect from it. As to @Alexey's solution, +1 - that's probably what i'll come up with ; one could go further and abstract this behavior with metaprogramming. This would make a nice macro like `filter :active_cars, options: {cars: {year: :year}, makes: {make: :id}, models: {model: :id}}`. The macro would reflect on associations, build necessary scopes and map params keys to columns."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:46:25.310",
"Id": "14423",
"ParentId": "13790",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T14:52:29.100",
"Id": "13790",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Ruby Rails - Snippets from a project that don't seem so eloquent"
}
|
13790
|
<p>This is just playing around and practicing javascript. I am learning JavaScript from Codecademy and I practice coding everyday so I can learn much as possible. I have a lot of <code>if</code> statements, prompt boxes, some alert boxes. I just got finished learning about functions and returns. I just don't know how to use the return in a browser for like <code>document.write</code> or even an alert box.</p>
<pre><code>function prompter() {
var toc = prompt("What do you prefer? Tea or Coffee");
if ((toc == "tea") || (toc == "Tea")) {
} else if ((toc == "coffee") || (toc == "Coffee")) {
}
var foc = prompt("What do you prefer? Facebook or MySpace");
if ((foc == "facebook") || (foc == "Facebook")) {
} else if ((foc == "myspace") || (foc == "Myspace")) {
}
document.write("<center><h2>So you like " + toc + " and " + foc + " that is awesome.</h2></center>");
}
function pickAColour() {
var fun = prompt("What is your favorite colour? , mine is red.");
document.write("<center><h2>You like the colour " + fun + " that is a nice colour</h2></center>");
}
function pickANumber() {
alert("Lets do some math, do you like Math?");
var pan = prompt("Please pick a number");
var nap = prompt("Please pick another number");
var symbol = prompt("Please pick one of the following symbols + - * /");
pan = parseInt(pan); //The parseInt() function parses a string and returns an integer.
nap = parseInt(nap); //The parseInt() function parses a string and returns an integer.
if (symbol == "+") {
alert("You picked the Add symbol");
alert("Lets add both these numbers together. " + pan + " " + symbol + " " + nap);
document.write("<center>Your number is " + (pan + nap) + "</center>");
}
if (symbol == "-") {
alert("You picked the Minus symbol");
alert("Lets Minus both of these numbers. " + pan + " " + symbol + " " + nap);
document.write("<center>Your number is " + (pan - nap) + "</center>");
}
if (symbol == "*") {
alert("You picked the Multiply symbol");
alert("Lets Multiply both these numbers. " + pan + " " + symbol + " " + nap);
document.write("<center>Your number is " + (pan * nap) + "</center>");
}
if (symbol == "/") {
alert("You picked the Divide symbol");
alert("Lets Divide both these numbers. " + pan + " " + symbol + " " + nap);
document.write("<center>Your number is " + (pan / nap) + "</center>");
}
}
function run() {
var name = prompt("What is your name?");
document.write("<h1><center>Welcome to this special JavaScript page " + name + "</center></h1>");
prompter();
pickAColour();
pickANumber();
document.write("<center>Thank You for visting this page</center>");
}
run();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T22:40:17.010",
"Id": "22289",
"Score": "3",
"body": "Any learning resource that teaches you to use document.write should be shunned and avoided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T22:30:07.747",
"Id": "22305",
"Score": "1",
"body": "... good going! I'd suggest making friends with [JSHint](http://www.jshint.com/) if you have not already. It picks up a lot of piddly stuff that if you learn to avoid early on, will help develop clarity and adherence to best practices. When practicable that is ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T11:23:44.493",
"Id": "23120",
"Score": "0",
"body": "You should definitely try http://www.codeschool.com/courses/jquery-air-first-flight for learning about much better ways of manipulating your web pages. It's like Code Academy on steroids."
}
] |
[
{
"body": "<p>Take a look at this - I modified and left a couple of comments. You're on the right path :) </p>\n\n<pre><code>function stristr (haystack, needle) {\n var pos = 0\n haystack += ''\n\n pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase())\n if (pos >= 0) return haystack.substr(0, pos)\n}\n\nfunction prompter() {\n var toc, foc /* Define your variables up here, not in body */\n\n /* No need for empty if/else statements - if you need them in the future, \n * use (stristr(toc) == \"tea\") for example. */\n toc = prompt(\"What do you prefer? Tea or Coffee\")\n foc = prompt(\"What do you prefer? Facebook or MySpace\")\n\n /* Let's add some really basic error checking */\n toc != \"\" ? toc = \"like \" + toc : toc = \"don't like tea or coffee \"\n foc != \"\" ? foc = \" you like \" + foc : foc = \" you don't like Facebook or MySpace\"\n\n /* <center> is deprecated :) */\n document.write(\"<h2 style='text-align:center'>So you \" + toc + \" and \" + foc + \". That is awesome.</h2>\")\n}\n\nfunction pickAColour() {\n /* 'fun' is not an appropriate descriptive variable name, lets change it to 'color' */\n var color = prompt(\"My favorite color is red. What is your favorite colour?\")\n\n /* <center> is deprecated :) */\n document.write(\"<h2 style='text-align:center'>You like the colour \" + color + \" that is a nice colour</h2>\")\n}\n\nfunction pickANumber() {\n var firstNumber, secondNumber, symbol, problem, answer\n\n /* Don't ask 'Do you like math?\" as the user will then expect an input to answer that question */\n alert(\"Lets do some math.\")\n pan = prompt(\"Please pick a number\")\n nap = prompt(\"Please pick a second number\")\n symbol = prompt(\"Please pick one of the following symbols + - * /\")\n\n /* Get rid of the parseInt calls and re-store and just set a problem string for later usage */\n problem = parseInt(pan) + \" \" + symbol + \" \" + parseInt(nap)\n\n /* Let's get an answer while we're at it */\n answer = eval(problem)\n\n /* Let's make life easier and get the symbol name via a switch statement */\n switch(symbol){\n case \"+\" : symbolWord = \"addition\"\n break\n case \"-\" : symbolWord = \"subtraction\"\n break\n case \"*\" : symbolWord = \"multiplication\"\n break\n case \"/\" : symbolWord = \"division\"\n break\n }\n\n alert (\"You picked the \" + symbolWord + \" symbol\")\n alert (\"The math problem you chose was: \" + problem)\n alert (\"The answer to the problem you chose is \" + answer)\n}\n\nfunction run() {\n var name = prompt(\"What is your name?\")\n document.write(\"<h1><center>Welcome to this special JavaScript page \" + name + \"</center></h1>\")\n prompter()\n pickAColour()\n pickANumber()\n document.write(\"<center>Thank You for visting this page</center>\")\n}\n\nrun()\n</code></pre>\n\n<p>.</p>\n\n<pre><code> ==--==--==--== EDIT EDIT EDIT ==--==--==--==\n</code></pre>\n\n<p>To answer a comment below - true - semicolons should be used as they are in many other languages. I guess I've been spending too much time with python lately :) </p>\n\n<p>As Danny said - it is indeed a Ternary Operator (<a href=\"http://en.wikipedia.org/wiki/Ternary_operation\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Ternary_operation</a>) and its basically a short hand if/else statement. Like this:</p>\n\n<pre><code>trueOrFalseStatementHere ? ifTrueDoThis : ifFalseDoThis \n</code></pre>\n\n<p>example:</p>\n\n<pre><code>(1 + 1 == 2) ? print \"1 plus 1 is 2\" : print \"1 plus 1 is not 2\" \n</code></pre>\n\n<p>For your question on the stristr function - its basically a replica of the PHP stristr function. </p>\n\n<pre><code>function stristr (haystack, needle) {\n var pos = 0\n haystack += ''\n\n pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase())\n if (pos >= 0) return haystack.substr(0, pos)\n}\n</code></pre>\n\n<p>It does indeed turn everything to lower case - that way you don't have to check the user input for every single case...for example, with your old method, if the user entered \"coFFee\", it would not pick it up since you were only checking for \"Coffee\" and \"coffee\"...but with this stristr function, the user input \"coFFee\" would become \"coffee\" and you only have to check for 1 case: \"coffee\". See the PHP manual's definition of <code>stristr</code> for a more accurate explanation <a href=\"http://php.net/manual/en/function.stristr.php\" rel=\"nofollow\">http://php.net/manual/en/function.stristr.php</a>. </p>\n\n<p>With your method, you would have to check for 9 variations of \"tea\" </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:28:01.103",
"Id": "22279",
"Score": "4",
"body": "I personally find better to use semicolons always as it has a big impression on many languages like Java or C# etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:47:29.703",
"Id": "22280",
"Score": "0",
"body": "Thanks, this was very helpful. I am searching a few things you have added, trying to understand some of them. The first one would be the stristr function, does it take the answers from the prompt and lowercase all the letters?. Next thing I don't understand is the basic error checking, toc !=\"\" ? toc = \"\" part. I know ! means is not, but I havn't seen $ yet. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T06:23:09.530",
"Id": "22301",
"Score": "1",
"body": "That's called the [Terenary Operator](http://en.wikipedia.org/wiki/Ternary_operation) and is common for short conditional statements. That section could be expanded to this:\n\n`if (toc != \"\") { toc = \"like \" + toc } else { toc = \"don't like tea or coffee \" }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T07:55:42.047",
"Id": "22303",
"Score": "3",
"body": "@YasinOkumus Even in JavaScript, if you don't use semicolons, some statements won't get parsed the way you expected. I think you should always use semicolons because of that (one less pitfall to worry about)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T09:57:13.627",
"Id": "22310",
"Score": "1",
"body": "@svick Thank you very much. I'll keep it in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:23:14.543",
"Id": "22330",
"Score": "0",
"body": "See edited answer for more details and answers to comments here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T20:18:51.013",
"Id": "22335",
"Score": "1",
"body": "Generally, it's good practice to avoid using the ternary operator unless assigning a value. There's a lot of debate about this, but [see this StackOverflow thread](http://stackoverflow.com/questions/6248920/expressions-in-javascript-ternary-operator-and-jslint) for some interesting arguments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:00:24.897",
"Id": "22338",
"Score": "0",
"body": "@ChrisFrancis I'd generally agree with you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:44:39.203",
"Id": "22341",
"Score": "0",
"body": "All this information is great, will be looking over this over and over. Thanks everyone. I also seemed to learn that <pre> var e = document.getElementById('color');\n e.innerHTML = \"You like the colour \" + fun + \" that is a nice colour\";<code> Doesn't seem to work in IE 9, but it is still great to know, and everyone says alert boxs is best to test with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:52:04.117",
"Id": "22343",
"Score": "0",
"body": "sorry, I don't know how to put code into code tags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:17:02.143",
"Id": "22395",
"Score": "0",
"body": "Yep, some browsers don't support certain features or ways that features are scripted. \n\nBy the way - to put code in code tags in comments, use the backtick ` followed by four spaces, then your code, then another backtick."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T08:53:32.643",
"Id": "23041",
"Score": "0",
"body": "@SamSatanas , `code` : use a back-tick (`) to open the code and another to close it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T15:24:08.090",
"Id": "23058",
"Score": "0",
"body": "Yea, I just found out that you can't use `document.getElementById` in a loop ether. I wanted it to print out 1-10 just like `document.write`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T18:23:08.643",
"Id": "23067",
"Score": "0",
"body": "@SamSatanas - I don't see why document.getElementById shouldn't work in a loop..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T20:07:22.200",
"Id": "23094",
"Score": "0",
"body": "@jsanc623 I been searching all morning on google, I found some where that document.getElementById only prints once. In which it did, it printed number 10 on screen in stead of number 1, number 2 etc. Like a for loop."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T18:35:13.420",
"Id": "13804",
"ParentId": "13791",
"Score": "0"
}
},
{
"body": "<p>You seem to be on the right track, at least with grasping how to do some basic coding. </p>\n\n<p>Right now, I only see one major issue: <code>document.write()</code></p>\n\n<p><code>document.write()</code> is used to build pages out of javascript, something that is both impractical and ill-advised (in almost every situation). Moving forward, you should start building your pages in HTML and use javascript to tweak the page from that point.</p>\n\n<p>To do this, you will want to replace <code>document.write()</code> with <code>document.getElementById()</code>. Lets look at an example:</p>\n\n<p>You have the following HTML block:</p>\n\n<pre><code><h1 id='welcome'></h1>\n</code></pre>\n\n<p>Now, to insert text into this block, we would do something like this:</p>\n\n<pre><code>var welcomeElement = document.getElementById('welcome');\nwelcomeElement.innerHTML = \"This is my welcome message!\";\n</code></pre>\n\n<p>There's many things you can do with elements once you have gotten them, but I'll leave that for a later experiment. </p>\n\n<hr>\n\n<p>At this point, I'll leave you to learn how to update your code. If you get confused or stuck however, you can view my rendition of your code here: </p>\n\n<p><a href=\"http://jsfiddle.net/danthegoodman/v7gLE/\">http://jsfiddle.net/danthegoodman/v7gLE/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T07:02:26.173",
"Id": "13824",
"ParentId": "13791",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>variables names that are three letter abbreviations aren't helpful when you come back. Don't be concerned about the number of characters (within reason) for your names. </p>\n\n<p><code>teaOrCoffeeAnswer</code> is easier to read or even <code>drinkAnswer</code></p></li>\n<li><p>I'm surprised no-one has pointed this out but <code>\"somestring\".toLowerCase()</code> can help you heaps. (or <code>.toUpperCase()</code>) Its a good thing to try and find some built in functions if it seems like something that would be common.</p>\n\n<pre><code>turns \n\nif ((toc == \"tea\") || (toc == \"Tea\")) {\n\n} else if ((toc == \"coffee\") || (toc == \"Coffee\")) {\n\n}\n</code></pre>\n\n<p>into </p>\n\n<pre><code>if (toc == \"tea\"){\n\n} else if (toc == \"coffee\") {\n\n}\n</code></pre>\n\n<p>I'd suggest something like:</p>\n\n<pre><code>var drinkAnswer = prompt(\"What do you prefer? Tea or Coffee\");\ndrinkAnswer = (drinkAnswer || \"\").toLowerCase();\nif (drinkAnswer == \"tea\") {\n\n} else if (drinkAnswer == \"coffee\") {\n\n}\n</code></pre>\n\n<p><em>(the</em> <code>drinkAnswer || \"\"</code> <em>means that you won't get a null reference exception.)</em></p></li>\n<li><p><code>parseInt()</code> has a \"hidden\" feature. it turns any string beginning with \"0\" into an octal number (base 8). Assume your user always enters a decimal number and instead force the method to parse in decimal (base 10)</p>\n\n<pre><code>parseInt(numberAsString, 10); \n</code></pre>\n\n<p>this will save a lot of headaches later.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:00:29.747",
"Id": "23042",
"Score": "0",
"body": "On 3, I would in the end suggest [using + to coerce an integer value](http://stackoverflow.com/a/2243631/148412) instead of sending the base-10 into parseInt: `var number = +inputFromUser;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:28:14.727",
"Id": "23047",
"Score": "1",
"body": "@ANeves I personally don't find that very intuitive for a JavaScript learner to put in their \"toolkit\". It doesn't always act the way you expect. (e.g. `+\" \"`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T09:30:21.740",
"Id": "23048",
"Score": "0",
"body": "Oh. Scratch that, then, and back to `parseInt(foo, 10)`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T02:41:48.277",
"Id": "14240",
"ParentId": "13791",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:00:38.680",
"Id": "13791",
"Score": "3",
"Tags": [
"javascript",
"beginner"
],
"Title": "Personal questionnaire using JavaScript prompts"
}
|
13791
|
<p>Given the following HTML form (fragment):</p>
<pre><code><fieldset id="timesheet-rows">
<legend>Add Entries</legend>
<div id="timesheetrow-0" class="timesheet-row">
<label for="project-0">Project</label>
<select id="project-0" name="project-0" required>
<option value="" />
</select>
<label for="department-0">Department</label>
<select id="department-0" name="department-0" required>
<option value="" />
</select>
<label for="task-0">Task: </label>
<select id="task-0" name="task-0" required>
<option value="" />
</select>
<label for="hours-0">Hours: </label>
<input type="number" step="0.25" id="hours-0" name="hours-0" width="1" placeholder="2.0" required />
<label for="comment-0">Comment: </label>
<input type="text" id="comment-0" name="comment-0" width="50" />
</div>
<input type="button" id="add-row" name="add-row" value="Add row" />
</fieldset>
</code></pre>
<p>I have implemented the following jQuery (fragment) to clone each 'timesheet row' <code><div /></code> along with the <code><label /></code> tags, which are not caught by <code>$(':input')</code>:</p>
<pre><code>$(document).ready(function() {
var current_id = 0;
$('#add-row').click(function(){
next_element($('#timesheetrow-0'));
})
function next_element(element){
var new_element = element.clone(),
id = current_id + 1;
current_id = id;
new_element.attr("id",element.attr("id").split("-")[0]+"-"+id);
// Ajuster les `id` et `name` dans les <input />s et <select />s
$(':input', new_element).each(function(){
var field_id = $(this).attr("id"),
field_name = $(this).attr("name");
$(this).attr("id", field_id.split("-")[0]+"-"+id );
$(this).attr("name", field_name.split("-")[0]+"-"+id );
});
// Ajuster le for="" dans les <label />s
$('label', new_element).each(function(){
field_for = $(this).attr("for");
$(this).attr("for", field_for.split("-")[0]+"-"+id );
});
new_element.appendTo($("#timesheet-rows"));
};
});
</code></pre>
<p>(Above jQuery was inspired by <a href="http://jsfiddle.net/32RgL/" rel="nofollow">http://jsfiddle.net/32RgL/</a> ).</p>
<p><strong>Is there a more elegant or complete way of doing this?</strong></p>
|
[] |
[
{
"body": "<p>Most of this code is due to the fact that you're increasing the numbers in your attributes. I think that's a mistake. Your rows should all have identical <code>name</code> attributes, stored in an array (e.g. <code>name=\"task[]\"</code>).</p>\n\n<p>The only problem would then be the identical IDs. Frankly, you shouldn't be using IDs in the first place. The only advantage of using IDs in this case is to associate the <code>label</code>s to the form fields (so that clicking the <code>label</code> focuses on the form field). <a href=\"http://jsfiddle.net/QqeyH/\" rel=\"nofollow\">This could easily be accomplished by wrapping the label around the form element</a>.</p>\n\n<p>So, to summarize, here are some points to consider:</p>\n\n<ol>\n<li>Get rid of the IDs</li>\n<li>Wrap the labels around the form elements to associate them with one another</li>\n<li>Get rid of the numbers from the <code>name</code>s</li>\n<li>Use array like notation (e.g. <code>name=\"task[]\"</code>) for your <code>name</code>s</li>\n</ol>\n\n<hr>\n\n<p>Once you've incorporated all this, you can simply clone the row when needed.</p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code><fieldset id=\"timesheet-rows\">\n <legend>Add Entries</legend>\n\n <div class=\"timesheet-row\">\n\n <label>Project:\n <select name=\"project[]\" required>\n <option value=\"\"></option>\n </select>\n </label>\n\n <label>Department:\n <select name=\"department[]\" required>\n <option value=\"\"></option>\n </select>\n </label>\n\n <label>Task: \n <select name=\"task[]\" required>\n <option value=\"\"></option>\n </select>\n </label>\n\n <label>Hours:\n <input type=\"number\" step=\"0.25\" name=\"hours[]\" width=\"1\" placeholder=\"2.0\" required />\n </label>\n\n <label>Comment:\n <input type=\"text\" name=\"comment[]\" width=\"50\" />\n </label>\n\n </div>\n\n <input type=\"button\" id=\"add-row\" name=\"add-row\" value=\"Add row\" />\n</fieldset>\n</code></pre>\n\n<p><strong>Javascript:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery(function($) {\n var $button = $('#add-row'),\n $row = $('.timesheet-row').clone();\n\n $button.click(function() {\n $row.clone().insertBefore( $button );\n });\n});\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/wd5y9/\" rel=\"nofollow\">http://jsfiddle.net/wd5y9/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T18:01:15.587",
"Id": "22273",
"Score": "0",
"body": "Thanks for your response, Joseph. Having worked in a11y design, I would note that implicit label tags are generally discouraged for WCAG 2.0 compliance as not all assistive technologies handle them correctly: *\"The HTML and XHTML specifications allow both implicit and explicit labels. However, some assistive technologies do not correctly handle implicit labels (for example, <label>First name <input type=\"text\" name=\"firstname\"></label>).\"* source: http://www.w3.org/TR/WCAG-TECHS/H44 I had forgotten the `name=\"array[]\"` method though! Thanks for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T18:04:03.087",
"Id": "22274",
"Score": "0",
"body": "Just saw your added jQuery; love it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T18:08:19.300",
"Id": "22275",
"Score": "0",
"body": "@msanford - The info you're quoting from the W3C website is pretty outdated. I doubt that's still true today..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T14:37:35.910",
"Id": "22609",
"Score": "0",
"body": "Joseph, it applies to a *version* of JAWS which while indeed quite outdated is still in use by a lot of people (see IE6). Still, for my internal application, it's not going to be a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:34:22.677",
"Id": "22888",
"Score": "0",
"body": "Follow-up: I implemented the changes you recommended and like them a lot. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T19:17:52.113",
"Id": "22902",
"Score": "0",
"body": "@msanford - Great! Happy I could help you out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:46:35.297",
"Id": "32448",
"Score": "1",
"body": "Note: a part of this answer is discussed at http://stackoverflow.com/q/14189108/1591669"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T17:50:15.423",
"Id": "13803",
"ParentId": "13794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T15:23:21.273",
"Id": "13794",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"html5",
"form"
],
"Title": "Dynamically adding rows to an accessible HTML form"
}
|
13794
|
<p>I have a function that implements parts of reading iCal repetition rules, and returns a list of dates when a certain event takes place.</p>
<p>Questions/Concerns of mine</p>
<ol>
<li>Any comments on the use of anonymous functions? I added them to keep the code as <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a> as possible.</li>
<li>One thing I rather dislike is the line <code>return strtotime('+' . $increment . ' ' . $rrule_freq_map[$rrule['FREQ']], $start_timestamp);</code> which casts from integer to string and back for no good reason. Couldn't think of a better way to accomplish the adding of time.</li>
<li>On a <a href="http://drupal.org" rel="nofollow">Drupal</a> specific note, maybe the use of <a href="http://se2.php.net/manual/en/function.date.php" rel="nofollow">date</a> in <code>$single_day_output()</code> should be replaced with <a href="http://api.drupal.org/api/drupal/includes!common.inc/function/format_date" rel="nofollow">format_date</a>, but I'm not sure if there are any gains from that.</li>
<li><code>$next_timestamp()</code> will break if used in more than one location. Currently not an issue, would be interesting to hear suggestions on that.</li>
</ol>
<p></p>
<pre><code>/**
* Render the date and times of events.
*
* Has some internal helper functions do not make sense outside of this scope.
*/
function _bornholm_custom_calendar_event_dates($datetime) {
// Ensure we have the date_repeat_split_rrule().
module_load_include('inc', 'date_api', 'date_api_ical');
$start_timestamp = strtotime($datetime['value']);
$start_day = date('Y-m-d', strtotime($datetime['value']));
$end_day = (isset($datetime['value2'])) ? date('Y-m-d', strtotime($datetime['value2'])) : NULL;
$end_timestamp = (isset($datetime['value2'])) ? strtotime($datetime['value2']) : NULL;
$output = '';
// Build the output for a single days event information.
$single_day_output = function($timestamp) {
$output = t('@day d. @date t. @time', array(
'@day' => t(date('D', $timestamp)),
'@date' => date('d.m.Y', $timestamp),
'@time' => date('H:i', $timestamp),
));
return ucfirst($output);
};
// Check whether or not the current has a repeat rule.
$repeats = function ($datetime) {
if ($datetime['rrule'] !== NULL) {
list($rrule, $exceptions, $additions) = date_repeat_split_rrule($datetime['rrule']);
if ($rrule['FREQ'] !== 'NONE') {
return $rrule;
}
}
return NULL;
};
// When an event repeats, step forward the timestamp once.
$next_timestamp = function($rrule, $start_timestamp) {
static $count = 0;
$rrule_freq_map = array(
'DAILY' => 'day',
'WEEKLY' => 'week',
'MONTHLY' => 'month',
);
$increment = $count++ * $rrule['INTERVAL'];
return strtotime('+' . $increment . ' ' . $rrule_freq_map[$rrule['FREQ']], $start_timestamp);
};
if ($rrule = $repeats($datetime)) {
for ($i = 0; $i < $rrule['COUNT'] && $i < 100; $i++) {
$new_timestamp = $next_timestamp($rrule, $start_timestamp);
if ($end_day === NULL || $start_day === $end_day) {
$output .= $single_day_output($new_timestamp);
if ($end_timestamp) {
$output .= ' - ' . date('H:i', $new_timestamp + ($end_timestamp - $start_timestamp));
}
}
else {
$output .= $single_day_output($new_timestamp) . ' ' . t('until') . '<br/>' . $single_day_output($new_timestamp + ($end_timestamp - $start_timestamp)) . '<br/>';
}
}
}
else {
if ($end_day === NULL || $start_day === $end_day) {
$output = $single_day_output($start_timestamp);
if ($end_timestamp) {
$output .= ' - ' . date('H:i', $end_timestamp);
}
}
else {
$output = $single_day_output($start_timestamp) . ' ' . t('until') . '<br/>' . $single_day_output($end_timestamp);
}
}
return $output;
}
</code></pre>
|
[] |
[
{
"body": "<p>Something to keep in mind about anonymous functions (also known as lambda functions), is that they should only be used for tasks that are only going to be performed once. These functions are not compiled at runtime and so must be explicitly compiled each time they are run. Another thing to keep in mind, just because you can do something, doesn't mean you should. Sure this works, but its confusing and hard to read. Why use lambda functions at all? It looks like what you actually want is a class.</p>\n\n<p>Judging by some of this code I'd hazard to say that you are coming from Java? I say this mostly because of the way you are throwing around lambda functions in a single \"main\" function. Reminds me of a lot of Java code I've seen. That and your calling an array a map. Just know that PHP is NOT Java. You don't need just one function/class, to house all your other functions. Just pretend they are in a class by default and you'll do fine. Or implement them to a PHP class, they are more or less the same. If you are not from Java, then you might want to look at class tutorials, but first forget you ever heard of lambda functions. You'll probably never need them.</p>\n\n<p>Another thing, that main function, <code>_bornhom_custom_calendar_event_dates()</code>, is entirely too long for a function. Functions should do one thing, and do it well. Classes should also do just one thing, but on a larger scale by using many functions to do smaller things. For example: A class could get a valid date set and have many functions (or methods in a class context) that cared for getting single dates, checking if they were valid, and compiling them together. Abstracting these lambda functions will help immensely with this and the DRY principle.</p>\n\n<p>For quoting DRY principle, I immediately spot code that violates it.</p>\n\n<pre><code>$start_timestamp = strtotime($datetime['value']);\n$start_day = date('Y-m-d', $start_timestamp);\n</code></pre>\n\n<p>Instead of checking if <code>$datetime['value2']</code> is set repeatedly, do it once to save processing time. And change that name. \"value2\" is entirely too vague. What differentiates it from value? What even is \"value\"? Try to be short, but descriptive. Describing what these \"values\" are supposed to contain will get you started.</p>\n\n<pre><code>$end_day = NULL;\n$end_timestamp = NULL;\n\n$value2 = isset( $datetime[ 'value2' ] ) ? strtotime( $datetime[ 'value2' ] ) : FALSE;\nif( $value2 ) {\n $end_day = date( 'Y-m-d', $value2 );\n $end_timestamp = $value2;\n}\n</code></pre>\n\n<p>Of course, if you could change your code so that <code>$end_timestamp</code> could have a default value of FALSE instead of NULL, you could just set <code>$end_timestamp</code> above and then check to see if <code>$end_day</code> needed to be set and completely bypass the need of a <code>$value2</code> variable.</p>\n\n<p>What is function <code>t()</code> as seen in your <code>$single_day_output</code> lambda function? Where does it come from? Just like above, please choose better names.</p>\n\n<p>What is \"rrule\" and why does it have a child named \"rrule\"? Maybe the first should be called a \"rule set\"? I don't know, but the names should be unique.</p>\n\n<p>Break up your long lines. There's no reason to have them so long.</p>\n\n<pre><code>$single_newday = $single_day_output($new_timestamp);\n$time = $single_day_output($new_timestamp + ($end_timestamp - $start_timestamp))\n$output .= $single_newday . ' ' . t('until') . '<br/>' . $time . '<br/>';\n</code></pre>\n\n<p>Right now I can't follow your code well enough to help you with any of your specific questions, but if you clean it up a bit I'll take another look. Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T15:50:19.607",
"Id": "13841",
"ParentId": "13799",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T16:16:09.960",
"Id": "13799",
"Score": "0",
"Tags": [
"php",
"datetime",
"drupal"
],
"Title": "Basic function to output repeating dates from iCal format"
}
|
13799
|
<p><strong>Base Info</strong></p>
<ul>
<li>Two tables: tData, tData2 </li>
<li>Exactly the same columns </li>
<li>About 200,000 records</li>
<li>SQL Server 2008 R2</li>
</ul>
<p><strong>Logic</strong></p>
<p>At first sight we need to insert tData rows into tData2. What else?</p>
<p>We need a renamed version of a column inside another (tData2)
with the condition checking it won't be an existing item when it's renamed.
Here's the code:</p>
<pre><code>INSERT INTO [tData2]
(
[Key],
Info1,
Info2
)
SELECT
REPLACE([Key],'_',' '),
Info1,
Info2
FROM
[tData]
WHERE
(REPLACE([Key],'_',' ') = [Key]) OR
(REPLACE([Key],'_',' ') NOT IN (SELECT [Key] FROM [tData]))
</code></pre>
<p>The problem is it's really slow for me on a top-notch 64 bit system. It has taken more than an hour so far and it's still executing.</p>
<p>How to speed it up? Any alternatives? Any ideas?</p>
|
[] |
[
{
"body": "<p>I'm not a DBA/DBMS guru, so just some ideas:</p>\n\n<ul>\n<li>Turn off indexes on <code>tData2</code> during the migration.</li>\n<li>Do it in smaller chunks for smaller transaction log. (<a href=\"https://stackoverflow.com/q/1602244/843804\">Batch commit on large INSERT operation in native SQL?</a>, <a href=\"https://stackoverflow.com/q/603724/843804\">How to implement LIMIT with Microsoft SQL Server?</a>)</li>\n<li>Make sure that <code>[tData].[Key]</code> has an index.</li>\n<li>I'd consider replacing the subselect with a join if it's possible at all.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T05:07:00.783",
"Id": "22300",
"Score": "0",
"body": "Anyway this is a valuable comment, I liked it, Could you please give an example on the last part you mentioned ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T09:37:35.117",
"Id": "22307",
"Score": "1",
"body": "@Sypress: I'm sorry, I've tried to rewrite the query but I gave it up after a few tries. I haven't used so complex SQL queries recently. Please let me know how went the migration and what worked or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T09:47:31.353",
"Id": "22308",
"Score": "1",
"body": "no problem friend, thanks again, your suggestions could be useful to me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:59:55.847",
"Id": "13808",
"ParentId": "13805",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T19:02:12.610",
"Id": "13805",
"Score": "1",
"Tags": [
"optimization",
"performance",
"sql",
"sql-server"
],
"Title": "SQL iteration-Insertion plus renaming"
}
|
13805
|
<p>I prompt the user for 9 numbers, store those numbers in 9 pointers and display the element 2. It seem to work just fine, but am I forgetting something? Can I improve it but keep it simple? I'm just a beginner testing what I have learned so far.</p>
<pre><code>int n;
int *array[9];
bool isUsed[10] = {0};
for(int i = 0; i < 9; i++)
{
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
{
if (isUsed[n] == false)
{
array[i] = new int;
*array[i] = n;
isUsed[n] = true;
}
else
{
cout << "Number has already been used." << endl;
i--;
}
}
else
{
cout << "Numbers from 0-9 only." << endl;
i--;
}
}
cout << *array[2]<<endl;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:50:54.880",
"Id": "22281",
"Score": "1",
"body": "use an array of int rather than array of int* would be a good start"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:51:03.097",
"Id": "22282",
"Score": "1",
"body": "Why use pointers??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:51:43.910",
"Id": "22283",
"Score": "0",
"body": "@JesseGood: Because he's a beginner and he should learn how this stuff works before jumping ship to the STL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:51:46.927",
"Id": "22284",
"Score": "0",
"body": "You have a memory leak if you forget to `delete` (or `delete[]`). There are better things to use such `std::array`, `int[]`, `std::vector`, NOT arrays of pointers for something this simple..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:52:04.037",
"Id": "22285",
"Score": "0",
"body": "To free the memory with `delete`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:53:16.610",
"Id": "22286",
"Score": "0",
"body": "Still though OP; do not let anyone sway you from learning all about pointers. Realize though that this is not well written C++ code in the sense that it does not use more modern concepts like RAII (smart pointers, containers, etc.). In \"professional\" level C++ code you will almost never see `new` or `delete`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:23:35.787",
"Id": "22287",
"Score": "0",
"body": "I don't like the `i--` at the end. make it `while(i<9)` and increase i only after You have found a good number. Also, magic numbers are bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T23:12:25.407",
"Id": "22290",
"Score": "3",
"body": "@EdS.: I actually think otherwise: you should learn the high level C++ (i.e. standard libraries, managed memory ... ) before jumping into the gory details. You can write good C++ language without raw pointers (as a matter of fact, good C++ code avoids raw pointers)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T01:02:54.657",
"Id": "22294",
"Score": "0",
"body": "@DavidRodríguez-dribeas: I suppose we'll have to disagree on that. I don't think using tools you don't understand teaches you much aside from syntax (which is the easy part). Of course you're right about good C++ code, but how can you appreciate a `vector` or smart pointer if you have no clue what problem it is solving (and the experience to know why it is so important)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T01:48:06.770",
"Id": "22295",
"Score": "0",
"body": "@EdS.: If you get a chance, take a peek into *Accelerated C++* by Koening and Moo. It starts from a high level point of view, and I believe it is a good method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T01:53:03.737",
"Id": "22296",
"Score": "0",
"body": "@DavidRodríguez-dribeas: I don't mean to come off as an expert on the subject, I just know that it works best for me if I have a firm grounding in the fundamentals. That said, I started with VB and am now a systems engineer who writes C and C++ all day, so it can work either way :D"
}
] |
[
{
"body": "<p>You can definitely improve it, by replacing the array of pointers with a <code>std::vector<int></code>.</p>\n\n<p>If you must track usage, I suggest using a map instead, where the keys are <code>0...9</code> and the values exist only if the respective index was added.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:50:32.840",
"Id": "13807",
"ParentId": "13806",
"Score": "8"
}
},
{
"body": "<p>Firstly: 9 is a magic number, hardcoded in 4 places (if you include the <code>isUsed[10]</code> as <code>9+1</code>).\nIf you decide to go for 11 numbers instead, there's a decent chance you'll forgot to change one of those 4 locations, and it's entirely avoidable.</p>\n\n<p>We'll switch to putting this in a single parameter (or single constant) so there's only one thing to change. Same for the magic number <code>2</code> ...</p>\n\n<pre><code>// permute integers 0..max\n// return the position'th integer in the permuted set\nint permute_and_select(int max, int position)\n{\n}\n</code></pre>\n\n<p>get your current functionality by calling <code>permute_and_select(9,2)</code>.</p>\n\n<hr>\n\n<p>Secondly, let's think about the algorithm a bit.\nYou're asking the user for some permutation of <code>[0..N]</code>, right? So our pseudo-code can be something like</p>\n\n<pre><code>for i in 1..N:\n get number\n if number < 1 or number > N: complain-and-repeat\n if number already used: complain-and-repeat\n record number used\n record number is i'th entry\nreturn 2nd entry\n</code></pre>\n\n<p>notes about this sketch:</p>\n\n<ol>\n<li>I put the sanity checks at the start, because I think it's easier to read the <em>successful</em> path if you already know the preconditions. Otherwise I find myself reading it, and then trying to remember it while I check the <code>else</code> branch to see what happens there. Also, it reduces the depth of nesting which is a largely aesthetic preference.</li>\n<li>the <em>complain-and-repeat</em> stuff is done twice, and I'm not happy with the way it modifies the loop counter. This is fragile in the face of changes to the loop logic, since we now have to update the <code>for</code> <em>and</em> each of the two <code>else</code> branches together. We'll make this more robust.</li>\n<li>using a <code>bool</code> array for the <em>number used</em> logic is fine: we could use a bitset or something, but I don't see it as a problem</li>\n<li>using an array of int pointers for the values is probably over-complicated, here: we know how much storage is required in advance, so we can allocate it all up-front</li>\n</ol>\n\n<hr>\n\n<p>Now, let's see how close the sample code is to the pseudo-code sketch ...</p>\n\n<pre><code>// permute integers 0..max\n// return the position'th integer in the permuted set\nint permute_and_select(int max, int position)\n{\n // track which numbers we've already used\n bool *used = new bool [max+1];\n // OR std::vector<bool> used(max+1, false);\n // OR std::unique_ptr<bool[]> used(new bool [max+1]);\n\n int *permuted = new int [max];\n // OR vector, unique_ptr etc. as above\n\n for (int index = 0; index < max; /*omit increment*/)\n {\n int number; // we can declare variables where they're used\n cout << \"Enter Number \" << index+1 << endl;\n cin >> number;\n\n if (number < 0 || number > max) { // check bounds\n cout << \"Numbers from 0-\" << max << \" only.\\n\";\n continue;\n }\n if (used[number]) { // check repetition\n cout << number \" has already be used.\\n\";\n continue;\n }\n\n // we have a new, valid selection, so:\n // record number used\n used[number] = true;\n // record number is index'th entry\n permuted[index] = number;\n // only on successful input\n ++index;\n }\n\n int selection = permuted[position];\n\n // note that vector or unique_ptr take care of this automatically\n delete [] used;\n delete [] permuted;\n\n return selection;\n}\n</code></pre>\n\n<p>There are a couple of gotcha's and niggles left in here:</p>\n\n<ol>\n<li>the <code>used</code> and <code>permuted</code> arrays are uninitialized. You can fix that with a loop or with memset, but it's another advantage of just using <code>vector</code></li>\n<li>it's not clear from the question whether you want <code>N+1</code> integers (covering <code>[0,N]</code> exactly) or <code>N</code> unique integers drawn from <code>[0,N]</code>. I've gone for the latter case, same as you, I'm just not certain it's what you meant.</li>\n</ol>\n\n<p>The code's already pretty long for a sketch though, so I'm leaving them as an exercise for the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:49:45.840",
"Id": "13812",
"ParentId": "13806",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T20:49:09.977",
"Id": "13806",
"Score": "2",
"Tags": [
"c++",
"beginner",
"homework"
],
"Title": "Displaying a certain element among inputted numbers"
}
|
13806
|
<p>I got some really good responses here last time, which really helped out quite a bit, so I thought I'd try again with a new batch.</p>
<p>Below is the second phase of my first Java project: Intercommunication between panels. This builds upon the old code, though it has been heavily modified since the first version. Many of the suggestions from the previous question have been implemented and a lot of new code and features have been added. In fact most of this is new code and does not concern the previous question. I only mention this in case you helped in the previous question or were curious. You may view the <a href="https://codereview.stackexchange.com/questions/13482/first-project-jframe-class">previous question</a> if you need more context. As before, specific questions and comments are located below the code.</p>
<p><strong>JFileParser.java(main)</strong></p>
<pre><code>package my;
import my.controllers.Logger;
import my.views.Deck;
import my.controllers.DeckNavigator;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.SwingUtilities;
public class JFileParser implements Runnable {
public static void main( String[] args ) {
SwingUtilities.invokeLater( new JFileParser() );
}
@Override
public void run() {
JFrame frame = new JFrame( "Java File Parser" );
Deck deck = new Deck();
DeckNavigator navigator = new DeckNavigator();
navigator.setDeck( deck );
deck.setNavigator( navigator );
deck.initDeck();
frame.getContentPane().add( deck, BorderLayout.NORTH );
frame.getContentPane().add( navigator, BorderLayout.SOUTH );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}
</code></pre>
<p><strong>Deck.java</strong></p>
<pre><code>package my.views;
import my.controllers.DeckNavigator;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.util.List;
import java.util.Arrays;
public class Deck extends JPanel {
private CardLayout layout;
private DeckNavigator navigator;
private static final String
EMPTY_PANEL = "New window",
FILE_CHOOSER = "File chooser",
FILE_PARSER = "File parser"
;
private List< String > deck = Arrays.asList(
EMPTY_PANEL,
FILE_CHOOSER,
FILE_PARSER
);
public Deck() {
setLayout( new CardLayout() );
layout = ( CardLayout ) getLayout();
}
public void setNavigator( DeckNavigator navigator ) {
this.navigator = navigator;
}
public void initDeck() {
add( new JPanel(), EMPTY_PANEL );
add( new ChooseFile(), FILE_CHOOSER );
add( new ParseFile(), FILE_PARSER );
navigator.setView( EMPTY_PANEL );
}
public void nextView( String view ) {
int currentView = deck.indexOf( view );
if( currentView != deck.size() - 1 ) {
setView( currentView + 1 );
}
}
public void previousView( String view ) {
int currentView = deck.indexOf( view );
if( currentView > 0 ) {
setView( currentView - 1 );
}
}
private void setView( int card ) {
String view = deck.get( card );
layout.show( this, view );
navigator.setView( view );
}
}
</code></pre>
<p><strong>DeckNavigator.java</strong></p>
<pre><code>package my.controllers;
import my.views.Deck;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class DeckNavigator extends JPanel {
private Deck deck;
private String view;
public DeckNavigator() {
addPrevious();
addNext();
}
public void setDeck( Deck deck ) {
this.deck = deck;
}
public void setView( String view ) {
this.view = view;
}
private boolean deckIsSet() {
return deck != null;
}
private boolean viewIsSet() {
return view != null;
}
private void addPrevious() {
JButton button = new JButton( "Back" );
button.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
if( deckIsSet() && viewIsSet() ) {
deck.previousView( view );
}
}
} );
add( button );
}
private void addNext() {
JButton button = new JButton( "Next" );
button.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
if( deckIsSet() && viewIsSet() ) {
deck.nextView( view );
}
}
} );
add( button );
}
}
</code></pre>
<p><strong>Notes:</strong></p>
<ul>
<li>My packages aren't that vague, I just abstracted them before posting this.</li>
<li>The logger is a pseudo class. All it does is print to the console for now. Though I'm not using it as much now...</li>
<li>My first panel is blank to simulate the need to click on the appropriate menu item</li>
</ul>
<p><strong>Questions</strong></p>
<ol>
<li>When using the <code>invokeLater()</code> method in my main class, would it be better, or possible to use <code>this</code> instead of getting a new instance of the same class? I just thought of this, so I haven't even tried it or looked it up yet. <strong>Edit:</strong> Just tested this, appears it doesn't work because <code>this</code> is not static, worth a shot.</li>
<li>After many hours on google, and very little sleep, the only way I could think to get my panels to communicate with each other was to do as you've just seen. And I didn't come up with that solution until after I did get some sleep. I say only because I don't think writing to a temp file is a very elegant solution in this instance. Is there a better way to do this? Already I'm seeing issues when I want another class to be able to change the view, and I'd hate to have to pass the deck and navigator to every panel on the off chance they or their children will need it at some point. I know I can streamline it by extending a parent class with those methods, but just curious what y'all have to say.</li>
<li>Is there a better way to navigate and/or store the deck? I initially thought of combining the "titles" and panels into an associative array, or HashMap as I've come to know they're called in Java, that way I could iterate over it to initialize the deck instead of having to explicitly call each panel. But that immediately presented problems when I tried to navigate sequentially through them as I couldn't get their position with <code>indexOf()</code>. I thought of creating an iterator for it, but, I admit, I'm not very familiar with the concept and didn't see a "previous" method available in the interface, which makes me think I would have to create a completely different iterator and deck but backwards if I wanted to step down.</li>
</ol>
<p>Please feel free to elaborate on other points than just those I listed. I'm still trying to learn, so any help is appreciated.</p>
|
[] |
[
{
"body": "<p>I have a few notes:</p>\n\n<ul>\n<li>The reason the this keyword doesn't work in main is because main is a static method. The this keyword refers to the current object, and in static methods, there is no current object. Static methods are associated with the class, not the instance. See <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html\" rel=\"nofollow noreferrer\">Using the this keyword</a>, <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html\" rel=\"nofollow noreferrer\">Understanding instance and class members</a></li>\n<li>Your DeckNavigator is not a controller. It's another view. A controller usually implements a listener and communicates with both the model and the view. A view is usually represented by a JComponent subclass. (Note: JPanel subclasses are JComponent subclasses.) With such a simple program, I would leave out MVC and put everything in the view. For something more complex, you'd need a model to handle the state changes and a real controller. See <a href=\"http://martinfowler.com/eaaDev/uiArchs.html\" rel=\"nofollow noreferrer\">GUI Architectures</a></li>\n<li>You should probably combine your two views into one and make that either the content pane or put it in the center of the content pane. Have two subpanels in that panel to replace the Deck and DeckNavigator. It will aid in communication between the panels because they will be in the same class.</li>\n<li>You shouldn't need to make the names of the subpanels of deck constant and then put them in a list, especially considering you only use them for the card layout. Make the list constant, and get the names exclusively from the list.</li>\n<li><p>I don't think you need a HashMap here. A list is sufficient. I would store the current index in an instance variable, that way you don't need to call indexOf which can be costly (O(n)). Then you can use a trick like this</p>\n\n<pre><code>private void prevIndex() {\n // Note: You cannot decrement the value of curIndex because curIndex\n // could become negative and modding a negative number gives\n // unexpected results. See http://www.velocityreviews.com/forums/t3883\n // 45-mod-of-a-negative-number.html\n curIndex = (curIndex + CARD_NAMES.size() - 1) % CARD_NAMES.size();\n}\n\nprivate void nextIndex() {\n curIndex = (curIndex + 1) % CARD_NAMES.size();\n}\n</code></pre></li>\n</ul>\n\n<p><strong>Edit addressing comments:</strong></p>\n\n<ul>\n<li><p>To be able to change the title of your window, you would need to pass the JFrame into the Controller. The controller should be the ActionListener for the buttons and the Model should hold the list of strings. The Controller gets the appropriate string from the Model and sets the title of the window. Something like this</p>\n\n<p>In JFileParser.java</p>\n\n<pre><code>public void run() {\n JFrame frame = new JFrame(\"Java File Parser\");\n JFileParserController controller = new JFileParserController(frame);\n controller.setModel(new JFileParserModel());\n frame.setContentPane(new JFileParserPanel(controller));\n // etc.\n</code></pre>\n\n<p>In JFileParserController.java</p>\n\n<pre><code>public void actionPerformed(ActionEvent e) {\n if (e.getActionCommand().equals(\"Back\") {\n model.prevPanel();\n frame.setTitle(model.getCurPanelName());\n // etc.\n</code></pre>\n\n<p>In JFileParserPanel.java</p>\n\n<pre><code>backButton.addActionListener(controller);\nbackButton.setActionCommand(\"Back\");\n\nnextButton.addActionListener(controller);\nnextButton.setActionCommand(\"Next\");\n</code></pre>\n\n<p>In JFileParserModel.java</p>\n\n<pre><code>private static final List<String> PANEL_NAMES =\n Arrays.asList(\"New window\", \"File Chooser\", \"File parser\");\n</code></pre></li>\n<li><p>Sorry if I was unclear earlier. The names of the subpanels should be in a constant list. Do not duplicate code by also making a separate string representation for each of them.</p></li>\n<li>My bad, usually people want a looping list. Storing the index should still work just check for whether the list is at the end before incrementing or decrementing.</li>\n</ul>\n\n<p><strong>Edit adding links for MVC:</strong></p>\n\n<p>Just found some good links that explain MVC more.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/3072979/830988\">This</a> answer to GUI not working after rewriting to MVC</li>\n<li><a href=\"http://www.oracle.com/technetwork/articles/javase/mvc-136693.html\" rel=\"nofollow noreferrer\">Java SE Application Design With MVC</a></li>\n<li><a href=\"https://stackoverflow.com/a/5533581/830988\">This</a> answer to MVC Progress Bar Threading</li>\n<li><a href=\"https://stackoverflow.com/a/2687871/830988\">This</a> answer to Java MVC - How to divide a done text game into MVC?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:17:22.273",
"Id": "22512",
"Score": "0",
"body": "Thank you for your answer, I'm particularly grateful for the links and will be looking over them shortly. I had figured that out about `this`, thus the edit. Thank you none-the-less I wasn't sure exactly why, only that it was because it wasn't static."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:17:35.800",
"Id": "22513",
"Score": "0",
"body": "You are quite right about DeckNavigator, not sure what I was thinking. This is only a simple program at this stage. I am adding on to it in small easily manageable phases, thus the need for the MVC pattern. I noticed that second link has much on the observer pattern. This is something I had found over the weekend and was looking into. It looks very much like what I am already doing, but slightly easier. I was already thinking of implementing it, but thank you for the link, I'm curious about what other methods there are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:17:44.550",
"Id": "22514",
"Score": "0",
"body": "Eventually these cards are going to be a part of a popup from a main window. I was thinking about how to use those subpanel names to change the JFrame title. In this instance should they still not be constant? Why should they not be constant now? I was under the impression that any variables you did not want or expect to change should be constant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:17:54.537",
"Id": "22515",
"Score": "0",
"body": "I was originally trying to use a list, but I needed a key/value pair and I could not figure out how to do so with a list. `List< String, JPanel >` doesn't seem to work, as it says that List only expects a single element. Also, unless I am mistaken, it appears that your example loops back around once it has reached the min/max. I want linear navigation, not circular."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T20:23:21.410",
"Id": "22546",
"Score": "0",
"body": "@showerhead Why do you need to keep a reference to the subpanels? It seems like you just need the list of names to change to the right panel. What else are you doing with the subpanels?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T20:23:50.380",
"Id": "22547",
"Score": "0",
"body": "@showerhead Also see my edit to address some of your other comments."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T10:01:10.633",
"Id": "13932",
"ParentId": "13809",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13932",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:11:03.803",
"Id": "13809",
"Score": "5",
"Tags": [
"java",
"swing"
],
"Title": "Intercommunication Between Cards"
}
|
13809
|
<pre><code>Function Enumerate-Properties($fileName)
{
$path = (Get-Item $fileName).FullName
$shell = New-Object -COMObject Shell.Application
$folder = Split-Path $path
$file = Split-Path $path -Leaf
$shellfolder = $shell.Namespace($folder)
0..287 | Foreach-Object {'{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_)}
}
Function Find-Property($fileName, $PropertyName)
{
$shell = New-Object -COMObject Shell.Application
$path = (Get-Item $fileName).FullName
$folder = Split-Path $path
$file = Split-Path $path -Leaf
$shellfolder = $shell.Namespace($folder)
$shellfile = $shellfolder.ParseName($file)
$found = $false
0..287 | Foreach-Object {
$test1 = $shellfolder.GetDetailsOf($null, $_)
if($PropertyName -eq $shellfolder.GetDetailsOf($null, $_))
{
$found = $true
return $_
break
}
}
if(!$found)
{
Write-Host "Property "$PropertyName " was not found"
}
}
Function Get-PropertyValue($fileName, $property)
{
$shell = New-Object -COMObject Shell.Application
$path = (Get-Item $fileName).FullName
$folder = Split-Path $path
$file = Split-Path $path -Leaf
$shellfolder = $shell.Namespace($folder)
$shellfile = $shellfolder.ParseName($file)
return $shellfolder.GetDetailsOf($shellfile,$property)
}
Function Create-List3($files, $property)
{
$array = @()
$propertyNum = Find-Property $files[0] $property
foreach($file in $files)
{
$file | Add-Member -MemberType noteproperty -Name $property -Value (Get-PropertyValue $file $propertyNum).toString() -force
$array = $array + $file
}
return $array
}
</code></pre>
<p>This code is designed to be used in something like the following fashion:</p>
<pre><code>$files = dir *.mp4
$propery = "Bit rate"
$array = Create-List3 $files $property
$array | Format-Table Name, Length, $property -auto
</code></pre>
<p>As far as I can tell, this code works when you give it a nice amount of .mp4 files. It fares less well when handed other things (folders and the like), the <code>break</code> statement in the <code>Find-Property</code> does nothing (and there has to be a better way to do that anyway).</p>
<p>I am mostly concerned that while this is valid Powershell code, it is very poor Powershell code, in that it is written in a psudo-C# style (that is where I am coming from) and not a Powershell style.</p>
<p>Additionally, I am positive that there easier ways to set up the COM Objects that I am using, and parsing filenames (and reusing them, but that is more complex probably).</p>
<p>How can I make this code better idiomatic Powershell?</p>
|
[] |
[
{
"body": "<p>A first thing to note is that you are creating a lot of COMObjects in a similar manner, we can simply extract that behavior as a separate function. Then, we note that you are expecting file names as parameters where you could expect an item instead; that allows you to pass on items to Create-List3 instead, thus allowing for piping Get-ChildItem into rather than doing extra conversion calls back and forth.</p>\n\n<p>As a result of this two things we're left with a lot of Split-Path calls, we can simply port them over to extracted function as well, it appared that you only needed one of the Split-Pat calls only once. After that, some small cleanup has been done (removing $test1, adding extra newlines and spaces for readability) and we already have much cleaner code to continue from:</p>\n\n<pre><code>Function Get-ShellFolder($fileItem)\n{\n $folder = Split-Path $fileItem.FullName\n\n $shell = New-Object -COMObject Shell.Application\n return $shell.Namespace($folder)\n}\n\nFunction Enumerate-Properties($fileItem)\n{\n $shellfolder = Get-ShellFolder $fileItem\n\n 0..287 | Foreach-Object {'{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_)}\n}\n\nFunction Find-Property($fileItem, $PropertyName)\n{\n $shellfolder = Get-ShellFolder $fileItem\n\n $found = false\n 0..287 | Foreach-Object {\n if ($PropertyName -eq $shellfolder.GetDetailsOf($null, $_))\n {\n $found = true\n return $_\n break\n }\n }\n\n if (!$found) {\n Write-Host \"Property \" $PropertyName \" was not found\"\n }\n}\nFunction Get-PropertyValue($fileItem, $property)\n{\n $shellfolder = Get-ShellFolder $fileItem\n\n $file = Split-Path $fileItem.FullName -Leaf\n $shellfile = $shellfolder.ParseName($file)\n\n return $shellfolder.GetDetailsOf($shellfile, $property)\n}\nFunction Create-List3($files, $property)\n{\n $array = @()\n $propertyNum = Find-Property $files[0] $property\n foreach($file in $files)\n {\n $file | Add-Member -MemberType noteproperty -Name $property -Value (Get-PropertyValue $file $propertyNum).toString() -force\n $array = $array + $file\n }\n return $array\n}\n</code></pre>\n\n<p>From here on, you could look for things that are already implemented in Powershell to make the code even more simple, as well as adding documentation to make some less obvious things easier to understand for fellow readers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T06:04:54.057",
"Id": "13859",
"ParentId": "13816",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "13859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T23:21:22.263",
"Id": "13816",
"Score": "5",
"Tags": [
"file",
"powershell"
],
"Title": "Inspecting properties of files"
}
|
13816
|
<p>
I am writing an API wrapper and the endpoint takes dates in a very specific format.</p>
<p>The user of the API can pass in the parameters in whatever format they prefer, but regardless of what they pass in, I want to be able to clean up their input prior to submitting their query.</p>
<p>My question centers around the best way to update the options hash in place, and I have thought of a few possible ways to implement.</p>
<ol>
<li>A helper method inside the class so you can overwrite <code>options = reformat_hash(options)</code></li>
<li><p>A singleton on that specific variable</p>
<pre class="lang-ruby prettyprint-override"><code>def options.clean_up!
# see internals below
end
</code></pre></li>
<li><p>Or open up <code>Hash</code> and do the cleaning from the class</p>
<pre class="lang-ruby prettyprint-override"><code>class Hash
def clean_hash!
self.each { |key, value|
if value.is_a? Date
self[key] = value.strftime('%Y-%m-%d %H:%M:%S')
else
self[key] = value.to_s
end
}
end
end
</code></pre>
<p>so that I can just call it on whatever the variable may be named like:</p>
<pre class="lang-ruby prettyprint-override"><code>def api_request(options={})
options.clean_hash!
# the options variable is now clean and I can pass it to the api
HHTParty.get(path, :query => options).parsed_response
end
</code></pre></li>
</ol>
<p>Is there a best practice for modifying or formatting hashes after they're passed into a method?</p>
<p>I feel like #3 is the neatest, but should I be worried about opening up <code>Hash</code> to do this?</p>
|
[] |
[
{
"body": "<p>Here, while it may look nice, the method clean_hash is not general enough to be valid across all Hashes. So adding a method such as clean_hash to all Hashes would only serve to increase the coupling which is bad. A second problem is that you are mutating your method argument which is almost never advisable.</p>\n\n<p>The solution is to define the <code>clean</code> method outside, perhaps as a part of your internal API object and call <code>HHTParty.get(path, :query => clean(options)).parsed_response</code>.</p>\n\n<p>I would also define the clean method this way</p>\n\n<pre><code>def clean(opt)\n Hash[opt.collect{|k,v| [k,v.is_a? Date : v.strftime('%Y-%m-%d %H:%m:%S'):v.to_s ]}]\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T08:33:38.487",
"Id": "22450",
"Score": "0",
"body": "thanks blufox. I think I will include it in the get query like that, although I may use a different enumerable based on this https://gist.github.com/3158814."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T04:08:31.240",
"Id": "13822",
"ParentId": "13820",
"Score": "2"
}
},
{
"body": "<p>Rather than extend the hash class with something that \"isn't general enough to be valid across all classes\" (blufox: well said), make a subclass of <code>Hash</code> named <code>CleanHash</code>. </p>\n\n<p>I added <code>|| value.is_a?(Time)</code> so you could format <code>Time</code> in addition to <code>Date</code>.</p>\n\n<pre><code>class CleanHash < Hash\n def self.[](opts)\n super(opts).clean!\n end\n\n def []=(key,value)\n super(key,clean(value))\n end\n\n def clean(value)\n if value.is_a?(Date) || value.is_a?(Time)\n value.strftime('%Y-%m-%d %H:%M:%S')\n else\n value.to_s\n end\n end\n\n def clean!\n self.each { |key, value|\n self[key] = value # don't clean(value) or it will clean twice\n }\n end\nend\n</code></pre>\n\n<p>Examples below.</p>\n\n<pre><code># example 1\nh = CleanHash[:s=>\"x\",:n=>9,:d=>Date.today,:t=>Time.now]\n# => {:s=>\"x\", :t=>\"2012-07-20 09:21:18\", :d=>\"2012-07-20 00:00:00\", :n=>\"9\"}\nh[:d2] = Date.yesterday\n# => {:d2=>\"2012-07-19 00:00:00\", :s=>\"x\", :t=>\"2012-07-20 09:21:18\", :d=>\"2012-07-20 00:00:00\", :n=>\"9\"}\n\n# example 2\ndef api_request(options={})\n clean_options = CleanHash[options]\n # the options variable is now clean and I can pass it to the api\n HHTParty.get(path, :query => clean_options).parsed_response\nend\n</code></pre>\n\n<p>It's still a <code>Hash</code> so you can pass it around as if it were a <code>Hash</code>.</p>\n\n<pre><code>h = CleanHash[:foo=>Date.today]\n#=> {:foo=>\"2012-07-20 00:00:00\"}\nh.class\n#=> CleanHash\nh.is_a?(Hash)\n#=> true\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:36:14.497",
"Id": "13874",
"ParentId": "13820",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13822",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T03:30:06.757",
"Id": "13820",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Reformatting a method options hash"
}
|
13820
|
<p>Every time I go to write an MVVM application (say every 4-6 months) I rewrite my <code>ViewModelBase</code> class. This is for a range of reasons but let's say either I don't have access to prior code, the previous code was built for a client and isn't my code, or I'm working on someone else's machine and still don't have the code.</p>
<p>So I rewrite the basic <code>INotifyPropertyChanged</code> implementation, and I think it's a little different each time. Here's what I've come up with today: </p>
<pre><code>public class ViewModelBase : INotifyPropertyChanged
{
protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
var property = (MemberExpression)expression.Body;
this.OnPropertyChanged(property.Member.Name);
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
</code></pre>
<p>I would like to get a nice implementation that is simple and small, and any improvements to this (what other functionality is required in a <code>ViewModelBase</code>?) would be great.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:19:14.580",
"Id": "22312",
"Score": "0",
"body": "I've never considered doing this. I'm interested to see what context would this be useful when using the view model on the view? Do you have any example code of it's usage?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T02:06:00.580",
"Id": "22572",
"Score": "1",
"body": "@dreza Which part in particular? Implementing the INotifiyPropertyChanged interface is basic functionality that a ViewModel needs to provide, and I'm just sharing that across my ViewModels..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T20:47:04.833",
"Id": "22617",
"Score": "0",
"body": "Yeah, I understand the functionality. I was interested to see in what context it was used as it it's my understanding that every view model does not need to provide the functionality. However I've done a bit of googling about it anyway cheers."
}
] |
[
{
"body": "<p>Specifically related to <code>NotifyPropertyChanged</code> I've found <code>VerifyPropertyName</code> to be useful.</p>\n\n<p>From Josh Smith's site: <a href=\"http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/\" rel=\"nofollow\">A base class which implements INotifyPropertyChanged</a></p>\n\n<pre><code>[Conditional(\"DEBUG\"), DebuggerStepThrough()]\npublic void VerifyPropertyName(string propertyName)\n{\n// Verify that the property name matches a real, \n// public, instance property on this object.\nif (TypeDescriptor.GetProperties(this)(propertyName) == null) {\n string msg = \"Invalid property name: \" + propertyName;\n\n if (this.ThrowOnInvalidPropertyName) {\n throw new Exception(msg);\n } else {\n Debug.Fail(msg);\n }\n}\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:00:47.570",
"Id": "13848",
"ParentId": "13823",
"Score": "1"
}
},
{
"body": "<p>I've used the below for a while:</p>\n\n<pre><code>public abstract class PropertyChangedBase : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void RaisePropertyChanged(string propertyName)\n {\n var propertyChanged = this.PropertyChanged;\n\n if (propertyChanged != null)\n {\n propertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n protected bool SetProperty<T>(ref T backingField, T Value, Expression<Func<T>> propertyExpression)\n {\n var changed = !EqualityComparer<T>.Default.Equals(backingField, Value);\n\n if (changed)\n {\n backingField = Value;\n this.RaisePropertyChanged(ExtractPropertyName(propertyExpression));\n }\n\n return changed;\n }\n\n private static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)\n {\n var memberExp = propertyExpression.Body as MemberExpression;\n\n if (memberExp == null)\n {\n throw new ArgumentException(\"Expression must be a MemberExpression.\", \"propertyExpression\");\n }\n\n return memberExp.Member.Name;\n }\n}\n</code></pre>\n\n<p>I can write my properties like this:</p>\n\n<pre><code> private int id;\n\n public int Id\n {\n get\n {\n return this.id;\n }\n\n set\n {\n this.SetProperty(ref this.id, value, () => this.Id);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:17:57.967",
"Id": "13849",
"ParentId": "13823",
"Score": "7"
}
},
{
"body": "<p>This is many years later, but anyone stumbling upon this now should be aware of <code>MVVM Light</code> and <code>PropertyChanged.Fody</code></p>\n\n<p>Both are on nuget.org</p>\n\n<ul>\n<li><a href=\"http://www.mvvmlight.net/\" rel=\"nofollow\">http://www.mvvmlight.net/</a></li>\n<li><a href=\"https://github.com/Fody/PropertyChanged\" rel=\"nofollow\">https://github.com/Fody/PropertyChanged</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T18:11:04.950",
"Id": "121811",
"ParentId": "13823",
"Score": "1"
}
},
{
"body": "<pre><code>protected void OnPropertyChanged<T>(Expression<Func<T>> expression)\n{\n var property = (MemberExpression)expression.Body;\n this.OnPropertyChanged(property.Member.Name);\n}\n</code></pre>\n\n<ul>\n<li><code>Expression<Func<T>></code> is a pretty expensive allocation, usually not a problem but good to know.\nUsed <a href=\"https://github.com/PerfDotNet/BenchmarkDotNet\" rel=\"nofollow\">BenchmarkDotNet</a> and ran a benchmark for fun, here are the results:</li>\n</ul>\n\n\n\n<pre><code> Method | Median | StdDev | Scaled |\n ------------------------ |-------------- |----------- |------- |\n SetWithCallerMemberName | 2.5169 ns | 0.3584 ns | 1.00 |\n SetWithExpression | 1,343.9223 ns | 38.2650 ns | 533.97 |\n</code></pre>\n\n<ul>\n<li>Adding some more validation may make sense. Maybe a debug assert checking that there is a property named <code>property.Member.Name</code>?</li>\n<li>If you are using C#6 and this overload should be removed. Use <code>nameof</code> instead.</li>\n</ul>\n\n\n\n<pre><code>protected void OnPropertyChanged(string name)\n{\n PropertyChangedEventHandler handler = PropertyChanged;\n if (handler != null)\n {\n handler(this, new PropertyChangedEventArgs(name));\n }\n}\n</code></pre>\n\n<ul>\n<li>Good that you copy to a temp before nullchecking.</li>\n<li><p>Depending on C# version <code>[CallerMemberName]</code> should be added like so:</p>\n\n<p><code>protected void OnPropertyChanged([CallerMemberName] string name = null)</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T19:32:51.310",
"Id": "121818",
"ParentId": "13823",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13849",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T04:49:42.807",
"Id": "13823",
"Score": "7",
"Tags": [
"c#",
"mvvm"
],
"Title": "Improvements to a ViewModelBase"
}
|
13823
|
<p>I'm using this pattern (for want of a better word) repeatedly in my code to call a REST API in my javascript code. Some particulars of the code below.</p>
<ol>
<li>I have a ConfigViewer javascript class that is responsible for creating, populating and handling events for DOM element.</li>
<li>This class constructor inits the DOM components, and then calls an REST API to get the data to populate these DOM components.</li>
<li>I need to handle the response to this API from my instance of ConfigViewer</li>
</ol>
<p>My question is related to the way I have the getAdminDataSuccessHandler() method to return a function that is called when the REST API succeeds: Is this the cleanest way to handle the response of the API call ? </p>
<pre><code>function ConfigViewer() {
this.createUIComponents();
this.ajaxLoadData("/adminData", this.getAdminDataSuccessHandler());
}
ConfigViewer.prototype.getAdminDataSuccessHandler = function() {
var self = this;
return function(data) {
// Handle successful data retrieval
self.populateUICoponents(data);
}
}
/**
* Execute the API in ajaxy fashion.
*/
ConfigViewer.prototype.ajaxLoadData = function(url, onSuccessHandler) {
$.ajax({
url : url,
success : function(jsonData, textStatus, XMLHttpRequest) {
onSuccessHandler(jsonData);
}
});
}
</code></pre>
|
[] |
[
{
"body": "<p>It doesn't look like your class has any data, so I must question what's the point. Any instance of the class\nwould be equal to each other.</p>\n\n<p>Your <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow\">constructor is also doing a lot of real work</a>, constructors should just initialize the object.</p>\n\n<p>You can also do what you are doing without manual closure plumbing by using <a href=\"http://api.jquery.com/jQuery.proxy/\" rel=\"nofollow\">jQuery's proxy</a>:</p>\n\n<pre><code>function ConfigViewer() {\n this.createUIComponents();\n this.ajaxLoadData(\"/adminData\").then($.proxy(this.successHandler, this));\n}\n\n\nConfigViewer.prototype.successHandler = function( data ) { \n this.populateUICoponents(data);\n};\n\nConfigViewer.prototype.ajaxLoadData = function(url) {\n return $.ajax({\n url : url\n });\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:03:29.687",
"Id": "13828",
"ParentId": "13826",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13828",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T09:50:41.323",
"Id": "13826",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "Closure handling in javascript / jquery ajax"
}
|
13826
|
<p>I am in the progress of creating a MVC structured website. I've opted to make my own instead of using pre-constructed MVC systems as a way to teach myself better coding and understanding how applications work. I've got everything laid out, but I'm not happy with my routing system. It is VERY crude and I'd like it to be more robust.</p>
<p>I'd like to get feedback to help improve my code.</p>
<p>Below is the full code for index.php, where my routing code is:</p>
<pre><code><?php
session_start();
// Estabilish Database Connections and system defaults
include('config.php');
function setReporting() {
if (DEVELOPMENT_ENVIRONMENT == true) {
error_reporting(E_ALL);
ini_set('display_errors','On');
} else {
error_reporting(E_ALL);
ini_set('display_errors','Off');
ini_set('log_errors', 'On');
ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');
}
}
function db_connect() {
$connection = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD);
if (!$connection) {
die("<h2>Error Connecting to Database</h2>");
}
if(!mysql_select_db(DATABASE, $connection)) {
die("<h2>Database Does Not Exist</h2>");
}
return $connection;
}
function hook() {
$params = parse_params();
$url = $_SERVER['REQUEST_URI'];
$url = str_replace('?'.$_SERVER['QUERY_STRING'], '', $url);
$urlArray = array();
$urlArray = explode("/",$url);
var_dump($urlArray);
if (isset($urlArray[2]) & !empty($urlArray[2])) {
$route['controller'] = $urlArray[2];
} else {
$route['controller'] = 'front'; // Default Action
}
if (isset($urlArray[3]) & !empty($urlArray[3])) {
$route['view'] = $urlArray[3];
} else {
$route['view'] = 'index'; // Default Action
}
include(CONTROLLER_PATH.$route['controller'].'.php');
include(VIEW_PATH.$route['controller'].DS.$route['view'].'.php');
var_dump($route['controller']);
var_dump($route['view']);
var_dump($urlArray);
var_dump($params);
// reseting messages
$_SESSION['flash']['notice'] = '';
$_SESSION['flash']['warning'] = '';
}
// Return form array
function parse_params() {
$params = array();
if(!empty($_POST)) {
$params = array_merge($params, $_POST);
}
if(!empty($_GET)) {
$params = array_merge($params, $_GET);
}
return $params;
}
// Prepare General Application Models
require($_SERVER['DOCUMENT_ROOT'].'/'.APP.'/'.'models/'.'general.php');
setReporting();
date_default_timezone_set(get_timezone());
$current_theme = current_theme();
hook();
if($_SESSION['flash']['notice']) {
echo $_SESSION['flash']['notice'];
}
</code></pre>
<p>One big problem is that my hook call won't work properly when the urls are two levels deep. Say I wanted to visit <code>mywebsite.com/admin</code>, it would work, however <code>mywebsite.com/admin/dashboard</code> would not. The problem is in the arrays. How could I get the array to load content after the 2nd level along with the second level?</p>
<p>Would it be best to create an array like this?</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Array
- controller
- view
- dashboard
</code></pre>
</blockquote>
<p>What would be the best way to set up "custom" URLs?</p>
<p>If I were to put in <code>mywebsite.com/announcement</code>, it would check to see if it has controllers. Failing that, it would check to see if it has custom content (maybe a file of the same name in "customs" folder, and then if there's nothing, execute the <em>404 page not found</em> stuff). This isn't a priority question though, but loosely associated in how the code works so I thought it best to add.</p>
|
[] |
[
{
"body": "<p>First off, congrats on making your own, that's the best way to learn and usually you don't need all the added overhead that a prefab provides.</p>\n\n<p>In the implementation of MVC I like to use, there is a router between the view and controller, so its more of a MVRC rather than MVC. Just another level of abstraction, but I like it. It seems like what you are trying to do here is similar. So maybe my experience will help. My routers are typically classes, but that's a preference. Here are some suggestions on your code, along with a possible solution to your problem.</p>\n\n<p><strong>Error Reporting</strong></p>\n\n<p>When you set error reporting, make sure you don't do the same thing twice, such as setting the same reporting level, it should always be the same, so just declare it before the if statement. This actually holds true for anything. This is called the DRY principle (Don't Repeat Yourself). Also, you might want to consider logging errors even while in the development environment. This ensures that you don't miss those \"silent\" errors and allows you to ensure that the logs are working correctly. So a possible rewrite of your <code>setReporting()</code> function.</p>\n\n<pre><code>function setReporting() {\n error_reporting(E_ALL);\n\n ini_set( 'display_errors', DEVELOPMENT_ENVIRONMENT );\n ini_set('log_errors', 'On');\n ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');\n}\n</code></pre>\n\n<p>Would change <code>DEVELOPMENT_ENVIRONMENT</code> to just <code>DEVELOPMENT</code> or my preferred <code>STAGING</code>.</p>\n\n<p><strong>Edit</strong> Above I meant to say <code>ENVIRONMENT</code> instead of <code>DEVELOPMENT</code>. This is because you are no longer using this constant to check the development environment, you are using it to set an environment.</p>\n\n<p>You might actually want to set up your error reporting and db connection using a config file of some sort and then just reference it in the router. Another level of abstraction, but a very common one.</p>\n\n<p><strong>Development Tools</strong></p>\n\n<p>Don't use <code>die()</code>, <code>var_dump()</code>, <code>print_r()</code>, etc... outside of you development environment. There are better, more elegant, ways of displaying data to the customer.</p>\n\n<p><strong>Unnecessary Work</strong></p>\n\n<p>Instead of using \"REQUEST_URI\" and removing \"QUERY_STRING\" from it, why not just use \"SCRIPT_NAME\"? It does the same thing.</p>\n\n<pre><code>$_SERVER[ 'SCRIPT_NAME' ];\n</code></pre>\n\n<p>You don't have to define <code>$urlArray</code> as an array if you are immediately going to assign an array to it. Essentially you are assigning it a value and then never using it, which is bad and confusing. This isn't Java or C, you don't have to type hint a variable before using it.</p>\n\n<p>Always check to see if the language you are working in provides a way for you to do something easier than you could do it yourself.</p>\n\n<p><strong>Defining a Default Value</strong></p>\n\n<p>This is a stylistic choice, but instead of using else statements to define default values, just define the default values first. If those values need to change, then change them.</p>\n\n<pre><code>$route[ 'view' ] = 'index';\nif (isset($urlArray[3]) & !empty($urlArray[3])) {\n $route['view'] = $urlArray[3];\n}\n</code></pre>\n\n<p><strong>Distinguishing Between isset() and empty()</strong></p>\n\n<p><code>isset()</code> returns TRUE only if a variable is set, and its value is not NULL.</p>\n\n<p><code>empty()</code> returns FALSE only if a variable is not FALSE, NULL, an empty string, any form of zero, or an empty array.</p>\n\n<p>Unless you explicitly need to distinguish between a variable not being set, or empty, then I would suggest only using <code>isset()</code>, not both.</p>\n\n<p><strong>list()</strong></p>\n\n<p>A better way to assign array values to specific variables is to use a <code>list()</code>. You'll need to use <code>array_pad()</code> to ensure the array is the proper length first, but don't worry, it won't add anything if its already past that length. Also, I don't know why you are passing these variables to an array and then never using that array. It's unnecessary. However, I do show how to pass these variables back to an array in case you are planning on expanding upon that function.</p>\n\n<pre><code>$urlArray = array_pad( $urlArray, 4, NULL );\nlist( , , $controller, $view ) = $urlArray;\n$route = compact( 'controller', 'view' );\n</code></pre>\n\n<p><strong>Your Problem</strong></p>\n\n<p>Your array, at least in the examples you provided, is not four fields long, its three. You've skipped the first empty field, but then, instead of using \"1\" as your index, you use two. Arrays start indexing their fields at zero. So When you call for the indices at \"2\" and \"3\", you are actually calling for the third and fourth elements. This is why your example will work for one level, but not another. I'm surprised your examples aren't throwing out of bounds errors.</p>\n\n<p>Anyways, a better way to write your hook.</p>\n\n<pre><code>function hook() {\n $params = parse_params();\n\n $url = $_SERVER[ 'SCRIPT_NAME' ];\n $url = trim( $url, '/' );//remove forward slash from beginning and end of $url\n\n $urlArray = explode( '/', $url );\n $urlArray = array_pad( $urlArray, 2, NULL );\n list( $controller, $view ) = $urlArray;\n\n if( ! $controller ) { $controller = 'front'; }\n if( ! $view ) { $view = 'index'; }\n\n $route = compact( 'controller', 'view' );\n}\n</code></pre>\n\n<p>Now if you want to extend to another level you would just adjust the padding, add to the list, add a default, and then add it to the compact.</p>\n\n<p><strong>Custom URLs</strong></p>\n\n<p>These are done through the htaccess file with mod_rewrite. At least, I think that's right. I haven't tried figuring this out yet, so I can't give you details, but it is well documented on the internet, just google it.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Looks good. I put an edit in one of the above sections because of a typo. You followed most of my previous advice, so there's not much I can add. I did just notice a couple of things though.</p>\n\n<p>It looks as if you are passing your post and get data directly to your PHP scripts. This is bad. You should always validate and sanitize them. If your PHP version is >= 5.2 you can use a helpful PHP function called <code>filter_input_array()</code>, or <code>filter_input()</code>.</p>\n\n<p>It is best to only use the concatenate <code>.</code> operator if you are adding variables to a string. Even though it doesn't look like much, it is still an operator and takes processing power. Admitedly not much, but you should still code so that you aren't blattantly ignoring such minor inefficiencies. Not to say that you need to go out of your way to make your script as quick as possible. Far from it. But if its a quick fix that doesn't hurt anything, why not. It may not present much improvement now, but say you find yourself working on a script with a massive array that you need to loop over. At such a point every little efficiency matters. If you are already taking care of some of the easier stuff automatically it won't be as difficult to refactor the rest.</p>\n\n<pre><code>require( $_SERVER[ 'DOCUMENT_ROOT' ] . '/' . APP . '/models/general.php' );\n</code></pre>\n\n<p>Last but not least, don't just copy-paste suggestions into your code. I notice my coding style made it into your code. Take time to understand suggestions and write them yourself. As you found out, my answer was not 100% operational and you had to adjust it. Even if all you are doing is manually typing out these suggestions, without any change, you will find you will remember it a little better for the next time you need it and something might even click so that you understand it better.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T02:15:30.847",
"Id": "22349",
"Score": "0",
"body": "My goodness, thank you so much. This was more than I could have asked for! Sadly I don't have enough points on code review to vote you up yet, but you win the internets from me today!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T02:33:36.457",
"Id": "22350",
"Score": "0",
"body": "Though I'm getting some errors when I try this out. Notice: Undefined index: PATH_INFO in /home3/keiranlo/public_html/flightDeck/index.php on line 32 Warning: array_pad() expects exactly 3 parameters, 2 given. I can't really commit my time to it right now due to other work required, so I'll see whats going on tonight. If you could help though that'd be great."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:27:21.963",
"Id": "22351",
"Score": "0",
"body": "@KeiranLovett: Sorry about that, I gave you the wrong index. Try SCRIPT_NAME instead. PATH_INFO looks at path information that comes after the file, for instance \"index.php/admin/dash\" instead of before \"/admin/dash/index.php\". Sorry, for the mixup. As for `array_pad()`, I forgot the final parameter, just add an empty string or null to the end of the parameter list. That is the \"padding\". I'll fix it above in a second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:33:57.523",
"Id": "22352",
"Score": "0",
"body": "Oh, and one more thing about SCRIPT_NAME, it includes the file name as well, so when you explode it the final array element will be the file name. When using list you don't have to declare all the array elements for it to work, but if you need to add more parameters you can pop that last element off the array before padding it to avoid getting the file name mixed up with something else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T05:49:48.207",
"Id": "22358",
"Score": "0",
"body": "Hrmm, now I'm getting this error.\nWarning: include(): Failed opening '/home3/keiranlo/public_html/flightDeck/controller/flightDeck.php' for inclusion (include_path='.:/usr/php/53/usr/lib64:/usr/php/53/usr/share/pear') in /home3/keiranlo/public_html/flightDeck/index.php on line 41 Warning: include(): Failed opening '/home3/keiranlo/public_html/flightDeck/views/flightDeck/index.php.php' for inclusion (include_path='.:/usr/php/53/usr/lib64:/usr/php/53/usr/share/pear') in /home3/keiranlo/public_html/flightDeck/index.php on line 42"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T16:13:59.303",
"Id": "22389",
"Score": "0",
"body": "@KeiranLovett First of all, always check to see if a dynamic path is actually a file before including it. This prevents these errors and allows you to display a 404 page in these cases. Second, SCRIPT_NAME returns the full file name, including extension, so in that second include, the \".php\" is redundant, just remove it. As for why your files aren't loading? I would hazard to guess that its because you are including from the \"home\" directory rather than system root. Your paths have to be full absolute paths. If you prefix `$_SERVER[ 'DOCUMENT_ROOT' ] to those include paths it should work fine."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:39:01.883",
"Id": "13851",
"ParentId": "13827",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "13851",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:02:07.610",
"Id": "13827",
"Score": "4",
"Tags": [
"php",
"array",
"mvc",
"url",
"url-routing"
],
"Title": "Routing in MVC with PHP"
}
|
13827
|
<p>I've created a database connection pool used on the serverside (of a client-server socket app) and was wondering what improvements can be made to help the design and/or efficiency of the solution. The pool is used from multiple threads so synchronisation is important.</p>
<p>The application has been running for a while now with seemingly few problems so the code does appear to work as intended.</p>
<p><strong>Theory:</strong></p>
<p>My basic theory is to have x amount of connections open at any one point in time taking from the top and putting back on the bottom. Connections will only stay alive for so long before they are freed and a new one is created. If I ever have too many because of high server demand a cleanup thread in the <em>ConnectionPool</em> class is responsibling for removing the extra connections as required.</p>
<p><strong>Classes</strong></p>
<ul>
<li><strong>ConnectionPool</strong>: Class used to contain the connections and manage
their usage</li>
<li><strong>CachedConnection</strong>: Just a wrapper for Connection and used so that I
only keep connections around for a limited time before they are
closed and new one takes their place</li>
<li><strong>DatabaseConnection</strong>: abstract class that holds the connection pool.
Children of this class will maintain connection strings etc</li>
</ul>
<p>Some classes not added but used in the code</p>
<ul>
<li><strong>EventLog</strong>: Just a logging class, I've actually posted already <a href="https://codereview.stackexchange.com/questions/12336/robust-logging-solution-to-file-on-disk-from-multiple-threads-on-serverside-code">here</a></li>
<li><strong>WebServer</strong>: A static class to contain some configuration options</li>
<li><strong>Stopwatch</strong>: Small class that acts as a stopwatch effectively</li>
</ul>
<p><strong>Code</strong>:</p>
<pre><code>public class CachedConnection {
private Connection _connection = null;
private Stopwatch _stopWatch;
private static int KEEP_ALIVE = 1000 * 60 * 20; // 20 minutes max connection life
private static long _connectionCounter = 0;
private final long _id;
public CachedConnection(Connection connection) {
_connection = connection;
_stopWatch = new Stopwatch(KEEP_ALIVE).start();
_id = newId();
}
public Connection getConnection() {
return _connection;
}
public long getId() {
return _id;
}
public boolean keepAlive() {
return !_stopWatch.isFinished();
}
public void close() throws SQLException {
_connection.close();
}
private synchronized long newId() {
return _connectionCounter++;
}
}
</code></pre>
<p>Actual Connection Pool class, the crux of the matter</p>
<pre><code>public class ConnectionPool implements Runnable {
// Number of initial connections to make.
private final int _maxConnections;
// A list of available connections for use.
private final Queue<CachedConnection> _availableConnections;
// A list of connections being used currently.
private final Queue<CachedConnection> _usedConnections;
// The URL string used to connect to the database
private final String m_URLString;
// The username used to connect to the database
private final String m_UserName;
// The password used to connect to the database
private final String m_Password;
// The cleanup thread
private Thread m_CleanupThread = null;
//Constructor
protected ConnectionPool(String urlString, String user, String passwd, int connections) throws SQLException {
// Initialize the required parameters
m_URLString = urlString;
m_UserName = user;
m_Password = passwd;
_maxConnections = connections;
_usedConnections = new LinkedBlockingQueue<CachedConnection>();
_availableConnections = new LinkedBlockingQueue<CachedConnection>();
setupAvailableConnections(_maxConnections);
startCleanUpThread();
}
public synchronized void checkin(CachedConnection cached) {
if(cached != null) {
// Remove from used list.
freeConnectionInUse(cached);
try {
Connection c = cached.getConnection();
if(!c.isClosed()) {
// only add it back to our connection pool if we haven't exceeded
// the max allowed connections
if(availableConnectionCount() < _maxConnections) {
addAvailableConnection(cached);
}
else {
closeConnection(cached);
}
}
} catch(SQLException ex) {
EventLog.write(ex, "ConnectionPool", "checkin");
}
}
}
public void run() {
try {
while(true) {
int cleanedConnections = 0;
while(availableConnectionCount() > _maxConnections) {
closeConnection(getNextAvailableConnection());
cleanedConnections++;
}
if(cleanedConnections > 0) {
EventLog.write("Cleaned " + cleanedConnections + " connections", "ConnectionPool", "run");
}
// Now sleep for 1 minute
Thread.sleep(60000 * 1);
}
}
catch(Exception e) {
EventLog.write(e, "ConnectionPool", "run");
}
}
public CachedConnection checkout() throws SQLException {
CachedConnection newConnxn = getNextAvailableConnection();
if(newConnxn != null && newConnxn.keepAlive()) {
// Add it to the in use list
connectionInUse(newConnxn);
} else {
// otherwise it's dead so archive it and try and get another instance
closeConnection(newConnxn);
// add a new available connection
newAvailableConnection();
// try to get the first next available connection
newConnxn = checkout();
}
// Either way, we should have a connection object now.
return newConnxn;
}
private void startCleanUpThread() {
// Create the cleanup thread
m_CleanupThread = new Thread(this);
m_CleanupThread.start();
}
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(m_URLString, m_UserName, m_Password);
}
private CachedConnection newCachedConnection() throws SQLException {
return new CachedConnection(getConnection());
}
private void setupAvailableConnections(int connections) throws SQLException {
int counter = 0;
while(counter++ < connections) {
// Add a new connection to the available list.
newAvailableConnection();
}
}
private synchronized CachedConnection getNextAvailableConnection() {
return _availableConnections.poll();
}
private synchronized void addAvailableConnection(CachedConnection connection) {
_availableConnections.add(connection);
}
private synchronized void newAvailableConnection() throws SQLException {
_availableConnections.add(newCachedConnection());
}
private synchronized void connectionInUse(CachedConnection connection) {
_usedConnections.add(connection);
}
private synchronized void freeConnectionInUse(CachedConnection connection) {
_usedConnections.remove(connection);
}
private void closeConnection(CachedConnection c)
{
if(c != null) {
// don't re-add it and the connection is being freed for garbage collection
try {
c.close();
} catch(SQLException ex) {
EventLog.write(ex, "ConnectionPool", "archive");
}
finally {
int av = availableConnectionCount();
EventLog.write("Closed old connection Id=" + c.getId() + ". Available connections=" + av, "ConnectionPool", "archive");
}
}
}
private synchronized int availableConnectionCount() {
return _availableConnections.size();
}
}
</code></pre>
<p>And it's used by children of DatabaseConnection</p>
<pre><code>public abstract class DatabaseConnection {
private CachedConnection _connection = null;
abstract protected ConnectionPool getInstance() throws SQLException;
public Connection getConnection() {
return _connection.getConnection();
}
public boolean isOpen() { return getConnection() != null; }
public synchronized void open() throws SQLException {
_connection = getInstance().checkout();
}
public void close() {
if(_connection != null ) {
try {
getInstance().checkin(_connection);
} catch(Exception ex) {
EventLog.write(ex.toString(), "DatabaseConnection", "Close" );
} finally {
_connection = null;
}
} else
EventLog.write("ERROR: Attempting to close a connection but connection is null", "DatabaseConnection", "close" );
}
}
</code></pre>
<p>And example of a DatabaseConnection child:</p>
<pre><code>public class ClientDatabase extends DatabaseConnection {
private final String _dbURL;
private final String _username = "saywhat";
private final String _password = "noway!";
private final int _connections;
private static ConnectionPool _pool = null;
public ClientDatabase() {
_dbURL = "what you talking about willis";
_connections = WebServer.CONNECTIONS;
}
@Override
protected ConnectionPool getInstance() throws SQLException {
if (_pool == null) {
synchronized(ClientDatabase.class) {
if (_pool == null)
_pool = new ConnectionPool(_dbURL, _username, _password, _connections);
}
}
return _pool;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would advice to look at DBCP library <a href=\"http://commons.apache.org/dbcp/\" rel=\"nofollow\">http://commons.apache.org/dbcp/</a>.</p>\n\n<p>If you are deploying your application in servlet container or application server then it has it's own implementation of the database connection pool. So you only have to configure database connection pool in xml or property file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T19:14:38.790",
"Id": "22407",
"Score": "0",
"body": "Cheers. My applet is not being served in a servlet container. I actually don't even know what that is :) It's jut being run on the server as a standard java application."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T12:38:33.597",
"Id": "13867",
"ParentId": "13829",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:07:23.923",
"Id": "13829",
"Score": "2",
"Tags": [
"java"
],
"Title": "Connection pooling with time-alive limited connections"
}
|
13829
|
<p>Code below is scattered all over the code base : </p>
<pre><code>if (StringUtils.contains(manager.getName, "custom")){
}
</code></pre>
<p>It just checks if an object attribute contains a predefined String and if it does, enter condition.</p>
<p>Is there a more elegant way of achieving above, perhaps using an enum?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T12:43:40.063",
"Id": "22316",
"Score": "1",
"body": "Is the string being searched for always the same?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T13:37:00.537",
"Id": "22319",
"Score": "0",
"body": "@Konrad Rudolph yes its always the same"
}
] |
[
{
"body": "<ol>\n<li><p>It seems <a href=\"http://c2.com/cgi/wiki?DataEnvy\" rel=\"nofollow noreferrer\">data envy</a>. I'd create <code>nameContains</code> method in the <code>Manager</code> class.</p>\n\n<pre><code>public boolean nameContains(final String searchText) {\n if (StringUtils.contains(name, searchText)) {\n return true;\n }\n return false;\n}\n</code></pre></li>\n<li><p>Instance variables (fields) should be private. See: <a href=\"https://stackoverflow.com/a/7622781/843804\">why instance variables in java are always private</a></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T12:43:08.940",
"Id": "22315",
"Score": "6",
"body": "`if (cond) return true; else return false;` => `return cond;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T18:27:48.837",
"Id": "22463",
"Score": "0",
"body": "+1 for the link to data envy. However, as Konrad suggested, the body of this method should be a one-liner."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:38:42.090",
"Id": "13832",
"ParentId": "13831",
"Score": "3"
}
},
{
"body": "<p>You can use a <code>static</code> reference for \"custom\" :</p>\n\n<pre><code> // In References.class declared 'final'\npublic final class References{\n static String refSearched = \"custom\";\n\n public static boolean methodControl1(final String s){\n return s.contains(refSearched);\n } \n .... // other fields/methods\n}\n\n // In other classes\n if(References.methodControl1(newStringToSearchIn)){\n ..;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T11:33:31.947",
"Id": "13833",
"ParentId": "13831",
"Score": "2"
}
},
{
"body": "<p>Are the strings like <code>\"custom\"</code> pre-defined? If the number of such strings are limited, then you would also profit by making them into methods such as <code>Manager.hasCustom()</code> if not, you can go for <code>Manager.has(Manager.CUSTOM)</code> where <code>CUSTOM</code> could be an attribute in the <code>Manager</code> class.</p>\n\n<p>Consider memoizing the lookup.</p>\n\n<pre><code>class Manager {\n public final String CUSTOM = \"custom\";\n public boolean has(String key) {\n if (!map.containsKey(key)) map.put(StringUtils.contains(name, key))\n return map.get(key);\n }\n public boolean hasCustom() { return has(CUSTOM); }\n}\n</code></pre>\n\n<p>Finally, if your class takes decisions based on a flag in another class, you might want to rewrite it to reduce coupling. And perhaps use a pattern like <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T16:01:15.613",
"Id": "13842",
"ParentId": "13831",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13832",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T10:27:11.247",
"Id": "13831",
"Score": "2",
"Tags": [
"java",
"strings"
],
"Title": "How to re-factor a common String comparison"
}
|
13831
|
<p>I was trying to find a way to redirect to different pages on authorization and authentication failure. I found <a href="https://stackoverflow.com/a/9018300/887149">this</a> to be a possible solution.</p>
<p>However, I ended with a different solution by myself. It seems to work fine, however, I am not sure if it is the right thing to do.</p>
<p>I created a custom Authorize Attribute that redirects to an action if the request is Authenticated but not Authorized.</p>
<pre><code>public class HandleAuthorizeAttribute : AuthorizeAttribute {
public static string GlobalUnAuthorizationUrl { get; set; }
private const string DefaultUnAuthorizationUrl = "~/Account/UnAuthorized";
private static readonly char[] RolesSeparator = { ',' };
public string UnAuthorizedUrl { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if(httpContext.User.Identity.IsAuthenticated) {
if(string.IsNullOrEmpty(Roles)) {
return true;
} else {
var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
var authorizedRoles = Roles.Split(RolesSeparator);
var common = rolesOfUser.Intersect(authenticatedRoles);
if(common.Count() == 0) {
httpContext.Response.Redirect(
string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
return false;
}
return true;
}
} else {
return false;
}
}
private string ActiveUnAuthorizedUrl {
get {
if(!string.IsNullOrEmpty(UnAuthorizedUrl)) {
return UnAuthorizedUrl;
}
if(!string.IsNullOrEmpty(GlobalUnAuthorizationUrl)) {
return GlobalUnAuthorizationUrl;
}
return DefaultUnAuthorizationUrl;
}
}
}
</code></pre>
<p>Is it alright to redirect to a URL in the middle of a non-action method? Does it have any potential drawbacks?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T12:30:11.757",
"Id": "22318",
"Score": "0",
"body": "If you are confused with how the URL to redirect is formed, just ignore it. Its NOT important!"
}
] |
[
{
"body": "<p>There is something wrong with this Method that makes it a bit confusing.</p>\n\n<blockquote>\n<pre><code> protected override bool AuthorizeCore(HttpContextBase httpContext) {\n if(httpContext.User.Identity.IsAuthenticated) {\n if(string.IsNullOrEmpty(Roles)) {\n return true;\n } else {\n var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);\n var authorizedRoles = Roles.Split(RolesSeparator);\n\n var common = rolesOfUser.Intersect(authenticatedRoles);\n\n if(common.Count() == 0) {\n httpContext.Response.Redirect(\n string.Format(\"{0}?{1}={2}\", ActiveUnAuthorizedUrl, \"requestUrl\", httpContext.Request.Url.AbsoluteUri));\n return false;\n }\n\n return true;\n }\n } else {\n return false;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>first thing that I noticed is that the <code>authorizedRoles</code> variable isn't being used, then I saw that you use a variable that isn't declared or initialized anywhere in your code, <code>authenticatedRoles</code>, I am assuming that these are supposed to be the same variable when I removed the <code>common</code> variable like this</p>\n\n<pre><code> protected override bool AuthorizeCore(HttpContextBase httpContext) {\n if(httpContext.User.Identity.IsAuthenticated) {\n if(string.IsNullOrEmpty(Roles)) {\n return true;\n } else {\n var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);\n var authorizedRoles = Roles.Split(RolesSeparator);\n\n if((rolesOfUser.Intersect(authorizedRoles)).Count == 0) {\n httpContext.Response.Redirect(\n string.Format(\"{0}?{1}={2}\", ActiveUnAuthorizedUrl, \"requestUrl\", httpContext.Request.Url.AbsoluteUri));\n return false;\n }\n return true;\n }\n } else {\n return false;\n }\n }\n</code></pre>\n\n<p>I removed some of the else statements that were making this code a little cluttered as well, I was tempted to remove some of these return statements and replace it with a single bool and then just return at the end of the method, but I think that would have made this code messier and harder to read, so this is what I came up with, and it should do the same thing as your code assuming that those two variables I mentioned earlier are the same variable.</p>\n\n<pre><code>protected override bool AuthorizeCore(HttpContextBase httpContext) {\n if(httpContext.User.Identity.IsAuthenticated) {\n if(string.IsNullOrEmpty(Roles)) {\n return true;\n } \n var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);\n var authorizedRoles = Roles.Split(RolesSeparator);\n\n if((rolesOfUser.Intersect(authorizedRoles)).Count == 0) {\n httpContext.Response.Redirect(\n string.Format(\"{0}?{1}={2}\", ActiveUnAuthorizedUrl, \"requestUrl\", httpContext.Request.Url.AbsoluteUri));\n return false;\n }\n return true;\n } \n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-28T15:06:59.893",
"Id": "61356",
"ParentId": "13838",
"Score": "5"
}
},
{
"body": "<p>By using some early returns, you could eliminate some nesting, and in my opinion, make the code more readable.</p>\n\n<p>In addition, I would ditch the <code>ActiveUnAuthorizedUrl</code> property and make it a function that returns a usable URL. Since \"unauthorized\" is a single English word, the \"A\" should not be capitalized. Prefer \"unauthorized\" to \"unauthorization\", as the latter is not a word.</p>\n\n<p>Is there any reason why those URLs would be set to an empty string instead of <code>null</code>? I would just use the null coalescing operator.</p>\n\n<pre><code>protected override bool AuthorizeCore(HttpContextBase httpContext)\n{\n if (!httpContext.User.Identity.IsAuthenticated) return false;\n if (string.IsNullOrEmpty(Roles)) return true;\n\n var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);\n var authorizedRoles = Roles.Split(RolesSeparator);\n\n var common = rolesOfUser.Intersect(authenticatedRoles);\n\n if (common.Count() == 0)\n {\n httpContext.Response.Redirect(UnauthorizedUrlForContext(httpContext));\n return false;\n }\n\n return true;\n}\n\nprivate string UnauthorizedUrlForContext(HttpContextBase httpContext)\n{\n return string.Format(\"{0}?{1}={2}\",\n UnauthorizedUrl ?? GlobalUnauthorizedUrl ?? DefaultUnauthorizedUrl,\n \"requestUrl\", httpContext.Request.Url.AbsoluteUri));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-29T18:17:56.090",
"Id": "111643",
"Score": "1",
"body": "you could take this one step farther if you invert the other if statement, make it `if (common.Count() != 0) { return true;}` doesn't really add or take away though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-28T21:38:39.480",
"Id": "61402",
"ParentId": "13838",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-07T12:18:59.787",
"Id": "13838",
"Score": "7",
"Tags": [
"c#",
"http",
"asp.net-mvc-3",
"url",
"authorization"
],
"Title": "Custom Authentication Attribute"
}
|
13838
|
<p>I have a button group that looks like this:</p>
<p><img src="https://i.stack.imgur.com/X2ZLA.png" alt="Button group"></p>
<p>The user selects one of the options and they can search for a person based on that criteria.</p>
<p>I wrote a switch statement that populates the URL to make the ajax call to get the data based on the option selected.</p>
<p>However, the down side of this is that every time an option is added or removed, I have to modify the corresponding <code>JavaScript</code>.</p>
<p>Should I re-factor the code to use <code>data-</code> attributes on the <code>a tags</code>, that contain the URL to use? </p>
<pre><code> <li><a href="#" id="btUsername" data-url="SearchByUsername">Username</a></li>
<li><a href="#" id="btLastName" data-url="SearchByLastName">Last Name</a></li>
<li><a href="#" id="btStudentID" data-url="SearchByStudentID">Student ID</a></li>
</code></pre>
<p>Or is that considered bad mojo?</p>
<hr>
<p><strong>What I have working:</strong></p>
<p><strong>HTML</strong></p>
<pre><code><div id="go-btn-group" class="btn-group">
<a class="btn dropdown-toggle btn-success" data-toggle="dropdown" href="#">
<img src="../../img/search.png" alt="Search" />
<span class="caret"></span>
</a>
<ul id="btGo-dropdown" class="dropdown-menu">
<li><a href="#" id="btUsername">Username</a></li>
<li><a href="#" id="btLastName">Last Name</a></li>
<li><a href="#" id="btStudentID">Student ID</a></li>
</ul>
</div>
</code></pre>
<hr>
<p><strong>JS</strong></p>
<pre><code> // All of the list items in the drop down
var $searchOptions = $('#btGo-dropdown li');
$searchOptions.click(function (e) {
var searchBy = '';
// find all of the child links, which are
// the options themselves
var $lis = $searchOptions.find('a');
// remove the active class, if exists
$lis.filter('.active').removeClass('active');
// add the active class to show the criteria selected
var clickedOptionId = e.target.id;
$('#' + clickedOptionId).addClass('active');
// depending on the option selected, populate
// searchBy with the URL to make the ajax call to
switch (clickedOptionId) {
case "btUsername":
searchBy = 'SearchByUsername';
break;
case "btLastName":
searchBy = 'SearchByLastName';
break;
case "btStudentID":
searchBy = 'SearchByStudentID';
break;
default:
}
// create an object that abstracts the search data
var search = {
url: searchBy,
data: { criteria: $search.attr('value') }
};
// make the call to the controller and get the raw Json
var itemModels = $.ajax({
url: search.url,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: search.data,
async: false
}).responseText;
// Use knockout.js to bind the information to the page
viewModel.rebindSearchItems(itemModels);
});
</code></pre>
|
[] |
[
{
"body": "<p>I don't really think putting the URL in your HTML is a good idea; Separating presentation from functionality and all that...</p>\n\n<p>However, instead of using a switch statement, you should be using an object literal to map the URLs to the <code>clickedOptionId</code> key:</p>\n\n<pre><code>var searchURLs = {\n 'btUsername' : 'SearchByUsername',\n 'btLastName' : 'SearchByLastName',\n 'btStudentID' : 'SearchByStudentID'\n};\n\nvar search = {\n url: searchURLs[clickedOptionId],\n data: { criteria: $search.attr('value') }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T18:09:14.520",
"Id": "22327",
"Score": "0",
"body": "Ah, I like that. The reason why I suggested the URL in the HTML is because that's what a lot of people do for autocompletes. I have seen data-autocomplete-url attributes used quite a bit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T17:48:58.540",
"Id": "13847",
"ParentId": "13840",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T15:39:29.777",
"Id": "13840",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "JavaScript switch statement to make an AJAX call"
}
|
13840
|
<p>I made this small class the allows me to navigate large arrays using something like: key1/key2/key3</p>
<p>I made this because I was creating large arrays to hold my classes configs and needed a simpler way of accessing the data.</p>
<p>Here is the project:
- <a href="https://github.com/AntonioCS/settingsManager" rel="nofollow">https://github.com/AntonioCS/settingsManager</a></p>
<p>The class is here:</p>
<pre><code><?php
namespace SettingsManager;
/**
* To ease access of config data
*
*/
class settingsManager {
/**
* Where that data will be held
* @var array
*/
private $_data = array();
/**
* To speed up access
* @var array
*/
private $_cache = array();
/**
* To use or not to use the cache (that is the question!!)
* @var bool
*/
private $_useCache = true;
/**
* Allow the settings to be changed
* @var bool
*/
private $_allowChange = false;
/**
* Initialize the class and set the settings data
*
* @param array $data
* @param bool $allowChange - Default false
* @param bool $useCache - Default true
*/
public function __construct($data, $allowChange = false, $useCache = true) {
$this->_data = $data;
$this->_allowChange = $allowChange;
$this->_useCache = $useCache;
}
/**
* Access the _config property and return specified section
*
* @param string $section - Example: section/config
* @return mixed
*
* @throws OutOfBoundsException
*/
public function get($section) {
if ($this->_useCache && isset($this->_cache[$section]))
return $this->_cache[$section];
return $this->_engine($section);
}
/**
* If allowed this will set the given section to the given value
*
* @param string $section
* @param mixed $value
* @return mixed
*
* @throws OutOfBoundsException
* @throws TryToChangeImmutableObjectException
*/
public function set($section, $value) {
return $this->_engine($section, $value);
}
/**
* Check and see if section exists
*
* @param string $section
* @return bool
*/
public function exists($section) {
try {
$this->get($section);
}
catch (\OutOfBoundsException $e) {
return false;
}
return true;
}
/**
* Clear cache
*/
public function clearCache() {
$this->_cache = array();
}
/**
* Get/Set a value from the settings property
*
* @param string $section
* @param mixed $value
* @return mixed
*
* @throws \OutOfBoundsException
* @throws TryToChangeImmutableObjectException
*/
private function _engine($section, $value = null) {
if ($value && !$this->_allowChange)
throw new TryToChangeImmutableObjectException();
$sections = explode('/',$section);
$tempSectionData = &$this->_data;
foreach ($sections as $currentSection) {
if (!isset($tempSectionData[$currentSection])) {
throw new \OutOfBoundsException($section . ' - ' . $currentSection);
}
$tempSectionData = &$tempSectionData[$currentSection];
}
if ($value) {
$tempSectionData = $value;
if ($this->_useCache && isset($this->_cache[$section]))
unset($this->_cache[$section]);
}
return $tempSectionData;
}
}
class TryToChangeImmutableObjectException extends \Exception {}
</code></pre>
<p>So a simple use case would be:</p>
<pre><code><?php
$_testData = array(
'data' => 1,
'data2' => array(
'date3' => 4
)
);
$object = new SettingsManager\settingsManager($_testData);
echo $object->get('data2/date3'); //Should echo 4
</code></pre>
<p>Any comments or suggestions?</p>
|
[] |
[
{
"body": "<p>I swear I've seen this approach somewhere before, I'll have to see if I can't find that link again. Anyways, a couple of drawbacks of this approach is lack of portability and lack of familiarity. Portability meaning no one can move that code without also taking that class with it. Familiarity meaning not well known. Though I do have to admit, I would love to see PHP natively adopt an xpath navigation style for arrays. Would make life so much easier.</p>\n\n<p>I would steer clear of using method names that are similar to PHP's reserved words. In other words <code>get()</code> would be better as <code>fetch()</code> or <code>query()</code> or something similar. Same for <code>set()</code> and <code>exists()</code>. This helps avoid confusion. The only time \"get\" or \"set\" is generally used is when defining a specific getter or setter such as <code>getPath()</code> or <code>setPath()</code>. <code>_engine()</code> is also oddly named, would expect <code>_parse()</code> or <code>_evaluate()</code> or something similar. But this is all stylistic.</p>\n\n<p>The only \"real\" criticism I have for this bit of code is that occasionally you neglect your braces. These are always important. Please remember them.</p>\n\n<pre><code>if ($this->_useCache && isset($this->_cache[$section]))\n return $this->_cache[$section];\n</code></pre>\n\n<p>The only improvement I can suggest is to abstract your caching to a different class in case you ever decide to change it.</p>\n\n<p>Have you thought about creating relative pathing support? In other words, using your example, you could get the same results by using just \"//date3\"? The previous project I was thinking about did this and I was quite impressed. If there was more than a single match it would return a set of results. It also knew only to look one level deep relative to the array passed to it.</p>\n\n<p>Overall, very impressive though. Sorry I couldn't add more to it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T08:33:00.547",
"Id": "22363",
"Score": "0",
"body": "Thanks for this. I will try to improve where you suggested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:51:28.140",
"Id": "13855",
"ParentId": "13843",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T16:09:15.897",
"Id": "13843",
"Score": "3",
"Tags": [
"php",
"array"
],
"Title": "Small class to manage config data"
}
|
13843
|
<p>I have written a script, introduced <a href="http://hermannn.com/programs/aa/" rel="nofollow">here</a>, that improves the Linux terminal experience. It basically displays the content of the terminals current folder in a nicer way than the 'ls' command does. I use it all the time myself.</p>
<pre><code>#!/usr/bin/perl
###########################################################################
# role: this program shows all files and directories in current location.
# about: its a replacement to the 'ls' command.
# about: different from the ls command, this program is easily cutomize-able and improve-able.
# about: the code is available, readable and change-able on site.
# tofix: the 'length' function fails when there are icelandic letters. have to find another solution.
# tofix: could figure out beforehand what the largest filename is, and then position the file-size category accordingly.
# tofix: also, the header should be either singular or plural, not both.
# tofix: sorting week1 .. week12 does not work correctly.
# tofix: add: type(eg .pm) and line_quantity.
###########################################################################
#get all the pathfiles at current path.
chdir("$ENV{PWD}") or die "$!";
opendir(CDIR, ".") or die "$!";
@pathfiles_and_directories_here=grep {/.*/} readdir CDIR;
foreach(@pathfiles_and_directories_here) {$_="$ENV{PWD}"."/$_";}
close CDIR;
@pathfiles_and_directories_here=grep { !/\/\.{1,2}/ }
@pathfiles_and_directories_here;#dont want '.' and '..'.
#establish pathfiles, paths and files.
@pathfiles_here =grep(! -d,@pathfiles_and_directories_here);
@files_here =grep(! -d,@pathfiles_and_directories_here);
foreach(@files_here) {s/$ENV{PWD}\///g;}
@directories_here= grep( -d,@pathfiles_and_directories_here);
foreach(@directories_here) {s/$ENV{PWD}\///g;}
#sort the pathfiles, files and directories.. alphabetically.
@files_here=sort_alphabetically(@files_here);
$file_quantity=($#files_here+1);
@pathfiles_here=sort_alphabetically(@pathfiles_here);
#seperate directories into if they start with a number or a letter.
my @directories_starting_with_letter= grep /\A\D.*/i, @directories_here;
my @directories_starting_with_number= grep /\A\d.*/, @directories_here;
#sort them accordingly
@directories_starting_with_number=sort_numerically(@directories_starting_with_number);
@directories_starting_with_letter=sort_alphabetically(@directories_starting_with_letter);
#put them back into the directory list.
undef @directories_here;
@directories_here=(@directories_starting_with_number,@directories_starting_with_letter);
$directory_quantity=($#directories_here+1);
#get file_sizes_byte_quantity and file_sizes_human_readable.
map($file_sizes_byte_quantity{$_}=-s ,@pathfiles_here);
%file_sizes_human_readable=make_values_human_readable(%file_sizes_byte_quantity);
#get total file size.
$total_file_size_bytes=get_total_file_size(%file_sizes_byte_quantity);
$total_file_size=make_byte_quantity_human_readable($total_file_size_bytes);
#get type with the most lines.
if($#files_here>=$#directories_here) {$column_with_most_lines=$#files_here;}
if($#files_here<$#directories_here) {$column_with_most_lines=$#directories_here;}
$column_with_most_lines+=2;
system "clear";
#spaces become underscored.
print STDOUT "\033\[32\;4mDirectories \| Files Size \n\033[0m";
for(my $cline=0; $cline<=$column_with_most_lines; $cline++){
my $cpathfile=$pathfiles_here[$cline];
my $cdirectory=$directories_here[$cline];
my $cfilename=$files_here[$cline];$cfilename =~ s/$ENV{PWD}\///g;
my $csize=$file_sizes_human_readable{$cpathfile};
#fs=fillup_string.
my $csize_fs= get_fillup_string($csize, 10);
my $cdirectory_fs= get_fillup_string($cdirectory, 24);
my $directory_quantity_fs=get_fillup_string($directory_quantity, 24);
my $cfilename_fs= get_fillup_string($cfilename, 30);
my $file_size_fs= get_fillup_string($total_file_size, 10);
my $file_quantity_fs= get_fillup_string($file_quantity, 30);
#write the folder.
if($cline<=($#directories_here+0)) {print STDOUT "\033\[1\;33m$cdirectory$cdirectory_fs\033[0m";}
if($cline==($#directories_here+1)) {print STDOUT "\033\[62\;32m------------------------\033[0m"; $cdirectory_fs='';}
if($cline==($#directories_here+2)) {print STDOUT "\033\[62\;32m$directory_quantity"."$directory_quantity_fs\033[0m";}
if($cline>=($#directories_here+3)) {print STDOUT "\033\[62\;32m \033[0m";}
#if at least one of them is still in their listing, then print the seperator, otherwise just spacebar.
if($cline<=$#directories_here || $cline<=$#files_here) {print STDOUT "\033\[32\;3m\|\033[0m";}
else {print STDOUT "\ ";}
#write the file.
if($cline<=($#files_here+0)) {print STDOUT " $cfilename$cfilename_fs$csize$csize_fs\n";}
if($cline==($#files_here+1)) {print STDOUT "\033\[62\;32m------------------------------------------------------------------------------\n\033[0m";}
if($cline==($#files_here+2)) {print STDOUT "\033\[62\;32m $file_quantity$file_quantity_fs$total_file_size$file_size_fs\n\033[0m";}
if($cline>=($#files_here+3)) {print STDOUT "\033\[62\;32m \n\033[0m";}
}
undef $column_with_most_lines;
print STDOUT "\n";
###############################################
#this function has already been copied to modules.
sub get_fillup_string{
my $string=shift;
my $wanted_string_length=shift;
#function 'length' fails when there are icelandic letters. have to find another solution.
my $string_length=length $string;
my $missing_string_length=($wanted_string_length-$string_length);
while($missing_string_length>0) {$fillup_string.=' '; $missing_string_length--;}
my $temp=$fillup_string; undef $fillup_string;
return $temp;
}
###############################################
#this function has already been copied to modules.
#arg: returns the array sent in, sorted alhpabetically.
sub sort_alphabetically{
my @sorted=sort{lc($a) cmp lc($b)} @_;
return @sorted;
}
###############################################
#this function has already been copied to modules.
#arg: returns the array sent in, sorted alhpabetically.
sub sort_numerically{
#my @sorted=sort @_;
#print STDOUT "";
#sleep 1;
my @sorted= sort {$a <=> $b} @_;
return @sorted;
}
##############################################
#this functino will never be copied to modules.
sub make_values_human_readable{
my %file_sizes_byte_quantity=@_;
foreach my $ckey (keys %file_sizes_byte_quantity){
my $cvalue=$file_sizes_byte_quantity{$ckey};
$file_sizes_human_readable{$ckey}=make_byte_quantity_human_readable($cvalue);
}
return %file_sizes_human_readable;
}
####################################################
#this function has not been copied to modules.
sub make_byte_quantity_human_readable{
my $cvalue=shift;
#the size must use sensible units.
if($cvalue<=100000 && $cvalue>0){
$cvalue/=1000;
$cvalue=sprintf("%.1f", $cvalue);
$cvalue="$cvalue".'kb';
}
if($cvalue>100000){
$cvalue/=1000000;
$cvalue=sprintf("%.1f", $cvalue);
$cvalue="$cvalue".'mb';
}
#gb next time.
return $cvalue;
}
###############################################
#this function will never be copied to modules.
sub get_total_file_size{
my %file_sizes_byte_quantity=@_;
$total_file_size=0;
foreach my $ckey (keys %file_sizes_byte_quantity){
$total_file_size+=$file_sizes_byte_quantity{$ckey};
}
my $temp=$total_file_size; undef $temp;
return $total_file_size;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>use strict;</code> and <code>use warnings;</code> are missing. Add them and declare all your variables.</p>\n\n<pre><code>opendir(CDIR, \".\") or die \"$!\";\n</code></pre>\n\n<p>I believe that it’s advised to use variables in modern Perl:</p>\n\n<pre><code>opendir(my $cdir, '.') or die $!;\n</code></pre>\n\n<p>…</p>\n\n<pre><code>@pathfiles_and_directories_here=grep {/.*/} readdir CDIR;\n</code></pre>\n\n<p><code>grep {/.*/}</code> is meaningless since it accepts everything.</p>\n\n<pre><code>@pathfiles_and_directories_here=grep { !/\\/\\.{1,2}/ }\n@pathfiles_and_directories_here;#dont want '.' and '..'.\n</code></pre>\n\n<p>Why didn’t you grep for this pattern right at the beginning? I also dislike the line break here, it makes the lines look like unrelated statements =></p>\n\n<pre><code>my @files_and_dirs = grep { !/^\\.{1,2}/ } readdir $cdir;\n</code></pre>\n\n<p>I’ve also shortened the variable name. The previous name was too long, and prevented, rather than helped, readability. In general, the long variable names make it really hard to discern any structure when looking over your code. Furthmore, the suffix <code>_here</code> after each variable name isn’t conveying useful information.</p>\n\n<p>Next,</p>\n\n<pre><code>foreach(@pathfiles_and_directories_here) {$_=\"$ENV{PWD}\".\"/$_\";}\n</code></pre>\n\n<p>The string concatenation is redundant. Furthermore, this look looks like a place for map.</p>\n\n<pre><code>@files_and_dirs = map { \"$ENV{PWD}/$_\" } @files_and_dirs;\n</code></pre>\n\n<p>But why are you doing this anyway? Further down the road, you remove the file path again from the files and paths.</p>\n\n<pre><code>#establish pathfiles, paths and files.\n</code></pre>\n\n<p>You should explain what the difference between pathfiles and regular files is. The comment, as it stands, doesn’t tell the reader anything interesting.</p>\n\n<p>I’m not convinced that <code>sort_alphabetically</code> and <code>sort_numerically</code> help readability. Just replace the calls by <code>sort</code> with the appropriate comparer, that should be readable enough, and is just as short.</p>\n\n<p>Furthermore, a note on formatting: you need to indent your code properly and remove dead code. This:</p>\n\n<pre><code>sub sort_numerically{\n#my @sorted=sort @_;\n#print STDOUT \"\";\n#sleep 1;\nmy @sorted= sort {$a <=> $b} @_;\nreturn @sorted;\n}\n</code></pre>\n\n<p>cries “sloppy”. Writing clean code is a fundamental part of maintainability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:40:41.210",
"Id": "13875",
"ParentId": "13845",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "13875",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T17:19:28.897",
"Id": "13845",
"Score": "4",
"Tags": [
"perl",
"linux"
],
"Title": "Improved remake of the Linux 'ls' command"
}
|
13845
|
<p>So I decided to create a trait that I could add to my classes that would add a simple way of binding functions to an event, and to fire those events. It ended up going a little further than I expected it to, and I am getting into things I do not normally work with, such as defining an object via a variable, <code>$a = new $b()</code>, and working with anonymous functions. </p>
<p>I don't really have any friends who program so I guess I am just looking for a second, third, or twentieth pair of eyes to look it over and give me some feedback. Below is the everything needed to create events, and over at <a href="https://github.com/mrkmg/phpevents" rel="nofollow">https://github.com/mrkmg/phpevents</a> I have a few examples.</p>
<p>event.php:</p>
<pre><code><?php
trait EventTemplate
{
protected $_event_types = array();
protected $_event_binds = array();
protected $_event_defaults_processed = false;
public function bind($type,$action)
{
$this->_event_check_defaults();
return $this->_event_bind($type,$action);
}
public function unbind($type,$action)
{
$this->_event_check_defaults();
if(!key_exists($action,$this->_event_binds))
return false;
unset($this->_event_binds[$type][array_search($action,$this->_events_binds)]);
return true;
}
public function fire($type)
{
$this->_event_check_defaults();
$this->_event_fire($type);
}
private function _event_bind($type,$action)
{
if(!key_exists($type,$this->_event_types))
{
throw new Exception('Type not defined');
}
if(!isset($this->_event_binds[$type]) || !is_array($this->_event_binds[$type])) $this->_event_binds[$type] = array();
$this->_event_binds[$type][] = $action;
return true;
}
private function _event_check_defaults()
{
if(!$this->_event_defaults_processed) $this->_event_process_defaults();
}
private function _event_set_type($type,$class="Event")
{
$this->_event_types[$type] = $class;
}
private function _event_fire($type)
{
$event = new $this->_event_types[$type]($type,$this);
foreach($this->_event_binds[$type] as $bind)
{
if(is_callable($bind))
$this->_event_fire_closure($bind,$event);
elseif(is_string($bind))
$this->_event_fire_string($bind,$event);
}
}
private function _event_fire_string($string,&$event)
{
call_user_func($string,$event);
}
private function _event_fire_closure($closure,&$event)
{
$closure($event);
}
private function _event_process_defaults()
{
if(isset($this->_event_default_types))
{
foreach($this->_event_default_types as $type=>$class)
{
if(is_int($type))
{
$type = $class;
$class = "Event";
}
$this->_event_set_type($type,$class);
}
}
if(isset($this->_event_default_binds))
{
foreach($this->_event_default_binds as $event=>$methods)
{
foreach($methods as $method)
{
$this->_event_bind($event,function($event) use($method){$this->{$method}($event);});
}
}
}
$this->_event_defaults_processed = true;
}
}
class Event
{
public $type;
public $object;
public $microtime;
public $backtrace;
const PRINT_HTML = 0;
const PRINT_CMD = 1;
public function __construct($type,&$object)
{
$this->type = $type;
$this->object = &$object;
$this->microtime = microtime(true);
$backtrace = debug_backtrace();
array_shift($backtrace);
array_shift($backtrace);
$this->backtrace = $backtrace;
}
/**
* Bill Getas
* http://www.php.net/manual/en/function.debug-backtrace.php#101498
*/
public function print_backtrace($type = self::PRINT_HTML)
{
switch($type)
{
case 0:
array_walk( $this->backtrace,function($a,$b) {print "<br /><b>". basename( $a['file'] ). "</b> &nbsp; <font color=\"red\">{$a['line']}</font> &nbsp; <font color=\"green\">{$a['function']}()</font> &nbsp; -- ". dirname( $a['file'] ). "/";});
break;
case 1:
array_walk( $this->backtrace,function($a,$b) {print "\n".basename( $a['file'] )."\t{$a['line']}\t{$a['function']}()\t".dirname( $a['file'] ). "/";});
break;
default:
throw new Exception('Could not understand type.');
}
}
}
?>
</code></pre>
<p>Here is an example of how it could be used for logging</p>
<p>logexample.php</p>
<pre><code><?php
include('event.php');
class Person {
use EventTemplate;
private $data = array();
private $inited = false;
public function __construct()
{
$this->_event_set_type('get_data');
$this->_event_set_type('save_data');
$this->_event_set_type('write_property');
$this->_event_set_type('delete_data');
}
public function __get($name)
{
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null;
}
public function __set($name,$value)
{
if (array_key_exists($name, $this->data)) {
$this->data[$name] = $value;
$this->fire('write_property');
return true;
}
return false;
}
public function get($id)
{
//GET info from database
$this->data = array(
'name'=>'Test Person',
'email'=>'test@demo.com',
'username'=>'tperson'
);
$this->inited = true;
//Fire the get_data event
$this->fire('get_data');
return true;
}
public function save()
{
//send data to database
//Fire update_data event
$this->fire('save_data');
}
public function delete()
{
//remove data from database
//Fire delete_data event
$this->fire('delete_data');
}
}
function logEv($event)
{
echo 'Event: '.$event->type.' for user: '.$event->object->username;
$event->print_backtrace(Event::PRINT_HTML);
echo "<br /><br />\n";
}
//make a new person
$person = new Person;
//Bind events to logEv function
$person->bind('get_data','logEv');
$person->bind('save_data','logEv');
$person->bind('delete_data','logEv');
$person->bind('write_property','logEv');
//Load an existing user from db
$person->get('id_of_person');
//Change the users users email
$person->email = 'tperson@domain.com';
//Save the user to the db
$person->save();
//Change the users users username
$person->username = 'testp';
//Save the user to the db
$person->save();
//Delete the user from the db
$person->delete();
?>
</code></pre>
<p>This example does not use all the features, but gives you an idea.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T21:13:06.267",
"Id": "22339",
"Score": "0",
"body": "Please provide an example implementation. I find it easier than trying to figure out how something works given no context. Initial comments: All your methods that are prefixed as `_event_*` should probably be part of the event class. Which would remove the necessity of the prefix. You've started a profiling session with `microtime()` but never finished it. TIL: `debug_backtrace()` Though in this context I don't think its necessary. If all you want is the function and its arguments, you can just use `__FUNCTION__` and `func_get_args()` respectively. I'll give it another whack pending example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T12:56:06.197",
"Id": "22369",
"Score": "0",
"body": "I am not using microtime to profile a session, I am using it to give the event handler a timestamp, but more accurate than seconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T23:23:21.713",
"Id": "22436",
"Score": "1",
"body": "Generalised code like this is hard to follow without documentation to give it context. I would recommend getting into the habit of writing phpdoc (http://en.wikipedia.org/wiki/PHPDoc) blocks for every function."
}
] |
[
{
"body": "<p>I'm not sure I really understand the purpose of this code. From the looks of it, you are recreating the factory design pattern but in a more complicated fashion. Not that I can be sure that this statement is true, your code is pretty hard to follow. But that's what comes from using variable-variables and variable-functions. I'll go over the code and give you some suggestions, but I can't get too specific about the implementation because I'm unsure if I'm understanding it completely. If you are actually trying to create a class that creates other classes and uses their functions, then I would definitely take a look at the factory design pattern. If not, my apologies for misunderstanding your post.</p>\n\n<p><strong>Suggestions</strong></p>\n\n<p><strong>Disclaimer:</strong> I know this was just an example for usage, but its all I have to go on. So my apologies in advance if I bash this code rather harshly. Take these suggestions with an open mind and try to see how they relate to your actual code.</p>\n\n<p>First of all, please, for the love of god, always, always, always use braces in your statements. For a while there, when you were setting the <code>$_event_binds[ $type ]</code> array, I thought that if statement just went on to the end of the function. Lack of braces leads to difficult to read code. Difficult to read code leads to hard to maintain code. Hard to maintain code leads to a headache. Its a vicious cycle. Speaking of that if statement though: Why are you checking if its an array? I can find no other places where this is set for it to have magically become anything else. I would think just checking to see if it is set would be enough.</p>\n\n<pre><code>if( ! isset( $this->_event_binds[ $type ] ) ) {\n $this->_event_binds[ $type ] = array();\n}\n</code></pre>\n\n<p>What is the purpose of <code>_event_check_defaults()</code>? This method is called from public methods <code>bind()</code>, <code>unbind()</code>, and <code>fire()</code>. Why? After the first run through nothing ever happens again. So even if this should be run, it should only be done once. The fact that this method is called in not one, but three different methods, and methods that are likely to see a lot of use, is not good. Not that anything happens during the first run through anyways, there are no default arrays. At least not in the example you gave me. Nor are those defaults defined as class properties anywhere, which they should be to avoid them falling into the public scope by accident, which I'm assuming you want to avoid seen as how you prefixed them like they are supposed to be private. And since you are setting them in the class properties, that also means changing that <code>isset()</code> to an <code>empty()</code> check instead. If this should only ever be run once, and should be done before anything else, it should be declared in the constructor where you are assured of that. Which also means no more need of the <code>$_event_defaults_processed</code> property, nor the <code>_event_check_defaults()</code> method wrapper, and it also means you will have to define those two arrays in the constructor as well. But why is it necessary at all? Just define default values to the <code>$_event_types</code> and <code>$_event_binds</code> and append onto those as needed. No need to take up processing power to do something you can manually do quicker and easier.</p>\n\n<p>If you end up removing the <code>_event_check_defaults()</code> method, then you will want to look at combining the <code>_event_*</code> prefixed methods with their non prefixed wrappers where applicable.</p>\n\n<p>I did not realize at first that this was a trait. I understand why traits would be ideal here, but I don't think this implementation is an accurate depiction of one. I admit, I'm not 100% on the the whole traits idea myself, but from my understanding they are used to enhance code reuse. So the idea behind it is that you give it code that is going to be run every single time it is used and then cover any specifics in the class that uses it. Right now it looks as if you are doing it backwards. I see no difference between this trait and a normal parent class. Again, not 100% on traits, I just think you might want someone else to take a look at this specifically to determine if its a good example of a trait.</p>\n\n<p>Why do so many of your methods, <code>bind()</code> for example, return TRUE? I can't find anywhere where you use these return values. The only reason I could foresee needing a boolean return value on these kinds of methods is if I were trying to judge the method's success, in which case you need to return FALSE at some point. In some cases you are throwing an error as well. There's nothing wrong with that, I just don't see why the return is necessary even in this instance.</p>\n\n<p>What is the purpose of <code>$id</code> in your <code>get()</code> method? I know this is an example, but was there supposed to be a purpose for this? You pass it as a parameter then never use it. I'm assuming it is meant to fetch the appropriate table from the database, but just wanted to clarify. Again, why does this return true?</p>\n\n<p>Why does your setter return TRUE/FALSE? You don't verify that it has been set, so I see no purpose.</p>\n\n<p>Your getter should not return NULL, it should throw an error. Returning NULL by default could cause problems. What if the actual value of that property is null? You will have no way of verifying that it is actually being returned. Or if you are using the NULL value to determine if it is a valid property, then you will be surprised when it tells you a property that should be accessible isn't just because it hasn't been set yet. Throwing an error ensures that your code does not try accessing properties you don't want it to and ensures you are made aware of the difference between an inaccessible property and an unset one.</p>\n\n<p>I hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:06:32.710",
"Id": "13879",
"ParentId": "13850",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:23:12.777",
"Id": "13850",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "PHP 5.4 Event System, just looking for general feedback"
}
|
13850
|
<p>I have a rather large javascript array of objects that I am transforming into an HTML table. Each object in the array looks like:</p>
<pre><code>{
name:'Document Title',
url:'/path/to/document.html',
categories:['Some Category'],
protocols:['ID Number','Another ID'],
sites:['Location']
}
</code></pre>
<p>It's possible to have multiple categories, protocols, and sites, hence why they are in arrays.</p>
<p>The jQuery I've written to do the transformation is:</p>
<pre><code>var table = $('<table class="table table-bordered table-condensed table-striped data-table">'),
tbody = $('<tbody>'),
thead = $('<thead><tr><th width="100">Protocol</th><th>Report Name</th><th width="140">Category</th><th width="220">Site</th></tr></thead>');
$.each(reports,function(i,report) {
var tr = document.createElement('tr'),
cellProtocol = document.createElement('td'),
cellName = document.createElement('td'),
cellCategory = document.createElement('td'),
cellSite = document.createElement('td'),
reportLink = document.createElement('a');
// If property doesn't exist, set to empty array
report.protocols = report.protocols || [];
report.sites = report.sites || [];
report.categories = report.categories || [];
reportLink.setAttribute('href',report.url);
reportLink.appendChild(document.createTextNode(report.name));
cellProtocol.appendChild(document.createTextNode(report.protocols.join(', ')));
cellName.appendChild(reportLink);
cellCategory.appendChild(document.createTextNode(report.categories.join(', ')));
cellSite.appendChild(document.createTextNode(report.sites.join(', ')));
tr.appendChild(cellProtocol);
tr.appendChild(cellName);
tr.appendChild(cellCategory);
tr.appendChild(cellSite);
tbody[0].appendChild(tr);
});
$('#report-table').empty().append(table.append(thead,tbody));
</code></pre>
<p>It currently takes about 2 seconds to transform 4200 objects into table rows and display the finished table. In the <code>$.each</code> loop I am using <code>appendChild</code> as I understand it is faster than using <code>innerHTML</code> or <code>$.append</code>.</p>
<p>Are there any improvements here I can make in performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T20:09:30.063",
"Id": "22333",
"Score": "0",
"body": "Did you take a look at documentFragment (which is known to be faster) ? Usage : https://developer.mozilla.org/en/DOM/document.createDocumentFragment and article talking about it : http://ejohn.org/blog/dom-documentfragments/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T18:29:14.927",
"Id": "22398",
"Score": "0",
"body": "You didn't mention which browser. http://www.quirksmode.org/dom/innerhtml.html (which, I know, it's old) would imply that you need to use innerHTML to load all of your content. But using the handy tests on the page, I found that using DOM node creation, etc. was fastest in Chrome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T03:01:40.440",
"Id": "22411",
"Score": "1",
"body": "$.each is actually quite slow too http://jsperf.com/for-vs-each-vs-each/3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:26:26.940",
"Id": "22481",
"Score": "0",
"body": "A jsPerf would be good for something like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T12:14:51.737",
"Id": "22502",
"Score": "0",
"body": "Repeating jsanc623's remark: Why not do the HTML server-side? As the matter of the fact: Why are you using AJAX here in the first place?"
}
] |
[
{
"body": "<p>If this is on an intranet, with similar machines running this JS, then 2 seconds is fairly ok for 4,200 records...but if its on the internet, you might want to think about doing this server side and just ajax'ing the server generated table code via js...someone running this on an iPad would probably take considerably longer to generate 4,200 records vs someone running an overclocked i7 machine for instance. Just food for thought. </p>\n\n<p><strike>As for actual improvements to the code, I don't really see any glaring items...although someone else might want to pipe in.</strike> Seems someone already piped in :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T18:34:52.157",
"Id": "22399",
"Score": "0",
"body": "Valid point; this timing was local on my own development machine. Potential end users include outside users accessing it via the internet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T15:37:35.257",
"Id": "22507",
"Score": "0",
"body": "@jackwanders - which would add to the time it would take to parse everything...if a node somewhere between your system and the user is overloaded - it's going to take a whole lot more than 2 seconds, especially considering most sites take that long to load nowadays."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T18:00:52.227",
"Id": "13881",
"ParentId": "13852",
"Score": "2"
}
},
{
"body": "<p>This looks like something you'd want to do server-side, mainly because you can cache the result. So for every request but the first one you're essentially just downloading a file.</p>\n\n<p>If you can't do it server-side, here are a few improvements:</p>\n\n<ul>\n<li>Ditch jQuery. If you are looking for performance you don't want to be doing dozens of checks for bugs in browsers that you don't support anyway.</li>\n<li>Don't use <code>forEach</code>, <code>each</code>, etc - that's the slowest possible way to loop through the objects. Instead try <code>for (i = 0; report = reports[i]; i++)</code>, which will be performant on an array this large. Or, more simply, <code>for (i = 0, len = reports.length; i < len; i++)</code>, because most browsers have optimized the hell out of it.</li>\n<li>Ensure that the objects always have <code>categories</code>, <code>protocols</code>, and <code>sites</code> properties, even if they are empty arrays, so that you don't have to waste time filling in defaults. Alternatively, if there are a large number of empty arrays and sending them all would be a waste of bandwidth, you can still optimize this by skipping the default checks and replacing <code>report.protocols.join(', ')</code> with <code>report.protocols ? report.protocols.join(', ') : ''</code>, which avoids creating unnecessary arrays.</li>\n<li>This is very minor, but caching globals could help. So, <code>var createElement = document.createElement;</code>. There is a catch though, which is that browsers have heavily optimized built-in objects like <code>document</code> and <code>Math</code>, and in some cases this doesn't carry over to local pointers. So, strangely enough, in some browsers a local pointer to <code>document</code> will actually be slower than the global pointer to <code>document</code>. But I've found that this is not usually the case, and therefore caching globals is still an optimization even when the globals are built-in objects.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T01:32:06.593",
"Id": "14034",
"ParentId": "13852",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T19:55:02.220",
"Id": "13852",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"performance",
"array"
],
"Title": "Improve speed of object-to-html transform in javascript?"
}
|
13852
|
<p><strong>Windows PowerShell</strong></p>
<p><a href="/questions/tagged/powershell" class="post-tag" title="show questions tagged 'powershell'" rel="tag">powershell</a> is an interactive shell and scripting language originally included with Microsoft Windows 7 and Microsoft Windows Server 2008 R2 and above. It includes a command-line shell (<a href="https://technet.microsoft.com/en-us/library/bb978526.aspx" rel="nofollow noreferrer">Windows PowerShell</a>) for interactive use, an underlying scripting environment to run scripts away from the command-line and a GUI script editing / debugging environment (<a href="https://technet.microsoft.com/en-us/library/dd819514.aspx" rel="nofollow noreferrer">Windows PowerShell ISE</a>). See: <a href="https://technet.microsoft.com/en-us/library/hh857337.aspx" rel="nofollow noreferrer">Getting Started with Windows PowerShell</a>.</p>
<p>As a language, <a href="/questions/tagged/powershell" class="post-tag" title="show questions tagged 'powershell'" rel="tag">powershell</a> has syntax for literal arrays and hashtables, support for regexes, pattern matching and string expansion. It's built on the .NET framework so it has Unicode support, can be locale/culture aware, and can access .NET framework methods directly.</p>
<p>As a command-line shell, it is designed around cmdlets named in the form {Verb}-{Noun}, intending that the same kinds of commands work across many domains. E.g. <code>Get-Date</code> returns the current date, and <code>Get-Process</code> returns an array of objects representing running processes which can be piped to other commands that work with process objects. Many commands and keywords have short aliases to reduce typing.</p>
<p>As a system management environment, Windows components and Microsoft products have been extended to provide native PowerShell interfaces as part of creating a unified managing system for Windows systems, including:</p>
<ul>
<li>EventLogs, Task Scheduler, WMI, COM objects.</li>
<li><a href="http://technet.microsoft.com/en-us/library/hh852274.aspx" rel="nofollow noreferrer">Active Directory</a>, <a href="http://technet.microsoft.com/en-us/library/hh848559.aspx" rel="nofollow noreferrer">Hyper-V</a>, <a href="http://technet.microsoft.com/en-us/library/hh867899.aspx" rel="nofollow noreferrer">IIS</a>, <a href="http://technet.microsoft.com/en-us/library/dn249523.aspx" rel="nofollow noreferrer">Remote Desktop Services and other Roles and Features</a></li>
<li><a href="http://technet.microsoft.com/en-us/library/bb123778(v=exchg.150).aspx" rel="nofollow noreferrer">Exchange Server</a></li>
<li><a href="http://technet.microsoft.com/en-us/library/hh245198.aspx" rel="nofollow noreferrer">SQL Server</a></li>
<li><a href="http://technet.microsoft.com/en-us/sharepoint/jj672838.aspx" rel="nofollow noreferrer">SharePoint</a></li>
<li><a href="http://technet.microsoft.com/en-us/library/f5f906a0-24ad-4888-bb10-6a783cc56473(v=crm.6)" rel="nofollow noreferrer">Dynamics CRM</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj156055.aspx" rel="nofollow noreferrer">Windows Azure cloud services</a></li>
<li><a href="http://technet.microsoft.com/en-us/magazine/hh750396.aspx" rel="nofollow noreferrer">Office 365</a></li>
<li>As well as the usual scripting tasks — working with files/folders, user accounts, string manipulation, running external programs, etc.</li>
</ul>
<p>Third-party vendors also offer PowerShell integration, including:</p>
<ul>
<li><a href="https://www.vmware.com/support/developer/PowerCLI/" rel="nofollow noreferrer">VMware vSphere PowerCLI</a></li>
</ul>
<p><a href="/questions/tagged/powershell" class="post-tag" title="show questions tagged 'powershell'" rel="tag">powershell</a> takes the Unix idea of piping text between programs and manipulating text, and enhances it by piping .NET object instances around. Because objects carry type information (e.g. dates and times), and complex state (e.g. properties and methods, hashtables, parsed XML data, live network sockets) this makes many tasks easy that would be difficult or impractical to do by passing text between programs.</p>
<p>Along with interacting with the PowerShell console or the PowerShell ISE, there are also several 3rd party IDE options including Sapien's <a href="https://www.sapien.com/software/primalscript" rel="nofollow noreferrer">PrimalScript ISE</a>.</p>
<p><strong>Example Usage</strong></p>
<pre><code># List all processes using > 100 MB of PagedMemory in descending sort order (v3_
C:\PS> Get-Process | Where PagedMemorySize -GT 100MB | Sort -Descending
# PowerShell can handle numbers and arithmetic
C:\PS> (98.6 - 32) * 5/9
37
# Production orientation allows experimentation and confirmation
C:\PS> Get-ChildItem C:\Users\John *.bak -r |
Where {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} |
Remove-Item -WhatIf
What if: Performing operation "Remove File" on Target "C:\Users\John\foo.bak"
C:\PS> Get-Process iexp* | Stop-Process -Confirm
Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "iexplore (7116)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is Y):
</code></pre>
<p><strong>Common Gotchas</strong></p>
<p>Executing EXEs via a path with spaces requires quoting the path and the use of the call operator - <code>&</code></p>
<pre><code>C:\PS> & 'C:\Program Files\Windows NT\Accessories\wordpad.exe'
</code></pre>
<p>Calling PowerShell functions does not require parenthesis or comma separated arguments. PowerShell functions should be called just like a cmdlet. The following examples demonstrates the problem caused by this issue e.g.:</p>
<pre><code>C:\PS> function Greet($fname, $lname) {"My name is '$lname', '$fname' '$lname'"}
C:\PS> Greet('James','Bond') # Wrong way to invoke this function!!
My name is '', 'James Bond' ''
</code></pre>
<p>Note that both 'James' and 'Bond' are packaged up as a single argument (an array) that is passed to the first parameter. The correct invocation is:</p>
<pre><code>C:\PS> Greet James Bond
My name is 'Bond', 'James' 'Bond'
</code></pre>
<p>Note that in PowerShell 2.0, the use of <code>Set-StrictMode -version 2.0</code> will catch this type of problem.</p>
<p><strong>Extensible functionalities</strong></p>
<p>One of the great features of PowerShell is its extensibility:
we can add functionality by importing modules which are package of cmdlets, functions and aliases specialised on a particular domain (such as database administration, virtual machine administration etc.).</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="https://technet.microsoft.com/en-us/scriptcenter/powershell.aspx" rel="nofollow noreferrer">Microsoft Windows PowerShell Home</a></li>
<li><a href="https://devblogs.microsoft.com/powershell/" rel="nofollow noreferrer">Windows PowerShell Team Blog</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/dd835506%28v=VS.85%29.aspx" rel="nofollow noreferrer">MSDN Windows PowerShell</a></li>
<li><a href="http://poshcode.org/" rel="nofollow noreferrer">PowerShell Code Repository</a></li>
<li><a href="https://devblogs.microsoft.com/powershell/new-v3-language-features" rel="nofollow noreferrer">New features in Powershell version 3</a></li>
<li><a href="https://technet.microsoft.com/en-us/library/hh857339.aspx" rel="nofollow noreferrer">New features in Powershell version 4</a></li>
<li><a href="https://technet.microsoft.com/en-us/library/hh857339.aspx#BKMK_new50" rel="nofollow noreferrer">New features in Powershell version 5</a></li>
<li><a href="https://en.wikipedia.org/wiki/PowerShell" rel="nofollow noreferrer">PowerShell Wikipedia Article</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-20T08:51:49.777",
"Id": "13860",
"Score": "0",
"Tags": null,
"Title": null
}
|
13860
|
Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and CIM enabling management of remote Linux systems and network devices.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T08:51:49.777",
"Id": "13861",
"Score": "0",
"Tags": null,
"Title": null
}
|
13861
|
<p>I have a PhoneGap application that I wrote some time ago. After looking Doug Crockford's video seminar <a href="http://www.youtube.com/watch?v=hQVTIJBZook" rel="nofollow"><em>JavaScript: The Good Parts</em></a>.</p>
<p>I was just wondering if the code could be improved for better maintainability and readability as it now could be hard for others to understand what's happening. Maybe taking advantage of using the module pattern and closures?</p>
<p>I know there's a big chunk of code in this post, so any help on implementing these patterns is well appreciated.</p>
<p>I'm pretty much following Rohit Ghatol's book <em>Beginning PhoneGap</em> code examples and design. That is, my app has the following execution order:</p>
<pre><code>document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function() {
// Initiate the application
bind();
});
}
function bind() {
initiateDatabases();
initiateDashboardPage();
initiateReserveBtn();
initiateReservePage();
initiateCentersBtn();
initiateCentersPage();
initiateDonationsBtn();
initiateDonationsPage();
initiateSettingsBtn();
initiateSettingsPage();
initiateQuestionsBtn();
initiateQuestionsPage();
initiateInformationBtn();
initiateInformationPage();
initiateMapPage();
}
</code></pre>
<p>In each of those <code>initiateX()</code> function I bind different jQuery Mobile page and button handling events, which will then call other functions. For example, <code>initiateReservePage()</code> looks like this:</p>
<pre><code>function initiateReservePage() {
// When reserve page is shown
$('#reserve-page').live('pageshow', function () {
populateReserveList();
});
var did_user_swipe = false;
// Bind mousedown/mouseup/mousemove events to 'refresh reserve' button
$('#refreshReserveBtn').bind('vmousedown', function () {
did_user_swipe = false;
}).bind('vmousemove', function() {
did_user_swipe = true;
}).bind('vmouseup', function (e) {
if(!did_user_swipe && e.which === 0) {
// DOWNLOAD THE RESERVE
downloadReserve();
}
});
did_user_swipe = null;
}
</code></pre>
<p>As it could be seen, that function either call <code>downloadReserve()</code> or <code>populateReserve()</code> function depending on the event being fired.</p>
<p>Could some sort of pattern be used here to combine those 2 functions?</p>
<p>Here are those 2 functions in question:</p>
<pre><code>function downloadReserve() {
// URL to download reserve from
var reserveURL = 'http://myremotesite.com/file.xml';
try {
$.ajax({
type: 'GET',
url: reserveURL,
dataType: "xml",
contentType: "text/xml; charset=utf-8",
beforeSend: function (XMLHttpRequest) {
$.mobile.loadingMessage = 'Loading...';
$.mobile.showPageLoadingMsg();
},
complete: function(jqXHR) {
$.mobile.hidePageLoadingMsg();
},
success: function(data, textStatus, jqXHR) {
// This is a global variable to cache the fetched data
cachedReserve = [];
// Reserve descriptions for different states
var reserveDescription = ['Critical', 'Adequate', 'Normal', 'Good'],
// Reserve item from XML
$item,
// Group for item
group = '',
// State for item
state = '',
// Description for item
desc = '',
// Reserve object for item
tmpReserveObj = {};
$(data).find('item').each(function() {
$item = $(this);
group = $item.find('group').text();
state = $item.find('state').text();
if (state == 'A') {
desc = reserveDescription[0];
} else if (state == 'B') {
desc = reserveDescription[1];
} else if (state == 'C') {
desc = reserveDescription[2];
} else if (state == 'D') {
desc = reserveDescription[3];
}
// Create a temporary reserve object
tmpReserveObj = { 'group':group, 'state':state, 'desc':desc };
// Push temporary object into global cached array
cachedReserve.push(tmpReserveObj);
});
$item = null;
group = null;
state = null;
desc = null;
tmpReserveObj = null;
reserveDescription = null;
// Insert reserve array into local storage and populate list
insertReserve(cachedReserve);
},
error: function (xhr, ajaxOptions, thrownError){
// Show an alert here
}
});
} catch (e) {
console.log('Error while performing ajax get call to download the reserve ' + e);
}
reserveURL = null;
}
</code></pre>
<p>...and...</p>
<pre><code>function populateReserveList() {
try {
// Get the reserve from local storage
var reserve = JSON.parse(window.localStorage.getItem('reserve'));
} catch (e) {
alert('error getting the reserve from local storage: ' + e);
return false;
}
if (reserve !== null && reserve.length > 0) {
// If more than a week old
if (isReserveDataOld()) {
$.mobile.hidePageLoadingMsg();
// Show alert box to ask user whether to download reserve again
navigator.notification.confirm(
'Your downloaded reserve seems to be old. Do you want to download it again?',
function(buttonIndex) {
// If 'OK' button clicked
if (buttonIndex === 2) {
// DOWNLOAD THE RESERVE AGAIN
downloadReserve();
}
},
'Download the reserve',
'Cancel,OK');
} else {
// Reserve list container
var list = document.getElementById('reserveList'),
// Timestamp for when reserve was inserted into local storage
timestamp = '',
// Date based on timestamp
_date;
// Empty the reserve list container and remove all event handlers from child elements
$(list).empty();
try {
timestamp = window.localStorage.getItem('reserveInserted');
timestamp = ((timestamp != null && timestamp != 'undefined' && timestamp.length > 0) ? timestamp : 0);
_date = new Date(timestamp - 0);
} catch (e) {
alert('Error while getting reserveInserted from local storage ' + e);
}
var infoBarText = '<h3>Downloaded' +
'<span>' +_date.getDate() + '. ' + monthNames[_date.getMonth()] + 'ta ' + _date.getFullYear()+ '</span></h3>';
var infoBarElem = document.createElement('div');
infoBarElem.setAttribute('id', 'infoBar');
infoBarElem.className = 'downloaded';
infoBarElem.innerHTML = infoBarText;
list.appendChild(infoBarElem);
infoBar = null;
infoBarText = null;
var reserveDetailsContainer = document.createElement('div');
var reserveListContainer = document.createElement('div');
var reserveHeadingElem = document.createElement('h3');
reserveDetailsContainer.className = 'detailsContainer';
reserveListContainer.className = 'listContainer';
list.appendChild(reserveDetailsContainer);
list.appendChild(reserveListContainer);
// Global variable to cache reserve data
cachedReserveData = [];
var htmlData = '';
var reserveHeadingContainer;
var did_user_swipe = false;
// Iterate through all reserve items
for ( var index = 0 ; index < reserve.length ; index++ ) {
var item = reserve[index];
cachedReserveData.push(item);
reserveHeadingContainer = reserveHeadingElem.cloneNode(false);
reserveHeadingContainer.setAttribute('id', index);
reserveHeadingContainer.setAttribute('name', item.group.toLowerCase());
htmlData = 'Group: ' + item.group + '<span>Show group</span>';
reserveHeadingContainer.innerHTML = htmlData;
reserveHeadingContainer.className += ' state_' + item.state;
reserveListContainer.appendChild(reserveHeadingContainer);
$(reserveHeadingContainer).bind('vmousedown', function(event) {
did_user_swipe = false;
}).bind('vmousemove', function () {
did_user_swipe = true;
}).bind('vmouseup', function(e) {
// If triggered manually or by user
if (passDataBetweenPages == 'trigger' || (!did_user_swipe && e.which == 0)) {
try {
var id = parseInt($(this).attr('id'));
// Empty the reserve details container and remove all event handlers from child elements
$(reserveDetailsContainer).empty();
htmlData = '<div>' +
'<p>' +cachedReserveData[id].desc+ '</p>' +
'</div>';
// Replace contentContainer's content with clicked list items's data
reserveDetailsContainer.innerHTML = htmlData;
var newHeading = $(this).clone();
newHeading.find('span').html('State');
$(reserveDetailsContainer).prepend(newHeading);
$(reserveListContainer).find('h3.active').removeClass('active');
$(this).addClass('active');
newHeading = null;
// Scroll to top
scroll(0, 0);
} catch (e) {
alert('Error while clicking listItem with id = ' + $(this).attr('id') + ' ' + e);
}
}
});
}
// Get group from local storage
var group = getItemFromLocalStorage('group');
// Open corresponding group or if not found, the first item on the list
if (group && group != '0') {
var listItem = $(reserveListContainer).find('h3[name="' +group+ '"]').get(0);
passDataBetweenPages = 'trigger';
$(listItem).trigger('vmouseup');
passDataBetweenPages = null;
listItem = null;
} else {
var listItem = $(reserveListContainer).find('h3').get(0);
passDataBetweenPages = 'trigger';
$(listItem).trigger('vmouseup');
passDataBetweenPages = null;
listItem = null;
}
group = null;
}
} else {
$.mobile.hidePageLoadingMsg();
// Show alert box to ask user whether to download the reserve
navigator.notification.confirm(
'The reserve has not been downloaded yet. Do you want to download it now?',
function(buttonIndex) {
console.log(buttonIndex);
if (buttonIndex === 2) {
// DOWNLOAD THE RESERVE
downloadReserve();
}
},
'Download the reserve',
'Cancel,OK');
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think your code looks fine (except for <code>populateReserveList</code>).</p>\n\n<ul>\n<li>I would look into replacing <code>.live()</code> calls with <code>.on()</code> calls as <code>.live()</code> has been deprecated since a while.</li>\n<li>Your <code>success</code> function is so large, it ought to be a function on it's own</li>\n<li><p>You could put the state -> description mapping in an object</p>\n\n<pre><code>var stateDescriptionMap = { 'A' : 0 , 'B' : 1 , 'C' : 2 , 'D' : 3 }\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>desc = reserveDescription[ stateDescriptionMap[ state ] ];\n</code></pre></li>\n<li><p>I am not sure what you want to accomplish with ( your code should work without this? )</p>\n\n<pre><code> $item = null;\n group = null;\n state = null;\n desc = null;\n tmpReserveObj = null;\n reserveDescription = null;\n</code></pre></li>\n<li><p><code>populateReserveList</code> is far too large and has to be broken up in logical parts.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T15:41:34.653",
"Id": "38329",
"ParentId": "13862",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T09:17:58.993",
"Id": "13862",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"design-patterns",
"mobile",
"phonegap"
],
"Title": "Improving PhoneGap/JavaScript application"
}
|
13862
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.