body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>CoffeeScript is an alternative syntax for JavaScript. Unlike other languages that compile to JavaScript, it deliberately retains the exact semantics of JavaScript. Furthermore, it provides syntax help to enable you to write correct, verbose, JS code concisely.</p>
<p><a href="http://coffeescript.org/" rel="nofollow">CoffeeScript.org</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T09:13:36.897",
"Id": "3864",
"Score": "0",
"Tags": null,
"Title": null
}
|
3864
|
CoffeeScript is a little language that compiles into JavaScript. Underneath all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T09:13:36.897",
"Id": "3865",
"Score": "0",
"Tags": null,
"Title": null
}
|
3865
|
<p>In my model, I have things called Reports that have known workflow associated with them. </p>
<p>I've got a requirement to output at which state a report currently is.</p>
<pre><code>public abstract partial class Report{
public virtual string StateStatus(){
if (Check.IsSuccessful) return "Approved";
if (Check.AreClarificationsSent) return "Clarifications";
if (Check.IsInProgress) return "Check in progress";
if (IsTemplateSent) return "Sent";
if (IsReceived) return "Received";
return "Not received";
}
...
}
</code></pre>
<p>I dislike this method. It won't break, but leaves some nausea in my head, just doesn't feel right.</p>
<p>Got any recommendations for improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T13:53:39.423",
"Id": "5805",
"Score": "0",
"body": "Are those calculated properties you are checking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T14:39:01.127",
"Id": "5808",
"Score": "0",
"body": "@ChaosPandion For calculating something, I'm always using methods. Properties are static, with already known values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T16:23:40.947",
"Id": "5812",
"Score": "0",
"body": "can it so happen, that all Check.xxx properties are true? If not is there a logic, which implements radio-button-like functionality - i.e. changing one of these changes the rest?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T20:57:07.720",
"Id": "5822",
"Score": "0",
"body": "@Sunny No, Check.IsSuccessful and Check.IsInProgress are mutually exclusive. However - Check.IsInProgress and Check.AreClarificationsSent can be true simultaneously. StateStatus() method should give priority to \"Clarifications\". What exactly that changes, what are You thinking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T13:07:42.937",
"Id": "5849",
"Score": "0",
"body": "I was thinking for a Status property, which changes whenever some of these change - i.e. move the proper logic where it belongs. It could be not good fit for you. But check my answer for another possible solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T10:11:19.197",
"Id": "5874",
"Score": "0",
"body": "@Sunny I'm quite sure this is just an awkward requirement and in reality - there is no real report status. State machine seems to be inappropriate here."
}
] |
[
{
"body": "<p>A state machine. This tidies up all of those messy methods into a single property which stores the current state of your object. The downside to this is you'll need to tidy up your other objects, too...</p>\n\n<pre><code>public partial class Report {\n\n public enum State {\n NotReceived = 0,\n Received = 1,\n TemplateSent = 2,\n InProgress = 3,\n ClarificationSent = 4,\n Successful = 5\n }\n\n public State Status { get; protected set; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T15:07:21.900",
"Id": "5809",
"Score": "0",
"body": "Have thought about this. #1 InProgress means that report check is in progress and not report itself. I don't want to pull out knowledge about check outside of it. #2 this increases coupling. I really don't want to think about sending report template and processing clarifications simultaneously that this enum would force me to. So I kind a dislike this approach equally much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T14:56:49.927",
"Id": "3875",
"ParentId": "3872",
"Score": "1"
}
},
{
"body": "<p>Add check state enum and create Check.State property.</p>\n\n<p>Same for the report.</p>\n\n<p>Then your method will look like (pseudo):</p>\n\n<pre><code>{\n var ret = report.State.ToString();\n if (Check.State != CheckState.Unprocessed)\n {\n ret = Check.State.ToString();\n }\n\n return ret;\n}\n</code></pre>\n\n<p>or (ugly):</p>\n\n<pre><code>return (Check.State == CheckState.Unprocessed) ? State.ToString() : Check.State.ToString();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T16:32:31.283",
"Id": "3877",
"ParentId": "3872",
"Score": "1"
}
},
{
"body": "<p>It seems that you are wanting your <code>Check</code> enum to be able to provide a little more information for you without the messiness of the <code>if-then</code> clutter. What about combining the status strings with the enumerator? Something like: </p>\n\n<pre><code>public class CheckStatus{\n public static readonly CheckStatus \n IsSuccessful = new CheckStatus { Value = \"Approved\" },\n AreClarificationsSent = new CheckStatus { Value = \"Clarifications\" },\n IsInProgress = new CheckStatus { Value = \"Check in progress\" },\n IsTemplateSent = new CheckStatus { Value = \"Sent\" },\n IsReceived = new CheckStatus { Value = \"Received\" },\n NotReceived = new CheckStatus { Value = \"Not Received\" };\n\n private CheckStatus() { }\n public string Value{ get; private set; }\n}\n</code></pre>\n\n<p>Very easy to maintain and puts the minor implementation details behind the purpose of the <code>Check</code> enumerator. Provides much the same benefit of an enumeration. I would have liked to make this a struct, but I would not (without going into IL) have a parameterless private ctor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T20:52:43.200",
"Id": "5821",
"Score": "0",
"body": "This ain't bad stuff. Using class enums myself. But that is still enum which couples all these vaguely related processes together too tightly. Also - `Check` is object for itself - it is responsible for checking [un]success of report. `IsTemplateSent`, `IsReceived` flags belong to report not its check (report template is generated, then - received filled out and that triggers report check to be available). It makes no sense for Check to be responsible for state of Report."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T20:58:34.127",
"Id": "5823",
"Score": "0",
"body": "@Arnis L. - Now what if we renamed it `CheckStatus` and attached the instance to the `Check` object? I would also rename the instance property to `Value`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T07:59:07.040",
"Id": "5846",
"Score": "0",
"body": "@ChaosPandion IsTemplateSent belongs to report not check. It is not status of check."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T12:11:48.453",
"Id": "5847",
"Score": "0",
"body": "@Arnis: Both, `IsTemplateSent` and `IsReceived` looked like bool members of Report. Remove those from CheckStatus if you like. In your original sample, the problem is that the status returned by IsTemplateSent will overwrite any return value from CheckStatus. The resulting values \"Received\" and \"Not Received\" do make sense as return status values - obviously, you can make whatever changes you like."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T17:51:35.383",
"Id": "3880",
"ParentId": "3872",
"Score": "5"
}
},
{
"body": "<p>I've used StringEnum as defined <a href=\"http://www.codeassociate.com/caapi/html/T_CA_Common_Attributes_StringEnum.htm\" rel=\"nofollow\">here</a> several times and it works quite nicely. It works much like IAbstract's solution, but without needing to implement a separate class.</p>\n\n<p>Then, wherever you need to reference the StringValue you can just use</p>\n\n<pre><code>enum Check \n{\n [StringValue(\"Check in progress\")] InProgress,\n [StringValue(\"Not yet received\")] NotReceived \n}\n\nCheck c = Check.InProgress;\nstring text = StringEnum.GetStringValue(c);\n</code></pre>\n\n<p>To avoid expansive rewrites you may want to use this approach. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T20:44:41.387",
"Id": "3906",
"ParentId": "3872",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T13:04:50.227",
"Id": "3872",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Refactoring a series of if-return statements."
}
|
3872
|
<pre><code>public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
{
if (o == null) return defaultValue;
DateTime dt;
if (DateTime.TryParse(o.ToString(), out dt))
return dt;
else
return defaultValue;
}
</code></pre>
<p>The code feels too wordy and smells bad. Is there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T17:55:25.910",
"Id": "5816",
"Score": "1",
"body": "You could get rid of the \"else\" (because in the true case it has already returned), but that's not much of an improvement. Other than that, this looks pretty optimal (clarity-wise) to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T04:36:51.883",
"Id": "58734",
"Score": "0",
"body": "return o as DateTime ?? defaultValue;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T04:42:18.073",
"Id": "58735",
"Score": "0",
"body": "`DateTime` is a value type and thus could not be used with the `as` operator nor set to `null`. That would be invalid code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T01:54:39.663",
"Id": "58736",
"Score": "0",
"body": "As @Jeff Mercado says, you cannot use a DateTime object with the `as` keyword. A failed conversion cannot be set to null. However, if you use a `DateTime?` (nullable DateTime) instead, your code would work."
}
] |
[
{
"body": "<p>I like @ChaosPandion's solution however I find the following a bit quicker to read. </p>\n\n<pre><code>public static DateTime ObjectToDateTime(object o, DateTime defaultValue)\n{ \n DateTime result;\n if (DateTime.TryParse((o ?? \"\").ToString(), out result)) {\n return result;\n } else {\n return defaultValue;\n }\n}\n</code></pre>\n\n<p>If you prefer the explicit null check, modify the if statement a bit... </p>\n\n<pre><code> if (o != null && DateTime.TryParse(o.ToString(), out result)) {\n</code></pre>\n\n<p>Coming from a language without the ?? operator, I find this even easier to quickly read and understand the intent of however I recognize that is probably just because I'm not used to reading ??.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T19:23:45.673",
"Id": "3882",
"ParentId": "3879",
"Score": "3"
}
},
{
"body": "<p>On the offhand chance that your object is <em>already</em> a <code>DateTime</code>, you're performing unnecessary conversions to and from strings.</p>\n\n<pre><code> if (o is DateTime)\n return (DateTime)o;\n</code></pre>\n\n<p>This also strikes me as something you might be doing for a database item, for example. In which case, I'd encourage you to know and trust your data types and then use existing methods of retrieval. </p>\n\n<p>For example, if you have a <code>DataTable</code> with a column <code>CreatedDate</code>, you should know it's a date, what you might not know is if it has a value if the column is nullable at the database. That's fine, you can handle that in code. </p>\n\n<pre><code> var createdDate = row.Field<DateTime?>(\"CreatedDate\"); \n</code></pre>\n\n<p>There we go, a <code>DateTime?</code>, no coding of a conversion necessary. You can even specify a default and type if to <code>DateTime</code></p>\n\n<pre><code> var createdDate = row.Field<DateTime?>(\"CreatedDate\").GetValueOrDefault(DateTime.Now);\n var createdDate = row.Field<DateTime?>(\"CreatedDate\") ?? DateTime.Now;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T20:15:26.087",
"Id": "3886",
"ParentId": "3879",
"Score": "30"
}
},
{
"body": "<p><em>Side note</em></p>\n\n<p>Since C# 7 it is now possible to declare the variables within the <em>is</em> clause which can come handy. For example</p>\n\n<pre><code> if (o1 is DateTime startDate &&\n o2 is DateTime endDate &&\n startDate > endDate)\n return true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-24T16:45:18.550",
"Id": "324078",
"Score": "1",
"body": "And to match OP code you may also show it with `out var dt` in `TryParse() `"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-24T15:55:56.667",
"Id": "171047",
"ParentId": "3879",
"Score": "3"
}
},
{
"body": "<p>The big problem I see here is your method name. I'd expect <code>ObjectToDateTime</code> to parse my object to a <code>DateTime</code> but that's not exactly what happens, right? Your method tries to parse the input and returns a default value if this doesn't work. Your method name should reflect that sentence. I'd call it <code>ParseDateTimeOrDefault</code> or something like that. It kind of follows the <code>IEnumerable.SingleOrDefault</code> trend.</p>\n\n<p>Now, there's another problem. Your intention seems to be to cast an <code>object</code> to a <code>DateTime</code>, but you actually parse the <code>ToString()</code> of the object. </p>\n\n<p>The point is, as a user of your method, I'd expect this to return the default value : </p>\n\n<pre><code>DateTime someDateTime; /*= Unimportant*/\ndt = DateTime.Now;\nObjectToDateTime(dt.ToString(), someDateTime);\n</code></pre>\n\n<p>Why? Because the <code>object</code> I pass as a parameter isn't a <code>DateTime</code>, it's a <code>string</code>. You <em>parse</em> a string, if it doesn't work, you return a value. That's your method.</p>\n\n<p>The question is : In your application, is there a scenario where you don't know if you'll either receive a <code>string</code> or a <code>DateTime</code>? Because that seems like a design flaw in my opinion. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-25T00:35:32.860",
"Id": "171083",
"ParentId": "3879",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "3886",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T17:45:45.603",
"Id": "3879",
"Score": "24",
"Tags": [
"c#",
"datetime",
"converting"
],
"Title": "Convert Object to a DateTime"
}
|
3879
|
<p>I created this class to keep track of a user's role:</p>
<pre><code>class UserRoleHelper extends AppHelper
{
public $helpers = array('Session');
private $role = NULL;
const CUSTOMER = 'customer';
const ASSOCIATE = 'associate';
const MANAGER = 'manager';
const ADMIN = 'admin';
const DEVELOPER = 'developer';
private $score = array(
self::CUSTOMER => 0,
self::ASSOCIATE => 1,
self::MANAGER => 2,
self::ADMIN => 3,
self::DEVELOPER => 4,
);
public function role()
{
if($this->role == NULL)
{
$this->role = strtolower($this->Session->read('Auth.User.role')) ?: 'customer';
}
return $this->role;
}
private function is($role)
{
return $this->score[$this->role()] >= $this->score[$role];
}
public function admin()
{
return $this->is(self::ADMIN);
}
public function manager()
{
return $this->is(self::MANAGER);
}
public function associate()
{
return $this->is(self::ASSOCIATE);
}
}
</code></pre>
<p>The idea is to be able to have an expression like:</p>
<pre><code>if($this->UserRole->manager())
{
//do something
}
</code></pre>
<p>And have it evaluate true if you are a manager or higher (admin, developer).</p>
<p>I also tried to design it so if there is ever the need to add a level like GENERAL_MANGER = 3 which would shift the values of ADMIN and DEVELOPER up one, it won't effect anything.</p>
<p>I originally had the keys in the <code>$score</code> array as strings, but it seemed redundant when I had constants already defined with the same values. I have never seen an array definition with constants for keys in a class body before. I know variables are not allowed but it seems to work with constants. Still don't know if that is bad or not though.</p>
<p>Is there anything I have missed or can do to make this better? </p>
|
[] |
[
{
"body": "<p>Use an <a href=\"http://www.php.net/manual/de/class.splenum.php\" rel=\"nofollow\">enumerator</a>?</p>\n\n<p>And use it like this:</p>\n\n<pre><code>if($this->isInRole(Roles::MANAGER)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T08:54:12.070",
"Id": "5898",
"Score": "1",
"body": "It's still considered experimental -> http://www.php.net/manual/en/intro.spl-types.php"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T14:21:03.713",
"Id": "3897",
"ParentId": "3884",
"Score": "2"
}
},
{
"body": "<p>It looks fine, the internal logic is encapsulated.</p>\n\n<p>Maybe this number comparison based role logic will not work if you have VIP_CUSTOMER and VIP_MANAGER roles and VIP_MANAGER's can't manage non-VIP CUSTOMERs/functions and simple MANAGER's can't manager VIP_CUSTOMERs/functions. In this case you can change implementation without any change in the client code to support this. </p>\n\n<p>(For example the VIP_MANAGER's score is 3 and MANAGER's score remains 2 then every VIP_MANAGER would be a MANAGER. If MANAGER's score is 3 and VIP_MANAGER's score is 2 then every MANAGER would be a VIP_MANAGER. None of them is good but you can modify the <code>manager</code> (and the imaginary <code>vipManager</code>) method to support this.\n)</p>\n\n<p>Changing the internal logic also a nice solution when the MANAGERs are not allowed to buy anything, so they shouldn't have the CUSTOMER role. You just change the <code>manager</code> method and it will work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T19:42:18.447",
"Id": "5790",
"ParentId": "3884",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T19:45:05.047",
"Id": "3884",
"Score": "3",
"Tags": [
"php"
],
"Title": "Keeping track of user role's"
}
|
3884
|
<p>I have designed this model which is very flexible. For example, you can create asset types, assets and combinations of them infinitely. It is the front end to a Python Pyramid website, so all the validation and business logic is handled by the web app.</p>
<p>However, not being a db guy, I have this sneaking suspicion that the schema totally sucks. There may be performance issues etc that I haven't foreseen etc.</p>
<pre><code>class Asset(Entity):
has_field('TimeStamp', Unicode, nullable=False)
has_field('Modified', Unicode)
belongs_to('AssetType', of_kind='AssetType', inverse='Assets')
has_many('Values', of_kind='Value', inverse='Asset')
Assets = ManyToMany('Asset')
@property
def Label(self):
if self.AssetType:
for f in self.AssetType.Fields:
if f.Label:
if self.Values:
for v in self.Values:
if v.Field.Name == f.Name:
return v.Value
def __repr__(self):
return '<Asset | %s>' % self.id
class AssetType(Entity):
has_field('Name', Unicode, primary_key=True)
has_field('Plural', Unicode)
has_many('Assets', of_kind='Asset', inverse='AssetType')
has_many('Fields', of_kind='Field', inverse='AssetType')
class Value(Entity):
has_field('Value', Unicode)
belongs_to('Asset', of_kind='Asset', inverse='Values')
belongs_to('Field', of_kind='Field', inverse='Values')
class Field(Entity):
has_field('Name', Unicode)
has_field('Unique', Unicode, default=False)
has_field('Label', Boolean, default=False)
has_field('Searchable', Boolean, default=False)
has_field('Required', Boolean, default=False)
has_many('Values', of_kind='Value', inverse='Field')
belongs_to('FieldType', of_kind='FieldType', inverse='Fields')
belongs_to('AssetType', of_kind='AssetType', inverse='Fields')
class FieldType(Entity):
has_field('Name', Unicode, primary_key=True)
has_field('Label', Unicode, unique=True)
has_many('Fields', of_kind='Field', inverse='FieldType')
</code></pre>
|
[] |
[
{
"body": "<p>You've reinvented a database inside a database. Basically, the Asset/AssetType is a simulation of a database inside a database which will as a result be slow. Also, you are going to spend a lot of effort reimplementing database features.</p>\n\n<p>You could do this by using a NoSQL database which is designed to handle less structured data might be a good idea. Or you could create a table for each asset type which will perform better. </p>\n\n<pre><code>@property \ndef Label(self):\n if self.AssetType:\n for f in self.AssetType.Fields:\n if f.Label:\n if self.Values:\n for v in self.Values:\n if v.Field.Name == f.Name:\n return v.Value\n</code></pre>\n\n<p>That's really nested which is bad sign. I suggest something like:</p>\n\n<pre><code>@property\ndef Label(self):\n if self.AssetType:\n label = self.AssetType.Label\n field = self.find_field(label)\n if field:\n return field.Value\n</code></pre>\n\n<p>Or if you use the Null Object pattern:</p>\n\n<pre><code>@property\ndef Label(self):\n return self.find_field(self.AssetType.label).Value\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T04:37:00.070",
"Id": "5829",
"Score": "0",
"body": "Thanks @Winston, you're right about the db in the db idea. I'm a bit scared of locking the schema because the business rules here are changing rapidly. I had a look at CouchDB which is very flexible, but I can't get my head around map/reduce. I'll take a look at NoSQL. Failing that, I think I'll take your advice and just structure it. Thanks for the rewrites above too, I learned a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T22:26:57.017",
"Id": "5916",
"Score": "0",
"body": "ok CouchDB IS NoSQL... and it's documentation has come a long way since I first looked into it. CouchDB is exactly what I need for a db in this case, and as it turns out, it will probably suffice as a web server too. Woot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:52:12.193",
"Id": "5997",
"Score": "0",
"body": "@MFB, The fact that your business rules are changing shouldn't drive you to NoSQL. In that case, I'm just going to constantly update the schema."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T13:22:14.247",
"Id": "6036",
"Score": "0",
"body": "you're right. It's not my only reason for looking at Couch. The more I look at Couch though, the more sense it makes to me, for this application at least. Almost everything in my business model can be described as an asset (or Document). The flexibility to continually add and subtract keys is just a huge bonus."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T03:24:49.977",
"Id": "3890",
"ParentId": "3888",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "3890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T01:04:52.997",
"Id": "3888",
"Score": "3",
"Tags": [
"python",
"pyramid"
],
"Title": "Elixir db model"
}
|
3888
|
<p>A naïve quicksort will take O(n^2) time to sort an array containing no unique keys, because all keys will be partitioned either before or after the pivot value. There are ways to handle duplicate keys (like one described in Quicksort is Optimal). The proposed solution only works for the Hoare partition, but I've implemented the Lomuto partition. To deal with duplicate keys, I alternated between moving duplicates to the left of the pivot and moving duplicates to the right of the pivot. Here's my quicksort (ignore the lack of generics):</p>
<pre><code>public static void swap(Comparable[] sort, int a, int b){
Comparable temp=sort[a];
sort[a]=sort[b];
sort[b]=temp;
}
public static void quicksort(Comparable[] sort, int start, int end){
while(end-start>1){//normal case
int pivot=gen.nextInt(end-start)+start;//random pivot
swap(sort, pivot, start);
int index=start;//walking index
boolean dupHandler=false;//init to true works also
for(int i=start+1; i<end; ++i){//Lomuto partition
int val=sort[start].compareTo(sort[i]);
if(val>0 || ( val==0 && (dupHandler=!dupHandler) ) )
swap(sort, ++index, i);
}
swap(sort, start, index);
if(index-start<end-index-1){//recurse into smaller partition
quicksort(sort, start, index);
start=index+1;//use iteration for other partition
}
else{
quicksort(sort, index+1, end);
end=index;
}
}
}
</code></pre>
<p>Is there a better (more efficient) way to handle duplicate keys? If not, is there any way to significantly improve my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T04:02:33.343",
"Id": "5828",
"Score": "1",
"body": "This is code review, not pseudocode review. If you want reviews of your code, please post your actual code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T04:56:44.310",
"Id": "5832",
"Score": "0",
"body": "Naive quicksort is O(n^2) full stop; it has nothing to do with duplicate keys."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:02:39.363",
"Id": "5833",
"Score": "0",
"body": "@Winston Code is posted"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:07:13.273",
"Id": "5834",
"Score": "0",
"body": "@Rafe I know, but even a quicksort with random pivot selection will degenerate to the O(n^2) case if all keys are equal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:10:08.573",
"Id": "5835",
"Score": "0",
"body": "Consider sorting an ascending list of numbers. To guarantee O(n log n) you do quicksort for the first k log n levels of recursion, then back off to a guaranteed O(n log n) sort, albeit with a larger constant factor than quicksort (e.g., merge sort)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:11:48.853",
"Id": "5836",
"Score": "0",
"body": "I believe that's [Introsort](http://en.wikipedia.org/wiki/Introsort)"
}
] |
[
{
"body": "<ol>\n<li>Use a swap function rather then repeating the three lines required to swap elements three times</li>\n<li>Put spaces around your operators</li>\n<li>You avoid recursing for the second partition. I don't think the performance gain from this is sufficient for the extra complexity in your code.</li>\n</ol>\n\n<p>Rather then swapping before/after for the element equal to the pivot, count the number of elements equal to the pivot. Then when you sort the subarray make the one subarray shorter so as not to sort the elements equal to the pivot.</p>\n\n<p>Another issue as Rafe has noted is that there are other issues besides duplicate keys that can cause a O(n^2) behavior. Your code doesn't handle any of those. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:54:34.293",
"Id": "5839",
"Score": "0",
"body": "1. I just changed the code inside the loop so that the lines aren't repeated. Is that better or worse than before?\n\n2. Too lazy to do that now, but you're right\n\n3. The added complexity doesn't seem like much to me; it's just one extra if-else statement\n\n4. I like that way of handling duplicates, I'll implement it when it's not 2AM\n\n5. I do choose a random pivot... the only more efficient pivot choices are the median-of-three (still no O(nlogn) guarantee) and the O(n) selection algorithms (these esnure O(nlogn) time but increase those pesky constant factors)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:55:21.377",
"Id": "5840",
"Score": "0",
"body": "I don't know how to put newlines in comments... sorry 'bout that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T06:07:10.290",
"Id": "5841",
"Score": "0",
"body": "@Derek, 1. you are still repeating the swap code three times. 3. There is also the while loop (which would be an if statement) but just generally your code obscures the nature of the quicksort algorithm. 5. Choosing a random pivot is good, but that doesn't guarantee you won't have problems. You could randomnly choose bad pivots."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T06:12:56.570",
"Id": "5842",
"Score": "0",
"body": "1. OH RIGHT... I forgot about the other swaps...\n\n\n3. The complexity of the code is of no concern, so long as I can understand it; I'm coding this for fun (yes, I do that)\n\n5. I'm open to any pivot-selection algorithms; any one in particular that you recommend?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T06:22:45.080",
"Id": "5843",
"Score": "1",
"body": "@Derek, 3. This is code review, I reserve the right to complain that your code has been made less readable for probably undetectable performance gains. You can reserve the right to ignore me. :) 5. I'm not suggesting a better pivot selection algorithm. I'm wondering whether your strategy has any advantage over something like introsort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T06:36:37.550",
"Id": "5845",
"Score": "0",
"body": "3. I'm cool with that\n\n5. I have a working heapsort, so introsort will be my next project. I'll test it against this quicksort and see what happens"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T05:43:18.233",
"Id": "3891",
"ParentId": "3889",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "3891",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T02:55:43.463",
"Id": "3889",
"Score": "4",
"Tags": [
"java",
"quick-sort"
],
"Title": "Handling duplicate keys in quicksort"
}
|
3889
|
<p>I am trying to create an extension method that builds a POCO object (copies all the fields) for an Entity Object.</p>
<p>When Entity object is simple (no navigation, no sub collections), it works fine.
I want to improve it so it could also deal with sub-entities. </p>
<p>For this example I take Nortwind database and use Customer and Order entities.
My POCOs:</p>
<pre><code> public class CustomerPOCO : BaseDataItemModel
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
List<OrderPOCO> orders;
[PropertySubCollection]
public List<OrderPOCO> Orders
{
get { return orders; }
set { orders = value; }
}
public CustomerPOCO()
{
orders = new List<OrderPOCO>();
}
}
public class OrderPOCO : BaseDataItemModel
{
public int OrderID { get; set; }
public string ShipName { get; set; }
public string ShipCity { get; set; }
}
</code></pre>
<p>Extension Method:</p>
<pre><code> public static void CopyPropertiesFrom<TObjectTarget>(
this ICollection<TObjectTarget> targetitems, System.Collections.IEnumerable sourceitems)
where TObjectTarget : new()
{
foreach (var source in sourceitems)
{
TObjectTarget targetObject = new TObjectTarget();
PropertyInfo[] allProporties = source.GetType().GetProperties();
PropertyInfo targetProperty;
foreach (PropertyInfo fromProp in allProporties)
{
targetProperty = targetObject.GetType().GetProperty(fromProp.Name);
if (targetProperty == null) continue;
if (!targetProperty.CanWrite) continue;
//check if property in target class marked with SkipProperty Attribute
if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue;
//Sub Collection -> set it here
if (targetProperty.GetCustomAttributes(typeof(PropertySubCollection), true).Length != 0)
{
}
else
targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null);
}
targetitems.Add(targetObject);
}
}
static void Main(string[] args)
{
List<CustomerPOCO> customers;
using (NorthwindEntities northcontext = new NorthwindEntities())
{
var cus = from customer in northcontext.Customers
select customer;
customers = new List<CustomerPOCO>();
customers.CopyPropertiesFrom(cus);
}
}
</code></pre>
<p>Note: Extension should know the type of sub-entity and a type of sub-poco...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:22:32.793",
"Id": "5850",
"Score": "0",
"body": "Well for better speed I would cache the PropertyInfo[], so you don't have to use reflection everytime, this will speed up your application a lot, if you are calling this extension often."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:24:36.883",
"Id": "5851",
"Score": "0",
"body": "@George Duckett, well I mean add a new feature..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:25:50.133",
"Id": "5852",
"Score": "0",
"body": "Ahh ok, you're probably right. (deleted my previous comment)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:25:52.147",
"Id": "5853",
"Score": "0",
"body": "What would speed it up more would be to construct a lamda expression that does the copying. You could then compile the expression so the analysis is only done once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:31:21.740",
"Id": "5854",
"Score": "0",
"body": "Bob Vale, can you please show what you mean?"
}
] |
[
{
"body": "<p>For this task, i would use <a href=\"http://automapper.codeplex.com/\" rel=\"nofollow\">AutoMapper</a>, it does exactly what you need, and can work with complex entities.</p>\n\n<p>If you are writing this mapper yourself, consider using expression compilation feature.\nSuch code will execute at the speed of a custom written code, with all reflection interpretation done beforehand. See the <a href=\"http://msdn.microsoft.com/en-us/library/bb301790.aspx\" rel=\"nofollow\">code example</a> for Expression.MemberInit</p>\n\n<p>As for the sub-objects in your code, you will figure out the recursive procedure, as soon as you rewrite your extension to work with a Type argument, not a generic argument. This way you can easily call the procedure for the properties, knowing their type from PropertyInfo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T10:47:49.850",
"Id": "5855",
"Score": "0",
"body": "What do you mean not a generic argumen? `CopyPropertiesFrom<TObjectTarget>` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T19:53:44.400",
"Id": "5975",
"Score": "0",
"body": "I think he meant something like `CopyPropertiesFrom(Type objectTargetType)`. You can't call generic methods with computed type parameter without using recursion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-04T16:26:28.413",
"Id": "221472",
"Score": "0",
"body": "Completely agree with this solution ... there's already a great tool built for exactly this ... might as well use it, it's pretty lightweight too!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T09:26:28.233",
"Id": "3896",
"ParentId": "3895",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:18:23.447",
"Id": "3895",
"Score": "2",
"Tags": [
"c#",
"entity-framework",
"reflection",
"extension-methods"
],
"Title": "Creating Extension Method to map entity with subentities object to Poco object"
}
|
3895
|
<p>In the index view a user can search with any combination of one to all of the following parameters: <code>firstname</code>, <code>lastname</code> or <code>ssn</code>. The found search results are displayed in the search results view. In my <code>HomeOfficeController</code> I have written the code like this, but most of the code is repeating.</p>
<p>Can someone suggest a neater way of writing this code?</p>
<pre><code> [HttpPost]
public ActionResult Index(HomeOfficeViewModel viewModel)
{
TempData["FirstName"] = viewModel.FirstName;
TempData["LastName"] = viewModel.LastName;
TempData["SSN"] = viewModel.FullSsn;
return RedirectToAction("SearchResults", "HomeOffice");
}
public ActionResult SearchResults(HomeOfficeViewModel viewModel, UserSessionContext sessionContext)
{
TempData.Keep();
if (TempData["FirstName"] != null)
{ viewModel.FirstName = TempData["FirstName"].ToString(); }
if (TempData["LastName"] != null)
{ viewModel.LastName = TempData["LastName"].ToString(); }
if (TempData["SSN"] != null)
{ viewModel.FullSsn = TempData["SSN"].ToString(); }
if (viewModel.FirstName != null && viewModel.LastName == null && viewModel.FullSsn == null)
{
var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "First Name searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn == null)
{
var ph = _policyHolderRepository.Where(x => x.LastName == viewModel.LastName).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "Last Name searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn != null)
{
var ph = _policyHolderRepository.Where(x => x.Ssn == viewModel.FullSsn).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "SSN searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn == null)
{
var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.LastName == viewModel.LastName).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "Combination of First Name and Last Name searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName != null && viewModel.LastName == null && viewModel.FullSsn != null)
{
var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.Ssn == viewModel.FullSsn).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "Combination of First Name and SSN searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn != null)
{
var ph = _policyHolderRepository.Where(x => x.LastName == viewModel.LastName && x.Ssn == viewModel.FullSsn).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "The Customer Name and SSN were not found. Please revise your search.");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn != null)
{
var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.LastName == viewModel.LastName && x.Ssn == viewModel.FullSsn).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId,
AccountVerified = p.AccountVerified
};
ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
return View("SearchResults", new SearchResultsViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
SearchResults = searchresults.ToList()
});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "Combination of First Name, Last Name and SSN searched does not exist in our records");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
}
else if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn == null)
{
ModelState.AddModelError("User Error", "Atleast enter one of the search criteria");
var homeOfficeViewModel = new HomeOfficeViewModel()
{
PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
};
return View("Index", homeOfficeViewModel);
}
else
{
return View();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is roughly how I would refactor it (note: I have not tried to compile this so I'm sure some tweaking will be needed).</p>\n\n<pre><code>public ActionResult SearchResults(HomeOfficeViewModel viewModel, UserSessionContext sessionContext)\n{\n TempData.Keep();\n if (TempData[\"FirstName\"] != null)\n { viewModel.FirstName = TempData[\"FirstName\"].ToString(); }\n if (TempData[\"LastName\"] != null)\n { viewModel.LastName = TempData[\"LastName\"].ToString(); }\n if (TempData[\"SSN\"] != null)\n { viewModel.FullSsn = TempData[\"SSN\"].ToString(); }\n\n if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn == null)\n {\n ModelState.AddModelError(\"User Error\", \"Atleast enter one of the search criteria\");\n var homeOfficeViewModel = new HomeOfficeViewModel()\n {\n PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,\n LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate\n };\n return View(\"Index\", homeOfficeViewModel);\n }\n else\n {\n\n var ph = _policyHolderRepository;\n if (viewModel.FirstName != null)\n {\n var ph = ph.Where(x => x.FirstName == viewModel.FirstName);\n ViewData[\"FirstName\"] = \"<<< First Name >>> is '\" + viewModel.FirstName + \"'\";\n }\n if (viewModel.LastName != null)\n {\n var ph = ph.Where(x => x.LastName == viewModel.LastName);\n ViewData[\"LastName\"] = \"<<< Last Name >>> is '\" + viewModel.LastName + \"'\";\n }\n if (viewModel.FullSsn != null)\n {\n var ph = ph.Where(x => x.Ssn == viewModel.FullSsn);\n ViewData[\"SSN\"] = \"<<< Social Security No. >>> is '*****\" + viewModel.FullSsn.Substring(5) + \"'\";\n }\n var searchresults = from p in ph.ToList()\n select new SearchResultsViewModel\n {\n FullSsn = p.Ssn,\n FullName = p.FirstName + \" \" + p.LastName,\n UserId = p.UserId,\n AccountVerified = p.AccountVerified\n };\n if (searchresults.Count != 0)\n {\n return View(\"SearchResults\", new SearchResultsViewModel()\n {\n PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,\n LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,\n SearchResults = searchresults.ToList()\n });\n }\n else\n {\n ModelState.Clear();\n ModelState.AddModelError(\"Error\", \"Your search returned no results. Please revise your search.\");\n var homeOfficeViewModel = new HomeOfficeViewModel()\n {\n PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,\n LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate\n };\n return View(\"Index\", homeOfficeViewModel);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T16:20:12.063",
"Id": "5863",
"Score": "0",
"body": "var ph = ph.Where(x => x.FirstName == viewModel.FirstName);\nvar ph = ph.Where(x => x.LastName == viewModel.LastName); var ph = ph.Where(x => x.Ssn == viewModel.FullSsn); why are we doing this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T16:28:03.333",
"Id": "5864",
"Score": "0",
"body": "@Theja - What it does is build up your query dynamically. So for instance say that the user entered a first name and a last name but not a SSN. Then the first two if blocks get executed. The first one makes your query look like this -> _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName). Then the second if get executed, making your query look like this -> _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName).Where(x => x.LastName == viewModel.LastName). The query builds up until ph.ToList() is called and then the query is executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T16:30:04.890",
"Id": "5865",
"Score": "0",
"body": "(cont.) This lets you build up the query with only the parts that are needed and lets you disregard the parts that aren't relevant (the SSN in this case). You may want to look up how LINQ does lazy execution of queries."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T15:14:42.197",
"Id": "3901",
"ParentId": "3899",
"Score": "0"
}
},
{
"body": "<p>You could look at putting the core of the logic into a service layer. This will help keep the controller skinny as well as help with writting unit tests as well. I wrote this in notepad so it's not tested but gives an idea of what I mean.</p>\n\n<p>This could be done even more by things such as providing a way to expose properties for the displaymessage rather than having it hard coded to '<<< field >>>' etc This would give more power to the view to determine how to render the message.</p>\n\n<pre><code>public ActionResult Index(HomeOfficeViewModel viewModel)\n{\n\n HomeOfficeQueryService service = new HomeOfficeQueryService();\n List<HomeOfficeViewModel> searchResults = new List<HomeOfficeViewModel>();\n\n try\n {\n if(!ModelState.IsValid())\n {\n throw new NoResultsException(\"\"); \n }\n\n var critera = service.GetCriteria(viewModel);\n searchResults = service.GetQuery(criteria).ToList(); \n }\n catch(NoResultsException ex)\n {\n if(ex.GetMessage().Length() > 0)\n ModelState.AddModelError(\"Error\", ex.GetMessage()); \n }\n finally\n {\n return View(\"SearchResults\", new SearchResultsViewModel()\n {\n PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,\n LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate, \n SearchResults = searchResults\n }); \n }\n}\nclass HomeOfficeQueryCriteria \n{\n public Predicate<HomeOfficeViewModel> Criteria { get; set; }\n public string EmptySearchMessage { get; set; }\n public string DisplayMessage { get; set; }\n}\n\nclass HomeOfficeQueryService()\n{\n private Repository<T> _policyHolderRepository;\n\n public HomeOfficeQueryService(Repository<T> policyHolderRepository)\n {\n _policyHolderRepository = policyHolderRepository;\n }\n\n public HomeOfficeQueryCriteria GetCriteria(HomeOfficeViewModel viewModel)\n {\n if(!string.isNullOrWhiteSpace(viewModel.FirstName) && string.isNullOrWhiteSpace(viewModel.LastName) && string.isNullOrWhiteSpace(viewModel.FullSsn))\n {\n return new HomeOfficeQueryCriteria()\n {\n Criteria = (x) => x.FirstName == viewModel.FirstName,\n EmptySearchMessage = \"First Name searched does not exist in our records\".\n DisplayMessage = \"<<< First Name >>> is '\" + viewModel.FirstName + \"'\";\n };\n }\n else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn == null)\n {\n // fill out more criteria here\n }\n else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn == null)\n {\n // fill out more criteria here\n }\n else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn != null)\n {\n // fill out more criteria here\n }\n else\n {\n // Any more conditions here\n }\n\n }\n\n public IQueryable<SearchResultsViewModel> GetQuery(HomeOfficeQueryCriteria arg) where T : HomeOfficeViewModel\n {\n var items = _policyHolderRepository.Where(x => arg.Criteria);\n\n if(items.Any()\n {\n var query = var searchresults = from p in ph\n select new SearchResultsViewModel\n {\n FullSsn = p.Ssn,\n FullName = p.FirstName + \" \" + p.LastName,\n UserId = p.UserId,\n AccountVerified = p.AccountVerified\n };\n\n\n return query;\n }\n else\n {\n throw NoResultsException(arg.EmptySearchMessage);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T21:04:22.340",
"Id": "3907",
"ParentId": "3899",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "3907",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T14:51:55.150",
"Id": "3899",
"Score": "4",
"Tags": [
"c#",
"asp.net-mvc-3",
"controller"
],
"Title": "Controller for searching with certain parameters"
}
|
3899
|
<p>I was asked to make a Java application with main class q2.</p>
<p>How can I make it better and more efficient?</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Sort extends q2
{
public static double SWITCH;
}
class q2 extends JFrame
{
public static void main(String[] args)
{
q2 window = new q2();
Container cont = window.getContentPane();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
window.setVisible(true);
window.setSize(dim);
JPanel LeftPanel = new JPanel();
JPanel RightPanel = new JPanel();
JPanel MiddlePanel = new JPanel();
JPanel Middle1Panel =new JPanel();
JPanel Middle2Panel = new JPanel();
JPanel Middle3Panel = new JPanel();
MiddlePanel.add(Middle1Panel);
MiddlePanel.add(Middle2Panel);
MiddlePanel.add(Middle3Panel);
cont.setLayout(new GridLayout(1,3));
cont.add(LeftPanel);
cont.add(MiddlePanel);
cont.add(RightPanel);
LeftPanel.setBackground(Color.red);
RightPanel.setBackground(Color.black);
JRadioButton BubbleButton = new JRadioButton("BubbleSort");
JRadioButton SelectionButton = new JRadioButton("SelectionSort");
JRadioButton InsertionButton = new JRadioButton("InsertionSort");
RightPanel.add(BubbleButton);
RightPanel.add(SelectionButton);
RightPanel.add(InsertionButton);
ButtonGroup Group1 = new ButtonGroup();
Group1.add(InsertionButton);
Group1.add(SelectionButton);
Group1.add(BubbleButton);
BubbleButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
Sort.SWITCH = 1;
}
});
SelectionButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
Sort.SWITCH = 2;
}
});
InsertionButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
Sort.SWITCH = 3;
}
});
LeftPanel.setLayout(new GridLayout(2,1));
JPanel VariablePanel = new JPanel();
JPanel ResultPanel = new JPanel();
LeftPanel.add(VariablePanel);
LeftPanel.add(ResultPanel);
VariablePanel.setLayout(new GridLayout(10,1));
final JTextField [] VarField = new JTextField[20];
for(int q=0;q<10;q++)
{
VarField[q] = new JTextField();
VariablePanel.add(VarField[q]);
}
ResultPanel.setBackground(Color.black);
ResultPanel.setLayout(new GridLayout(10,10));
JButton SortButton = new JButton("Sort");
ResultPanel.add(SortButton);
Middle1Panel.setLayout(new GridLayout(4,2));
final JTextField Output = new JTextField(50);
Output.setText("OutputMinute");
ResultPanel.add(Output);
JLabel Min = new JLabel("Min");
Middle1Panel.add(Min);
final JTextField OutputMin = new JTextField(50);
Output.setText("OutputSecond");
Middle1Panel.add(OutputMin);
JLabel Sec = new JLabel("Sec");
Middle1Panel.add(Sec);
final JTextField OutputSec = new JTextField(50);
Output.setText("Output");
Middle1Panel.add(OutputSec);
JLabel Mill = new JLabel("Millisec");
Middle1Panel.add(Mill);
final JTextField OutputMill = new JTextField(50);
Output.setText("Output");
Middle1Panel.add(OutputMill);
JButton Randomise = new JButton("Randomise");
Middle1Panel.add(Randomise);
final Random randomise = new Random();
Randomise.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a)
{
for(int q=0;q<=9;q++)
{
VarField[q].setText(Integer.toString(randomise.nextInt()));
}
}
});
SortButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a)
{
if (Sort.SWITCH == 1)
{
Calendar bubblestart = Calendar.getInstance();
int w,mindiff,secdiff,millsecdiff,q;
int[] i =new int[10];
for(q=0;q<10;q++)
{
i[q]=Integer.parseInt(VarField[q].getText());
}
while (q != 0)
{
q=0;
for(int r=0;r<=8;r++)
{
if (i[r]>i[r+1])
{
q=1;
w=i[r];
i[r]=i[r+1];
i[r+1]=w;
}
}
}
Calendar bubbleend = Calendar.getInstance();
Output.setText(Integer.toString(i[0])+" "+Integer.toString(i[1])+" "+Integer.toString(i[2])+" "+Integer.toString(i[3])+" "+Integer.toString(i[4])+" "+Integer.toString(i[5])+" "+Integer.toString(i[6])+" "+Integer.toString(i[7])+" "+Integer.toString(i[8])+" "+Integer.toString(i[9]));
mindiff=bubbleend.get(Calendar.MINUTE)-bubblestart.get(Calendar.MINUTE);
secdiff=bubbleend.get(Calendar.SECOND)-bubblestart.get(Calendar.SECOND);
millsecdiff=bubbleend.get(Calendar.MILLISECOND)-bubblestart.get(Calendar.MILLISECOND);
OutputMin.setText(Integer.toString(mindiff));
OutputSec.setText(Integer.toString(secdiff));
OutputMill.setText(Integer.toString(millsecdiff));
}
else if (Sort.SWITCH == 2)
{
Calendar selectstart = Calendar.getInstance();
int w,serial=0,mindiff,secdiff,millsecdiff,q;
int[] i =new int[10];
for(q=0;q<10;q++)
{
i[q]=Integer.parseInt(VarField[q].getText());
}
for (q=0;q<9;q++)
{
w=i[q];
for(int r=q;r<=9;r++)
{
if(i[r]<w)
{
w=i[r];
serial=r;
}
}
if(i[q]!=w)
{
w=i[q];
i[q]=i[serial];
i[serial]=w;
}
}
Calendar selectend = Calendar.getInstance();
Output.setText(Integer.toString(i[0])+" "+Integer.toString(i[1])+" "+Integer.toString(i[2])+" "+Integer.toString(i[3])+" "+Integer.toString(i[4])+" "+Integer.toString(i[5])+" "+Integer.toString(i[6])+" "+Integer.toString(i[7])+" "+Integer.toString(i[8])+" "+Integer.toString(i[9]));
mindiff=selectend.get(Calendar.MINUTE)-selectstart.get(Calendar.MINUTE);
secdiff=selectend.get(Calendar.SECOND)-selectstart.get(Calendar.SECOND);
millsecdiff=selectend.get(Calendar.MILLISECOND)-selectstart.get(Calendar.MILLISECOND);
OutputMin.setText(Integer.toString(mindiff));
OutputSec.setText(Integer.toString(secdiff));
OutputMill.setText(Integer.toString(millsecdiff));
}
else if (Sort.SWITCH == 3)
{
Calendar insertstart = Calendar.getInstance();
int q,mindiff,secdiff,millsecdiff,loop1,loop2,temp1,temp2=0;
int[] i =new int[10];
for(q=0;q<10;q++)
{
i[q]=Integer.parseInt(VarField[q].getText());
}
for(loop1=1;loop1<=9;loop1++)
{
int in, out;
for(out=1; out<10; out++)
{
int temp = i[out];
in = out;
while(in>0 && i[in-1] >= temp)
{
i[in] = i[in-1];
--in;
}
i[in] = temp;
}
}
Calendar insertend = Calendar.getInstance();
Output.setText(Integer.toString(i[0])+" "+Integer.toString(i[1])+" "+Integer.toString(i[2])+" "+Integer.toString(i[3])+" "+Integer.toString(i[4])+" "+Integer.toString(i[5])+" "+Integer.toString(i[6])+" "+Integer.toString(i[7])+" "+Integer.toString(i[8])+" "+Integer.toString(i[9]));
mindiff=insertend.get(Calendar.MINUTE)-insertstart.get(Calendar.MINUTE);
secdiff=insertend.get(Calendar.SECOND)-insertstart.get(Calendar.SECOND);
millsecdiff=insertend.get(Calendar.MILLISECOND)-insertstart.get(Calendar.MILLISECOND);
OutputMin.setText(Integer.toString(mindiff));
OutputSec.setText(Integer.toString(secdiff));
OutputMill.setText(Integer.toString(millsecdiff));
}
else
{
Output.setText("Select a Sorting method");
}
}
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T16:26:07.507",
"Id": "12567",
"Score": "1",
"body": "please learn java naming conventions and stick to them"
}
] |
[
{
"body": "<p>Unless you absolutely <em>must</em> keep everything in <code>main</code>, this should probably be split up into a number of separate functions. At the very least, I'd think of:</p>\n\n<ol>\n<li>One function for the UI.</li>\n<li>One function for each sort.</li>\n<li>One function to randomize the data.</li>\n</ol>\n\n<p>If it were up to me, I think I'd split it out a bit more than this as well, with one function to create the UI, and separate one to update the UI with results. In reality, a lot of creating the UI is also pretty much identical code repeated three times, so you probably want to split that into a couple of pieces as well, with one to handle only the repeated part (that you can call three times) and another that handles the parts that aren't repeated per-button.</p>\n\n<p>If you want it to be nicer from an OO viewpoint, you could go a bit further than that, and define a <code>sort</code> interface, and then have <code>selectionSort</code>, <code>insertionSort</code> and <code>bubbleSort</code> each implement that interface. Right now you also have essentially identical timing code in triplicate (once for each sort); you'd probably be better off isolating that in one place as well, and applying it to each sort as you run it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T01:47:47.283",
"Id": "3910",
"ParentId": "3902",
"Score": "8"
}
},
{
"body": "<h1>Revision</h1>\n\n<p>Slightly longer but a lot more readable/extendable.</p>\n\n<h3>SortQ2Program.java</h3>\n\n<pre><code>import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class SortQ2Program implements Runnable {\n\n @Override\n public void run() {\n JFrame frame = new JFrame();\n frame.setContentPane(new SortQ2Panel());\n frame.pack();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new SortQ2Program());\n }\n\n}\n</code></pre>\n\n<h3>SortQ2Panel.java</h3>\n\n<pre><code>import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.GridLayout;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.swing.ButtonGroup;\nimport javax.swing.JButton;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JRadioButton;\nimport javax.swing.JTextArea;\nimport javax.swing.JTextField;\n\npublic class SortQ2Panel extends JPanel {\n\n private static interface SortingAlgorithm {\n\n public void sort(int[] values);\n\n }\n\n private static abstract class AbstractSortingAlgorithm\n implements SortingAlgorithm {\n\n protected void swap(int[] values, int aIndex, int bIndex) {\n int temp = values[aIndex];\n values[aIndex] = values[bIndex];\n values[bIndex] = temp;\n }\n\n }\n\n private static class BubbleSort extends AbstractSortingAlgorithm {\n\n @Override\n public void sort(int[] values) {\n boolean isSorted = false;\n\n while (!isSorted) {\n isSorted = true;\n\n for (int i = 0; i < N_VALUE_FIELDS - 1; ++i) {\n if (values[i] > values[i + 1]) {\n isSorted = false;\n swap(values, i, i + 1);\n }\n }\n }\n }\n\n }\n\n private static class SelectionSort extends AbstractSortingAlgorithm {\n\n @Override\n public void sort(int[] values) {\n for (int index = 0; index < N_VALUE_FIELDS; ++index) {\n int minIndex = findMinIndex(values, index);\n\n if (minIndex != index) {\n swap(values, index, minIndex);\n }\n }\n }\n\n private int findMinIndex(int[] values, int startIndex) {\n int minIndex = startIndex;\n\n for (int index = startIndex; index < N_VALUE_FIELDS; ++index) {\n if (values[index] < minIndex) {\n minIndex = index;\n }\n }\n\n return minIndex;\n }\n\n }\n\n private static class InsertionSort extends AbstractSortingAlgorithm {\n\n @Override\n public void sort(int[] values) {\n for (int index = 0; index < N_VALUE_FIELDS; ++index) {\n int insertionValue = values[index];\n int insertionIndex = findInsertionIndex(values, index,\n insertionValue);\n values[insertionIndex] = insertionValue;\n }\n }\n\n private int findInsertionIndex(int[] values, int startIndex,\n int value) {\n int result;\n\n for (result = startIndex;\n result > 0 && values[result - 1] > value; --result) {\n values[result] = values[result - 1];\n }\n\n return result;\n }\n\n }\n\n private static final long serialVersionUID = 1L;\n\n private static final int ROWS = 1;\n private static final int COLS = 3;\n\n private static final int N_VALUE_FIELDS = 10;\n\n private static final int OUTPUT_ROWS = 2;\n private static final int OUTPUT_COLS = 50;\n\n private static final int LEFT_PANEL_ROWS = 2;\n\n private static final int MIDDLE_PANEL_ROWS = 4;\n\n private static final int MIDDLE_PANEL_COLS = 2;\n\n private static final int RESULT_PANEL_ROWS = 2;\n\n @SuppressWarnings(\"serial\")\n private static final Map<String, SortingAlgorithm> SORTING_MAP =\n new HashMap<String, SortingAlgorithm>() {{\n put(\"BubbleSort\", new BubbleSort());\n put(\"SelectionSort\", new SelectionSort());\n put(\"InsertionSort\", new InsertionSort());\n }};\n\n private static final Random RANDOM_NUMBER_GENERATOR = new Random();\n\n private ButtonGroup mSortGroup = new ButtonGroup();\n\n private JTextField[] mNumFields = new JTextField[N_VALUE_FIELDS];\n\n private JTextArea mOutputField = new JTextArea(\"Output\", OUTPUT_ROWS, OUTPUT_COLS);\n\n private JTextField mOutputMinField = new JTextField(\"OutputMin\",\n OUTPUT_COLS);\n private JTextField mOutputSecField = new JTextField(\"OutputSec\",\n OUTPUT_COLS);\n private JTextField mOutputMillisecField = new JTextField(\"OutputMil\",\n OUTPUT_COLS);\n\n public SortQ2Panel() {\n super(new GridLayout(ROWS, COLS));\n initComponents();\n }\n\n @Override\n public Dimension getPreferredSize() {\n return Toolkit.getDefaultToolkit().getScreenSize();\n }\n\n private void initComponents() {\n mOutputField.setLineWrap(true);\n initLeftPanel();\n initMiddlePanel();\n initRightPanel();\n }\n\n private void initLeftPanel() {\n JPanel leftPanel = new JPanel(new GridLayout(LEFT_PANEL_ROWS, 1));\n leftPanel.setBackground(Color.RED);\n leftPanel.add(initNumPanel());\n leftPanel.add(initResultPanel());\n add(leftPanel);\n }\n\n private void initMiddlePanel() {\n JPanel middlePanel = new JPanel(\n new GridLayout(MIDDLE_PANEL_ROWS, MIDDLE_PANEL_COLS));\n middlePanel.add(new JLabel(\"Min\"));\n middlePanel.add(mOutputMinField);\n middlePanel.add(new JLabel(\"Sec\"));\n middlePanel.add(mOutputSecField);\n middlePanel.add(new JLabel(\"Millisec\"));\n middlePanel.add(mOutputMillisecField);\n\n JButton randomiseButton = new JButton(\"Randomise\");\n randomiseButton.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n for (JTextField numField : mNumFields) {\n int randInt = RANDOM_NUMBER_GENERATOR.nextInt();\n numField.setText(String.valueOf(randInt));\n }\n }\n\n });\n\n middlePanel.add(randomiseButton);\n add(middlePanel);\n }\n\n private void initRightPanel() {\n JPanel radioPanel = new JPanel();\n radioPanel.setBackground(Color.BLACK);\n\n for (String buttonName : SORTING_MAP.keySet()) {\n JRadioButton button = new JRadioButton(buttonName);\n button.setActionCommand(buttonName);\n button.setForeground(Color.WHITE);\n mSortGroup.add(button);\n radioPanel.add(button);\n }\n\n add(radioPanel);\n }\n\n private JPanel initNumPanel() {\n JPanel numPanel = new JPanel(new GridLayout(N_VALUE_FIELDS, 1));\n\n for (int count = 0; count < N_VALUE_FIELDS; ++count) {\n mNumFields[count] = new JTextField();\n mNumFields[count].setEditable(false);\n numPanel.add(mNumFields[count]);\n }\n\n return numPanel;\n }\n\n private JPanel initResultPanel() {\n JPanel resultPanel = new JPanel(new GridLayout(RESULT_PANEL_ROWS, 1));\n resultPanel.setBackground(Color.BLACK);\n resultPanel.add(initSortButton());\n resultPanel.add(mOutputField);\n return resultPanel;\n }\n\n private JButton initSortButton() {\n JButton sortButton = new JButton(\"Sort\");\n\n sortButton.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n long start = System.currentTimeMillis();\n int[] values = parseValues();\n String sortType =\n mSortGroup.getSelection().getActionCommand();\n SORTING_MAP.get(sortType).sort(values);\n long diff = System.currentTimeMillis() - start;\n outputValues(values);\n outputTime(diff);\n }\n\n });\n\n return sortButton;\n }\n\n private int[] parseValues() {\n int[] values = new int[N_VALUE_FIELDS];\n\n for (int index = 0; index < N_VALUE_FIELDS; ++index) {\n values[index] = Integer.parseInt(mNumFields[index].getText());\n }\n\n return values;\n }\n\n private void outputValues(int[] values) {\n String output = \"\";\n\n for (int value : values) {\n output += String.valueOf(value) + \" \";\n }\n\n mOutputField.setText(output);\n }\n\n private void outputTime(long time) {\n long min = TimeUnit.MILLISECONDS.toMinutes(time);\n long sec = TimeUnit.MILLISECONDS.toSeconds(time) -\n TimeUnit.MINUTES.toSeconds(min);\n long millisec = time - TimeUnit.SECONDS.toMillis(sec);\n\n mOutputMinField.setText(String.valueOf(min));\n mOutputSecField.setText(String.valueOf(sec));\n mOutputMillisecField.setText(String.valueOf(millisec));\n }\n\n}\n</code></pre>\n\n<h1>Design Notes</h1>\n\n<ul>\n<li><code>setVisible</code> should be the last thing called in your program. Before I moved it to the end, your program just showed up as a large blank.</li>\n<li>Class names for java should be in UpperCamelCase.</li>\n<li>Variable names for java should be lowerCamelCase.</li>\n<li>You don't need to subclass your main class just to add a constant that you use in the main class anyway. Put the constant in the main class.</li>\n<li>Don't use equals comparison with doubles. I think what you were going for with the <code>SWITCH</code> variable is an <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html\" rel=\"nofollow\">enum</a></li>\n<li>Don't use wildcard imports like <code>javax.swing.*</code>. It pollutes the namespace. Import the individual classes instead.</li>\n<li>Don't subclass JFrame. Instead subclass JPanel and make a separate class that holds the main method. Initialize a plain old JFrame there and set the content pane to your custom panel.</li>\n<li><p>All GUI code should be inside <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29\" rel=\"nofollow\"><code>SwingUtilities.invokeLater(Runnable)</code></a>. That puts it on the AWT event dispatching thread. </p>\n\n<p>From Sun's <a href=\"http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html\" rel=\"nofollow\">Threads and Swing article</a>:</p>\n\n<blockquote>\n <p>Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.</p>\n</blockquote></li>\n<li>All methods should be short, including main. I hate making rules like 15 lines or less, but basically treat your code like a baby: if it <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smells</a> change it.</li>\n<li>SLVNAHTR (Single Letter Variable Names Are Hard To Read)</li>\n<li>Variables should have one purpose and one purpose only.</li>\n<li>private static final int NUMBER_OF_WAYS_MAGIC_NUMBERS_SUCK = 800;<br>\nprivate static final String CONSTANTS = \"better\";</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> code is good code.</li>\n<li>I used the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy</a> design pattern to simplify you complicated if statement. Now you can easily add a new sorting algorithm if you'd like. Just extend <code>AbstractSortingAlgorithm</code> and add the new algorithm to <code>SORTING_MAP</code>.</li>\n<li><code>System.currentTimeMillis</code> or <code>System.nanoTime</code> is usually used for timing things.</li>\n<li>Get rid of unused variables. If you're trying to change the layout of the content pane, use the appropriate <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html\" rel=\"nofollow\">layout managers</a></li>\n<li>My refactoring is purposefully incomplete. It's in desperate need of comments, some of the variable names could be better, the program is slightly useless, and the general look of the GUI is kinda ugly. Tis up to you to fix that.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T11:22:18.303",
"Id": "13347",
"ParentId": "3902",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "3910",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T15:58:17.120",
"Id": "3902",
"Score": "3",
"Tags": [
"java"
],
"Title": "Java application for comparing sorting methods"
}
|
3902
|
<p><a href="http://jsfiddle.net/caimen/kMkrW/" rel="nofollow">Here</a> is a link to the code on JSFiddle.</p>
<p>This is my first attempt at playing with canvas. Before I move on doing anything else, it would be nice to have insight from somebody who knows canvas and JavaScript better than me.</p>
<p>Things I am looking for:</p>
<ul>
<li><p>Ways to optimize animation</p></li>
<li><p>Ways to optimize the lazer drawing (I know I need to clear the lazers from the array every once in awhile when they are no longer within the drawing area, just haven't gotten around to it yet.)</p></li>
<li><p>Ways to optimize the code in general and have good code re-use.</p></li>
</ul>
<p><strong>HTML:</strong></p>
<pre><code><canvas id="world" style="height: 300px; width: 300px;" />
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>console.log("Game starting...");
var ship = new Object();
ship.name = "Enterprise";
ship.x = 0;
ship.y = 0;
ship.width = 50;
ship.left = false;
ship.right = false;
ship.up = false;
ship.down = false;
ship.fire = false;
ship.firerate = 5;
ship.cfirerate = 0;
var lazers = new Array();
var world = document.getElementById('world');
var cxt = world.getContext("2d");
$(document).bind('keydown', function(e) {
if(e.keyCode==37){
ship.left = true;
}
if(e.keyCode==38){
ship.up = true;
}
if(e.keyCode==39){
ship.right = true;
}
if(e.keyCode==40){
ship.down = true;
}
if(e.keyCode==90){ //Z
console.log("pew pew");
ship.fire = true;
}
});
$(document).bind('keyup', function(e) {
if(e.keyCode==37){
ship.left = false;
}
if(e.keyCode==38){
ship.up = false;
}
if(e.keyCode==39){
ship.right = false;
}
if(e.keyCode==40){
ship.down = false;
}
if(e.keyCode==90){ //Z
ship.fire = false;
}
});
function createLazer(type) {
if (type == 1) {//LEFT LAZER
cxt.beginPath();
cxt.moveTo(125+ship.x,140+ship.y);
cxt.lineTo(125+ship.x,130+ship.y);
var l = new Object();
l.type = type;
l.x = ship.x;
l.y = ship.y;
return l;
}
else if (type == 2) {//RIGHT LAZER
cxt.beginPath();
cxt.moveTo(125+ship.x+ship.width,140+ship.y);
cxt.lineTo(125+ship.x+ship.width,130+ship.y);
var l = new Object();
l.type = type;
l.x = ship.x;
l.y = ship.y;
return l;
}
}
function drawWorld() {
cxt.fillStyle="#808080";
cxt.fillRect(0,0,300,300);
}
function drawLazers() {
for (x = 0; x < lazers.length; x++)
{
cxt.beginPath();
cxt.strokeStyle="#FF0000";
if (lazers[x].type == 1) {
cxt.moveTo(125+lazers[x].x,140+lazers[x].y);
cxt.lineTo(125+lazers[x].x,120+lazers[x].y);
}
else if (lazers[x].type == 2) {
cxt.moveTo(125+lazers[x].x+ship.width,140+lazers[x].y);
cxt.lineTo(125+lazers[x].x+ship.width,120+lazers[x].y);
}
cxt.stroke();
lazers[x].y = lazers[x].y - 6;
//console.log("drawing lazer" + lazers[x].x + lazers[x].y);
}
}
function drawShip() {
if (ship.left) { ship.x = ship.x -5; }
if (ship.right) { ship.x = ship.x +5; }
if (ship.up) { ship.y = ship.y -5; }
if (ship.down) { ship.y = ship.y +5; }
if (ship.fire) {
if (ship.cfirerate == 0) {
lazers.push(createLazer(1));
lazers.push(createLazer(2));
ship.cfirerate = ship.firerate;
}
}
if (ship.cfirerate != 0) {
ship.cfirerate = ship.cfirerate - 1;
}
cxt.beginPath();
cxt.strokeStyle="#000000";
cxt.moveTo(125+ship.x,140+ship.y);
cxt.lineTo(150+ship.x,120+ship.y);
cxt.lineTo(175+ship.x,140+ship.y);
cxt.stroke();
}
function clear() {
cxt.clearRect(0, 0, 300, 300);
}
function gameLoop() {
drawWorld();
drawShip();
drawLazers();
}
setInterval(function() {
clear();
gameLoop();
}, 30);
</code></pre>
|
[] |
[
{
"body": "<p>It's more personal preference than any hard requirement, but I always prefer object literal syntax to individual value assignments. That would turn your initial declarations into this:</p>\n\n<pre><code>var ship = {\n name: \"Enterprise\",\n x: 0,\n y: 0.\n width: 50,\n left: false,\n right: false,\n up: false,\n down: false,\n fire: false,\n firerate: 5,\n cfirerate: 0\n},\nlazers = [];\n</code></pre>\n\n<p>Additionally, multiple variables can be declared with a single <code>var</code> statement if separated by commas, also as demonstrated.</p>\n\n<p>You may also benefit from adding a boundary that prevents the Ship from moving off of the World. As it stands now you can lose it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T16:41:59.133",
"Id": "3990",
"ParentId": "3903",
"Score": "1"
}
},
{
"body": "<p>Cool program!</p>\n\n<p>I have put my review of the code on <a href=\"http://jsfiddle.net/gZDLE/10/\">JsFiddle</a>.</p>\n\n<p>A basic synopsis of what I thought to improve:</p>\n\n<ul>\n<li><p>Everything constant about the map, ship, lasers, and keycodes is all in one place to improve scalability.</p></li>\n<li><p>I used <a href=\"http://hubpages.com/hub/Creating-JavaScript-Objects-by-Literal-Notation\">object literals</a> and array literals instead of <code>new Object()</code> and <code>new Array()</code> because using them is shorter and and makes things easier to manipulate.</p></li>\n<li><p>The <code>keydown</code> and <code>keyup</code> event handlers were refactored to eliminate duplicate code.</p></li>\n<li><p>The <code>createLaser</code> and <code>drawLasers</code> methods were refactored. I removed some drawing code from <code>createLaser</code> because it didn't seem to do anything, and I removed calculations in <code>drawLasers</code> that were redundant with <code>createLaser</code>.</p></li>\n<li><p>I added code in <code>drawLasers</code> to remove lasers from the array that are no longer on the map. I also removed or rearranged drawing code that didn't do anything or was being called too many times. I removed the <code>clear()</code> function because it didn't seem to do anything.</p></li>\n<li><p>I changed statements of form <code>x = x + y</code>, <code>x = x - y</code> and <code>x = x + 1</code> to <code>x += y</code>, <code>x -= y</code>, and <code>x++</code>, respectively.</p></li>\n<li><p>I changed one instance of the form <code>array.push(x); array.push(y);</code> to <code>array.push(x,y);</code></p></li>\n<li><p>I renamed <code>lazer</code> to <code>laser</code> because I kept typing <code>laser</code> and it caused bugs that here hard to find. You can rename it back, if you are accustomed to typing <code>lazer</code>.</p></li>\n</ul>\n\n<p>Here is a copy of the revised code:</p>\n\n<pre><code>console.log(\"Game starting...\");\n\nvar ship = {\n name: \"Enterprise\",\n x: 125,\n y: 120,\n width: 50,\n height: 40,\n left: false,\n right: false,\n up: false,\n down: false,\n fire: false,\n firerate: 5,\n cfirerate: 0,\n moveInterval: 5,\n color: \"#000000\"\n},\n map = {\n width: 300,\n height: 300,\n color: \"#808080\",\n drawInterval: 30\n },\n laser = {\n height: 20,\n moveInterval: 6,\n color: \"#FF0000\"\n },\n lasers = [],\n keys = {\n left: 37,\n up: 38,\n right: 39,\n down: 40,\n fire: 90 //Z\n },\n getKey = function(key) {\n for (var i in keys) {\n if (keys.hasOwnProperty(i)) {\n if (keys[i] === key) {\n return i\n };\n }\n }\n },\n eventValues = {\n keyup: false,\n keydown: true\n },\n types = {\n right: 1,\n left: 2\n };\n\nvar world = document.getElementById('world');\nvar cxt = world.getContext(\"2d\");\n\n$(document).bind('keydown keyup', function(e) {\n var key = getKey(e.keyCode);\n ship[key] = eventValues[e.type];\n});\n\nfunction createLaser(type) {\n var x = ship.x;\n if (type === types.right) {\n x += ship.width;\n }\n var y = laser.height + ship.y;\n return {\n type: type,\n x: x,\n y: y,\n }\n}\n\nfunction drawWorld() {\n cxt.fillStyle = map.color;\n cxt.fillRect(0, 0, map.width, map.height);\n}\n\nfunction drawLasers() {\n cxt.beginPath();\n cxt.strokeStyle = laser.color;\n for (var i = 0; i < lasers.length; i++) {\n var lsr = lasers[i];\n if (lsr.y < -laser.height) {\n lasers.splice(i, 1);\n continue;\n }\n cxt.moveTo(lsr.x, lsr.y);\n cxt.lineTo(lsr.x, lsr.y - laser.height);\n cxt.stroke();\n lsr.y -= laser.moveInterval;\n }\n}\n\nfunction drawShip() {\n if (ship.left) {\n ship.x -= ship.moveInterval;\n }\n if (ship.right) {\n ship.x += ship.moveInterval;\n }\n if (ship.up) {\n ship.y -= ship.moveInterval;\n }\n if (ship.down) {\n ship.y += ship.moveInterval;\n }\n if (ship.fire) {\n if (ship.cfirerate === 0) {\n lasers.push(createLaser(types.left), createLaser(types.right));\n ship.cfirerate = ship.firerate;\n }\n }\n if (ship.cfirerate !== 0) {\n ship.cfirerate--;\n }\n\n cxt.beginPath();\n cxt.strokeStyle = ship.color;\n cxt.moveTo(ship.x, ship.y + (ship.height / 2));\n cxt.lineTo(ship.x + (ship.width / 2), ship.y);\n cxt.lineTo(ship.x + ship.width, ship.y + (ship.height / 2));\n cxt.stroke();\n}\n\nfunction gameLoop() {\n drawWorld();\n drawShip();\n drawLasers();\n}\n\nsetInterval(gameLoop, map.drawInterval)\n</code></pre>\n\n<p>If you see anything that you think is weird, or have a question about what I did, just ask me about it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T14:52:10.737",
"Id": "6060",
"Score": "0",
"body": "Theres something a little weird when shooting a single lazer sometimes. Sometimes the left lazer lags behind the right lazer. This codes looks 10 times better. Do you happen to know if this is the best way to produce this type of animation? Sometimes I experience just a little bit of flashing. Before I award you the points I am going to keep the question open so I can post an update later this weekend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T15:44:22.093",
"Id": "6061",
"Score": "0",
"body": "To be honest, I haven't played much with canvas (though it looks like something that would be really fun to mess around with) so I don't really know the fastest ways to do things. But I'm pretty sure the reason one laser lags behind the other is because one is created before the other. Try modifying the code to create them at the same time, instead of separately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T19:46:37.110",
"Id": "102219",
"Score": "0",
"body": "first of all nicely done\nDue to the (weird) scoping rules of JavaSCript it's generally recommended to declare all variables in a function at the top. E.g. your `lsr` variable is not limited to the for loop` but actually has `drawLasers` as it's scope. In this particular function it's doesn't create any problems but it's a good practice because when it does create a bug it's usually extremely hard to track down and btw the same goes for the iteration variable (i.e. `i`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T05:02:09.593",
"Id": "4001",
"ParentId": "3903",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "4001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T18:00:40.730",
"Id": "3903",
"Score": "7",
"Tags": [
"javascript",
"object-oriented",
"canvas"
],
"Title": "Simple JavaScript canvas game"
}
|
3903
|
<p>While this is working very well for storing setting variables for my applications, I've been using it for a number of years and really feel there is something better. I'm perhaps just looking to use some newer functions from the framework. </p>
<pre><code> public string Value { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
/// <summary>
/// Gets the selected setting from cache if it exists,
/// else returns the supplied default value
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string GetCacheSetting(string settingName, string defaultValue)
{
return LoadSettings().Contains(settingName) ? Convert.ToString(LoadSettings()[settingName]) : defaultValue;
}
/// <summary>
/// Returns the selected setting value from cache.
/// If cache is null then rebuild the cache.
/// </summary>
/// <returns></returns>
public static Hashtable LoadSettings()
{
Hashtable h;
h = (Hashtable)HttpRuntime.Cache["SiteSettings"];
if (h == null)
{
h = new Hashtable();
DataAccess da = new DataAccess(); //My DAL
foreach (DataRow row in da.GetSiteSettings().Tables[0].Rows)
{
Settings oSetting = new Settings();
oSetting.SettingsInitFromRow(row);
h.Add(oSetting.Name, oSetting.Value);
}
HttpRuntime.Cache.Insert("SiteSettings",
h,
null,
DateTime.Now.AddMinutes(120),
Cache.NoSlidingExpiration);
}
return h;
}
/// <summary>
/// Sets the values for the cache items
/// </summary>
/// <param name="row"></param>
private void SettingsInitFromRow(DataRow row)
{
this.Name = (string)row["Name"];
this.Value = (string)row["Value"];
}
</code></pre>
<p>The settings are stored in the database and created at install time/modified as needed. At most I have 20 to 30 setting values in the database. I'm using a Hashtable stored in cache to get my values to remove the need to access the database 2, 3, or more times on every page load just for settings in addition to the rest of the times for page content. Doing this was the last time I majorly changed it maybe 3 years ago. </p>
<p>Any ideas?</p>
|
[] |
[
{
"body": "<p>It look spretty good to me, but there are a couple of things I would likely change, none of which have to do with the use (or non-use) of a hashtable data structure as it is perfectly suited for this sort of thing.</p>\n\n<p>I would probably change the <code>LoadSettings</code> method a bit as it doesn't actually load settings each time it is called, and then definitely use the generic <code>Dictionary<K,V></code> instead of the antiquated <code>Hashtable</code> class, thereby removing the need for all that nasty casting. You could also avoid two lookups when attempting to retrieve a value from the cache by using <code>TryGetValue</code> instead of <code>Contains</code> and then performing another lookup, something like:</p>\n\n<pre><code>public static string GetCacheSetting(string settingName, string defaultValue)\n{\n string ret;\n Settings.TryGetValue( settingName, out ret );\n return ret ?? defaultValue;\n}\n\n// you may even want to make this private as a caller could\n// edit the contents of the cache directly. You could leave\n// GetCacheSetting as the only access point, adding a \n// SetCacheSetting method if needed.\nprivate static Dictionary<string, string> _settings;\npublic static Dictionary<string, string> Settings\n{\n get\n {\n if( _settings == null )\n {\n _settings = LoadSettings();\n } \n\n return _settings;\n }\n}\n\nprivate static Dictionary<string, string> LoadSettings()\n{\n HttpRuntime.Cache.Remove( _settings );\n _settings = new Dictionary<string,string>();\n DataAccess da = new DataAccess(); //My DAL\n foreach (DataRow row in da.GetSiteSettings().Tables[0].Rows)\n {\n Settings oSetting = new Settings();\n oSetting.SettingsInitFromRow(row);\n _settings.Add(oSetting.Name, oSetting.Value);\n }\n\n HttpRuntime.Cache.Insert(\"SiteSettings\", \n _settings, \n null, \n DateTime.Now.AddMinutes(120), \n Cache.NoSlidingExpiration); \n\n return _settings;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T02:59:01.380",
"Id": "5871",
"Score": "0",
"body": "I like the idea. I really do. A few comments. One, it looks like in `LoadSettings()` it's not checking for cache, and pulling from this rather than \"yet another DB call\" times 5. Or is this being checked here `if( _settings == null ){ _seetings = LoadSettings(); }`? As far as `TryGetValue` vs `Contains`, first off, I was not aware of it but I like it, a lot. Second I guess I just really like one liners. Never the less, I'll give it a whirl."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T04:21:52.520",
"Id": "5872",
"Score": "0",
"body": "So I changed `LoadSettings` to actually load the settings each time it is called. We only call it once however when the cahced settings are asked for the first time. After that `_settings` will not be null and we will just return that. You can do that part however you like of course, it's semantically the same as your version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T09:55:38.117",
"Id": "5899",
"Score": "0",
"body": "Wouldnt this \"foreach (DataRow row in da.GetSiteSettings().Tables[0].Rows)\" result in a NullReferenceException if the site had no settings? Just a heads up"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T18:12:14.833",
"Id": "5910",
"Score": "0",
"body": "@Mattias, this table by default will always have at least one item in it that is added as the DB is created. So while it is something to watch, this is static data so it's sort of a non-issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T18:14:05.533",
"Id": "5911",
"Score": "0",
"body": "Wow. I'm surprised at my results while testing. Here I thought my method was all well and good but really it's piss poor. Over 100k loop the initial startup takes 150ms. On each refresh it's around 135ms. With your method its about 110ms the first time, and 12ms on each refresh. Granted it's over 100k but still I'm sure it's going to help overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T20:39:38.557",
"Id": "5915",
"Score": "1",
"body": "Glad I could help, cheers."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T20:22:16.570",
"Id": "3905",
"ParentId": "3904",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "3905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T19:33:46.187",
"Id": "3904",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"cache"
],
"Title": "Possible solutions to remove the use of a Hashtable"
}
|
3904
|
<p>I am trying to solve an exercise in which I am given the following function:</p>
<pre><code>/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
</code></pre>
<p>the exercise is:</p>
<blockquote>
<p>Write an alternative version of squeeze(s1,s2) that deletes each
character in s1 that matches any character in the string s2.</p>
</blockquote>
<p>I have came up with this: </p>
<pre><code>#define COPY 1
#define NOCOPY 0
void multisqueeze(char s[], char f[])
{
int i, j,k, state;
i = j = k = 0;
state = COPY;
while (s[i] != '\0')
{
state = COPY;
while (f[k] != '\0' && state == COPY)
{
printf("s is %c, f is %c\n", s[i], f[k]);
if (tolower(f[k]) == tolower(s[i]))
{
state = NOCOPY;
printf("Nocopy set \n");
}
k++;
}
k=0;
if (state == COPY)
{
printf("Copying a character, %c\n", s[i]);
s[j++] = s[i];
}
i++;
}
printf("Loop ended, s is %c\n", s[i]);
s[j] = '\0';
}
</code></pre>
<p>This seems to be a valid solution for the problem and outputs the correct answer. But I have been told that the implementation is messy and not readable because of the use of the state variable and that there are more elegant ways of doing it. I have been trying to wrap my head around it for some time and I simply can't see a way to not use the state variable at all. I think this exercise is from <em>The C programming Language</em> by Brian Kernighan and Dennis Ritchie.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T00:03:17.410",
"Id": "5869",
"Score": "0",
"body": "Are you restricted to only writing code in one single function or could you add helper functions? Does it have to be optimized for speed (or other metric)? Case sensitive? Do you really need to leave those debug messages in your code? You should consider how much of a divergence your code went from the original, surely you'd agree, the original is much easier to read than yours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T23:12:59.277",
"Id": "5882",
"Score": "0",
"body": "Why are you calling `tolower()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:58:28.413",
"Id": "5896",
"Score": "0",
"body": "Actually I don't think he wants me to use helper functions, cause I first just looped squeeze over the string and he just smiled and said no :p"
}
] |
[
{
"body": "<p>Although there are quite a few ways to do this, I think I'd represent the \"set\" of characters to be skipped as an array of \"boolean\"s -- which is to say an integer for each possible character, saying whether to copy that character or not:</p>\n\n<pre><code>char copy[CHAR_MAX];\n\n// by default, we copy all characters:\nmemset(copy, 1, sizeof(copy));\n\n// but we don't copy any that are contained in f:\nwhile (*f)\n copy[*f++] = 0;\n</code></pre>\n\n<p>Then I'd walk through the string just about like in the original function, but for each character, instead of checking whether that equals <code>c</code>, I'd check whether that item in the <code>copy</code> array was set to 0 or 1. Copy each character if and only if that spot in <code>copy</code> is set to 1 (or at least that it's not 0 -- keep in mind that 0 evaluates to <code>false</code>, and anything else evaluates to <code>true</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T01:35:51.087",
"Id": "3909",
"ParentId": "3908",
"Score": "1"
}
},
{
"body": "<p>What you have is an O(n^2) solution.</p>\n\n<p>But lets look at tidying it up first:</p>\n\n<ol>\n<li>Do you really need these macros.<br>\nIf you must have them then why not name the variable copy and use the macros TRUE/FALSE</li>\n</ol>\n\n\n\n<pre><code>#define COPY 1\n#define NOCOPY 0\n</code></pre>\n\n<ol>\n<li>Declaring variables using the comma is lazy and considered bad practice, but you should also use more descriptive variable names. i/j/k do not explain what they are being used for. Also if you function is longer and you need to change it looking for all instances of a variable 'i' may take a while longer because of all the false positives on a search so maintenance wise it is also a bad idea.<br>\nThere are a couple of edge cases where the declaration can go wrong. So in general it is just best to stay clear.</li>\n</ol>\n\n\n\n<pre><code>int i, j,k, state;\n</code></pre>\n\n<ol>\n<li>You are using a while() loop. But a for(;;) loop would have been neater. It allows initialization test and increment in the same statement. This puts all work done on the k variable in the same place.</li>\n</ol>\n\n\n\n<pre><code> while (f[k] != '\\0' && state == COPY)\n</code></pre>\n\n<ol>\n<li>Are you sure you actually want to do this test?</li>\n</ol>\n\n\n\n<pre><code> if (tolower(f[k]) == tolower(s[i]))\n</code></pre>\n\n<ol>\n<li>OK. The heart of the problem. Use of the state variable.<br>\nThe reason you have this test is to break out of this while loop and then avoid doing the actual work in the next loop. You already have the failed state information implicitly by the place you are in the loop while testing so all you need to do is break out of the current loop. You do not need to do an explicit test in the condition but just use a break statement.</li>\n</ol>\n\n\n\n<pre><code> state = NOCOPY;\n</code></pre>\n\n<ol>\n<li>So if we re-write your version taking into account my comments we get:</li>\n</ol>\n\n\n\n<pre><code>void multisqueeze(char s[], char f[])\n{\n int i = 0; // Iterate over s[]\n int j = 0; // Iterate over s[] as elements are copied (this is the dst)\n\n for(i = 0; s[i] != '\\0'; ++i)\n {\n int k = 0; // Iterate over f[]\n for(k = 0; f[k] != '\\0'; ++k)\n {\n if (tolower(f[k]) == tolower(s[i]))\n {\n break;\n }\n }\n\n if (f[k] != '\\0') // Then we never reached the end of the loop\n { // This means we found a match in the f[] array\n s[j++] = s[i];\n }\n }\n s[j] = '\\0';\n}\n</code></pre>\n\n<p>But there is an O(n) solution.<br>\nWhat you need to do is convert the search of the second string into a single comparison.</p>\n\n<p>Since char is a limited range (0-255) we can swap space for time.<br>\nAllocate an array that represents every character possible character. Then we can use this as a way to look-up the existence of a character.</p>\n\n<p>So rather than doing this:</p>\n\n<pre><code> for(k = 0; f[k] != '\\0'; ++k)\n {\n if (tolower(f[k]) == tolower(s[i]))\n {\n break;\n }\n }\n</code></pre>\n\n<p>for each iteration of s[]. What you want to do is iterate over f[] <strong>once</strong> and save the state of each character. So that you can just look up the answer in one step rather than an iteration. To do this we hoist this loop out of the inner loop and allocate an array for all possible values of char, then mark any we find in f[] as true in our allocated array.</p>\n\n<p>This is what mine would look like (actually mine would look slightly different as I would have written in the C++ style but I have translated into C to make it consistent with the question).</p>\n\n<pre><code>void squeeze(char s[], char f[])\n{\n int loopF;\n int loopS;\n int squeeze = 0;\n int test[256] = {0}; // One for each character. Default to false.\n // I would use bool here. But C does not have bool\n // Could use char to save space but that can be confusing\n // as not everybody considers a char as an integer type. \n\n for(loopF = 0; f[loopF] != '\\0'; ++loopF)\n { test[tolower(f[loopF])] = 1; // Mark every character in test that is in f as true.\n test[toupper(f[loopF])] = 1; // Thus we can test for existence just by looking it up\n }\n\n for(int loopS=0; s[loopS]; ++loopS)\n {\n if (test[s[loopS]]) // Test to see if the character in s is also marked true in test.\n { squeeze++;\n continue;\n }\n // move characters down the squeezed amount\n s[loopS-squeeze] = s[loopS];\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:46:38.747",
"Id": "5895",
"Score": "0",
"body": "Great answer, it was really helpful and had a lot of detail. If I could upvote, I would."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T06:22:41.233",
"Id": "3913",
"ParentId": "3908",
"Score": "8"
}
},
{
"body": "<p>A very good solution was given taking into account that there is only 256 chars in C and using an array of finite and acceptable size to perform the comparison in O(1). But if we were in Java (or other Unicode language), or if the problem involves ints or longs instead of chars, representing all possible values in an array can become impractical. To keep the algorithm as fast as possible, a hashtable can be used, keeping the comparison in O(1), but needing more memory. If you are low on memory, this is an algorithm in O(n*log(n)) time complexity and in O(n) memory usage:</p>\n\n<ol>\n<li>Sort both input, keeping the original index of the data in temp arrays,</li>\n<li>Remove the matching data,</li>\n<li>Sort back by index.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T12:01:34.643",
"Id": "3915",
"ParentId": "3908",
"Score": "1"
}
},
{
"body": "<p>I can provide an alternative solution. It does not use any state variable.</p>\n\n<pre><code>void multisqueeze(char s[], char f[]) {\n char *from = s, *to = s, *p;\n for( ; *from; from++ ) {\n for ( p = f; *p; p++ )\n if ( *from == *p )\n break;\n if ( !*p ) {\n *to = *from;\n to++;\n }\n }\n *to = '\\0';\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T22:52:51.147",
"Id": "3918",
"ParentId": "3908",
"Score": "2"
}
},
{
"body": "<p>for long discard string create a lookup</p>\n\n<pre><code>#include <string.h>\n\nvoid multisqueeze(char *s, char *f)\n{\n char mapping[256];\n bzero(mapping, 256);\n for(; *f != '\\0'; f++) mapping[*f] = 1;\n char* w = s;\n while (*s != '\\0') {\n if (! mapping[*s])\n *w++ = *s;\n s++;\n }\n *w = '\\0';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T23:12:14.127",
"Id": "5884",
"Score": "1",
"body": "`memset` is in the C language standard; `bzero` isn't (but is likely to be available)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T23:46:09.863",
"Id": "5885",
"Score": "0",
"body": "Sorry but `bzero` in 2011 is absurd."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T23:58:33.320",
"Id": "5886",
"Score": "0",
"body": "The standard function `memset` supplanted `bzero` a long time ago."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T22:52:57.903",
"Id": "3919",
"ParentId": "3908",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "3913",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T22:58:28.930",
"Id": "3908",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "Delete each character in one string that matches any character in another"
}
|
3908
|
<p>For a personal project, I'm working on a Java profiler that specifically targets <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html" rel="nofollow noreferrer">ThreadPoolExecutor</a> and its subclasses and provides statistics about throughput of executed tasks. To support this I've written the following utility classes, which are intended to help compute a smoothed average rate of events over time. They are intended to be thread-safe and lock-free; I want to interfere as little as possible with the threads that are counting (and executing) tasks.</p>
<p>First is the <strong>EventMeter</strong>, which is used to count one type of event. This supports computing an average rate of events by keeping a running sum of counted events and being able to discard old data. (Pardon my TODO.)</p>
<pre><code>public final class EventMeter {
private final long bucketLengthNanos;
private final double[] buckets;
private volatile double sum;
private int bucketNum;
private AtomicLong accumulator;
public EventMeter(int numBuckets, long bucketLengthNanos) {
// TODO assert that numBuckets >= 1, bucketLengthNanos >= some small number
this.bucketLengthNanos = bucketLengthNanos;
this.buckets = new double[numBuckets];
this.sum = 0.0;
this.bucketNum = 0;
this.accumulator = new AtomicLong(Double.doubleToLongBits(0.0));
}
public long getBucketLengthNanos() {
return bucketLengthNanos;
}
public void countEvent() {
long oldAccumulator;
long newAccumulator;
do {
oldAccumulator = accumulator.get();
newAccumulator = Double.doubleToLongBits(Double.longBitsToDouble(oldAccumulator) + 1.0);
} while (!accumulator.compareAndSet(oldAccumulator, newAccumulator));
}
public double getRate() {
return sum / buckets.length;
}
public void fillBucketFromAccumulator(double accumulatorFraction) {
long oldAccumulator;
long newAccumulator;
do {
oldAccumulator = accumulator.get();
newAccumulator = Double.doubleToLongBits(Double.longBitsToDouble(oldAccumulator) * (1.0 - accumulatorFraction));
} while (!accumulator.compareAndSet(oldAccumulator, newAccumulator));
double oldAccumulatorValue = Double.longBitsToDouble(oldAccumulator);
double oldBucketContents = buckets[bucketNum];
double newBucketContents = oldAccumulatorValue * accumulatorFraction;
buckets[bucketNum] = newBucketContents;
bucketNum = (bucketNum + 1) % buckets.length;
sum = sum - oldBucketContents + newBucketContents;
}
}
</code></pre>
<p>Next is the <strong>EventMeterManager</strong>, which uses a worker thread to advance the "buckets" in a collection of EventMeters at a constant rate.</p>
<pre><code>public final class EventMeterManager {
private final DelayQueue<AdvanceMeterTask> meterQueue;
private final Map<EventMeter, AdvanceMeterTask> tasks;
private final AtomicInteger activeMeters;
private AtomicReference<Thread> worker;
public EventMeterManager() {
this.meterQueue = new DelayQueue<AdvanceMeterTask>();
this.worker = new AtomicReference<Thread>();
this.tasks = new ConcurrentHashMap<EventMeter, AdvanceMeterTask>();
this.activeMeters = new AtomicInteger(0);
}
public EventMeter startEventMeter(int numBuckets, long bucketLengthNanos) {
final EventMeter meter = new EventMeter(numBuckets, bucketLengthNanos);
if (activeMeters.incrementAndGet() == 1) {
final Thread newWorker = new Thread(new DriverWorker(), "EventMeterManager worker");
// It will either already be null or it will be shortly.
while (!worker.compareAndSet(null, newWorker)) {}
newWorker.start();
}
final AdvanceMeterTask advanceTask = new AdvanceMeterTask(meter, System.nanoTime());
tasks.put(meter, advanceTask);
meterQueue.put(advanceTask);
return meter;
}
public void stopEventMeter(EventMeter meter) {
final AdvanceMeterTask cancelledTask = tasks.remove(meter);
if (cancelledTask != null) {
cancelledTask.cancel();
if (activeMeters.decrementAndGet() == 0) {
worker.get().interrupt();
worker.set(null);
}
}
}
private class DriverWorker implements Runnable {
@Override
public void run() {
try {
while (!Thread.interrupted()) {
final AdvanceMeterTask task = meterQueue.take();
task.run();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private class AdvanceMeterTask implements Delayed, Runnable {
private final EventMeter meter;
private long bucketStartTime;
private long bucketEndTime;
private volatile boolean cancelled;
public AdvanceMeterTask(final EventMeter meter, final long firstBucketStartTime) {
this.meter = meter;
this.bucketStartTime = firstBucketStartTime;
this.bucketEndTime = this.bucketStartTime + meter.getBucketLengthNanos();
}
@Override
public int compareTo(Delayed o) {
final long difference = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
if (difference < 0) {
return -1;
} else if (difference > 0) {
return 1;
} else {
return 0;
}
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(bucketEndTime - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public void run() {
if (!cancelled) {
final long now = System.nanoTime();
final long bucketLength = meter.getBucketLengthNanos();
while (bucketEndTime < now) {
double bucketFraction = (double) bucketLength / (now - bucketStartTime);
meter.fillBucketFromAccumulator(bucketFraction);
bucketStartTime = bucketEndTime;
bucketEndTime += bucketLength;
}
meterQueue.put(this);
}
}
public void cancel() {
this.cancelled = true;
}
}
}
</code></pre>
<p>In addition to general commentary (which is always appreciated) I'd like specific feedback, if possible on these things:</p>
<ul>
<li>Are these classes as thread-safe as I hope they are?</li>
<li>These classes seem pretty coupled but in the interest of not creating a bunch of unnecessary threads I didn't want EventMeter to create its own worker thread. Is there an approach I can take allows EventMeters to share a thread without requiring a client to use EventMeterManager?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T13:50:07.017",
"Id": "5957",
"Score": "1",
"body": "What's the point of the buckets?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-21T18:47:43.390",
"Id": "458480",
"Score": "0",
"body": "Can you show a driver method / sample use case? How do these classes get used? With no java-doc comments I'm finding it hard to understand how to even start with a review."
}
] |
[
{
"body": "<p>Method <code>fillBucketFromAccumulator()</code> is not <a href=\"https://en.wikipedia.org/wiki/Thread_safety\" rel=\"nofollow noreferrer\">thread-safe</a>. Two threads can write to the same slot in the array, and then both advance by one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-09T13:50:48.967",
"Id": "3984",
"ParentId": "3912",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-06T03:45:42.087",
"Id": "3912",
"Score": "5",
"Tags": [
"java",
"multithreading"
],
"Title": "Concurrent event counter/averager utility classes"
}
|
3912
|
<p>I have several utility classes who should only ever have one instance in memory, such as <code>LogHelper</code>, <code>CacheHelper</code>, etc. One instance to rule them all.</p>
<p>I've never implemented <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">Singleton</a> in Java before, so I wanted to post my first pass and see if anybody had major issues with this, or just helpful critiques. I want to make sure that my design will have the intended affect when I go to use these singleton classes throughout my <a href="https://en.wikipedia.org/wiki/Codebase" rel="nofollow noreferrer">codebase</a>.</p>
<p>Singleton:</p>
<pre><code>public class Singleton
{
private static Singleton instance;
protected Singleton()
{
super();
}
public static synchronized Singleton getInstance()
{
if(instance == null)
instance = instantiate();
return instance;
}
// Wanted to make this abstract and let subclasses @Override it,
// but combining 'abstract' and 'static' is illegal; makes sense!
protected static Singleton instantiate()
{
return new Singleton();
}
}
</code></pre>
<p>LogHelper (a singleton since all my classes will use it to write messages to the same destinations):</p>
<pre><code>public class LogHelper extends Singleton
{
protected static LogHelper instantiate()
{
return new LogHelper(...blah...);
}
public LogHelper(...blah...)
{
// Initialize the singleton LogHelper
}
// More methods for logging, etc.
}
</code></pre>
<p>Here's how I'd like to use it throughout my codebase:</p>
<pre><code>LogHelper logHelper = LogHelper.getInstance();
logHelper.logInfo("...");
</code></pre>
<p><em>What I'm worried about</em> is that I may have inadvertently designed this wrong and heading down the wrong avenue. Can anybody weigh-in on my design?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T02:50:29.483",
"Id": "5887",
"Score": "0",
"body": "Make the constructor private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T07:21:18.720",
"Id": "5955",
"Score": "0",
"body": "In most cases Singletons are simply a **bad** idea. They are hard to test, and you are in trouble if you need multiple instances later. The factory pattern is better, but clearly the best solution is Dependency Injection (check out Guice or Spring)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T02:08:25.793",
"Id": "6426",
"Score": "0",
"body": "What's wrong with using existing logging frameworks?? See: http://www.slf4j.org/, http://logging.apache.org/log4j/1.2/, and http://logback.qos.ch/"
}
] |
[
{
"body": "<p>Unfortunately, there is no way (that I know of) to prevent a subclass from exposing a public constructor - as a result, creating a <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">Singleton</a> base-class may not be in your best interest. If your goal is to enforce Singleton-ness, it is probably best to just implement something like the following on a class-by-class basis:</p>\n\n<pre><code>public class SomeSingletonClass {\n public static final SomeSingletonClass INSTANCE = new SomeSingletonClass();\n\n private SomeSingletonClass(){\n }\n\n // ...\n}\n</code></pre>\n\n<p>Many IDE-s (such as <a href=\"https://www.jetbrains.com/idea/\" rel=\"nofollow noreferrer\">IntelliJ</a>) will create the boiler-plate <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">Singleton</a> code for you with the click of a button.</p>\n\n<p>If you prefer to access the <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a> via a method, you can always make INSTANCE private and add a public static <code>getInstance()</code> method.</p>\n\n<p>I also noticed you have a lazy/synchronized initializer for your example - this is probably not necessary in most cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T12:37:39.283",
"Id": "5888",
"Score": "0",
"body": "Perhaps you can say how this is better than using an `enum` with one instance. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T20:22:30.353",
"Id": "5913",
"Score": "0",
"body": "Why have you accepted your own answer when there is a better alternative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:46:48.670",
"Id": "6497",
"Score": "0",
"body": "Bohemian's answer is the way to go if you want lazy loading."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-06T02:45:17.850",
"Id": "3921",
"ParentId": "3920",
"Score": "6"
}
},
{
"body": "<p>The \"original\" Singleton design pattern relied on a class not exposing public constructors so that it could control instantiations of itself, by encapsulating all usages of <code>new</code> within the class:</p>\n\n<pre><code>public class SomeSingletonClass\n{\n private static SomeSingletonClass instance;\n\n //disallow other classes from instantiating new instances\n private SingletonClass()\n {\n }\n\n public synchronized SomeSingletonClass getInstance()\n {\n if(instance == null)\n instance = new SomeSingletonClass(); // instantiate here\n return instance;\n }\n}\n</code></pre>\n\n<p>By subclassing the singleton, you would allow subclasses to create multiple instances of the singleton, there by losing the singleton property for the parent. So, the following line will likely result in multiple instances of the <code>Singleton</code> being created in your case:</p>\n\n<pre><code>public LogHelper(...blah...)\n{\n // Initialize the singleton LogHelper\n}\n</code></pre>\n\n<p>But it is much worse than you can predict. If a client of <code>LogHelper</code> invokes the following:</p>\n\n<pre><code>LogHelper logHelper = new LogHelper(...blah...);\nLogHelper anotherHelper = new LogHelper(...blah...);\n</code></pre>\n\n<p>you will have two <code>LogHelper</code> instances no matter what - the culprit is the public visibility of the <code>LogHelper</code> constructor. So your subclass is not a singleton at all.</p>\n\n<p>If you want to implement the singleton pattern across multiple classes, it is better to not treat it as a property than can be inherited. Rather, you must recreate the behavior in every individual class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T02:58:35.450",
"Id": "3922",
"ParentId": "3920",
"Score": "1"
}
},
{
"body": "<p>i've always found this singleton code snippet robust . the synchronize on 'LOCK' object make the singleton creation thread safe </p>\n\n<pre><code>public class Singleton{\n\n private static final Object LOCK = new Object();\n private static Singleton singleton;\n\n private Singleton(){}\n/**\n * Returns the singleton instance of <CODE>Singleton</CODE>, creating it if\n * necessary.\n * <p/>\n *\n * @return the singleton instance of <Code>Singloton</CODE>\n */\n public static Singleton getInstance() {\n\n // Synchronize on LOCK to ensure that we don't end up creating\n // two singletons.\n synchronized (LOCK) {\n if (null == singleton) {\n\n\n singleton = new Singleton();\n\n\n }\n }\n\n return singleton;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T04:45:54.980",
"Id": "3923",
"ParentId": "3920",
"Score": "1"
}
},
{
"body": "<p>The best pattern for singleton that is guaranteed to be thread safe and minimizes lock overhead (because it has none) is this:</p>\n\n<pre><code>public class Singleton {\n private Singleton() {}\n\n private static class InstanceHolder {\n static Singleton INSTANCE = new Singleton();\n }\n\n public static Singleton getInstance() {\n return InstanceHolder.INSTANCE;\n }\n}\n</code></pre>\n\n<p>This is <a href=\"http://en.wikipedia.org/wiki/Lazy_initialization\">lazy initialized</a> but carries no locking overhead. It is guaranteed safe by the <a href=\"http://en.wikipedia.org/wiki/Java_Memory_Model\">Java Memory Model</a>: The inner static class is not loaded until the first call to <code>getIinstance()</code> <em>and</em> all static initializtion is guaranteed to be completed before the class is used, therefore INSTANCE is fully constructed when first accessed.</p>\n\n<p>Note: The <a href=\"http://en.wikipedia.org/wiki/Double-checked_locking\">double checked locking pattern</a> is BROKEN - see <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\">this article</a> that explains exactly why.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T20:25:02.207",
"Id": "5914",
"Score": "0",
"body": "I knew it was broken in C++ (unless you know the compiler details (which means its generally broken)), interesting to note it is also broken in Java. Thanks for the reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T02:05:19.637",
"Id": "6425",
"Score": "0",
"body": "Hmmm, starting from Java 5 you can use the double checked locking by making sure to declare the holder as `volatile`. See my answer on http://stackoverflow.com/questions/6445310/ways-to-implement-the-singleton-design-pattern/6447579#6447579"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T06:25:45.693",
"Id": "3924",
"ParentId": "3920",
"Score": "8"
}
},
{
"body": "<p>The simplest Singleton since Java 5.0 (2004) is to use an enum.</p>\n\n<pre><code>public enum SomeSingletonClass {\n INSTANCE;\n}\n</code></pre>\n\n<p>Classes are loaded lazily and if the only purpose of the class is to be a singleton, you don't need additional lazy loading.</p>\n\n<p>However in your cause you only need a Utility class.</p>\n\n<pre><code>enum Log {;\n public static void info(String text) { }\n}\n\nLog.info(\"...\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T12:35:37.177",
"Id": "3925",
"ParentId": "3920",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "3921",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-06T02:34:45.310",
"Id": "3920",
"Score": "5",
"Tags": [
"java",
"object-oriented",
"singleton"
],
"Title": "Request for Comments: Singleton pattern implemented in Java"
}
|
3920
|
<p>The following implementation is of a <em>repository proxy</em>.</p>
<p>I will post only the code for <code>NHibernate</code> Repository here. Everything else (including configurers and tests) can be found on the <a href="http://pastebin.com/kjSHgDnR" rel="nofollow">pastebin</a>.</p>
<p><strong>P.S. :</strong> I changed all the XML-like comments to their more readable representation, so the actual code still has nice XML documentation.</p>
<pre><code>public interface IRepository
{
// Retrieves every entity of the specified type stored in the repository.
IQueryable<T> RetrieveEntities<T>() where T : IRepositoryEntity;
// Retrieves every entity filtered by the supplied expression.
// As long as the result is models 'IQueryable', it implies on the lazy result
// evaluation and therefore doesn't have significant performance impact.
IQueryable<T> RetrieveEntities<T>(Expression<Func<T, bool>> expression) where T : IRepositoryEntity;
// New items are added to the repository and existing are updated.
void AddEntities<T>(IQueryable<T> sequence) where T : IRepositoryEntity;
void AddEntities<T>(params T[] entities) where T : IRepositoryEntity;
// Removes every entity of the specified type stored in the repository.
void RemoveEntities<T>() where T : IRepositoryEntity;
// Removes entities of the specified type which fit under the specified expression.
void RemoveEntities<T>(Expression<Func<T, bool>> expression) where T : IRepositoryEntity;
// Removes every entity in the sequence from the repository. Throws if at least one entity
// from the sequence doesn't belong to the database.
void RemoveEntities<T>(IQueryable<T> sequence) where T : IRepositoryEntity;
void RemoveEntities<T>(params T[] entities) where T : IRepositoryEntity;
}
</code></pre>
<hr>
<pre><code>public class NHibernateRepository : IRepository
{
private readonly Configuration configuration;
private readonly ISessionFactory sessionFactory;
private readonly ISession session;
public NHibernateRepository(NHibernateRepositoryConfigurer repositoryConfigurer)
{
// Build and store the NHibernate-specific configuration.
configuration = repositoryConfigurer.Configuration.BuildConfiguration();
// Build the corresponding session factory and open the session.
sessionFactory = repositoryConfigurer.SessionFactory;
session = sessionFactory.OpenSession();
}
public IQueryable<T> RetrieveEntities<T>() where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
return session.Query<T>();
}
public IQueryable<T> RetrieveEntities<T>(Expression<Func<T, bool>> expression) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
return session.Query<T>().Where(expression);
}
public void AddEntities<T>(IQueryable<T> sequence) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
WithinTransaction(() =>
{
foreach (var entity in sequence)
{
session.Merge(entity);
}
});
}
public void AddEntities<T>(params T[] entities) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
AddEntities(entities.AsQueryable());
}
public void RemoveEntities<T>() where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
WithinTransaction(() =>
{
foreach (var entity in session.Query<T>())
{
session.Delete(entity);
}
});
}
public void RemoveEntities<T>(Expression<Func<T, bool>> expression) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
WithinTransaction(() =>
{
foreach (var entity in session.Query<T>().Where(expression))
{
session.Delete(entity);
}
});
}
public void RemoveEntities<T>(IQueryable<T> sequence) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
WithinTransaction(() =>
{
foreach (var entity in sequence)
{
session.Delete(entity);
}
});
}
public void RemoveEntities<T>(params T[] entities) where T : IRepositoryEntity
{
CheckTypeMappings(typeof(T));
RemoveEntities(entities.AsQueryable());
}
// Performs the entire specified action within a single unit of work.
private void WithinTransaction(Action action)
{
var transaction = session.BeginTransaction();
try
{
action();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
finally
{
transaction.Dispose();
}
}
// Throws if the type is not mapped to the database.
private void CheckTypeMappings(Type type)
{
if (type.IsInterface) return;
if (configuration.ClassMappings.Any(x => x.MappedClass == type)) return;
// The 'type' is definitely doesn't have an appropriate persister.
throw new MappingException("Type " + type.FullName + " doesn't have an appropriate persister");
}
</code></pre>
|
[] |
[
{
"body": "<p>Two things i notied:</p>\n\n<p>Wrap the transaction in a using-statement and also log the exception.</p>\n\n<pre><code> // Performs the entire specified action within a single unit of work.\n private void WithinTransaction(Action action)\n {\n using(var transaction = session.BeginTransaction()){\n\n try\n {\n action();\n transaction.Commit();\n }\n catch (Exception ex)\n {\n transaction.Rollback();\n _logger.ErrorFormat(\"Error description here... {0}\", ex.Message);\n throw;\n }\n finally\n {\n transaction.Dispose();\n }\n }\n }\n</code></pre>\n\n<p>And also you should make the interface generic instead of each method (unless there is a reason for that). Makes sense and results in higher readability.</p>\n\n<pre><code> public interface IRepository<T> where T : IRepositoryEntity\n {\n IQueryable<T> RetrieveEntities<T>();\n IQueryable<T> RetrieveEntities<T>(Expression<Func<T, bool>> expression); \n\n void AddEntities<T>(IQueryable<T> sequence);\n void AddEntities<T>(params T[] entities); \n\n void RemoveEntities<T>();\n void RemoveEntities<T>(Expression<Func<T, bool>> expression);\n void RemoveEntities<T>(IQueryable<T> sequence);\n void RemoveEntities<T>(params T[] entities);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T08:57:19.047",
"Id": "3936",
"ParentId": "3926",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T21:37:21.043",
"Id": "3926",
"Score": "1",
"Tags": [
"c#",
"beginner",
"repository"
],
"Title": "Repository wrapper"
}
|
3926
|
<p>Please review this.</p>
<pre><code>public int InsertQuery(string Query)
{
int LastInsertedID = -1;
MySqlCommand MySqlCmd = new MySqlCommand(Query, this.sqlConn);
try
{
MySqlCmd.ExecuteNonQuery();
LastInsertedID = int.Parse(MySqlCmd.LastInsertedId.ToString());
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not execute INSERT Query.<br />" + Query + "<br /> Error: <br />" + excp.Message, excp);
throw (myExcp);
}
return LastInsertedID;
}
public int AddChannel(NameValueCollection FormValues)
{
string Keys = string.Join(",",FormValues.AllKeys);
string Values = string.Join(",", FormValues.AllKeys.Select(key => String.Format("\"{0}\"", HttpContext.Current.Server.HtmlEncode(FormValues[key]))));
return InsertQuery("INSERT INTO channels (" + Keys + ") VALUES (" + Values + ");");
}
</code></pre>
|
[] |
[
{
"body": "<p>Don't take shortcuts. Build a proper insert statement using a parameterized query and validate each of the form inputs that they're also of the proper type (ie., not sending a string into an integer field). </p>\n\n<p>Do this to protect the integrity of your data, both from improper types and from malicious (or even unintended) attacks. </p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/652978/parameterized-query-for-mysql-with-c\">this</a> and other related questions on SO for constructing proper parameterized queries with MySql.</p>\n\n<p>More than that, you don't want your class that deals with data inserts to also interact with your UI. These concerns should be seperated. Seperate your UI code from your business logic code from your data access code. Don't let these things mingle, because your UI could change, your logic could change, and your data strategy could change, and they could change independently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:02:28.647",
"Id": "5891",
"Score": "0",
"body": "lol the string into integer is the exact problem im experiencing now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T23:05:11.957",
"Id": "3930",
"ParentId": "3927",
"Score": "6"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/questions/3927/please-review-my-code-inserting-an-entire-form-into-mysql-database/3930#3930\">Anthony suggests</a>, build a proper data access layer.<br>\nNever build SQL by string concatenation.</p>\n\n<p>If you're sure you don't want the heavinesss usually associated with the use of an OR mapper such as Entity Framework or NHibernate, take a look at <a href=\"http://code.google.com/p/dapper-dot-net/\" rel=\"nofollow noreferrer\">Dapper micro ORM</a>. It is just one file to be added to project, is blazingly fast and simple. See <a href=\"https://stackoverflow.com/questions/5957774/performing-inserts-and-updates-with-dapper\">here</a> on how to insert the data.</p>\n\n<p>By using a class instead of <code>NameValueCollection</code>, you'll also make your queries safer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T13:03:40.010",
"Id": "3964",
"ParentId": "3927",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "3930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T21:59:22.133",
"Id": "3927",
"Score": "3",
"Tags": [
"c#",
"mysql"
],
"Title": "Inserting an entire form into MySQL database"
}
|
3927
|
<p>I wonder what is better code practice or just what looks better in Java:</p>
<p>Version 1:</p>
<pre><code>protected Boolean doSomething(int amount) {
if (amount < 1) return false;
return insertToDb(fillImages(fetchInfo(REQUEST_URL, amount)));
}
</code></pre>
<p>Version 2:</p>
<pre><code>protected Boolean doSomething(int amount) {
if (amount < 1) return false;
Data[] data = fetchInfo(REQUEST_URL, amount);
fillImages(data);
// or even
// data = fillImages(data);
return insertToDb(data);
}
</code></pre>
<p>This could be a problem if we had more functions chained like that. I would like to make my code nicer, for anyone else who might have to edit it, and just to know that I am not writing anything that looks stupid.</p>
|
[] |
[
{
"body": "<p>I definitely prefer the second version. The steps taken just \"leap out\" of the code and the method is easier to read. It will also be a lot easier to debug (or to pinpoint the problem in a stack trace).</p>\n\n<p>Always go for readability, it makes for easier understanding when going back to your old code and it's a lot easier for someone else to understand what is going on.</p>\n\n<p>I also prefer the \"data = fillImages(data)\" if possible. It makes clear that the data is modified.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:02:49.750",
"Id": "5892",
"Score": "0",
"body": "Than you for the input. Still the `data = something(data)` style looks really funny to me, but I guess it does make it quite obvious that something has been changed, and I see how this is useful for later times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T15:07:18.800",
"Id": "5903",
"Score": "1",
"body": "Version 2 also improves merging efforts with SCM."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T15:48:03.730",
"Id": "5905",
"Score": "0",
"body": "@Jeremy: Had not really thought of that but that definitely would make things easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T02:41:50.883",
"Id": "5923",
"Score": "0",
"body": "IMO, we don't really want methods modifying outside-referenced values in Java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T16:56:44.947",
"Id": "5943",
"Score": "0",
"body": "Another reason for Version 2 is also that it forces the relavant classes to be declared as an import, which is sometimes used to calculate the complexity of a class (the more classes it imports the more complex it is)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T22:43:28.320",
"Id": "3929",
"ParentId": "3928",
"Score": "13"
}
},
{
"body": "<p>In some cases method chaining improves readability (see <a href=\"http://www.infoq.com/articles/internal-dsls-java\">this article</a>) but you usually pay close attention to build your interface to be fluent and most APIs are not designed that way. </p>\n\n<p>In your case, method chaining did not improve readability, so I prefer the second version. </p>\n\n<p>One of the challenges to write readable code is the fact that when you write it, you have all the context in your head. Most code that you write will make sense the time you write it. The challenge is to write code that you (and others) can understand fast when you do not have the context. </p>\n\n<p>One of the things that helped me in the past is to revisit code I wrote months ago and try to understand it. If I struggled with understanding my own code, I tried to improve it to 'tell the story' better. Changed variable names, rearranged methods, extracted code into methods with good names, so the code read like a DSL, like a story. </p>\n\n<p>Oops I guess this is not only about method chaining any more, though I hope it helps :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:00:17.567",
"Id": "5889",
"Score": "0",
"body": "Thank you for your thoughts and the article. I hope this way I can avoid future headaches while debugging :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T23:07:31.330",
"Id": "3931",
"ParentId": "3928",
"Score": "6"
}
},
{
"body": "<p>You can always format v1 like this for more readability:</p>\n\n<pre><code> return insertToDb(\n fillImages(\n fetchInfo(REQUEST_URL, amount))\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T15:52:20.900",
"Id": "5906",
"Score": "2",
"body": "If you take the time to reformat, I strongly suggest that you split it in separate statements (like v2). The minute someone will use an auto-formatter in that code, that careful formatting will be over. And even without auto-formatting, someone else might very well not understand why it is formatted in such a weird way and \"correct\" it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:53:08.010",
"Id": "3933",
"ParentId": "3928",
"Score": "0"
}
},
{
"body": "<p>For me, the 2nd version is better, especially in this case:</p>\n\n<pre><code>protected Boolean doSomething(int amount) {\n if (amount < 1) return false;\n\n return insertToDb(fillImages(fetchInfo(REQUEST_URL, amount)), other_method_call());\n}\n</code></pre>\n\n<p>as you hardly know the order of evaluation of the method calls (maybe Java defines something on this, but C does not). It could be:</p>\n\n<ul>\n<li>fetchInfo, fillImages, other_method_call</li>\n<li>fetchInfo, other_method_call, fillImages</li>\n<li>other_method_call, fetchInfo, fillImages</li>\n</ul>\n\n<p>See this \"<a href=\"https://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c\">Parameter evaluation order before a function calling in C</a>\" for more information on this matter on the C language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T14:15:47.443",
"Id": "5902",
"Score": "0",
"body": "Thank you very much for this. It's always fun to learn new stuff like this, and it is certainly interesting to see how funny such undefined behavior is. Now I have to find out if that is also the case with Java :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T12:07:33.727",
"Id": "3937",
"ParentId": "3928",
"Score": "1"
}
},
{
"body": "<p>My answer is:</p>\n\n<pre><code>protected Boolean doSomething(int amount) {\n return \n amount < 1 ?\n false : \n insertToDb(fillImages(fetchInfo(REQUEST_URL, amount)));\n}\n</code></pre>\n\n<p>If you plan to chain more functions just use whitespace. People have autoformatters so they can read it more easily, so they will change it (unless you provide autoformatter settings with your code).</p>\n\n<p>Keep it short. Every new line you introduce is a place for another bug. Creating temporary variables is sometimes a mess because of naming issues which can lead to creepy bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T16:46:30.703",
"Id": "5942",
"Score": "3",
"body": "I fail to see how this is short. There is the same number of instructions as v2. However, this is obscure and convoluted, difficult to read and to debug. Every new *instruction* is a place for another bug, you do not have any less."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T01:11:35.707",
"Id": "3950",
"ParentId": "3928",
"Score": "0"
}
},
{
"body": "<p>Neither. Both violate the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a>. Your example shows that you need to <a href=\"https://stackoverflow.com/a/163139/830988\">rethink the structure</a> of your classes, and refactor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T13:50:33.913",
"Id": "20584",
"ParentId": "3928",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "3929",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-06T22:17:39.263",
"Id": "3928",
"Score": "8",
"Tags": [
"java"
],
"Title": "Different functions in Java"
}
|
3928
|
<p>I am currently reading <em>The C++ Programming Language</em> (Special Edition) and am learning about using templates. One of the exercises asks you to program a generic version of quicksort. I am hoping to build a namespace called <code>Sorters</code> that has a class for each sorter, just for learning purposes. I would like to also be able to sort objects and avoid copying them when performing swaps, etc.</p>
<p>Basically I am looking for advice on how to improve my algorithm/namespace to work with a wide variety of objects. For now I will stick with quicksort to keep things simple.</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <ctime>
#include <assert.h>
/* Namespace for all types of sorters */
namespace Sorters
{
using std::vector;
using std::copy;
using std::ostream;
using std::ostream_iterator;
using std::cout;
using std::endl;
using std::next_permutation;
using std::distance;
template<class T> class QSorter
{
/* Member functions are described where they are defined */
public:
void PermTester( int N );
void Qsort( typename vector<T>::iterator l, typename vector<T>::iterator r );
private:
vector<T> m_data;
void Swap( typename vector<T>::iterator l, typename vector<T>::iterator r );
friend ostream& operator<< ( ostream &stream, QSorter &qs )
{
copy( qs.m_data.begin( ), qs.m_data.end( ), ostream_iterator<T>( cout, " " ) );
return stream;
}
};
/* This method is for testing my algorithm, it create 1!, 2!, ... N! permutations
for an ordered set of N elements and then passes that to quick sort to be sorted */
template<class T>
void QSorter<T>::PermTester( int N )
{
for( int x=0; x<=N; x++ )
{
m_data = vector<T>( x );
vector<T> perm;
for( int y=0; y<x; y++ )
{
perm.push_back( y+1 );
}
do
{
copy( perm.begin( ),perm.end( ),m_data.begin( ) );
cout << "*****************************************************************" << endl;
cout << "Going to Sort: " << (*this) << endl;
cout << "*****************************************************************" << endl;
Qsort( m_data.begin( ), m_data.end( ) );
cout << "*****************************************************************" << endl;
cout << "Sorted: " << (*this) << endl;
cout << "*****************************************************************" << endl;
} while( next_permutation( perm.begin( ),perm.end( ) ) );
}
m_data.clear( );
}
/* This method is designed to swap two elements pointed to by iterators */
template<class T>
void QSorter<T>::Swap( typename vector<T>::iterator l, typename vector<T>::iterator r )
{
T tmp = (*r);
(*r) = (*l);
(*l) = tmp;
}
/* This is the actual quick sort, it gets the pivot from the middle of the partition */
/* swaps the left element of partition with pivot, then calculates/sorts a left and */
/* and right partition around that pivot. The pivot is moved back between left an*/
/* right partitions and the sort is then called on the left and right side of the*/
/* partitions.*/
template<class T>
void QSorter<T>::Qsort( typename vector<T>::iterator l, typename vector<T>::iterator r )
{
if( r<=l+1 )
{
}
else
{
typename vector<T>::iterator it_pivot =l+distance(l,r)/2;
T pivot = (*it_pivot);
Swap( l,it_pivot );
typename vector<T>::iterator it_l = l+1; // +1 because pivot is at l
typename vector<T>::iterator it_r = r-1; // -1 because r is outside partition
while( it_l <= it_r )
{
while( (*it_l) <= pivot && it_l <= it_r ) ++it_l;
while( (*it_r) >= pivot && it_l <= it_r ) --it_r;
if( it_l <= it_r )
{
Swap( it_l,it_r );
}
}
Swap( l,it_r );
Qsort( l, it_r );
Qsort( it_r, r );
}
}
}
int main( int argc, char *argv[ ] ) {
Sorters::QSorter<float> qs;
qs.PermTester( 5 );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-25T05:03:07.627",
"Id": "166383",
"Score": "0",
"body": "Explaining the unaccepting of the answer doesn't belong in the original post. Instead, provide comments to the answerer."
}
] |
[
{
"body": "<p>First thing your swap is going to kill you on expensive swaps:</p>\n\n<pre><code>template<class T>\nvoid QSorter<T>::Swap( typename vector<T>::iterator l, typename vector<T>::iterator r )\n{\n T tmp = (*r);\n (*r) = (*l);\n (*l) = tmp;\n}\n</code></pre>\n\n<p>Use swap() on the de-referenced types.</p>\n\n<pre><code>template<class T>\nvoid QSorter<T>::Swap( typename vector<T>::iterator l, typename vector<T>::iterator r )\n{\n // If the type T has a defined swap() function this will be used.\n // otherwise it will use std::swap<T> which does what your original code did.\n swap(*l, *r);\n}\n</code></pre>\n\n<p>Here you are making an un-necessary swap. and a copy.</p>\n\n<pre><code> T pivot = (*it_pivot);\n Swap( l,it_pivot );\n</code></pre>\n\n<p>You don't need to choose the value at the pivot point as the value to pivot on. Since the value is random just choose the value at (*l) as the pivot point (this also makes sure it will not be moved as less or equal to the pivot point goes on the left. Thus you can reduce the above too:</p>\n\n<pre><code> T& pivot = *l;\n</code></pre>\n\n<p>All things that are less than or equal go on the left. All things <strong>greater</strong> go on the right. Thus this statement does not work:</p>\n\n<pre><code> while( (*it_r) >= pivot && it_l < it_r ) --it_r;\n // ^^^^ // Your sets or joined.\n</code></pre>\n\n<p>You can make a different choice on how to split the sets but they should be mutually exclusive sets objects should either be on the right or left there should not be objects that can appear on both. </p>\n\n<p>No need to do a continue/swap if they are equal!</p>\n\n<pre><code>/*1*/ while( it_l <= it_r ) // If they are equal no need to continue \n\n /*2*/ if( it_l <= it_r ) // If they are equal no need to swap\n</code></pre>\n\n<p>Looks like this:</p>\n\n<pre><code>void QSorter<T>::Qsort( typename vector<T>::iterator l, typename vector<T>::iterator r ) \n{\n if (distance(l,r) < 2)\n { return;\n }\n // return quickly rather than using an else block.\n // Personally I think this makes the code look cleaner.\n //\n // Note: Because of RAII it is not bad to return early from a C++ function.\n // Though it is considered bad in C (because you need to consider resource release).\n\n\n T& pivot = (*l);\n\n typename vector<T>::iterator it_l = l+1; // +1 because pivot is at l\n typename vector<T>::iterator it_r = r-1; // -1 because r is outside partition\n\n while( it_l < it_r ) \n {\n while( (*it_l) <= pivot && it_l < it_r ) { ++it_l;}\n while( (*it_r) > pivot && it_l < it_r ) { --it_r;}\n if( it_l < it_r ) \n {\n Swap( it_l,it_r );\n }\n }\n // Move the pivot element to the pivot point.\n // Optimized if the values are the same no need to swap\n if (*lt_l < *l) // Note we need to do this because we choose not \n { // to include the pivot point in the loop of comparisons by doing \n // lt = l + 1 above. Thus small arrays of two elements may not be sorted\n Swap(lt_l, l);\n } \n Qsort( l, it_l ); // Sort things smaller than the pivot point\n Qsort( it_r+1, r ); // Sort things larger than the pivot point\n // Note: Do not include pivot point in recursive sort\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T04:57:20.537",
"Id": "5925",
"Score": "0",
"body": "I appreciate your emphasis on increasing performance, very helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-25T23:12:45.360",
"Id": "166518",
"Score": "0",
"body": "Sorting a vector v = [1 3 2] will fail in the above algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-26T05:00:05.853",
"Id": "166550",
"Score": "0",
"body": "@MatthewHoggan: Seems to work for me (after fixing a few minor typos to make it compile)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T19:04:07.103",
"Id": "3943",
"ParentId": "3932",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T00:01:03.263",
"Id": "3932",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"quick-sort",
"template"
],
"Title": "More generic sorting algorithm: using namespaces"
}
|
3932
|
<p>This is a class from my rails application. It is used as non-database model in my RoR application and uses syntax similar to AR design pattern. I wonder is there a way to make this look more like Ruby code?</p>
<pre><code>class Role
def self.all
role_list = Array.new
r1 = Role.new
r1.id = 1
r1.symbol = :owner
r1.name = "Owner"
r1.has_all_permissions = true
role_list << r1
r2 = Role.new
r2.id = 2
r2.symbol = :admin
r2.name = "Administrator"
r2.has_all_permissions = false
role_list << r2
r3 = Role.new
r3.id = 3
r3.symbol = :gamemaster
r3.name = "Gamemaster"
r3.has_all_permissions = false
role_list << r3
role_list
end
def self.find(id)
roles = Role.all
roles.each do |role|
if role.id == id
return role
end
end
nil
end
def self.find_by_symbol(symbol)
roles = Role.all
roles.each do |role|
if role.symbol == symbol
return role
end
end
nil
end
def assign_permission(symbol)
permission = Permission.find_by_symbol(symbol)
if permission == nil
return nil
end
permission_roles = PermissionRole.where(:permission_id => permission.id, :role_id => self.id)
if permission_roles.size == 0
permission_role = PermissionRole.new
permission_role.permission_id = permission.id
permission_role.role_id = self.id
return permission_role.save
end
true
end
def has_permission?(symbol)
permission = Permission.find_by_symbol(symbol)
if permission == nil
raise StandardError, "Permission does not exist"
end
permission_roles = PermissionRole.where(:permission_id => permission.id, :role_id => self.id)
if permission_roles.size > 0
return true
else
return false
end
end
attr_accessor :id
attr_accessor :symbol
attr_accessor :name
attr_accessor :has_all_permissions
end
</code></pre>
|
[] |
[
{
"body": "<p>For starters:</p>\n\n<pre><code>def initialize(attributes = {})\n attributes.each do |attr, value|\n self.send \"#{attr}=\", value\n end\nend\n</code></pre>\n\n<p>Would allow you to turn:</p>\n\n<pre><code>r1 = Role.new\nr1.id = 1\nr1.symbol = :owner\nr1.name = \"Owner\"\nr1.has_all_permissions = true\nrole_list << r1\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>role_list << Role.new {:id => 1,\n :symbol => :owner,\n :name => \"Owner\",\n :has_all_permissions => true}\n</code></pre>\n\n<p>which is much more ActiveRecord-like.</p>\n\n<hr>\n\n<p>Storing the roles_list in a global variable might be acceptable for your application and would also allow you to have:</p>\n\n<pre><code>def self.create(attributes = {})\n $roles_list << Role.new(attributes)\nend\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>def self.all\n return $roles_list if $roles_list\n\n # rest of code to init $roles_list with default roles\nend\n</code></pre>\n\n<p>for further ActriveRecord-ness</p>\n\n<hr>\n\n<p>Then:</p>\n\n<pre><code>def self.find(id)\n roles = Role.all\n\n roles.each do |role|\n if role.id == id\n return role\n end\n end\n\n nil\nend\n</code></pre>\n\n<p>could be re-written like so:</p>\n\n<pre><code>def self.find(id)\n Role.all.find{|r| r.id == id}\nend\n</code></pre>\n\n<p>That is because Array has its own #find method. The same refactoring could be applied to <code>self.find_by_symbol</code>.</p>\n\n<hr>\n\n<p>As a final note, I would move the <code>attr_accessor</code> lines to the top.</p>\n\n<p>Hope I helped :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-21T21:31:09.930",
"Id": "8371",
"Score": "0",
"body": "You could also include ActiveModel in this to give it a nice AR-style interface even without a DB connection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:23:24.450",
"Id": "4472",
"ParentId": "3934",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4472",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T06:05:11.073",
"Id": "3934",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"classes"
],
"Title": "How would you ruby-fy this non-AR model class for Ruby on Rails app?"
}
|
3934
|
<p>I have something like this in my program:</p>
<pre><code> private void tspBrush_Click(object sender, EventArgs e)
{
currentTool = new Brush(tileLayers);
UncheckToolstripButtons();
tspBrush.Checked = true;
}
private void tspBucket_Click(object sender, EventArgs e)
{
currentTool = new Bucket(tileLayers);
UncheckToolstripButtons();
tspBucket.Checked = true;
}
private void tspCut_Click(object sender, EventArgs e)
{
currentTool = new Cut(tileLayers);
UncheckToolstripButtons();
tspCut.Checked = true;
}
</code></pre>
<p>As I increase the amount of tools this list will only get longer. Is there something I could do to shorten it? </p>
|
[] |
[
{
"body": "<p>I'm calling the common item \"Tool\" but I'm sure you have another name for it...</p>\n\n<pre><code>private void tspBrush_Click(object sender, EventArgs e)\n {\n setTool(tspBrush);\n }\n\nprivate void tspBucket_Click(object sender, EventArgs e)\n {\n setTool(tspBucket);\n }\n\nprivate void tspCut_Click(object sender, EventArgs e)\n {\n setTool(tspCut);\n }\n\nprivate void setTool(Tool tool)\n {\n currentTool = new Brush(tileLayers);\n\n UncheckToolstripButtons();\n\n tool.Checked = true;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T16:55:38.070",
"Id": "5909",
"Score": "0",
"body": "I'm not sure how this works? setTool just creates a new brush for all of them and Tool does not have a Checked property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T14:41:22.960",
"Id": "5940",
"Score": "0",
"body": "I knew I shouldn't have called it \"Tool\". The thing is, whatever class tspCut, tspBrush, and tspBucket are - that is the correct class to be the parameter to setTool. Maybe I should have called it Tsp."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T16:31:13.583",
"Id": "3939",
"ParentId": "3938",
"Score": "1"
}
},
{
"body": "<p>one way of shortening might be: </p>\n\n<ul>\n<li><p>having a HashMap consisting of pairs of objects (sender) and Tools. This way you could look up the appropriate Tool for each sender in one single method like this:</p>\n\n<pre><code>HashMap<object, Tool> hashMap = new HashMap<object, Tool>( );\n\nhashMap.put(sender1, new Brush(tileLayers));\n\n// ...add the rest of the Tools\nprivate void clickHandler(object sender, EventArgs e)\n{\n currentTool = hashMap.get(sender);\n\n UncheckToolstripButtons( );\n tspBrush.Checked = true;\n}\n</code></pre></li>\n<li><p>If tspXxxx cannot be retrieved from the sender directly, use another HashMap to map senders to tspXxxx objects.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T01:51:49.017",
"Id": "5922",
"Score": "0",
"body": "+1: Can't really tell if the OP is C# or Java, but it looks like a HashMap is the same as a `Dictionary<TKey, TValue>` ...???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T10:02:33.543",
"Id": "5932",
"Score": "2",
"body": "Just had a look at the C# class Dictionary<TKey, TValue> and it seems to implement the same functionality as HashMap in Java, yeah. And since the parameter type 'object' is written in lowercase it's C#, sorry for my assuming it was Java. But the solution does apply though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T17:02:20.563",
"Id": "3940",
"ParentId": "3938",
"Score": "11"
}
},
{
"body": "<p>Apologise errors in the pseudo-code please - I don't have a C# compiler on this machine. \nIf it is possible to make an interface \"Checkable\" that tspCut, tspBrush, tspBucket and their future siblings must obey, you could use a Factory.</p>\n\n<pre><code>private void tspCut_Click(object sender, EventArgs e) \n{ \n createTool( Click.GetType(), tspCut ); \n} \n\nprivate void createTool( ToolType tt, Checkable tsp ) \n{ \n currentTool = ToolFactory.create( tt ); \n UncheckToolstripButtons( ); \n tsp.Checked = true; \n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T17:20:50.543",
"Id": "3941",
"ParentId": "3938",
"Score": "1"
}
},
{
"body": "<p>It's difficult to say something definit, because a lot of information is missing.\nBut here is my approach:<br>\n1. Create type of the tool:</p>\n\n<pre><code> private enum ToolType\n {\n Brush,\n Bucket,\n Cut\n }\n</code></pre>\n\n<p>2. Create inner helper class:</p>\n\n<pre><code> // Inner class that represents a tool in this particular form (control, page)\n private class UITool\n {\n public MyToolType Type { get; set; }\n public Tool Tool { get; set; } //'Tool' is the parent of Brush, Bucket, Cut\n public CheckBox ToolCheckBox { get; set; } //'CheckBox' a base class for tspBrush, tspBucket, tspCut\n\n /*If tspBrush, tspBucket, tspCut don't belong to the same base class with Checked property,\n then don't use ToolCheckBox property and use SetToolCollback instead.\n public Action SetToolCollback { get; set; } */\n }\n</code></pre>\n\n<p>3. Create private property</p>\n\n<pre><code>private List<UITool> _uiTools = new List<UITool>();\n</code></pre>\n\n<p>4. Init it somewhere</p>\n\n<pre><code> _uiTools.Add(new UITool()\n {\n Type = ToolType.Brush,\n Tool = new Brush(tileLayers),\n ToolCheckBox = tspBrush\n });\n</code></pre>\n\n<p>or if you use SetToolCollback property:</p>\n\n<pre><code> _uiTools.Add(new UITool()\n {\n Type = ToolType.Brush,\n Tool = new Brush(tileLayers),\n SetToolCollback = () => tspBrush.Checked = true\n });\n</code></pre>\n\n<p>5. Create method:</p>\n\n<pre><code> private void SelectTool(ToolType toolType)\n {\n var utTool = _uiTools.Select(i => i.Type == toolType).Single();\n currentTool = utTool.Tool;\n UncheckToolstripButtons();\n utTool.ToolCheckBox.Checked = true; \n //If using SetToolCollback\n //utTool.SetToolCollback();\n }\n</code></pre>\n\n<p>6. Use this method:</p>\n\n<pre><code>private void tspBrush_Click(object sender, EventArgs e)\n{\n SelectTool(ToolType.Brush);\n}\n</code></pre>\n\n<p>As a variant, you can replace ToolType with the type of 'sender' and use common event handler for all tools like Jan Bolting have suggested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T01:46:28.807",
"Id": "5921",
"Score": "0",
"body": "using the enumerator seems to make this much more difficult than it should be"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T07:33:32.000",
"Id": "5928",
"Score": "1",
"body": "@IAbstract - It may seems difficult, but in the end it allows you to add new tools more easily. Actually, this approach is like Jan Bolting's approach, the only difference is in the helper class UITool. So, instead of getting a concrete tool from the HasMap and getting 'tspXXX' from another HasMap, you get a UITool with all nessesary data."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T18:14:54.880",
"Id": "3942",
"ParentId": "3938",
"Score": "1"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/questions/3938/this-code-looks-really-repetitive-any-way-to-shorten-it/3940#3940\">Jan's answer</a> converted to C# (assuming <code>tspBrush</code> is a <code>ToolStripMenuItem</code>):</p>\n\n<pre><code> Dictionary<ToolStripMenuItem, Tool> tools = new Dictionary<ToolStripMenuItem, Tool>();\n\n // for each tool:\n tools.Add(tspBrush, new Brush(tileLayers));\n tspBrush.Click += toolMenuItem_Click;\n\n\n private void toolMenuItem_Click(object sender, EventArgs e)\n {\n var menuItem = (ToolStripMenuItem)sender;\n\n currentTool = tools[menuItem];\n UncheckToolstripButtons();\n menuItem.Checked = true;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T12:48:32.000",
"Id": "3962",
"ParentId": "3938",
"Score": "0"
}
},
{
"body": "<p>A more attractive solution IMHO would be to associate your tool items with the buttons themselves using the <code>Tag</code> property. That way you could have one single click event handler for all your tool buttons. Remember, the <code>sender</code> that is passed to your handler is the control that initiated the event so you don't need to wire it to a specific control, but more general to be used for all controls. Furthermore, using <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\" rel=\"nofollow\"><code>Lazy<T></code></a> wrapping your tools to ensure that you only instantiate one instance of them only when you need it (if and when you need it). This would go smoothly if all your tools implemented a certain interface or derived from the same class.</p>\n\n<pre><code>// associating the buttons\ntspBrush.Tag = new Lazy<ITool>(() => new Brush(tileLayers));\ntspBucket.Tag = new Lazy<ITool>(() => new Bucket(tileLayers));\ntspCut.Tag = new Lazy<ITool>(() => new Cut(tileLayers));\n\n// THE click handler\nprivate void ToolButton_Click(object sender, EventArgs e)\n{\n var button = sender as ToolStripButton;\n if (button == null) return;\n var lazy = button.Tag as Lazy<ITool>;\n if (lazy == null) return;\n\n currentTool = lazy.Value;\n UncheckToolstripButtons();\n button.Checked = true;\n}\n</code></pre>\n\n<p>If you need to recreate the tools every time, then rather than using <code>Lazy<T></code> to wrap it, you could use the <code>Func<ITool></code> instead to create the tool every time. Then it would be:</p>\n\n<pre><code>// associating the buttons\ntspBrush.Tag = new Func<ITool>(() => new Brush(tileLayers));\ntspBucket.Tag = new Func<ITool>(() => new Bucket(tileLayers));\ntspCut.Tag = new Func<ITool>(() => new Cut(tileLayers));\n\n// THE click handler\nprivate void ToolButton_Click(object sender, EventArgs e)\n{\n var button = sender as ToolStripButton;\n if (button == null) return;\n var factory = button.Tag as Func<ITool>;\n if (factory == null) return;\n\n currentTool = factory();\n UncheckToolstripButtons();\n button.Checked = true;\n}\n</code></pre>\n\n<p>However if you needed to go this route, I would suggest adding methods to update the tools instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T20:28:14.787",
"Id": "3971",
"ParentId": "3938",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "3940",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T16:00:18.837",
"Id": "3938",
"Score": "5",
"Tags": [
"c#"
],
"Title": "This code looks really repetitive. Any way to shorten it?"
}
|
3938
|
<p>I am preparing myself for some job interviews. This is a simple array (with the error handling left out for brevity). Any input or suggestions on style and the use of templates would be appreciated.</p>
<pre><code> #include <iostream>
template <class T>
class Array {
public:
explicit Array(const int&);
Array(const int&, const T&);
Array(const Array&);
virtual ~Array();
T getVal(const int&) const;
void setVal(const int&, const T&);
T& operator[] (T);
Array& operator= (const Array&);
template <class U>
friend std::ostream& operator<< (std::ostream&, const Array<U>&);
private:
T* arr;
int size;
};
template <class T>
Array<T>::Array(const int& init_size) {
arr = new T[init_size];
size = init_size;
}
template <class T>
Array<T>::Array(const int& init_size, const T& init_value) {
arr = new T[init_size];
size = init_size;
for (int i = 0; i < size; ++i) {
arr[i] = init_value;
}
}
template <class T>
Array<T>::Array(const Array& original) {
size = original.size;
arr = new T[size];
for (int i = 0; i < size; ++i) {
arr[i] = original.arr[i];
}
}
template <class T>
Array<T>::~Array() {
delete [] arr;
}
template <class T>
T Array<T>::getVal(const int& index) const {
return arr[index];
}
template <class T>
void Array<T>::setVal(const int& index, const T& value) {
arr[index] = value;
}
template <class T>
T& Array<T>::operator[] (T index) {
return arr[index];
}
template <class T>
Array<T>& Array<T>::operator= (const Array& copy) {
if (arr == copy.arr)
return *this;
size = copy.size;
delete [] arr;
arr = new T[size];
for (int i = 0; i < size; ++i) {
arr[i] = copy.arr[i];
}
return *this;
}
template <class T>
std::ostream& operator<< (std::ostream& out, const Array<T>& self) {
out << "[ ";
for (int i = 0; i < self.size-1; ++i) {
out << self.arr[i] << ", ";
}
out << self.arr[self.size-1] << " ]";
return out;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T19:53:36.880",
"Id": "5912",
"Score": "0",
"body": "White space is your friend when it comes to readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T22:41:12.080",
"Id": "5917",
"Score": "0",
"body": "Oddly enough, I killed off much of the white space in order to post it. I know not to do that now."
}
] |
[
{
"body": "<p>Any reason why you pass integers as const references - it will merely slow down your code, and possible confuse the reader, for no benefit.</p>\n\n<p>I'm rusty on templates, so I could be wrong, but doesn't </p>\n\n<pre><code> Array(const Array&);\n</code></pre>\n\n<p>Allow you to try to construct an Array from an Array - shouldn't it be</p>\n\n<pre><code> Array(const Array<T>&);\n</code></pre>\n\n<p>Likewise for assignment operator.</p>\n\n<p>Just a couple of thoughts off the top of my head on a Sunday evening.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T20:11:58.837",
"Id": "3945",
"ParentId": "3944",
"Score": "0"
}
},
{
"body": "<p>In the constructor that just takes a size. I would initialize all members to their default value even if POD.</p>\n\n<pre><code>template <class T>\nArray<T>::Array(const int& init_size)\n{\n arr = new T[init_size]();\n // ^^^^^ Add braces. on types it makes no difference.\n // On POD it will force zero initialization.\n size = init_size;\n}\n</code></pre>\n\n<p>Use the initializer lists in your constructors.</p>\n\n<pre><code>template <class T>\nArray<T>::Array(const int& init_size)\n : arr(new T[init_size]())\n , size(init_size)\n{}\n</code></pre>\n\n<p>Use copy and swap idiom for assignment operator (it automatically provides the strong exception guarantee).</p>\n\n<pre><code>template <class T>\nArray<T>& Array<T>::operator= (const Array& copy)\n{\n if (arr == copy.arr) // This is the wrong test.\n return *this; // Though it works as a side effect you will confuse the maintainer.\n\n size = copy.size;\n delete [] arr; // breaks the strong exception gurantee.\n // What it the next line fails? Then you are left with an object\n // in an inconsistent state. (arr points at de-allocated memory)\n arr = new T[size];\n\n for (int i = 0; i < size; ++i)\n {\n arr[i] = copy.arr[i];\n }\n return *this;\n}\n</code></pre>\n\n<p>If you want to do this the hard way then it should look like this:</p>\n\n<pre><code>template <class T>\nArray<T>& Array<T>::operator= (const Array& copy)\n{\n if (this == &copy) // Return quickly on assignment to self.\n { return *this;\n }\n\n // Do all operations that can generate an expception first.\n // BUT DO NOT MODIFY THE OBJECT at this stage.\n T* tmp = new T[size];\n for (int i = 0; i < size; ++i)\n {\n tmp[i] = copy.arr[i];\n }\n\n // Now that you have finished all the dangerous work.\n // Do the operations that change the object.\n std::swap(tmp, arr);\n size = copy.size;\n\n // Finally tidy up\n delete tmp; // Notice the swap above.\n\n // Now you can return\n return *this;\n}\n</code></pre>\n\n<p>Alternatively use the copy and swap idiom</p>\n\n<pre><code>template <class T>\nArray<T>& Array<T>::operator=(Array const& rhs)\n{\n // 1 Copy\n Array copy(rhs); // Use the copy constructor to make a safe copy.\n\n // 2 Swap\n swap(arr, copy.arr);\n swap(size, copy.size);\n\n} // 3 as the local copy goes out of scope it destroys the old array.\n</code></pre>\n\n<p>Note this can be optimized too:</p>\n\n<pre><code>Array<T>& Array<T>::operator=(Array rhs) // 1 implicit copy as parameter is passed by value\n{\n // 2 Swap\n swap(arr, copy.arr);\n swap(size, copy.size);\n\n} // 3 as the local copy goes out of scope it destroys the old array.\n</code></pre>\n\n<p>You <strong>don't need</strong> a get/set methods. Infact get/set is an obvious indication of bad design.</p>\n\n<pre><code>template <class T>\nT Array<T>::getVal(const int& index) const {\n return arr[index];\n}\n\ntemplate <class T>\nvoid Array<T>::setVal(const int& index, const T& value) {\n arr[index] = value;\n}\n</code></pre>\n\n<p>Just remove both these methods. What you want to do is return a reference to the internal object in your overload of operator[] (which you do) bit the index is an integer usually.</p>\n\n<pre><code>template <class T>\nT& Array<T>::operator[] (size_t index)\n{ // ^^^^^^^ Changed type here.\n return arr[index];\n}\n</code></pre>\n\n<p>You also need to provide a verision to use when your array is const.</p>\n\n<pre><code>template <class T>\nT const& Array<T>::operator[] const (size_t index)\n//^^^^^ Here ^^^^^ and here.\n{\n return arr[index];\n}\n</code></pre>\n\n<p>If you provide an output operator you should generally by symmetric and provide an input operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T22:42:40.860",
"Id": "5918",
"Score": "0",
"body": "Your review has proven to be extremely helpful. I am taking it all in and will attempt another data structure with these comments in mind. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T23:29:48.307",
"Id": "5919",
"Score": "0",
"body": "\"Copy and swap\" idiom is clever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T00:00:57.017",
"Id": "5920",
"Score": "0",
"body": "@Charles: I did not mention it. But if you look at the stl, all the containers provide an explicit swap() method. This allows assignment operator to be implemented as a single call to swap. This is done becuase you generally want to be able to implement the swap function (not method) as a simple call to a swap method anyway. Thus by having a swap method you keep the code in a single place. Note: swap() and destructor() are usually the two functions are declared as no throw operations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T20:12:47.730",
"Id": "3946",
"ParentId": "3944",
"Score": "10"
}
},
{
"body": "<p>@Martin (in particular) has already given some excellent advice on a number of points, but I think there are a few more that are worth mentioning.</p>\n\n<p>First of all, you've used the thrice-accursed <code>array new</code> expression to allocate your memory. Although this works (for a sufficiently loose definition of \"works\") it's not ideal, at least in my opinion.</p>\n\n<p>I'd prefer to use <code>::operator new</code> to allocate \"raw\" memory, and then using placement new to copy objects into the array.</p>\n\n<p>Second, you've provided both an explicit constructor to create uninitialized storage, and an two-parameter constructor to create an Array initialized to a specified value. I think I'd prefer to condense the two into a single constructor with a default argument for the initial value, so you can never (even accidentally) create an <code>Array</code> of uninitialized data.</p>\n\n<p>Third, if (for whatever reason) the user's copy ctor throws an exception while we're initializing our data, we want to ensure that we destroy (only) the objects we've created. Incorporating those, we end up with a ctor something like this:</p>\n\n<pre><code>template <class T>\nArray<T>::Array(size_t init_size, const T& init_value) : \n arr((T *)::operator new(init_size * sizeof(T))),\n{\n for (size = 0; size<init_size; ++size)\n new(arr+size) T(init_value);\n}\n</code></pre>\n\n<p>Note that instead of a local variable to walk through the array and initialize the values, we use <code>size</code>, so <em>if</em> an exception got thrown during the loop, <code>size</code> will contain a count of the items we successfully initialized. Of course, we need to modify the copy ctor to match:</p>\n\n<pre><code>template <class T>\nArray<T>::Array(const Array &original) :\n arr((T *)::operator new(original.size * sizeof(T))),\n{\n for (size = 0; size < original.size; ++size) \n new(arr+size) T(original.arr[size]);\n}\n</code></pre>\n\n<p>Then in our dtor, we can make use of that to destroy exactly/only the objects that were successfully constructed. To fit normal conventions, we destroy those in reverse order of creation:</p>\n\n<pre><code>template <class T>\nArray<T>::~Array() {\n for (size_t i=size+1; i>0; --i)\n arr[i-1].~T();\n ::operator delete(arr);\n}\n</code></pre>\n\n<p>To go with this, you (of course) need to modify your class definition to match:</p>\n\n<pre><code>template <class T>\nclass Array {\n T* arr;\n size_t size;\npublic:\n explicit Array(size_t, const T& init_value = T());\n Array(const Array&);\n ~Array();\n T& operator[] (size_t);\n Array& operator= (Array);\n};\n</code></pre>\n\n<p>One last minor detail: you had your dtor marked as <code>virtual</code>, but since the class contains no other virtual functions, it doesn't seem to be particularly suited to use as a base class. That being the case, I've made the dtor non-virtual.</p>\n\n<p>The other thing I think I'd do if I were writing a class like this would be to add enough for it to act as a container, as that's defined by the standard (define an <code>iterator</code> type, <code>value_type</code>, <code>begin()</code> and <code>end()</code> that return iterators, etc.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T03:00:42.210",
"Id": "4000",
"ParentId": "3944",
"Score": "3"
}
},
{
"body": "<p>Seeing as you provide <code>operator[]</code>, you do not need to make <code>operator<<</code> a friend: you can be fairly certain that <code>operator[]</code> will be inlined, anyway (although you should provide a const version of it, as someone suggested).</p>\n\n<p>Personally, I would use a scoped pointer for arr in order to make it more exception-safe (with NDEBUG enabled, it should not cause any runtime overhead). (The copy-and-swap idiom works for this, too.)</p>\n\n<p>By the way, I'm guessing your <code>operator[]</code> taking a <code>T</code> was a typo -- it should take <code>size_t</code>, as should pretty much everything that currently takes <code>int</code>.</p>\n\n<p>I don't see an issue with your <code>getVal</code> and <code>setVal</code> functions -- they do exactly the same thing as <code>operator[]</code>, and are just a more verbose way of writing things out (more normal is an <code>at</code> function that does out-of-bounds checking and returns a reference, but not a big deal).</p>\n\n<p>I wouldn't call your class <code>Array</code>, as this, in my mind, associates with things of a compile-time size -- at least <code>DynArray</code> would be more accurate.</p>\n\n<p>Finally, a function that would be trivial to implement is <code>size</code>, and I think the lack of it could be very troublesome.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T17:18:59.940",
"Id": "4091",
"ParentId": "3944",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "3946",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-07T19:50:04.700",
"Id": "3944",
"Score": "7",
"Tags": [
"c++",
"array",
"template"
],
"Title": "Simple array implementation without bounds-checking"
}
|
3944
|
<p>I am attempting to learn R programming by going through the questions in <a href="http://projecteuler.net/index.php?section=problems" rel="nofollow">Project Euler</a>. </p>
<p>The code below is my solution to <a href="http://projecteuler.net/index.php?section=problems" rel="nofollow">problem 5</a> which asks for the smallest number that is evenly divisible by 1 through 20.</p>
<p>The code works but takes a very very long time. Project Euler states that all of their problems should take a modern computer < 1 minute. </p>
<p>I know R is not as efficient as other languages but would it be possible to make my solution more efficient?</p>
<pre><code>divis <- function(){
count = 11
tst <- 1:20 %% count # create vector of remainders
while(sum(tst) != 0){ # test if all remainders are 0
count <- count + 1
tst <- count %% 1:20
print(count)
print(tst)
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You should change the algorithm in order to make your program run faster. The while loop is performed over 200 million times (printing out information in every iteration) until it reaches the desired number.</p>\n\n<p>If you calculate the answer using LCM (taking the least common multiple of all numbers between 1 and 20), the program should run instantly in pretty much any programming language.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T08:41:10.290",
"Id": "3960",
"ParentId": "3953",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "3960",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T02:23:55.140",
"Id": "3953",
"Score": "4",
"Tags": [
"project-euler",
"r"
],
"Title": "How can I get this R code to pass the \"1 minute\" test for this Project Euler question?"
}
|
3953
|
<p>I'm writing GUI controls and there are many places where there are many nested <code>if</code>s checking for some result.</p>
<pre><code>function TMyObject.GetCursor: TCursor;
begin
if CanDragX then
begin
if CanDragY then
Result := crSizeAll
else
Result := crSizeWE;
end
else if CanDragY then
Result := crSizeNS
else
if CanClick then
Result := crHandPoint
else
Result := crArrow;
end;
</code></pre>
<p>How would you format/rewrite this code?</p>
|
[] |
[
{
"body": "<p>I would do this:</p>\n\n<pre><code>function TMyObject.GetCursor: TCursor;\nbegin\n if CanDragX and CanDragY then\n Result := crSizeAll\n else if CanDragX then\n Result := crSizeWE\n else if CanDragY then\n Result := crSizeNS\n else\n if CanClick then\n Result := crHandPoint\n else\n Result := crArrow;\nend;\n</code></pre>\n\n<p>But really it is a matter of style and what is most readable to you (and the person who will maintain it).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T08:03:16.513",
"Id": "5929",
"Score": "0",
"body": "Thanks for your answer. I know this is a trivial case, but maybe I'm overlooking something, thats why I asked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T12:27:34.237",
"Id": "5935",
"Score": "0",
"body": "@Krom The only change I'd suggest to this answer is to put the \"if CanClick then\" on the same line with the preceeding \"else\" and adjust the following indentation accordingly. Like Martin said, it's just a matter of style."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T07:00:57.933",
"Id": "3957",
"ParentId": "3954",
"Score": "5"
}
},
{
"body": "<p>I'm not sure of what your language is. Instead of assigning to Result, I prefer mid-function returns in a case like this; then I don't need else.</p>\n\n<pre><code>function TMyObject.GetCursor: TCursor;\nbegin\n if CanDragX && CanDragY then return crSizeAll;\n if CanDragX then return crSizeWE;\n if CanDragY then return crSizeNS;\n if CanClick then return crHandPoint;\n return crArrow;\nend;\n</code></pre>\n\n<p>If that works in your language (VB?), I think that's much cleaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T05:11:13.470",
"Id": "5954",
"Score": "3",
"body": "It's Delphi, unfortunately there was no Delphi tag prior my question, I should have added that. In Delphi2009+ it would be \"Exit (crSizeAll)\" instead of \"return crSizeAll\". Thats a nice idea, unfortunately it does not work in Delphi7. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T15:05:48.967",
"Id": "3967",
"ParentId": "3954",
"Score": "4"
}
},
{
"body": "<p>Using bitwise OR, and assuming this is some form of Pascal, but same applies to any languiage:</p>\n\n<pre><code>VAR:\n res : integer\n\nres := (ord(CanClick) * 4) OR (ord(CanDragY) * 2) OR ord(CanDragX);\ncase res of\n 0: Result := crArrow; // 0 0 0 \n 1, 5: Result := crSizeWE; // 0 0 1 or 1 0 1\n 2, 6: Result := crSizeNS; // 0 1 0 or 1 1 0\n 3, 7: Result := crSizeAll; // 0 1 1 or 1 1 1\n 4: Result := crHandPoint; // 1 0 0\nend;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T11:11:02.310",
"Id": "20939",
"Score": "2",
"body": "The need for comments should be an alarm bell screaming: Houston we have a problem!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T18:37:11.313",
"Id": "3969",
"ParentId": "3954",
"Score": "0"
}
},
{
"body": "<p>As there are only 8 possible results, you can put them into mapping array. Then function itself will be one-liner only.</p>\n\n<pre><code>const\n CursorMap: array [boolean, boolean, boolean] // CanClick, CanDragX, CanDragY\n of TCursor = // see CanClick, CanDragX indexes values below:\n (((crArrow, crSizeNS), // false, false\n (crSizeWE, crSizeAll)), // false, true\n ((crHandPoint, crSizeNS), // true, false\n (crSizeWE, crSizeAll))); // true, true\n\n\nfunction TMyObject.GetCursor: TCursor;\nbegin\n Result:= CursorMap[CanClick, CanDragX, CanDragY];\nend;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T11:08:58.007",
"Id": "20938",
"Score": "0",
"body": "Clever way to make the function itself a single line. But you've moved all the complexity into `CursorMap`, and the need for comments should be proof enough that this is a bad idea. As you add more variables, the problem simply gets worse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T15:20:52.483",
"Id": "20950",
"Score": "2",
"body": "@CraigYoung, I just told that there is such way also. May it'll be useful for somebody.\nMy personal favorite answer is with `return`s, by @CarlManaster"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-10T18:53:24.457",
"Id": "5289",
"ParentId": "3954",
"Score": "2"
}
},
{
"body": "<p>In a method like this I like to make it clear up front that the default Result is crArrow and the rest of the routine is simply considering situations in which the default would be insufficient.</p>\n\n<pre><code>function TMyObject.GetCursor: TCursor;\nbegin\n Result := crArrow;\n\n if CanDragX and CanDragY then Result := crSizeAll\n else if CanDragX then Result := crSizeWE\n else if CanDragY then Result := crSizeNS\n else if CanClick then Result := crHandPoint;\nend;\n</code></pre>\n\n<p>This is somewhat similar to <a href=\"https://codereview.stackexchange.com/a/3967/14352\">Carl's answer</a>, but compensating for the fact that Delphi does not provide a single operation to both set Result and return.</p>\n\n<p>A key difference to note here is that it is very important to be aware of the impact of <code>else if</code> vs simple <code>if</code>. For example, if you reverse the order of the checks, then you have to implement as follows:</p>\n\n<pre><code>if CanClick then Result := crHandPoint;\nif CanDragY then Result := crSizeNS;\nif CanDragX then Result := crSizeWE;\nif CanDragX and CanDragY then Result := crSizeAll;\n</code></pre>\n\n<p>A more direct translation of Carl's answer might prove a little less error prone, albeit more verbose:</p>\n\n<pre><code>if CanDragX and CanDragY then\nbegin\n Result := crSizeAll;\n Exit;\nend;\nif CanDragX then\nbegin\n Result := crSizeWE;\n Exit;\nend;\n...\n</code></pre>\n\n<p>Even then I suspect mistakes would be easy to make.<br>\nAlthough I dislike both Sunny's and Sergiy's answers because they <strong>need</strong> comments for clarification, there's a lot to be said for explicitly mapping each permutation. Consider the following pseudo-code:</p>\n\n<pre><code>case [DragX, DragY, Click] of\n [CanDragX, CanDragY, CanClick] : Result := crSizeAll;\n [CanDragX, CanDragY, NotClick] : Result := crSizeAll;\n [CanDragX, NotDragY, CanClick] : Result := crSizeWE;\n [CanDragX, NotDragY, NotClick] : Result := crSizeWE;\n [NotDragX, CanDragY, CanClick] : Result := crSizeNS;\n [NotDragX, CanDragY, NotClick] : Result := crSizeNS;\n [NotDragX, NotDragY, CanClick] : Result := crHandPoint;\n [NotDragX, NotDragY, NotClick] : Result := crArrow;\nend;\n</code></pre>\n\n<p>It would be wonderful if Delphi's enums and sets supported such syntax, but similar can be achieved using a self-documenting variation of <a href=\"https://codereview.stackexchange.com/a/3969/14352\">Sunny's</a> answer:</p>\n\n<pre><code>const\n cCannotDo = 0;\n cCanDragX = 1;\n cCanDragY = 2;\n cCanClick = 4;\nvar\n LMouseOptions: Integer;\nbegin\n LMouseOptions := Ord(CanDragX)*cCanDragX +\n Ord(CanDragY)*cCanDragY +\n Ord(CanClick)*cCanClick;\n case LMouseOptions of\n cCanDragX + cCanDragY + cCanClick : Result := crSizeAll;\n cCanDragX + cCanDragY + cCannotDo : Result := crSizeAll;\n cCanDragX + cCannotDo + cCanClick : Result := crSizeWE;\n cCanDragX + cCannotDo + cCannotDo : Result := crSizeWE;\n cCannotDo + cCanDragY + cCanClick : Result := crSizeNS;\n cCannotDo + cCanDragY + cCannotDo : Result := crSizeNS;\n cCannotDo + cCannotDo + cCanClick : Result := crHandPoint;\n cCannotDo + cCannotDo + cCannotDo : Result := crArrow;\n else\n //Either raise error or return crArrow as default\n end;\nend;\n</code></pre>\n\n<p>However, the permutations can get unwieldy as more flags and even multi-value options are added. So personally I would go for my first option, and implement unit tests to run through all the cases of interest.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T12:24:32.407",
"Id": "12971",
"ParentId": "3954",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "3957",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T05:51:59.267",
"Id": "3954",
"Score": "5",
"Tags": [
"delphi"
],
"Title": "Nested IF code in GUI Controls"
}
|
3954
|
<p>Is this code too cryptic? Simple yes or no question. Feedback is optional.</p>
<pre><code>int recursive_euclidean( int num1, int num2 )
{
int gcd=0;
if( num1 == num2 || num1 < 0 || num2 < 0 )
( ( num1 == num2 ) ? ( gcd = num1 ) : ( ( num1 < 0) ? ( gcd = num2 ) :
( gcd = num1 ) ) );
else
( ( num1 > num2 ) ? ( gcd = recursive_euclidean( num1-num2, num2 ) ) :
( gcd = recursive_euclidean( num1, num2-num1 ) ) );
return gcd;
}
int iterative_euclidean( int num1, int num2 )
{
while( num1 != num2 && num1 > 0 && num2 > 0 )
(( num1 > num2 ) ? (num1-=num2) : (num2-=num1) );
return (num1>0) ? num1 : num2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T11:15:05.210",
"Id": "5933",
"Score": "0",
"body": "Mathematically this is not quite correct, `gcd(2, -2) = 2` is a better choice. `gcd(2, -2) = -2` is also correct, as in terms of divisibility `n` and `-n` are essentially the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T11:16:15.410",
"Id": "5934",
"Score": "2",
"body": "Note that for an efficient `gcd` computation you need to use the `%` operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T16:42:45.303",
"Id": "5941",
"Score": "0",
"body": "perhaps you mean \"**too** cryptic\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T01:04:39.747",
"Id": "6506",
"Score": "0",
"body": "Yes this code is WAY too cryptic. gcd? what's that? If it's greatest common denominator, then name your variable \"greatest_common_denominator\". Favor *read-time* convenience over *write-time* convenience. It reminds me of the cryptic K&R old school C style. Make your code read like English. I'd suggest reading the books \"Code Complete\" and also \"Clean Code\"."
}
] |
[
{
"body": "<p>I don't like the multiple different assignments inside the operator.<br>\nThey currently all assign to <code>gcd</code> but you need to study it in detail to work that out.<br>\nI would make the assignment explicit and the ternary operator return the correct value.</p>\n\n<p>The other thing with ternary operator is that they are not trivial to read. So use white space to try and make it obvious that it's happening. Also I prefer to explicitly use '{' '}' to make sure that things don't accidentally become associated with the a different statement. I would lay it out like this:</p>\n\n<pre><code>int recursive_euclidean( int num1, int num2 )\n{\n int gcd;\n\n if( num1 == num2 || num1 < 0 || num2 < 0 ) \n {\n gcd = (num1 == num2)\n ? num1\n : (num1 < 0)\n ? num2\n : num1;\n }\n else\n {\n gcd = (num1 > num2)\n ? recursive_euclidean( num1-num2, num2 )\n : recursive_euclidean( num1, num2-num1 );\n }\n return gcd;\n}\n</code></pre>\n\n<p>Actually reading this again I would refactor more to this:</p>\n\n<pre><code>int recursive_euclidean( int num1, int num2 )\n{\n int gcd;\n\n if ( num1 == num2)\n { gcd = num1;\n }\n else if (num1 < 0)\n { gcd = num2;\n }\n else if (num2 < 0)\n { gcd = num1;\n }\n else\n {\n gcd = (num1 > num2)\n ? recursive_euclidean( num1-num2, num2 )\n : recursive_euclidean( num1, num2-num1 );\n }\n return gcd;\n}\n</code></pre>\n\n<p>Then here, I would not personally not use the ternary operator.</p>\n\n<pre><code>int iterative_euclidean( int num1, int num2 )\n{\n while( num1 != num2 && num1 > 0 && num2 > 0 )\n {\n if (num1 > num2 )\n { num1-=num2;}\n else{ num2-=num1;}\n }\n return (num1>0) ? num1 : num2;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T07:12:01.400",
"Id": "3958",
"ParentId": "3955",
"Score": "21"
}
},
{
"body": "<p>I think the simple test would be to have an outsider read the code and understand what it does. I did just that, and its perfectly readable to me. Actually, I find it to be a perfect mix of readability and compactness.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T08:15:37.497",
"Id": "3959",
"ParentId": "3955",
"Score": "0"
}
},
{
"body": "<p>Why do you use || between the three conditions only to then make a decision about the conditions seperately? Why don't you write it like this:</p>\n\n<pre><code>int recursive_euclidean( int num1, int num2 )\n{\n if( num1 == num2 )\n return num1;\n else if( num1 < 0 )\n return num2;\n else if( num2 < 0)\n return num1;\n else if( num1 > num2) \n return gcd = recursive_euclidean( num1-num2, num2 ) ) :\n else\n return recursive_euclidean( num1, num2-num1 ) ) );\n}\n</code></pre>\n\n<p>I hereby ban you from use of the ternary operator due to egregious abuse. Not seriously, but its not clear why you are trying to bring it in here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T18:44:29.083",
"Id": "5968",
"Score": "0",
"body": "Thanks for you banning me from using the ternary operator. I wrote the code to spite my friend who likes curly braces. We had long debates over if my code was kosher, so I decided to get outside opinions. This is not how I usually code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T18:57:18.443",
"Id": "5970",
"Score": "4",
"body": "@Matthew, I feel a lot better then. But writing code to spite people, that's just odd."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T06:07:06.643",
"Id": "3981",
"ParentId": "3955",
"Score": "18"
}
},
{
"body": "<p>I just like this:</p>\n\n<pre><code>int recursive_euclidean( int num1, int num2 )\n{\n return num1 == num2 ? num1 \n : num1 < 0 ? num2\n : num2 < 0 ? num1\n : num1 > num2 ? recursive_euclidean( num1-num2, num2 )\n : recursive_euclidean( num1, num2-num1 );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T18:28:22.820",
"Id": "24725",
"ParentId": "3955",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "3958",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T06:10:37.797",
"Id": "3955",
"Score": "17",
"Tags": [
"c++",
"algorithm",
"recursion",
"iteration"
],
"Title": "Recursive and iterative Euclidean algorithms"
}
|
3955
|
<p>Here is a class that I made to validate forms data. I will really appreciate any criticism and hints.</p>
<pre><code> <?php
class formvalidator {
public $filtered, $errors,$db,
$fields_type = Array(), $error_msgs = Array();
public function validate($form, $fields, $error_msgs) {
$this->fields_type = $fields;
$this->error_msgs = $error_msgs;
foreach ($form as $field => $data) {
if (isset($this->fields_type[$field])) {
if (method_exists($this, $this->fields_type[$field])) {
$_POST[$field] = call_user_func_array(array($this, $this->fields_type[$field]), array($data));
if ($_POST[$field] === false) {
$this->errors[$field] = sprintf($this->error_msgs[$field], $data);
}
}
} else {//Else ? unset it Security ?
unset($_POST[$field]);
}
}
//Manual validation for password and password confirmation
if($_POST['form'] == 'signup' or $_POST['form'] == 'login')
if (!isset($_POST['password'])) {
$this->errors[$field] = sprintf($this->error_msgs['password'], '');
}
if (isset($_POST['repassword']) and $_POST['password'] != $_POST['repassword']) {
$this->errors[$field] = sprintf($this->error_msgs['repassword'], '');
}
//End of password confirmation and password check.
//
$_POST = $this->clean($_POST);
if (is_null($this->errors)) {
return true;
} else {
return false;
}
}
public function value_calss($input) {
if (isset($_POST[$input])) {
if (isset($this->errors[$input])) {
echo ' error ';
} else {
echo '" value = "' . $_POST[$input];
}
}
}
public function errors() {
if (!is_null($this->errors)) {
echo '<div class=" messagebox errorbox"><br><h4>Please Fix these:</h4><br><ul>';
foreach ($this->errors as $error)
echo "<li>$error</li>";
echo '</ul><br></div><br>';
}
}
public function setError($error) {
$this->errors[] = $error;
}
//Validations
public function IsEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
public function IsAlphaNum($str) {
if (ctype_alnum($str))
return trim($str);
else
return false;
}
public function IsString($str) {
if (preg_match("/^[A-Za-z0-9\s]+[^ ]$/", $str))
return trim($str);
else
return false;
}
//Explite will return false on empty values which will cause raise error flag.
public function explite($input) {
return trim($input);
}
public function text($input){
return trim(htmlentities($input));
}
public function IsDate($is_date){
if(strtotime($is_date))
return date("Y-m-d",strtotime($is_date));
else
return false;
}
public function file($input)
{
return $input;
}
public function boolen($input)
{
if($input)
return true;
else false;
}
public function clean($input) {
$clean = Array();
foreach ($input as $field => $data) {
$clean[$field] = mysql_real_escape_string($data);
}
return $clean;
}
}
?>
</code></pre>
<p>Update: <a href="https://gist.github.com/2011557" rel="nofollow">New Version on gist</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-12T01:36:53.637",
"Id": "8021",
"Score": "0",
"body": "Comment to self: Rename `valure_class()` method with `attributes()` as it either returns class or value."
}
] |
[
{
"body": "<p>One thing that I see right off the bat, is the <code>clean()</code> method. Why are you escaping things arbitrarily?</p>\n\n<pre><code>public function clean($input) {\n $clean = Array();\n foreach ($input as $field => $data) {\n $clean[$field] = mysql_real_escape_string($data);\n }\n return $clean;\n}\n</code></pre>\n\n<p>All you're doing is making it harder to trace code, and harder to prove if your code is secure or not. Not to mention that's a <em>major</em> breach of the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>.</p>\n\n<p>It's a huge side-effect and should be removed.</p>\n\n<p>Always escape or quote as close as possible to where you're putting it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T13:52:25.190",
"Id": "3966",
"ParentId": "3965",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T13:47:27.897",
"Id": "3965",
"Score": "2",
"Tags": [
"php",
"php5",
"form",
"validation"
],
"Title": "Validating forms data"
}
|
3965
|
<p>I've been reading <em>Cracking the Coding Interview</em> and at the very beginning I got to the strange statement that the next complexity will be \$O(n^2)\$.</p>
<pre><code>public String makeSentence(String[] words){
String sentence = "";
for (String w:words){
sentence+=w;
}
return sentence;
}
</code></pre>
<p>I can't get it. Why is it \$O(n^2)\$? Here I found <a href="http://c2.com/cgi/wiki?StringBufferExample" rel="nofollow noreferrer">another article</a> on this topic.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T20:53:18.810",
"Id": "5952",
"Score": "6",
"body": "This would be more appropriate for [SO] I would think."
}
] |
[
{
"body": "<p>For every call to <code>String.concat()</code>, a new string instance is created. To create that instance, the contents of the previous string needs to be copied to the new one plus the contents of the concatenated string. This is done for every string in the collection. So if you look at in in terms of how many strings are concatenated (and not the characters copied), you're copying the contents of the <code>n</code> strings by the time you reach the <code>n</code>th iteration and all that matters is the worst case (the last iteration). <em>Therefore it has \\$O(n^2)\\$ performance.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T23:20:34.983",
"Id": "8583",
"Score": "0",
"body": "Doesn't this assume that you know how String is implemented in your particular runtime? At the very least the question should indicate what JRE they are talking about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-29T00:41:37.267",
"Id": "8586",
"Score": "0",
"body": "@Peter: If you are interviewing for a Java position and you don't know that Java strings are immutable then you have already failed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-29T03:58:05.850",
"Id": "8590",
"Score": "0",
"body": "@Ed S.: Yes, the javadoc says they are immutable. However, that alone does not lead inevitably to concatenation in a loop exhibiting n^2 behavior. That is a consequence of String's current internal representation. Alternate representations can give you different algorithmic characteristics. I just want the question to be more precise about its assumptions, even if they are assumptions most people make without realizing it. TLDR: String's contract does not guarantee quadratic behavior in the given example, though its current implementation does"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T21:01:25.993",
"Id": "3973",
"ParentId": "3972",
"Score": "17"
}
},
{
"body": "<p>As Jeff points out a new string is created every time you do += on the string.<br>\nAnd thus correctly explains why the complexity is O(2)</p>\n\n<p>The key point is the <a href=\"http://download.oracle.com/javase/6/docs/api/java/lang/String.html\" rel=\"nofollow\">java.lang.String is <strong>not</strong> mutable</a>.</p>\n\n<blockquote>\n <p>Strings are constant; <strong>their values cannot be changed</strong> after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.</p>\n</blockquote>\n\n<p>So any attempt to modify it generated a completely new string (which to programmers in most other languages is strange).</p>\n\n<p>The solution is to use the <a href=\"http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html\" rel=\"nofollow\">java.lang.StringBuffer</a>. This behaves like most other languages string object and allows mutation. The objective is to build a string inside a StringBuffer and when you are finally finished covert this into a string.</p>\n\n<blockquote>\n <p>A thread-safe, <strong>mutable sequence of characters</strong>. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. </p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T18:58:10.670",
"Id": "5971",
"Score": "2",
"body": "[`StringBuilder`](http://download.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) should be used over `StringBuffer` for new code that doesn't need to work under 1.4 JVMs or earlier. \"Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T20:51:28.950",
"Id": "5976",
"Score": "1",
"body": "Agree with @Mike - `StringBuilder` should be used here over `StringBuffer` - The builder itself isn't visible outside the scope of the method, so there isn't any problem regarding threading issues/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T21:18:12.190",
"Id": "5977",
"Score": "0",
"body": "@Mike: I would be more than happy to vote your answer up. My Java was good many moons ago but it is not currently my main language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T21:20:24.590",
"Id": "5978",
"Score": "0",
"body": "@Martin, I can't add anything to your answer besides this minor quibble so have no answer for you to vote on."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T21:35:29.567",
"Id": "3974",
"ParentId": "3972",
"Score": "2"
}
},
{
"body": "<p>Immutability is not really the issue here. It is possible to write a mutable string class where this still would be \\$O(n^2)\\$ or an immutable string class of lower complexity (Sun could have done the latter anyway). The problem here is that at each iteration, the algorithm is rereading the string from the previous iteration in order to produce a new string. </p>\n\n<p>To reduce it by an order of magnitude, you need to shift references. In some cases, the compiler very well might do this anyway, depending upon the sophistication of code optimization. In the case of the class String however, I think it still does it the expensive way, by design. </p>\n\n<p>StringBuffer may be mutable, but I don't see how that is what makes it more efficient in this case. What matters is that at each iteration, it simply appends a reference to the list of characters instead of reads each item for any reason, whether to copy them into a new string instance as String does in this example, or for some other silly reason. But to focus on this as a mutability/immutability issue I think misses the point. </p>\n\n<p>Simple illustration of what I mean. Input a string of letters. At each iteration, you read the previous string to create a new string, and then the current index of the input string to append to the new string. The general relation is the length of the string produced by the previous iteration plus one, which gives you a complexity of \\$n^2 - 1\\$, or \\$O(n^2)\\$. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T22:19:48.177",
"Id": "3975",
"ParentId": "3972",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T20:47:54.107",
"Id": "3972",
"Score": "5",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "String manipulation complexity"
}
|
3972
|
<p><img src="https://i.stack.imgur.com/Jwz0G.gif" width="100"></p>
<p>This tag is used for questions about the <a href="http://www.lua.org/" rel="nofollow noreferrer">Lua programming language</a>.</p>
<p>From <a href="http://www.lua.org/about.html" rel="nofollow noreferrer">Lua's About page</a>:</p>
<blockquote>
<h2><em>What is Lua?</em></h2>
<p>Lua is a powerful, fast, lightweight, embeddable scripting language.</p>
<p>Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping. </p>
</blockquote>
<p>The official implementation of Lua <a href="http://www.lua.org/faq.html#1.1" rel="nofollow noreferrer">is written in ANSI C</a>, but a list of several other implementations can be found on <a href="http://lua-users.org/wiki/LuaImplementations" rel="nofollow noreferrer">the Lua Users Wiki page on Lua Implementations</a>.</p>
<p>The current official version of Lua is <a href="http://www.lua.org/versions.html#5.3" rel="nofollow noreferrer">5.3</a>.</p>
<hr>
<p>Please note that the official name of this programming language is Lua (<a href="http://www.lua.org/about.html#name" rel="nofollow noreferrer">a Portuguese word for Earth's moon</a>). It is not an acronym -- it is not spelled LUA.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-08T23:14:04.850",
"Id": "3977",
"Score": "0",
"Tags": null,
"Title": null
}
|
3977
|
<p>I have the need to programatically create a context menu using names for the menu items which aren't known until the program loads user data.</p>
<p>Here's how I have implemented it. I'm not happy with the cast to get the menu item text to find out which item they have clicked on. Is there a better way that I'm missing?</p>
<pre><code>public partial class Form1 : Form
{
private readonly string[] cards = new string[] {"HBOS", "EGG", "RBOS"};
ContextMenu mnuContextMenu = new ContextMenu();
private void Form1_Load(object sender, EventArgs e)
{
ContextMenu = mnuContextMenu;
SetupRightClickmenu();
}
private void SetupRightClickmenu()
{
MenuItem bank1MenuItem = new MenuItem(BankNames.Bank1);
MenuItem bank2MenuItem = new MenuItem(BankNames.Bank2);
MenuItem bank3MenuItem = new MenuItem(BankNames.Bank3);
MenuItem cashMenuItem = new MenuItem("Cash");
MenuItem creditCardMenuItem = new MenuItem("Credit Card");
bank1MenuItem.Click += bank1MenuItem_Click;
bank2MenuItem.Click += bank2MenuItem_Click;
bank3MenuItem.Click += bank3MenuItem_Click;
cashMenuItem.Click += cashMenuItem_Click;
mnuContextMenu.MenuItems.Add(bank1MenuItem);
mnuContextMenu.MenuItems.Add(bank2MenuItem);
mnuContextMenu.MenuItems.Add(bank3MenuItem);
mnuContextMenu.MenuItems.Add(cashMenuItem);
mnuContextMenu.MenuItems.Add(creditCardMenuItem);
MenuItem creditCardSubMenuItem;
foreach(string card in cards)
{
creditCardSubMenuItem = new MenuItem();
creditCardSubMenuItem.Text = card;
creditCardMenuItem.MenuItems.Add(creditCardSubMenuItem);
creditCardSubMenuItem.Click += creditCardSubMenuItem_Click;
}
}
void creditCardSubMenuItem_Click(object sender, EventArgs e)
{
MenuItem menuItem = (MenuItem) sender;
MessageBox.Show("You clicked on " + menuItem.Text);
}
void cashMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked on cash");
}
void bank3MenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked on bank 3");
}
void bank2MenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked on bank 2");
}
void bank1MenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked on bank 1");
}
}
</code></pre>
<p>In the actual version the cards array is received from the users data.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T13:32:12.013",
"Id": "5956",
"Score": "0",
"body": "I believe what you are looking for is dependency injection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T16:22:52.287",
"Id": "5965",
"Score": "0",
"body": "@IAbstract actually I think he's just curious how to get rid of the cast from sender to a specific type, which would mean altering the event signature and wouldn't be related to DI, though it's not entirely clear so I'm not certain"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T00:54:00.077",
"Id": "5983",
"Score": "0",
"body": "For the click event handlers, are you actually just displaying a message box for all in exactly the same way and nothing else? If so, it would probably be better to just use the `creditCardSubMenuItem_Click()` method for all of them as none of the others does anything significantly different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:53:07.000",
"Id": "5998",
"Score": "0",
"body": "The system allows the users to enter transactions against accounts. The accounts can either be to one of 3 bank accounts, the petty cash account or a credit card. The credit cards are created by the users. They can add or delete them as they need to. Right now there is no way to move a transaction from one account to another.I just need a way to give them a context menu when they right click on the transaction which has the list of accounts and existing credit cards. All I want from the menu is to know the name of the credit card they have selected so I can move the transaction to that card."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:54:14.923",
"Id": "5999",
"Score": "0",
"body": "@Jeff Mercado Those messages boxes are just temporary."
}
] |
[
{
"body": "<p>Though there are other things in this I am not sure are done in an ideal fashion, I'm not sure the whole scope so I will stick to just what you asked about:</p>\n\n<p>This cast from sender to a specific type which is the only type that will fire the event, is the standard way of doing exactly what you are doing with it. The only other way people do this, is to use the <code>as</code> which will return a null if the cast fails, but this should <em>only</em> be used when there's a chance of a different type than expected. If you know for certain that event handler will only be subscribed to an object of type <code>MenuItem</code>, then your cast is absolutely the correct way to do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T01:32:13.687",
"Id": "5984",
"Score": "0",
"body": "generally you wouldn't EVER use the Text of a menu item to find out your context though. Hence my answer. Especially if translation is involved"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T16:03:56.710",
"Id": "3988",
"ParentId": "3983",
"Score": "2"
}
},
{
"body": "<p>You can use the Tag property to store the card. Its normal to store the context object in the Tag.</p>\n\n<p>that way you can make the text whatever you like eg..</p>\n\n<pre><code>creditCardSubMenuItem.Text = string.Format(\"The card {0}\", card);\ncreditCardSubMenuItem.Tag= card;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T03:33:34.620",
"Id": "5986",
"Score": "1",
"body": "The `Tag` property is still of type `object`, so he'll need to cast it to get it a `MenuItem` out of it. There's also little need to put the object firing the event in the Tag, since it'll always be available as `sender` anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T21:30:33.223",
"Id": "6018",
"Score": "1",
"body": "I think his problem isn't so much the cast, but that he is having to use the text on the UI as a way to find out what was selected, which is ugly. The 'cast' is just adding to the noise of what seems to be a bad way of doing things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T21:35:57.613",
"Id": "6019",
"Score": "0",
"body": "Oh, I misread your suggestion. I thought you were putting the menu item in the tag for some reason. Derp. My bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T01:31:04.110",
"Id": "3999",
"ParentId": "3983",
"Score": "5"
}
},
{
"body": "<p>You can do something like this. Here, I've sub-classed MenuItem and overridden OnClick event. When a menu is clicked, I cook up an event args and pass it back to main form. If you are okay with casting 'sender' object, you can get rid of MenuActivatedEventArgs class. This code actually compiles as I'm pasting it from my VisualStudio editor. Ask me if you are not clear on any line. </p>\n\n<p>This probably may not the best way of doing it, but this is how I love to implement when things go crazy. I separate them out and look for places where I can apply some clean-coding and refactoring.</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\nnamespace ContextMenu {\n public partial class Form1 : Form\n {\n // info text for message box\n private const string InfoText = \"You clicked on {0}\";\n private readonly string[] MyCards = new[] { \"HBOS\", \"EGG\", \"RBOS\" };\n\n public Form1()\n {\n InitializeComponent();\n }\n\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n // set the context menu\n ContextMenu = new System.Windows.Forms.ContextMenu();\n // setup menuitems\n SetupRightClickMenu();\n }\n\n private void SetupRightClickMenu()\n {\n // add first few menu items which don't have any submenuitems\n ContextMenu.MenuItems.AddRange(\n new[]\n {\n CreateAndHookUpMenuItem(\"Bank 1\"),\n CreateAndHookUpMenuItem(\"Bank 2\"),\n CreateAndHookUpMenuItem(\"Bank 3\"),\n CreateAndHookUpMenuItem(\"Cash\"),\n\n });\n\n // create creditcard menu item\n var creditCardMenuItem = CreateAndHookUpMenuItem(\"Credit Card\") ;\n\n // add cards to creditcard menu item\n foreach (var card in MyCards)\n creditCardMenuItem.MenuItems.Add(CreateAndHookUpMenuItem(card));\n\n // finally, add creditcard menu item to the context menu\n ContextMenu.MenuItems.Add(creditCardMenuItem);\n }\n\n private MenuItem CreateAndHookUpMenuItem(string title)\n {\n var menuItem = new MyMenuItem(title);\n menuItem.OnMenuActivated += MyMenuItem_OnMenuActivated;\n return menuItem;\n }\n\n\n private void MyMenuItem_OnMenuActivated(object sender, MenuActivatedEventArgs e)\n {\n MessageBox.Show(String.Format(InfoText, e.ItsMenuItem.Text));\n }\n }\n\n\n class MyMenuItem : MenuItem\n {\n public MyMenuItem(string title) : base(title) { }\n\n // this can be just of type EventArgs but if you hate casting, this is one way of doing it\n public event EventHandler<MenuActivatedEventArgs> OnMenuActivated;\n\n protected override void OnClick(EventArgs e)\n {\n base.OnClick(e);\n InvokeMenuActivatedEvent();\n }\n\n private void InvokeMenuActivatedEvent()\n {\n var handler = OnMenuActivated;\n if (handler != null)\n {\n OnMenuActivated.Invoke(this, new MenuActivatedEventArgs(this));\n }\n }\n }\n\n class MenuActivatedEventArgs : EventArgs\n {\n public MyMenuItem ItsMenuItem { get; private set; }\n\n public MenuActivatedEventArgs(MyMenuItem item)\n {\n ItsMenuItem = item;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T21:57:39.163",
"Id": "4040",
"ParentId": "3983",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T13:19:02.503",
"Id": "3983",
"Score": "6",
"Tags": [
"c#",
"winforms"
],
"Title": "Programatically creating context menu"
}
|
3983
|
<p>I have a windows forms application in which a backgroundworker is called again and again.
I need to avoid concurrent access of the code in dowork method for the backgroundWorker; but also need to ensure that the code in the dowork method is called; hence I cannot simply avoid running the backgroundworker altogether if it is busy.</p>
<p>The code is provided below with detailed comments:
The code as it is works nicely; Please evaluate the code and this way of achieving the intended; Please let me know of any potential problems,code smells, design flaws or better way of doing this. Any kind of comments, answers will be of great help.</p>
<pre><code>using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// this timer calls bgWorker again and again after regular intervals
System.Windows.Forms.Timer tmrCallBgWorker;
// this is our worker
BackgroundWorker bgWorker;
// this is the timer to make sure that worker gets called
System.Threading.Timer tmrEnsureWorkerGetsCalled;
// object used for safe access
object lockObject = new object();
public Form1()
{
InitializeComponent();
// this timer calls bgWorker again and again after regular intervals
tmrCallBgWorker = new System.Windows.Forms.Timer();
tmrCallBgWorker.Tick += new EventHandler(tmrCallBgWorker_Tick);
tmrCallBgWorker.Interval = 100;
// this is our worker
bgWorker = new BackgroundWorker();
// work happens in this method
bgWorker.DoWork += new DoWorkEventHandler(bg_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
}
void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Complete");
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
// does a job like writing to serial communication, webservices etc
System.Threading.Thread.Sleep(100);
}
void tmrCallBgWorker_Tick(object sender, EventArgs e)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// if bgworker is not busy the call the worker
if (!bgWorker.IsBusy)
bgWorker.RunWorkerAsync();
}
finally
{
Monitor.Exit(lockObject);
}
}
else
{
// as the bgworker is busy we will start a timer that will try to call the bgworker again after some time
tmrEnsureWorkerGetsCalled = new System.Threading.Timer(new TimerCallback(tmrEnsureWorkerGetsCalled_Callback), null, 0, 10);
}
}
void tmrEnsureWorkerGetsCalled_Callback(object obj)
{
// this timer was started as the bgworker was busy before now it will try to call the bgworker again
if (Monitor.TryEnter(lockObject))
{
try
{
if (!bgWorker.IsBusy)
bgWorker.RunWorkerAsync();
}
finally
{
Monitor.Exit(lockObject);
}
tmrEnsureWorkerGetsCalled = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
tmrCallBgWorker.Start();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you can't enter the lock, this implies that the \"work-queue\" is getting backed up, right? This means that work is not occurring fast enough, so it's possible that <code>tmrEnsureWorkerGetsCalled</code> might get overwritten if <code>tmrCallBgWorker</code> fires twice while a single long-running job prevents the lock from being entered. The overwritten timer will live until the GC cleans it up, and will be lost. Therefore it has failed in its job to ensure that its delegate is executed.</p>\n\n<p>If you really need to ensure anything you fire into this code gets executed, why not use a Queue or ConcurrentQueue rather than creating an implicit queue via the use of timers?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T15:20:35.237",
"Id": "5964",
"Score": "1",
"body": "+1: ConcurrentQueue should be the answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T15:02:17.873",
"Id": "3986",
"ParentId": "3985",
"Score": "2"
}
},
{
"body": "<p>I needed something similar, in that I had code that was going to periodically check the database for new records and notify the user with baloon tips. Checking the database every n-secs caused a pause in the UI that I didn't want the user to experience so I moved the procedure to a thread.</p>\n\n<p>I had a System.Windows.Forms.Timer tick event, where the Thread was created something like (leaving out all the exception handling etc):</p>\n\n<pre><code>TIMER_TICK(object sender, EventArgs){\n Thread checkNow=new Thread(ProcessAutoCheck)\n checkNow.IsBackground=true;\n checkNow.Start();\n checkNow.Join(500);\n}\n</code></pre>\n\n<p>Then in the ProcessAutoCheck method, I used the lock approach to prevent thread contention:</p>\n\n<pre><code>**lock**(lockObject){\n{\n....\n</code></pre>\n\n<p>The program worked as designed, and I didn't consume resources with threads. It wasn't the fanciest solution. I learned a lot from <a href=\"http://www.albahari.com/threading/\" rel=\"nofollow\">Threading in C# - By Joseph Albahari</a>. Complete book online.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:03:20.307",
"Id": "8662",
"ParentId": "3985",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T14:44:41.353",
"Id": "3985",
"Score": "6",
"Tags": [
"c#",
"locking"
],
"Title": "Using Timer with Backgroundworker to ensure the doWork method is called"
}
|
3985
|
<p>I am working on a script that collects all comments from my DB and inserts them into a hash. I then do a collect on the comments hash and split the comments into two separate comment hashes (vid_comments & wall_comments)</p>
<pre><code>w_hash = Hash.new
w_hash["comments"] = []
contender.subscriber.videos.collect { |v| w_hash["comments"] << v.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)") }
w_hash["comments"] << contender.profile.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)")
w_hash["comments"].delete_if { |x| x.blank? }
w_hash["vid_comments"] = w_hash["comments"].collect { |c| !c.media_id.nil? }
w_hash["wall_comments"] = w_hash["comments"].collect { |w| w.parent_id == 0 }
w_hash.delete("comments")
</code></pre>
<p>Is there anyway to shorten the code? I am pretty new to Ruby (PHP import) so excuse my ignorance in things I may be doing wrong.</p>
|
[] |
[
{
"body": "<p>well, first of all your first query is extremely ineffective</p>\n\n<pre><code>contender.subscriber.videos.collect { |v| w_hash[\"comments\"] << v.comments.where(\"created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)\") }\n</code></pre>\n\n<p>this will query you db for each video you've got</p>\n\n<p>second, you really shouldn't duplicate you SQL queries, i propose that you add scope to your Comment model (you are using Rails 3, right?)</p>\n\n<pre><code>scope :recent, where(\"created_at > ?\", 1.day.ago)\n</code></pre>\n\n<p>to make your queries more effective you should use .joins method of ActiveRecord</p>\n\n<p>after all this you code would be something like that</p>\n\n<pre><code>comments = Comment.joins(:videos).where(:videos => { :subscriber => contender.subscriber }).recent\ncomments << contender.profile.comments.recent\n\nw_hash = {}\nw_hash[\"vid_comments\"] = comments.collect { |c| !c.media_id.nil? }\nw_hash[\"wall_comments\"] = comments.collect { |c| c.parent_id == 0 }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T19:51:31.797",
"Id": "5974",
"Score": "0",
"body": "Thanks for the tips! I will begin implementing what you suggested!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T17:27:57.517",
"Id": "3991",
"ParentId": "3987",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "3991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T15:24:42.200",
"Id": "3987",
"Score": "5",
"Tags": [
"ruby",
"array"
],
"Title": "Ruby: working with arrays"
}
|
3987
|
<p>Presented for critique are a pair of classes which automate Sizer Creation and Layout in wxPython.</p>
<pre><code>import wx
from wx.lib.combotreebox import ComboTreeBox
from wx.lib.agw.floatspin import FloatSpin
wx.ComboTreeBox = ComboTreeBox
wx.FloatSpin = FloatSpin
class FormDialog(wx.Dialog):
def __init__(self, parent, id = -1, panel = None, title = "Unnamed Dialog",
modal = False, sizes = (-1, -1), refid = None):
wx.Dialog.__init__(self, parent, id, title,
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
if panel is not None:
self._panel = panel(self, refid)
self._panel.SetSizeHints(*sizes)
ds = wx.GridBagSizer(self._panel._gap, self._panel._gap)
ds.Add(self._panel, (0, 0), (1, 1), wx.EXPAND | wx.ALL, self._panel._gap)
ds.Add(wx.StaticLine(self), (1, 0), (1, 1), wx.EXPAND | wx.RIGHT | wx.LEFT, self._panel._gap)
self.bs = self.CreateButtonSizer(self._panel._form.get('Buttons', wx.OK | wx.CANCEL))
ds.Add(self.bs, (2, 0), (1, 1), wx.ALIGN_RIGHT | wx.ALL, self._panel._gap)
ds.AddGrowableCol(0)
ds.AddGrowableRow(0)
self.SetSizerAndFit(ds)
self.Center()
self.Bind(wx.EVT_BUTTON, self._panel.onOk, id = wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self._panel.onClose, id = wx.ID_CANCEL)
focused = self._panel._form.pop('Focus', None)
if focused:
self._panel.itemMap[focused].SetFocus()
if modal:
self.ShowModal()
else:
self.Show()
class Form(wx.Panel):
def __init__(self, parent = None, refid = None, id = -1, gap = 3, sizes = (-1, -1)):
wx.Panel.__init__(self, parent, id)
self.SetSizeHints(*sizes)
self._gap = gap
self.itemMap = {}
self.refid = refid
if not hasattr(self, 'q'):
self.q = getattr(self.GrandParent, 'q', None)
if hasattr(self, '_form'):
# Before building verify that several required elements exist in the form
# definition object.
self.loadDefaults()
self._build()
self._bind()
def _build(self):
"""
The Build Method automates sizer creation and element placement by parsing
a properly constructed object.
"""
# The Main Sizer for the Panel.
panelSizer = wx.BoxSizer(wx.VERTICAL)
# Parts is an Ordered Dictionary of regions for the form.
for container, blocks in self._form['Parts'].iteritems():
flags, sep, display = container.rpartition('-') #@UnusedVariable
if 'NC' in flags:
for block in blocks:
element, proportion = self._parseBlock(block)
panelSizer.Add(element, proportion, flag = wx.EXPAND | wx.ALL, border = self._gap)
else:
box = wx.StaticBox(self, -1, display)
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
for block in blocks:
element, proportion = self._parseBlock(block)
sizer.Add(element, proportion, flag = wx.EXPAND | wx.ALL)
if 'G' in flags:
sizerProportion = 1
else:
sizerProportion = 0
panelSizer.Add(sizer, sizerProportion, flag = wx.EXPAND | wx.ALL, border = self._gap)
continue
self.SetSizerAndFit(panelSizer)
def _bind(self): pass
def _parseBlock(self, block):
"""
The form structure is a list of rows (blocks) in the form. Each row
consists of a single element, a row of elements, or a sub-grid of
elements. These are represented by dictionaries, tuples, or lists,
respectively and are each processed differently.
"""
proportion = 0
if isinstance(block, list):
item = self.makeGrid(block)
elif isinstance(block, tuple):
item = self.makeRow(block)
elif isinstance(block, dict):
proportion = block.pop('proportion', 0)
item = self.makeElement(block)
return item, proportion
def makeElement(self, object):
"""
In the form structure a dictionary signifies a single element. A single
element is automatically assumed to expand to fill available horizontal
space in the form.
"""
sizer = wx.BoxSizer(wx.HORIZONTAL)
flags = object.pop('flags', wx.ALL)
element = self._makeWidget(object)
sizer.Add(element, 1, border = self._gap,
flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | flags)
return sizer
def makeRow(self, fields):
"""
In the form structure a tuple signifies a row of elements. These items
will be arranged horizontally without dependency on other rows. Each
item may provide a proportion property which can cause that element to
expand horizontally to fill space.
"""
sizer = wx.BoxSizer(wx.HORIZONTAL)
for field in fields:
proportion = field.pop('proportion', 0)
sizer.Add(self.makeElement(field), proportion,
flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL)
return sizer
def makeGrid(self, rows):
"""
In the form structure a list signifies a grid of elements (equal width
columns, rows with similar numbers of elements, etc).
"""
sizer = wx.GridBagSizer(0, 0)
for row, fields in enumerate(rows):
for col, field in enumerate(fields):
flags = field.pop('flags', wx.ALL)
# Each item may specify that its row or column 'grow' or expand to fill
# the available space in the form.
rowGrowable, colGrowable = (field.pop('rowGrowable', False),
field.pop('colGrowable', False))
if rowGrowable:
sizer.AddGrowableRow(row)
if colGrowable:
sizer.AddGrowableCol(col)
span = field.pop('span', (1, 1))
colpos = field.pop('colpos', col)
rowpos = field.pop('rowpos', row)
element = self._makeWidget(field)
sizer.Add(element, (rowpos, colpos), span, border = self._gap,
flag = wx.ALIGN_CENTER_VERTICAL | flags)
return sizer
def _makeWidget(self, params):
"""
This function actually creates the widgets that make up the form. In most
cases these will be items from the wx libraries, though they may be
'custom' elements which require delayed instantiation by leveraging
lambdas.
"""
type = params.pop('type')
if type == 'Custom':
lookup = params.pop('lookup')
element = self._form[lookup](self)
self.itemMap[lookup] = element
else:
# StaticText items may carry a bold attribute - retrieve it for use later.
if type == 'StaticText':
bold = params.pop('bold', False)
# ComboBoxes and ListBoxes need to have choices.
if type in ('ComboBox', 'ListBox'):
params['choices'] = self._form['Options'].get(params['name'], [])
element = getattr(wx, type)(self, -1, **params)
if type == 'ComboTreeBox':
choices = self._form['Options'].get(params['name'], [])
for category, options in choices:
id = element.Append(category)
for option in options:
element.Append(option, parent = id)
element.GetTree().Expand(id)
# Require the user to use the browse buttons for File / Folder browsing.
if type in ('DirPickerCtrl', 'FilePickerCtrl'):
element.GetTextCtrl().SetEditable(False)
if params.has_key('name'):
# Populate the itemMap - facilitates element retrieval / event bindings.
self.itemMap[params['name']] = element
# Default value assignment. Must unfortunately do a dance to check
# element type - some require ints / floats, while others are ok with
# strings.
value = self._form['Defaults'].get(params['name'], '')
if hasattr(element, 'SetValue'):
if type == 'SpinCtrl':
if value == '':
value = 0
element.SetValue(int(value))
elif type == 'FloatSpin':
if value == '':
value = 0
element.SetValue(float(value))
elif type in ('CheckBox', 'RadioButton'):
element.SetValue(bool(value))
else:
element.SetValue(unicode(value))
if type == 'ComboTreeBox':
element._text.SetInsertionPoint(0)
elif hasattr(element, 'SetPath'):
element.SetPath(value)
elif type != 'Button':
print element
# Check for elements we should disable at load time.
if params['name'] in self._form['Disabled']:
element.Enable(False)
# Check for a Validator and add it if required.
try:
validator = self._form['Validators'][params['name']]()
element.SetValidator(validator)
except KeyError: pass # No Validator Specified.
# Take the bold attribute into account for StaticText elements.
if type == 'StaticText' and bold:
font = element.GetFont()
font.SetWeight(wx.BOLD)
element.SetFont(font)
return element
def loadDefaults(self):
if 'Defaults' not in self._form: self._form['Defaults'] = {}
if 'Disabled' not in self._form: self._form['Disabled'] = []
if 'Validators' not in self._form: self._form['Validators'] = {}
self.loadOptions()
def loadOptions(self):
if 'Options' not in self._form: self._form['Options'] = {}
def onOk(self, evt):
self.onClose(evt)
def onClose(self, evt):
self.GetParent().Destroy()
</code></pre>
<p>The Form class is lengthy, and I appreciate the patience of anyone who's managed to read this far. The entire expectation is that Form should be subclassed like so:</p>
<pre><code>class GeneralSettings(Form):
def __init__(self, parent, refid = None):
self._form = {
'Parts': OD([
('Log Settings', [
({'type': 'StaticText', 'label': 'Remove messages after'},
{'type': 'FloatSpin', 'name': 'interval', 'min_val': 1, 'max_val': 10, 'digits': 2, 'increment': 0.1, 'size': (55, -1), 'flags': wx.LEFT | wx.RIGHT},
{'type': 'ComboBox', 'name': 'unit', 'flags': wx.LEFT | wx.RIGHT, 'style': wx.CB_READONLY},
{'type': 'StaticText', 'label': 'Log Detail:'},
{'type': 'ComboBox', 'name': 'log-level', 'flags': wx.LEFT | wx.RIGHT, 'style': wx.CB_READONLY, 'proportion': 1})
]),
('Folder Settings', [
[({'type': 'StaticText', 'label': 'Spool Folder:'},
{'type': 'DirPickerCtrl', 'name': 'dir', 'style': wx.DIRP_USE_TEXTCTRL, 'colGrowable': True, 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Temp Folder:'},
{'type': 'DirPickerCtrl', 'name': 'temp', 'style': wx.DIRP_USE_TEXTCTRL, 'flags': wx.EXPAND | wx.ALL})]
]),
('Email Notifications', [
[({'type': 'StaticText', 'label': 'Alert Email To:'},
{'type': 'TextCtrl', 'name': 'alert-to', 'colGrowable': True, 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Alert Email From:'},
{'type': 'TextCtrl', 'name': 'alert-from', 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Status Email From:'},
{'type': 'TextCtrl', 'name': 'status-from', 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Alert Email Server:'},
{'type': 'TextCtrl', 'name': 'alert-host', 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Login:'},
{'type': 'TextCtrl', 'name': 'alert-login', 'flags': wx.EXPAND | wx.ALL}),
({'type': 'StaticText', 'label': 'Password:'},
{'type': 'TextCtrl', 'name': 'alert-password', 'style': wx.TE_PASSWORD, 'flags': wx.EXPAND | wx.ALL})]
]),
('Admin User', [
({'type': 'CheckBox', 'name': 'req-admin', 'label': 'Require Admin Rights to make changes.'},
{'type': 'Button', 'name': 'admin-button', 'label': 'Customize Permissions ... '})
]),
('User Interface Behavior', [
({'type': 'StaticText', 'label': 'Job Drag Options'},
{'type': 'ComboBox', 'name': 'jobdrop', 'flags': wx.LEFT | wx.RIGHT | wx.EXPAND})
])
]),
'Options': {
'unit': ['Hours', 'Days', 'Months'],
'log-level': ['Minimal', 'Low', 'High', 'Debug'],
'jobdrop': ['Copy Job to Queue', 'Move Job to Queue']
},
'Defaults': {
'interval': 3,
'log-level': 'Low',
'req-admin': False,
'unit': 'Days',
'printtasks': 5,
'jobdrop': 'Copy Job to Queue'
}
}
Form.__init__(self, parent, refid)
</code></pre>
<p>Once the form is subclassed and the 'structure' is defined - the OrderedDict located in <code>self._form['Parts']</code>, you can open a dialog with the elements like this:</p>
<pre><code>FormDialog(frame, panel = GeneralSettings, title = "General Settings")
</code></pre>
<p>There are a number of initial critiques that I already have for it:</p>
<ol>
<li>Complicated "Form Structure" definition. It is deeply nested at times.</li>
<li>Uses type analysis - Lists represent a grid of elements broken up into one or more rows, Tuples are rows of elements, and Dictionaries are individual elements. This is traditionally non-pythonic.</li>
<li>Combined Properties - in the dictionaries that represent individual elements there are directives that are removed and used for Sizer Creation. Specifically, things like 'colGrowable', 'proportion', etc. These are included in the widget definition and popped out for use when adding the element to the sizer during construction.</li>
</ol>
<p>However, it provides the following benefits as well:</p>
<ol>
<li>Automated Sizers - no need to ever directly create a sizer, set one to expand, determine where they are parented, etc. This is all determined based on the aforementioned "Form Structure".</li>
<li>Easy conditional inclusion of elements or removal based on feature criteria. In the General Settings example above, one might add this to conditional remove a region from the form: <code>if featureDisabled: del self._form['Parts']['Admin User']</code>. Because the sizers are auto-generated there is no need to conditionally exclude the creation of the containing sizers, elements themselves, etc (typically spread across several methods in other layout helpers). This all happens during the _build method.</li>
<li>Easy, direct access to form elements. All Widgets are added to a member variable <code>self.itemMap</code>, keyed by the Name field for the widget. Anything with a name can be accessed from any other method of the form.</li>
<li>Combined Properties - centralized declaration of all relevant attributes for each widget. You declare a widget using its keyword values, but also provide sizer directives such as proportion or position. I consider this both convenient and counter-intuitive to new developers, which is why it's listed both in pros and in cons.</li>
</ol>
<p>There are a couple of additional <a href="http://code.ghostdev.com/posts/wxpython-form-builder" rel="nofollow">Demos</a> available.</p>
|
[] |
[
{
"body": "<pre><code>wx.ComboTreeBox = ComboTreeBox\nwx.FloatSpin = FloatSpin\n</code></pre>\n\n<p>Modifying the contents of another module is suspicious and likely to cause trouble. Your changes might not be there when another module is importing and could cause trouble.</p>\n\n<pre><code> ds = wx.GridBagSizer(self._panel._gap, self._panel._gap)\n\n ds.Add(self._panel, (0, 0), (1, 1), wx.EXPAND | wx.ALL, self._panel._gap)\n\n ds.Add(wx.StaticLine(self), (1, 0), (1, 1), wx.EXPAND | wx.RIGHT | wx.LEFT, self._panel._gap)\n\n self.bs = self.CreateButtonSizer(self._panel._form.get('Buttons', wx.OK | wx.CANCEL))\n</code></pre>\n\n<p>Empty lines can be used to put related statements together. The benefit is lost when you do it for every statement.</p>\n\n<pre><code> focused = self._panel._form.pop('Focus', None)\n</code></pre>\n\n<p>The _ in _form indicates that its for the internal use of the panel. So why are you accessing it here?</p>\n\n<pre><code>if not hasattr(self, 'q'):\n self.q = getattr(self.GrandParent, 'q', None)\n</code></pre>\n\n<p>What the fried monkey is q? It probably need a better name.</p>\n\n<pre><code>class GeneralSettings(Form):\n def __init__(self, parent, refid = None):\n self._form = {\n</code></pre>\n\n<p>Perhaps form should be a class attribute rather then an attribute. Then you don't have a define a constructor in this class whatsoever.</p>\n\n<pre><code> 'Parts': OD([\n</code></pre>\n\n<p>OD?</p>\n\n<pre><code> ('Log Settings', [\n ({'type': 'StaticText', 'label': 'Remove messages after'},\n {'type': 'FloatSpin', 'name': 'interval', 'min_val': 1, 'max_val': 10, 'digits': 2, 'increment': 0.1, 'size': (55, -1), 'flags': wx.LEFT | wx.RIGHT},\n</code></pre>\n\n<p>Instead of dictionaries, how about objects?</p>\n\n<pre><code> widgets.StaticText(label='Remove messages after'),\n widgets.ComboBox(name='unit', flags = wx.LEFT | wx.RIGHT, style = wx.CBREADONLY)\n</code></pre>\n\n<p>Then you can call methods on these objects to do all the work you are doing above. That way you can move all the widget specific data out of it. It should also make it easier to extend your system with new widgets. The system could also be extended to support things like OptionalSection, etc. </p>\n\n<pre><code> 'Defaults': {\n 'interval': 3,\n 'log-level': 'Low',\n 'req-admin': False,\n 'unit': 'Days',\n 'printtasks': 5,\n 'jobdrop': 'Copy Job to Queue'\n }\n</code></pre>\n\n<p>These are being defined far away from the rest of the widget. Why?</p>\n\n<p>You seem to comparing the ease of use of this versus manually writing the code. However, if I compare it to the use of a gui builder its not clear that its helpful. i.e. all the code that you are saving is already written for me by the builder tool and so it just isn't helpful on that front.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T22:07:16.660",
"Id": "5980",
"Score": "0",
"body": "OD is OrderedDict, imported and aliased. Missed that in the copy / paste. They're declared as attributes rather that class attributes because I wanted delayed instantiation (built when requested, not before hand). The same is true for storing dictionaries - the widgets have to be parented, and the parents don't exist when declaring the _form variable. Defaults are declared separately to facilitate loading them from some other data source. The `loadDefaults` method can be overridden to set custom values for `self._form['Defaults']`. Thanks for the feedback though! Much Appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T22:17:53.297",
"Id": "5981",
"Score": "0",
"body": "@g.d.d.c, the objects you'd create wouldn't be the widgets themselves. They'd be objects you define which know how to build the widgets, move data to/from the widgets, etc. It seems to me that creation those object should be no more problematic then creating the lists and dictionaries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-01T17:08:49.273",
"Id": "19620",
"Score": "0",
"body": "I wanted to come back to this and thank you for your suggestions. I ended up cleaning up large parts of it, and implementing classes in place of the dictionaries like you suggested. Thanks so much!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T21:58:56.813",
"Id": "3994",
"ParentId": "3989",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "3994",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T16:15:04.373",
"Id": "3989",
"Score": "3",
"Tags": [
"python",
"layout",
"user-interface"
],
"Title": "wxPython Form Builder - Sizer Automation"
}
|
3989
|
<p>Each product in my e-commerce website has Arabic and English values for the title, description and excerpt. I have this method <code>EditProduct</code> to update those values based on current culture (Arabic or English)</p>
<pre><code>public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
var product = DoSomeMagicToGetAProduct();
if (element == "title")
{
if (culture == "en")
{
if (edit1)
{
product.Title = text1;
}
if (edit2)
{
product.TitleAr = text2;
}
}
if (culture == "ar")
{
if (edit1)
{
product.TitleAr = text1;
}
if (edit2)
{
product.Title = text2;
}
}
}
if (element == "description")
{
// similar codes here
}
if (element == "excerpt")
{
// similar codes here
}
product.Save();
}
</code></pre>
<p>The method works well, but I think I can improve the way I write it to be more elegant.
Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T22:00:59.073",
"Id": "5979",
"Score": "0",
"body": "What are Title and TitleAr for? What do edit1 and edit2 mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T07:59:32.710",
"Id": "5991",
"Score": "0",
"body": "@Winston TitleAr is the arabic value of Title (english value). edit1 == true means user is editing text1."
}
] |
[
{
"body": "<p>You should try using a switch statement for the languages. Also move the languages to be the first statements to check instead of the element. This combined should reduce the size of your code.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/06tc147t%28v=vs.80%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/06tc147t%28v=vs.80%29.aspx</a></p>\n\n<p>Then for the edit booleans you can do this instead.</p>\n\n<pre><code> if (edit1)\n {\n product.Title = text1;\n }\n else \n {\n product.TitleAr = text2;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T22:02:49.457",
"Id": "3995",
"ParentId": "3993",
"Score": "0"
}
},
{
"body": "<p>I think the code is a little dodgy, and the design is dodgy. I'd store the translation in a dictionary of some sort.</p>\n\n<p>But addressing your immediate question, to simplify the code you have, you could do....</p>\n\n<pre><code>public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)\n {\n var product = DoSomeMagicToGetAProduct();\n\n var arText = culture == \"ar\" ? text1 : text2;\n var enText = culture == \"en\" ? text1 : text2;\n var updateEn = culture == \"en\" ? edit1 : edit2;\n var updateAr = culture == \"ar\" ? edit1 : edit2;\n\n if (element == \"title\")\n {\n if (updateEn) product.Title = enText;\n if (updateAr) product.TitleAr = arText; \n }\n\n if (element == \"description\")\n {\n if (updateEn) product.Description = enText;\n if (updateAr) product.DescriptionAr = arText; \n }\n\n if (element == \"excerpt\")\n {\n if (updateEn) product.Excerpt = enText;\n if (updateAr) product.ExcerptAr = arText; \n }\n\n product.Save();\n\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T07:55:09.723",
"Id": "5989",
"Score": "0",
"body": "Thank you very much, Nicholas. this looks better than mine. \nI also appreciate your suggestion on my design, but I'm afraid storing those values in some kind of dictionary is too much, since the website only support arabic & english."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T09:50:15.930",
"Id": "5993",
"Score": "0",
"body": "This certainly does tidy up the code, however removing parentheses could possibly contravene any coding standards in place. @Anwar Chandra I would suggest reading page 23 & 24 of C# Code Style Guide http://www.sourceformat.com/pdf/cs-coding-standard-bellware.pdf for inspiration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:59:47.290",
"Id": "6000",
"Score": "0",
"body": "instead of the ifs, use switch case statements."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T01:22:17.697",
"Id": "3998",
"ParentId": "3993",
"Score": "10"
}
},
{
"body": "<p>Why should you need if-else for culture change? .Net resources is the way to show localized web pages as per culture on user machine.\nYou should have just one product.title field and 2 resource files, one neutral culture which contains english words and another 'ar' culture which holds the arabic translation.</p>\n\n<p>Refer to <a href=\"http://msdn.microsoft.com/en-us/library/ms227427.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms227427.aspx</a> for an overview of asp.net resources.</p>\n\n<p>Hope this helps. If I am missing something here please post. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T07:56:54.120",
"Id": "5990",
"Score": "0",
"body": "Yes, localization in the website already handled by .Net resources. product isn't resource, and my users need to input its values manually on a daily basis."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T05:10:10.787",
"Id": "4002",
"ParentId": "3993",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "3998",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T21:30:40.330",
"Id": "3993",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Editing e-commerce website values"
}
|
3993
|
<p>I am still uncomfortable and new with working with classes.</p>
<p>I have made a User class that will return stuff about the user.</p>
<pre><code><?
class User {
public function age($id) {
$birth = new DateTime("$id");
$now = new DateTime();
$age = $now->diff($birth)->format("%y");
return $age;
}
public function avatar($id) {
$connect = Database::factory();
$id = $id;
$getQuery = $connect->prepare("SELECT photo_thumb FROM users_profile WHERE uID =:id");
$getQuery->bindValue(":id", $id);
$getQuery->execute();
$show = $getQuery->fetch();
$photoName = ((empty($show['photo_thumb'])) ? '' : $show['photo_thumb']);
return $photoName;
}
public function fullname($id, $full = 1) {
$connect = Database::factory();
$query = $connect->prepare("SELECT firstname, lastname FROM users WHERE id =:id");
$query->bindValue(":id", $id);
$query->execute();
$row = $query->fetch();
$full_name = $row["firstname"]." ".$row["lastname"];
return $full_name;
}
public function firstname($id) {
$connect = Database::factory();
$query = $connect->prepare("SELECT firstname, lastname FROM users WHERE id = '$id'");
$query->execute();
$row = $query->fetch();
$firstname = $row["firstname"];
return $firstname;
}
public function sex($id) {
$connect = Database::factory();
$query = $connect->prepare("SELECT sex FROM users WHERE id=:id");
$query->bindValue(":id", $id);
$query->execute();
$row = $query->fetch();
return $row["sex"];
}
}
</code></pre>
<p>If you look through it fast, you will notice how everything is like the same, apart from its grabbing another column name and sometimes from another table.</p>
<p>Otherwise it just execute, fetches and returns.</p>
<p>I wonder if I can improve this code any way, so it looks cleaner and not so copy+paste like now..</p>
|
[] |
[
{
"body": "<p>In short : its an extremely bad piece of code.</p>\n\n<p>Here is a list or \"whys\":</p>\n\n<ul>\n<li>you are mixing data access with logic ( sql queries should be handled by different object )</li>\n<li>you are using global state for DB access </li>\n<li>there is some mystical parameter <code>$full</code> in <code>full_name()</code> method</li>\n<li>all the methods are getters</li>\n<li>the SQL queries happen each time you use a getter</li>\n<li>parameter <code>$id</code> means nothing ( is it a string , a number , some other object ? )</li>\n</ul>\n\n<p>Basically what you have there are five standalone procedures wrapped up in an a class <em>just for show</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T01:43:18.690",
"Id": "5985",
"Score": "0",
"body": "Thanks for the list. I improved the code by this list but im having trouble making a object that handles the sql queries can you show example on a object that you can handle the sql queries in pdo. i get stuck at the bindvalue(), how to know what to bind and not to.."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T00:00:45.697",
"Id": "3997",
"ParentId": "3996",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-09T23:35:22.730",
"Id": "3996",
"Score": "2",
"Tags": [
"php"
],
"Title": "Improving my user class"
}
|
3996
|
<p>The point of this algorithm is to see if an element exists in a NxN matrix that has its rows and columns sorted.</p>
<p>What would you change? What did I do well? Both perspectives help so I am not left guessing.</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
/* Author: Matthew Everett Hoggan */
/* Date: August 8, 2011 */
/* Problem Statement: */
/* Given an matrix such that every row is sorted and every column is sorted */
/* write a function "find_kth_element_and_return_rowXcol" that returns a */
/* a pair<int,int> where the element was found. If it is not found return */
/* <N,N> to indicate to user that their value was not found */
namespace Matrix
{
/* This class is designed to solve the problem at hand */
/* The method definitions are described where they are defined */
/* Note this matrix is a N x N square matrix */
class RandomOrderedMatrix
{
public:
RandomOrderedMatrix( int N );
~RandomOrderedMatrix( );
void find_element( int element );
void print_matrix( );
std::pair<int,int>& get_coord( ) { return this->data; }
private:
void build_matrix( );
int **matrix;
std::pair<int,int> data;
int N;
friend std::ostream& operator<< ( std::ostream &out, Matrix::RandomOrderedMatrix &rom )
{
std::pair<int,int> d = rom.data;
return out << "<" << d.first << ", " << d.second << ">" << std::endl;
}
};
/* ctor */
RandomOrderedMatrix::RandomOrderedMatrix( int N )
{
this->N = N;
this->matrix = new int*[N];
for( int r=0;r<N;r++ ) matrix[r] = new int[N];
this->build_matrix( );
}
/* dtor */
RandomOrderedMatrix::~RandomOrderedMatrix( )
{
if( matrix )
{
for( int r=0;r<N;r++ ) delete [ ] matrix[r];
delete [ ] matrix;
}
}
/* This is the n lg(n) algorithm required to find the coord of an elem. */
/* Assuming that the rows and columns are all sorted we find the row */
/* with the right range matrix[row][0] <= element <= matrix[row][N] */
/* Once it finds the right row if it existis it performs binary search */
/* which is lg(n) to see if element exists on that row. If the element */
/* is found it prints sets the coordinate pair member variable to the */
/* row and column where it found it. If it did not find the elment it */
/* sets the member variable coordinate pair to N */
void RandomOrderedMatrix::find_element( int element )
{
int left_index = 0;
int right_index = N-1;
/* Scan the rows */
for( int r = 0; r < N; r++ )
{
/* Check the range for that row */
if( element >= matrix[r][0] && element <= matrix[r][N-1] )
{
/* Binary search */
while( right_index>left_index ) {
int middle = (right_index+left_index)/2;
if( element == matrix[r][middle] )
{
data.first = r;
data.second = middle;
return;
}
else if( element > matrix[r][middle] )
{
left_index = middle + 1;
}
else if( element < matrix[r][middle] )
{
right_index = middle - 1;
}
}
}
/* These last two cases are used when there are only two items */
/* left in the binary partition */
if( element == matrix[r][left_index] )
{
data.first = r;
data.second = left_index;
return;
}
if( element == matrix[r][right_index] )
{
data.first = r;
data.second = right_index;
return;
}
}
/* If function above did not find the elements then set them to N to */
/* notify the client that their pair could not be found */
data.first = N;
data.second = N;
}
/* Pretty Formating Print functino =) */
void RandomOrderedMatrix::print_matrix( )
{
std::cout << "Your Matrix is" << std::endl;
std::cout << std::setw( 6 ) << " ";
std::cout << std::setw( 6 ) << " ";
for( int c=0;c<N;c++ )
{
std::cout << std::setw( 6 ) << c;
}
std::cout << std::endl;
for( int r=0;r<N;r++ )
{
std::cout << std::setw( 6 ) << r;
std::cout << std::setw( 6 ) << "|";
for( int c=0;c<N;c++ )
{
std::cout << std::setw( 6 ) << matrix[r][c];
}
std::cout << std::setw( 6 ) << "|";
std::cout << std::endl;
}
}
/* Build a matrix such that the rows are sorted and the columns are */
/* sorted. */
void RandomOrderedMatrix::build_matrix( )
{
matrix[0][0] = rand( )%50;
for( int c=1; c<N; c++ ) matrix[0][c] = matrix[0][c-1] + rand( )%50;
for( int r=1; r<N; r++ )
{
for( int c=0; c<N; c++ )
{
if( c == 0 )
{
matrix[r][c] = matrix[r-1][N-1]+rand( )%50;
}
else
{
matrix[r][c] = matrix[r][c-1]+rand( )%50;
}
}
}
}
}
/* Driver function, normally found in another file, but to facilitate */
/* reading I have included it here */
/* I also included some unit testing code which automates the testing */
/* If you want you can uncomment it to make your testing easier */
int main( int argc, char *argv[ ] )
{
Matrix::RandomOrderedMatrix rom( 10 );
rom.print_matrix( );
srand((unsigned)time(NULL));
int element;
std::cout << "Please input a number to find in your matrix>>> ";
while( std::cin >> element )
{
rom.find_element( element );
std::pair<int,int> &results = rom.get_coord( );
if( results.first != 10 && results.second != 10 )
{
std::cout << "Results success, found " << element << " @ coord " << rom;
}
else
{
std::cout << "Results failed could not find " << element << " in matrix " << std::endl;
}
std::cout << "Please input a number to find in your matrix>>> ";
}
/* Slight Unit Testing
for( int x = 0; x < 20; x++ )
{
std::cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << std::endl;
int element = rand( )%10000;
rom.find_element( element );
std::pair<int,int> &results = rom.get_coord( );
if( results.first != 10 && results.second != 10 )
{
std::cout << "Results success, found " << element << " @ coord " << rom;
}
else
{
std::cout << "Results failed could not find " << element << " in matrix " << std::endl;
}
std::cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << std::endl;
}
//*/
}
</code></pre>
|
[] |
[
{
"body": "<p>I would replace:</p>\n\n<pre><code> int **matrix;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code> std::vector<std::vector<int> > matrix; /* or Boost::Matrix */\n</code></pre>\n\n<p>Then your constructor/destructor become:</p>\n\n<pre><code>RandomOrderedMatrix::RandomOrderedMatrix( int N )\n : matrix(N, std::vector<int>(N))\n\n // , N(N) Don't need this anymore size is part of the vector\n{\n build_matrix( );\n} \n\n/* dtor */\n// Don't need the de-structor\n</code></pre>\n\n<p>This also solves the problem of not obeying the \"rule of three\".</p>\n\n<p>Move this:</p>\n\n<pre><code>srand((unsigned)time(NULL));\n</code></pre>\n\n<p>To the first line of main() (note your build matrix uses rand() which is happening before the call to srand() thus you are not getting random numbers).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T08:44:37.693",
"Id": "5992",
"Score": "0",
"body": "I just finished reading C++ Programming Language (Special Edition) but don't recall seeing anything about the \"rule of three\" . Wikipedia (http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) was helpful, and I can recall context where such things were discussed. Where does this exact phrase come from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:40:25.410",
"Id": "5995",
"Score": "0",
"body": "I have a suspicion it's from Herb Sutter GoTW series, but I can't find a link right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T15:13:04.637",
"Id": "6002",
"Score": "0",
"body": "It comes from. If you need to write a special version of any destructor/assignment operator/copy constructor then you will probably need to write all three. Personally I think it is a silly name I prefer the rule of four (though nobody else uses it) because the compiler generates four methods automatically for you and if you have a RAW owned pointer in your class you will need to override all four (though I believe there are more now in C++0x with move). So we may be seeing a re-name soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T19:12:48.187",
"Id": "6087",
"Score": "0",
"body": "The \"Rule of Three++0x\" ?..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T07:36:40.323",
"Id": "4004",
"ParentId": "4003",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T05:47:38.573",
"Id": "4003",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"matrix",
"search"
],
"Title": "Determine if an element exists in a sorted NxN matrix"
}
|
4003
|
<p>I have implemented mutex and conditional variables using the <code>futex</code> syscall. I believe that my implementation is correct, but would like it to be verified by someone else. Any suggestions for further improvements in the performance of the mutex and conditional variables would also be appreciated.</p>
<pre><code> #ifndef __SYNCHRONIZATION__
#define __SYNCHRONIZATION__
#include <unistd.h>
#include <limits.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include "types.h"
#include "assembly.h"
typedef UINT32 mutex;
typedef struct condvar condvar;
struct condvar {
mutex *m;
int seq;
};
void mutex_init(mutex *m) {
*m = 0;
}
void mutex_destroy(mutex *m) {
*m = 0;
}
void mutex_lock(mutex *m) {
UINT32 c;
if((c = __sync_val_compare_and_swap(m, 0, 1)) != 0) {
do {
if((c == 2) || __sync_val_compare_and_swap(m, 1, 2) != 0)
syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
} while((c = __sync_val_compare_and_swap(m, 0, 2)) != 0);
}
}
void mutex_unlock(mutex *m) {
if(__sync_fetch_and_sub(m, 1) != 1) {
*m = 0;
syscall(SYS_futex, m, FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
}
}
void cond_init(condvar *c, mutex *m) {
c->m = m;
c->seq = 0;
}
void cond_destroy(condvar *c) {
c->m = NULL;
c->seq = 0;
}
void cond_signal(condvar *c) {
__sync_fetch_and_add(&(c->seq), 1);
syscall(SYS_futex, &(c->seq), FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
}
void cond_broadcast(condvar *c) {
__sync_fetch_and_add(&(c->seq), 1);
syscall(SYS_futex, &(c->seq), FUTEX_REQUEUE_PRIVATE, 1, (void *) INT_MAX, c->m, 0);
}
void cond_wait(condvar *c) {
UINT32 oldSeq = c->seq;
mutex_unlock(c->m);
syscall(SYS_futex, &(c->seq), FUTEX_WAIT_PRIVATE, oldSeq, NULL, NULL, 0);
while (xchg32(c->m, 2)) {
syscall(SYS_futex, c->m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
}
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T12:51:39.657",
"Id": "5996",
"Score": "0",
"body": "Doesn't pthreads map the mutex implementation onto a futex on Linux platforms for you for free?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T20:25:00.007",
"Id": "6015",
"Score": "0",
"body": "it does, but the use case that i am looking for does not permits using the pthread library"
}
] |
[
{
"body": "<p>I have no particular experience of Futex code, so take this with caution:</p>\n\n<p>Looking at <code>mutex_lock</code>, I think some comments would have been useful. As I\nunderstand it, this is what it does:</p>\n\n<ul>\n<li><p>Firstly let's define what your values 0, 1, 2 mean. I understand them to\nmean 'free', 'locked', 'locked and contested' respectively. Some #defined\nconstants would have made that clear (assuming it is right).</p></li>\n<li><p>The first compare-and-swap tries to lock the mutex. </p>\n\n<pre><code>if((c = __sync_val_compare_and_swap(m, 0, 1)) != 0) {\n</code></pre>\n\n<p>If this succeeds, the\nfunction exits with the mutex locked (ie. its value is 1). However if the\nmutex was not unlocked (0) this fails and we enter the do...while loop. </p></li>\n<li><p>At this point we know the mutex is (or was, to be precise - it might have\nchanged) either locked or contested. If it was contested we want to make a\nfutex system call to wait for it to be unlocked. </p>\n\n<pre><code> if((c == 2) || __sync_val_compare_and_swap(m, 1, 2) != 0)\n syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);\n</code></pre>\n\n<p>Hence we make the system\ncall either if we know the mutex <strong>was</strong> contested (c == 2) or if it was\nonly locked and we succeeded in setting it contested. But because the mutex\nmight have changed since the first compare-and-swap, we have to do another\ncompare-and-swap to swap its locked 1 for a contested 2. If the mutex\nchanged state and is no longer locked, this will fail and we don't make the\nsystem call. (Note that the system call itself has protection against the mutex changing state before it is entered, hence the '2' parameter which ensures that if <code>*m</code> is not 2 the kernel will not be entered.)</p></li>\n<li><p>If we either didn't make the system call (because the mutex had changed) or\nwe made the call and it returned (again because the mutex state had changed)\nwe reach the <code>while</code> part of the loop. </p>\n\n<pre><code>} while((c = __sync_val_compare_and_swap(m, 0, 2)) != 0);\n</code></pre>\n\n<p>We can expect the mutex to be free\n(0) at this point and that we can try to lock it. But instead the code\ntries to set it to contested (2). If it succeeds the loop and function exit\nwith the mutex set to contested, not just locked. This seems wrong - the\nlast compare-and-swap should be setting '1', not '2'. If we replace the 2\nwith a 1, the loop exit condition is the same as the condition at the start\nof the function and we can simplify to:</p>\n\n<pre><code>enum mutex_state {\n FREE = 0,\n LOCKED,\n CONTESTED\n};\n\nvoid mutex_lock(mutex *m)\n{\n enum mutex_state c;\n while ((c = __sync_val_compare_and_swap(m, FREE, LOCKED)) != FREE) // set locked\n {\n if ((c == CONTESTED) ||\n __sync_val_compare_and_swap(m, LOCKED, CONTESTED) != FREE) // set contested\n {\n syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, CONTESTED, NULL, NULL, 0);\n }\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T01:42:21.867",
"Id": "36615",
"ParentId": "4005",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T08:02:09.327",
"Id": "4005",
"Score": "4",
"Tags": [
"c",
"multithreading",
"linux"
],
"Title": "Mutex and condition variable implementation using futex"
}
|
4005
|
<h2>Aim:</h2>
<p>Use C++0x features to make function interposition safer. The problem is that it's easy to make a typo when wrapping and interposing on functions.</p>
<h2>Prototype Implementation:</h2>
<pre><code>#define MAKE_WRAPPER(x) static const wrapper<decltype(::x), ::x> x(#x)
namespace {
template<typename Sig, Sig& S>
struct wrapper;
template<typename Ret, typename... Args, Ret(&P)(Args...)>
struct wrapper<Ret(Args...), P> {
typedef Ret(*real_func)(Args...);
real_func f;
wrapper(const std::string& sym) : f(NULL) {
dlerror();
void *ptr = dlsym(RTLD_NEXT, sym.c_str());
f = (real_func)ptr;
if (NULL == f) {
std::cerr << "dlsym(): " << dlerror() << std::endl;
}
std::cout << "constructing wrapper: " << this << " for: " << sym << "(at " << ptr << ")" << std::endl;
}
Ret operator()(const Args&... args) const {
return f(args...);
}
};
}
</code></pre>
<h2>Example usage:</h2>
<pre><code>extern "C" {
void glXSwapBuffers(Display *dpy, GLXDrawable drawable) {
MAKE_WRAPPER(glXSwapBuffers);
// Do stuff here before making the call to the wrapper
glXSwapBuffers(dpy, drawable);
}
}
</code></pre>
<h2>Questions:</h2>
<ol>
<li>Is it worth the effort?</li>
<li>How can it be improved?</li>
</ol>
|
[] |
[
{
"body": "<p>[ I'm assuming your example is meant to <code>return x(dpy, drawable);</code> rather than call itself recursively. ]</p>\n\n<ol>\n<li><p>It's worth it if you have a use for it I guess.</p></li>\n<li><p>Printing to <code>std::cerr</code> is not error handling, it's error logging. Pick a real error handling strategy and stick to it. Similarly is printing to <code>std::cout</code> necessary? I also believe that the fewer library calls there are in the constructor, the fewer risks of your wrapper calling itself recursively during static initialization of <code>x</code>, which will be disastrous.</p></li>\n</ol>\n\n<p>Posix recommends the following way to cast when dealing with function types with <code>dlsym</code>:</p>\n\n<pre><code>*(void**)&f = dlsym(RTLD_NEXT, sym.c_str());\n</code></pre>\n\n<p><code>operator()</code> can use perfect forwarding:</p>\n\n<pre><code>Ret\noperator()(Args... args)\n{\n f(std::forward<Args>(args));\n}\n</code></pre>\n\n<p>The wrapping will cost two moves or one copy + one move per argument passed by value and one forward for reference types. It is transparent to the client; he or she won't need to use <code>std::move</code> unless the original function would already have him required to. Notice that the first copy or move of a by-value argument must be paid no matter what; the real <em>opportunity</em> cost of the wrapper is the (potential) move that comes after that, to pass the argument to the real function.</p>\n\n<p>By comparison using <code>Args const&...</code> breaks if the wrapped function is <code>void foo(T&&);</code>, due to reference collapsing rules the signature will be <code>void operator()(T&);</code></p>\n\n<p>Perhaps the macro should take the name of the variable as an argument; but that may not be necessary depending on your planned usage.</p>\n\n<p>Minor pet peeve: meaningful names. I would have called the constructor parameter <code>symbol</code>. The time it takes to type three more characters each time is simply negligible compared to the time it takes to write and maintain code. <code>function_type</code> instead of <code>real_func</code> possibly, too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:28:35.380",
"Id": "6077",
"Score": "0",
"body": "+1, thanks there's quite a few interesting things for me to think about in your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:33:35.437",
"Id": "6079",
"Score": "0",
"body": "(also the call to `glXSwapBuffers` in the example is correct, in that it isn't recursive. The name of the variable is derived from the macro parameter x)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:35:14.000",
"Id": "6080",
"Score": "0",
"body": "One of the things I was trying to work out was if I could make the constructor deduce the name of the symbol (by looking at `__FUNC__` and friends) rather than having to pass it in, but I think the `MAKE_WRAPPER` macro makes mostly that redundant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:46:31.683",
"Id": "6081",
"Score": "0",
"body": "@awoodland Looks like I forgot that `x` was the macro parameter by the time I got to reading the variable name, heh. `__func__` does get you the name of the function but as a string. So yeah, since you need the function for `decltype` that won't help."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:16:52.483",
"Id": "4062",
"ParentId": "4006",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T10:49:16.157",
"Id": "4006",
"Score": "4",
"Tags": [
"c++",
"c++0x"
],
"Title": "Typesafety with dlsym function loading"
}
|
4006
|
<p>I have the following (extremely simplified) database structure:</p>
<ul>
<li>Table: <code>Competitions</code>
<ul>
<li><code>Id</code>: string, unique</li>
</ul></li>
<li><p>Table: <code>Persons</code></p>
<ul>
<li><code>Id</code>: string, unique</li>
<li><code>Gender</code>: string</li>
</ul></li>
<li><p>Table: <code>Results</code></p>
<ul>
<li><code>CompetitionId</code>: string, references <code>Id</code> on the <code>Competitions</code> table</li>
<li><code>PersonId</code>: string, references <code>Id</code> on the <code>Persons</code> table</li>
<li><code>EventId</code>: string</li>
<li><code>RoundId</code>: string</li>
<li><code>Average</code>: int</li>
</ul></li>
</ul>
<p>Any Competition may hold <code>n</code> Results. Each Result is assigned to one Person.</p>
<p>I would like to get all Results (filtered for <code>Average > 0</code>, <code>EventId == "333"</code>, <code>RoundId == "f"</code>, such that it is the one with the lowest <code>Average</code> within the other Results having the same <code>CompetitionId</code>. Furthermore, I only want to get the Results of which the according person is female (<code>gender == "f"</code>).</p>
<p>I currently use a weird mixed LINQ construct that is both, ugly and inefficient. The query takes around 3 minutes on my machine (local MySQL database, Results row count is something close to 200k).</p>
<p>I know there are elegant and efficient ways to use one LINQ query, creating temporary tables, joining and such. I am not that much into it, thus I coded this ugly piece:</p>
<pre><code>var femalePersonIds =
from p in Persons
where p.Gender == "f"
select p.Id;
var results333 =
from r in Results
where (r.Average > 0) && (r.EventId == "333") && (r.RoundId == "f")
orderby r.Average
select r;
foreach (var c in Competitions) {
var results =
from r in results333
where (r.CompetitionId == c.Id)
select r;
if (results.Count() > 0) {
var bestCompResult = results.First();
if (femalePersonIds.Contains(bestCompResult.PersonId)) {
bestCompResult.Dump();
}
}
}
</code></pre>
<p>(This is LINQPad 4 compliant)</p>
<p>I would love to see any efficiency, elegance and shortening hints, in case you have some.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T14:41:02.820",
"Id": "6001",
"Score": "0",
"body": "If I'm reading this correctly, you want to throw out the lowest female score in each competition?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T19:31:52.437",
"Id": "6013",
"Score": "0",
"body": "Exactly. Low average is good in this case, don't get me wrong ;)"
}
] |
[
{
"body": "<p>Try this one:</p>\n\n<pre><code> var filteredResults =\n (from r in results \n where r.Average > 0 &&\n r.EventID == \"333\" &&\n r.RoundID == \"f\"\n select r).ToList();\n\n List<Results> bestResults = new List<Results>(); \n var resultsInCompenitions = filteredResults.GroupBy(r => r.CompetitionID);\n foreach (var resultsInCompetition in resultsInCompenitions)\n {\n var bestResultInCompetition = resultsInCompetition.OrderBy(r => r.Average).FirstOrDefault();\n if (bestResultInCompetition != null)\n {\n bestResults.Add(bestResultInCompetition); \n } \n }\n\n var femaleBestResults = \n from r in bestResults\n join p in persons on r.PersonID equals p.ID\n where p.Gender == \"f\"\n select r; \n\n return femaleBestResults; \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T19:00:29.263",
"Id": "6012",
"Score": "0",
"body": "Unfortunately, this one gets the best female competitors result from each competition. I'm looking for the best competitor who is female. I think I didn't make it clear enough in the thread, let me add some information..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T20:20:24.333",
"Id": "6014",
"Score": "0",
"body": "I've changed the code, and just out of curiosity - is it correct now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T06:17:33.857",
"Id": "6029",
"Score": "0",
"body": "Yep, works like a charm!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T14:29:32.590",
"Id": "4011",
"ParentId": "4008",
"Score": "3"
}
},
{
"body": "<p>I'm very confident a couple calls to <code>ToList</code> will solve your problems. Keep in mind that each interval of the loop will re-evaluate the two queries outside of the loop.</p>\n\n<pre><code>var femalePersonIds =\n (from p in Persons\n where p.Gender == \"f\"\n select p.Id).ToList();\n\nvar results333 =\n (from r in Results\n where (r.Average > 0) && (r.EventId == \"333\") && (r.RoundId == \"f\")\n orderby r.Average\n select r).ToList();\n\nforeach (var c in Competitions) {\n var results =\n (from r in results333\n where (r.CompetitionId == c.Id)\n select r).ToList();\n if (results.Count() > 0) {\n var bestCompResult = results.First();\n if (femalePersonIds.Contains(bestCompResult.PersonId)) {\n bestCompResult.Dump();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T18:54:16.057",
"Id": "6010",
"Score": "0",
"body": "Whoa, I didn't even know it re-evaulates the queries each time. That's pretty much it, thanks! Other improvements would be great too - I would love to see just one LINQ query that does the job..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T00:52:39.593",
"Id": "6027",
"Score": "0",
"body": "Abstractions that leak like a sieve..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T14:42:15.517",
"Id": "4012",
"ParentId": "4008",
"Score": "2"
}
},
{
"body": "<p>I may not totally understand what you're trying to do, but here's a go at it. </p>\n\n<pre><code>Results\n .Where(r => r.Average > 0 && r.EventId == \"333\" && r.RoundId == \"f\")\n .GroupBy(r => r.CompetitionId)\n .Where(r => r.Any(z => z.Person.Gender == \"f\"))\n .Dump();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T17:10:04.413",
"Id": "4019",
"ParentId": "4008",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4012",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T13:08:26.747",
"Id": "4008",
"Score": "3",
"Tags": [
"c#",
"performance",
"linq",
"database"
],
"Title": "Database of competition information"
}
|
4008
|
<p>Unlike most(?) smart pointers, boost::intrusive_ptr has a non-explicit constructor. Given that, one could write</p>
<pre><code>typedef boost::intrusive_ptr<Foo> FooPtr;
FooPtr MyFactory()
{
return new Foo(a, b, c);
}
</code></pre>
<p>Or one could write</p>
<pre><code>FooPtr MyFactory()
{
return FooPtr(new Foo(a, b, c));
}
</code></pre>
<p>The latter is more consistent with how the code would have to be written if FooPtr were another kind of smart pointer, like shared_ptr or unique_ptr. The former is more concise. I personally prefer concise as long as it doesn't lead to trouble for readers and maintainers later. I'm wondering whether the former case is "too" concise?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-25T22:10:39.793",
"Id": "8465",
"Score": "0",
"body": "On a side note, I subscribe to [Linus Torvalds' opinion on typedefs](http://lkml.indiana.edu/hypermail/linux/kernel/0206.1/0402.html) in as much as they are overused and not always a good idea."
}
] |
[
{
"body": "<p>When in doubt, be explicit. While both of the functions given will work, the second expresses programmer intent more clearly. Adding a comment along the lines of \"This will call intrusive_ptr's implicit constructor\" to the first can help, though at that point it's more concise to call the constructor directly. Returning a raw pointer and relying on the implicit constructor for <code>intrusive_ptr</code> may also be viewed as a mistake introduced by changing the declaration of <code>MyFactory()</code> but forgetting its definition. Relying on implicit constructors may also make the code harder to debug and maintain because by default, the constructor for <code>intrusive_ptr</code> increments the retain count in <code>Foo</code>. Calling it explicitly gives you the benefit of being able to search for \"FooPtr(\" when trying to track down every place a <code>Foo</code> is retained. Also, if the <code>Foo</code> constructor initializes its retain count to 1, you may be introducing a memory leak by relying on the implicit constructor. Explicitly specifying <code>FooPtr(new Foo(a, b, c), false)</code> would prevent this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-25T02:17:16.063",
"Id": "5560",
"ParentId": "4009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T14:15:54.920",
"Id": "4009",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Which is the better way to return a new instance of a boost intrusive_ptr"
}
|
4009
|
<p>I have two snippets that are going to be used in a walkthrough and I'd like some feedback on which one is more easily understandable</p>
<h1>1</h1>
<pre><code> property int hours, minutes, seconds
property real shift: 0.0
property bool night
function timeChanged() {
var date = new Date();
hours = date.getUTCHours() + Math.floor(clock.shift);
minutes = date.getUTCMinutes() + (clock.shift % 1) * 60;
seconds = date.getUTCSeconds();
night = (hours < 7 || hours > 19);
}
</code></pre>
<h1>2</h1>
<pre><code> property int hours, minutes, seconds
property real shift
property bool night
function timeChanged() {
var date = new Date;
hours = shift ? date.getUTCHours() + Math.floor(clock.shift) : date.getHours()
night = ( hours < 7 || hours > 19 );
minutes = shift ? date.getUTCMinutes() + ((clock.shift % 1) * 60) : date.getMinutes()
seconds = date.getUTCSeconds();
}
</code></pre>
<p>I personally feel that instantiating the shift variable and skipping the <code>?:</code> operator altogether is a better approach. </p>
<p>Note that both these snippets are aimed at a tutorial for people who are new to QML, and therefore I am charged with picking the one that seems simplest and clearest to people who don't know a lot about QML.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T23:02:10.703",
"Id": "98038",
"Score": "1",
"body": "What's the difference between `shift` and `clock.shift`? Where is `clock` defined? Finally, why can one version work without using the non-UTC versions. In short, I see far more differences than the ternary operator."
}
] |
[
{
"body": "<p>I don't know QML and I can pretty well understand what is going on in sample #1. The use of the <code>? :</code> syntax could be confusing to someone new to the language. </p>\n\n<p>Also, the example to define <code>shift</code> is a good one and is very readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T23:43:38.747",
"Id": "6025",
"Score": "4",
"body": "Looks to me like a ternary operator, which any programmer should be able to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T09:07:35.110",
"Id": "6032",
"Score": "1",
"body": "I disagree, the ternary operator is quite common for people who have a FP background / are in the habit of shortening their code in C-like languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T12:03:41.533",
"Id": "6034",
"Score": "0",
"body": "@Ed: Arnab is right. That is my concern with the ternary operator, the OP alluded to a demonstration of some sort. You shouldn't use any shorthand when demonstrating code to an audience who will/might not know the language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T17:17:57.883",
"Id": "6037",
"Score": "2",
"body": "Ok, It's just that almost every language I know has a ternary: Ruby, C, C++, C#, PHP, Java... the list goes on. I'm not a functional guy (though I toy around), but it seems like we cover a whole lot of programmers by saying *\"...people who have a FP background [or] are in the habit of shortening their code in C-like languages.\"* Anyways, not a biggie."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T18:17:42.570",
"Id": "4021",
"ParentId": "4013",
"Score": "0"
}
},
{
"body": "<p>I definitely think sample #1 is more readable. The main reason is the (lack of) ternary operator. Although any programmer should understand it, it increases the amount of code you have to read. With sample #1 you can quickly skip the parts after <code>+</code> in the <code>hours</code> and <code>minutes</code> assignments, whereas with <code>? :</code> you have to read more carefully.</p>\n\n<p>Also, in sample #2 you basically add handling of a special case without needing it, adding unneeded complexity.</p>\n\n<p>Another bonus in sample #1 is that <code>night</code> is not defined in the middle of the hours/minutes/seconds block, so the code is more logically grouped.</p>\n\n<p>By the way, I think the use of <code>shift</code> should be documented with a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T09:34:20.660",
"Id": "4034",
"ParentId": "4013",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4034",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T14:45:51.457",
"Id": "4013",
"Score": "3",
"Tags": [
"beginner",
"datetime",
"comparative-review",
"qml"
],
"Title": "Two code snippets involving time-change"
}
|
4013
|
<p>This working script directs incoming traffic to different locations depending on the value present in the session for referring URI. If there is a present value, it sends the user back to their original location. If not, then a random number is generated, checked against and used to direct the visitor to one of two possible locations, each with a likelihood of 50%.</p>
<p>It satisfies the basic requirement but I'm wondering if there might not be a better approach.</p>
<p>We have two sub directories, each one with a file within it, and one file at the root. Traffic generally hits the files in the sub dirs, but I wanted to create a root file to handle an event where a user might strip out everything in the URL but the domain.</p>
<p>Each of the files in the sub dirs use this logic to set the referrer:</p>
<pre><code>function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
function selfURL() {
if(!isset($_SERVER['REQUEST_URI'])) {
$serverrequri = $_SERVER['PHP_SELF'];
} else {
$serverrequri = $_SERVER['REQUEST_URI'];
}
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$_SESSION['ref'] = $protocol."://".$_SERVER['SERVER_NAME'].$port.$serverrequri;
}
selfURL();
</code></pre>
<p>The file at the root uses this logic to direct traffic:</p>
<pre><code>$refurl = $_SESSION['ref'];
if (isset($refurl)) {
header("Location: " . $refurl);
} else {
$loc1 = "dir1/file.php";
$loc2 = "dir2/file.php";
$num = mt_rand(1, 100);
if ($num > 50) {
header("Location: " . $loc1);
} else {
header("Location: " . $loc2);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T07:15:49.400",
"Id": "6030",
"Score": "1",
"body": "is there any way \"$_SERVER['REQUEST_URI']\" wont be set?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T03:13:56.663",
"Id": "6104",
"Score": "1",
"body": "This is pretty much decent code from my read. Don't expect you to get a lot of comments or answers as this is basically clean and proper from a language agnostic design perspective.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T19:07:48.427",
"Id": "60210",
"Score": "0",
"body": "Are you trying to reimplement PHP sessions? What is the purpose? You might want to read this: http://www.php.net/manual/en/book.session.php"
}
] |
[
{
"body": "<p>null coalesce does exist in php according to the google (per: <a href=\"https://stackoverflow.com/questions/1013493/coalesce-function-for-php\">https://stackoverflow.com/questions/1013493/coalesce-function-for-php</a> )</p>\n\n<pre><code>$s = $_SERVER[\"HTTPS\"] ?: \"\";\n$protocol = strleft(strtolower($_SERVER[\"SERVER_PROTOCOL\"]), \"/\").$s;\n</code></pre>\n\n<p>I'm not super familiar with php, but I think this should work from what I understand you're doing here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-14T08:44:17.650",
"Id": "10682",
"Score": "0",
"body": "nice! very useful, indeed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T03:10:12.767",
"Id": "4081",
"ParentId": "4018",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4081",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T16:33:53.020",
"Id": "4018",
"Score": "5",
"Tags": [
"php",
"url"
],
"Title": "Redirect incoming traffic based on referrer or random number"
}
|
4018
|
<p>This is my implementation of quicksort (algorithm taken from Cormen book). This is an in place implementation. Please let us know issues with this or any ideas to make it better. It performs at logN.</p>
<pre><code>import java.util.ArrayList;
public class MyQuickSort {
/**
* @param args
*/
public static void main(String[] args) {
//int[] a = { 1, 23, 45, 2, 8, 134, 9, 4, 2000 };
int a[]={23,44,1,2009,2,88,123,7,999,1040,88};
quickSort(a, 0, a.length - 1);
System.out.println(a);
ArrayList al = new ArrayList();
}
public static void quickSort(int[] a, int p, int r)
{
if(p<r)
{
int q=partition(a,p,r);
quickSort(a,p,q);
quickSort(a,q+1,r);
}
}
private static int partition(int[] a, int p, int r) {
int x = a[p];
int i = p-1 ;
int j = r+1 ;
while (true) {
i++;
while ( i< r && a[i] < x)
i++;
j--;
while (j>p && a[j] > x)
j--;
if (i < j)
swap(a, i, j);
else
return j;
}
}
private static void swap(int[] a, int i, int j) {
// TODO Auto-generated method stub
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:17:30.847",
"Id": "33099",
"Score": "4",
"body": "This is O(n log n) not log n"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:54:45.250",
"Id": "61399",
"Score": "0",
"body": "It will not scale due to recursion: the JVM has no tail call optimization, it will simply grow the method call stack to something proportional to the array to sort, and it will fail for too large an array. (and even for languages/platforms that *do* have tail call optimization I don't think they'd be able to actually apply it to this code)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-02T17:39:53.967",
"Id": "118165",
"Score": "0",
"body": "I think it's worth mentioning that the partition method does not make the pivot end to it's final destination, which is different from the classical QuickSort which you can check on wikipedia."
}
] |
[
{
"body": "<p>If the algorithm was taken from a book, then chances are it will be as good as it could possibly be. So as long as you followed it to the letter, there really shouldn't be any issues in your implementation.</p>\n\n<p>There is however one thing I think could be improved upon, the interface to initiate the sort. When I think of sorting a collection, I'd expect to provide a couple of things, the collection of course and possibly a comparer. Anything else that requires passing implementation specific values just feels \"wrong\" to me. It might be ok if these indices represented the start and stop range of values to sort, but I would still make that as a separate overload.</p>\n\n<p>Your implementation on the other hand requires the collection and indices necessary for the algorithm to work. This would not be an ideal interface to work with since you have to remember to pass in certain values to perform the sort when instead they could be calculated for me. I would expose an overload which only accepts the collection to sort which would call the actual implementation with the right arguments.</p>\n\n<p>Also, even though this is the well known quick sort algorithm, I'd still provide better variable names. Not really a problem here, personal preference.</p>\n\n<pre><code>// this overload is the public interface to do the sort\npublic static void quickSort(int[] collection)\n{\n quickSort(collection, 0, collection.length - 1);\n}\n\n// note: method is now private\nprivate static void quickSort(int[] collection, int pivotIndex, int rangeIndex)\n{\n // etc...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T23:05:53.217",
"Id": "6023",
"Score": "3",
"body": "+1 for the variable names this would make the code clearer. The code is pretty well separated into functions instead of the usual jumble we often seen (this is directed at no one in particular)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-10T18:55:24.650",
"Id": "4023",
"ParentId": "4022",
"Score": "22"
}
},
{
"body": "<p>I see one small improvement. Instead of...</p>\n\n<pre><code>i++;\nwhile ( i< r && a[i] < x)\n i++;\nj--;\nwhile (j>p && a[j] > x)\n j--;\n</code></pre>\n\n<p>...you can write:</p>\n\n<pre><code>do {\n i++;\n} while (i < r && a[i] < x);\ndo {\n j--;\n} while (j > p && a[j] > x);\n</code></pre>\n\n<p>And Jeff is right about the public interface.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T07:24:34.910",
"Id": "4033",
"ParentId": "4022",
"Score": "9"
}
},
{
"body": "<p>If you try to sort an already-sorted array size over 20000, it will cause a stack overflow. The partition has problems when encountering a large-sized sorted array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:43:09.513",
"Id": "25627",
"ParentId": "4022",
"Score": "6"
}
},
{
"body": "<p>I see another improvement. I think it makes more sense to think that the markers (<code>i</code> and <code>j</code>) should move after the swapping is done. It cleans up the code by a few lines and it makes more sense.</p>\n\n<pre><code>private static int partition(int[] a, int p, int r) {\n\n int x = a[p];\n int i = p;\n int j = r;\n\n while (true) {\n while (i < r && a[i] < x)\n i++;\n while (j > p && a[j] > x)\n j--;\n\n if (i < j) {\n swap(a, i, j);\n i++;\n j--;\n } else {\n return j;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T02:12:47.523",
"Id": "31969",
"ParentId": "4022",
"Score": "3"
}
},
{
"body": "<p>It looks really good, but I always recommend these guidelines when someone have to code a Quick sort again:</p>\n\n<ol>\n<li>Randomization: random permuting keys can avoid O(n²) when nearly-sorted data.</li>\n<li>Median of tree: use the median of first, middle and last elements to select you pivot. The bigger the data, more samples.</li>\n<li><p>Leave small sub-arrays for Insertion sort: finish Quicksort recursion and switch to insertion sort when fewer then 20 elements:</p>\n\n<pre><code> // Insertion sort on smallest arrays\n if (rangeIndex < 20) {\n for (int i=pivotIndex; i < rangeIndex + pivotIndex; i++)\n for (int j=i; j > pivotIndex && x[j-1]>x[j]; j--)\n swap(x, j, j-1);\n return;\n }\n</code></pre></li>\n<li>Do the smaller partition first: only O(logn) of space is needed for the recursion</li>\n</ol>\n\n<p>All this tips come from the excelent book <a href=\"http://www.algorist.com/\">The Algorithm Design Manual</a>, from Steven Skiena.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:24:47.957",
"Id": "37226",
"ParentId": "4022",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4023",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-05T07:04:26.963",
"Id": "4022",
"Score": "26",
"Tags": [
"java",
"sorting",
"quick-sort"
],
"Title": "Java Implementation of Quick Sort"
}
|
4022
|
<p>I have an application in which I am querying an XML web service continuously every 2 seconds in a thread. The returned XML is very big and I am retrieving lots of stuff from them using XPath and plugging the values into labels in the GUI, using delegates for thread safety.</p>
<p>But the way I've done this, it looks bizarre to me, and I cannot think out of the box and find a way to optimize the code. It's working perfectly but I think there must be a better way to do this.</p>
<pre><code>public void GetConditions(object activeDs)
{
string ds = (string)activeDs;
XPathDocument doc;
XmlNamespaceManager ns;
XPathNavigator navigator;
XPathNodeIterator nodes;
XPathNavigator node;
Thread unitThread = new Thread(new ParameterizedThreadStart(SetUnits));
unitThread.Start(ds);
while (contFlag)
{
try
{
doc = new XPathDocument(ds + "/current");
navigator = doc.CreateNavigator();
navigator.MoveToFirstChild();
string uri = navigator.LookupNamespace("");
ns = new XmlNamespaceManager(navigator.NameTable);
ns.AddNamespace("m", uri);
string devName = xmlParser.GetXmlValues(ns, "//m:Devm", "name", navigator);
tsa.SetText(devName, currDevName);
string execStatus = xmlParser.GetXmlValues(ns, "//m:Exec", navigator);
SetExecutionStatus(execStatus);
string spndlSpd = xmlParser.GetXmlValues(ns, "//m:Spieed", "subType", "ACTUAL", navigator);
double spndlSpdDbl; double.TryParse(spndlSpd, out spndlSpdDbl);
tsa.SetText(spndlSpdDbl.ToString("0.000"), spndSpdLbl);
string spndlSpdOvr = xmlParser.GetXmlValues(ns, "//m:Spieed", "subType", "OVERRIDE", navigator);
double spndlSpdOvrDbl; double.TryParse(spndlSpdOvr, out spndlSpdOvrDbl);
tsa.SetText(spndlSpdOvrDbl.ToString("0.000"), spndSpOrLbl);
string feedRt = xmlParser.GetXmlValues(ns, "//m:Parate", "subType", "ACTUAL", navigator);
double feedRtDbl; double.TryParse(feedRt, out feedRtDbl);
tsa.SetText(feedRtDbl.ToString("0.000"), feedLbl);
string feedRtOvr = xmlParser.GetXmlValues(ns, "//m:Paedrate", "subType", "OVERRIDE", navigator);
double feedRtOvrDbl; double.TryParse(feedRtOvr, out feedRtOvrDbl);
tsa.SetText(feedRtOvrDbl.ToString("0.000"), fdOrLbl);
string modeTxt = xmlParser.GetXmlValues(ns, "//m:ControllerMode", navigator);
tsa.SetText(modeTxt, modeLbl);
string progTxt = xmlParser.GetXmlValues(ns, "//m:Program", "name", "program", navigator);
tsa.SetText(progTxt, prgNameLbl);
string prtCntFrmStrm = xmlParser.GetXmlValues(ns, "//m:PartCount", navigator);
SetPartCount(prtCntFrmStrm);
BuildAlertList();
nodes = navigator.Select("//m:ComponentStream", ns);
int i = 1;
try
{
while (nodes.MoveNext())
{
node = nodes.Current;
string currComp = node.GetAttribute("component", ns.DefaultNamespace);
string currCompName = node.GetAttribute("name", ns.DefaultNamespace);
if (node.HasChildren)
{
XPathNodeIterator xn = node.SelectChildren(XPathNodeType.Element);
while (xn.MoveNext())
{
if (xn.Current.Name == "Condition")
{
XPathNodeIterator xpni = xn.Current.SelectChildren(XPathNodeType.Element);
while (xpni.MoveNext())
{
XPathNavigator xpn1 = xpni.Current;
string currAlrtType = xpn1.GetAttribute("type", ns.DefaultNamespace);
string currAlrt = xpn1.Name;
string[] addToList = new String[3] { currComp, currAlrtType, currAlrt };
ListViewItem ls = new ListViewItem(addToList);
tsa.AccessControlList(ls, condView);
}
}
}
}
i++;
}
}
catch { }
Thread.Sleep(2000);
}
catch (WebException ex)
{
MessageBox.Show("Cannot retrieve stream. Please check Data source.","Demo App");
xmlParser.AppState = 0;
Console.Write(ex.ToString());
break;
}
}
}
</code></pre>
<p>My main constraint is that I need to retrieve all this data and plug it in the GUI. Any pointers would be helpful for me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T04:45:26.093",
"Id": "6028",
"Score": "4",
"body": "I haven't looked at your code thoroughly yet but I can tell you one thing, switching over to using LINQ to XML and the `XDocument` could cut the code down to a much more reasonable size."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T01:04:29.623",
"Id": "6042",
"Score": "1",
"body": "The code doesn't look complete. What is `xmlParser`? The methods you call on it doesn't look familiar to me. Is that a third-party parser? An in-house built one? It's hard get an idea of what the documents look like as there's no real pattern to how you use it. That is, coming from an outsider's view. We'll need more detail about what's going on here if you'd want a more complete and well informed answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T03:10:54.223",
"Id": "6046",
"Score": "0",
"body": "xmlparser is just an inhouse built parser for the specific web service we are using. It will just traverse the navigator and returns a string that we request for based on the parameters provided. Consider that all xmlparser does is returns a string based on the parameters given."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T03:11:18.620",
"Id": "6047",
"Score": "0",
"body": "Reg linq this is a 2.0 app and linq to xml isnt available in 2.0.(or atleast i cant find one which just works)"
}
] |
[
{
"body": "<p>One minor change you can do: </p>\n\n<pre><code>new Thread(new ParameterizedThreadStart(SetUnits)); \n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>new Thread(SetUnits);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:01:03.770",
"Id": "4041",
"ParentId": "4030",
"Score": "4"
}
},
{
"body": "<p>First and largest thing I see here is the size of this method. When you're looking at a block of code and having difficulty recognizing how to simplify it, think of it like a bunch of data that you want to simplify, first thing you do is look for patterns by breaking the data up into pieces you can quantify. In your case this means breaking out blocks of the code into descriptively named methods.</p>\n\n<p>I would break up all those parse and tsa.SetText things you have into seperate methods (assuming your xmlParser object is a member level variable):</p>\n\n<pre><code>SetCurrentDevName();\nSetExecutionStatus(); // this can do the string parsing on it's own from the member level xmlParser\nSetSpndlGibberishAmbiguouslyNamedThing(); // spndlSpd is not a descriptive name for anything\nSetSpndlSpdOvrDbl();\nSetFeedRateDouble(); // I think that's what fdrtdbl is? Who knows\nSetFeedRateOverDouble();\nSetModeText();\nSetProgText();\nSetPartCount();\n</code></pre>\n\n<p>Next, you have a try block without a catch or finally after it, this serves no purpose unless I'm missing something..</p>\n\n<p>Lastly, make your whole nested while block a single seperate method.</p>\n\n<p>Breaking things up like this into seperate methods you will probably begin to see patterns emerge and realize more ways to simplify this.</p>\n\n<p>Edit:\nand as mentioned earlier, use LINQ and XDocuments, far far simpler than the old xmldocument/xpathnavigator stuff.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T01:47:13.373",
"Id": "4047",
"ParentId": "4030",
"Score": "6"
}
},
{
"body": "<p>On your window or base window class, implement a method like this:</p>\n\n<pre><code> protected virtual void InvokeIfRequired(Action action)\n {\n if (this.InvokeRequired)\n {\n this.Invoke(action);\n }\n else\n {\n action();\n }\n } \n</code></pre>\n\n<p>Then when you want to update a GUI element, do this:</p>\n\n<pre><code> this.InvokeIfRequired(() => textBox.Text = \"Some result\");\n // or a block\n this.InvoveIfRequired(() => {\n textBoxt2.Text = \"Some result 2\";\n textBoxt3.Text = \"Some result 3\";\n });\n</code></pre>\n\n<p>You call call <code>InvokeIfRequired()</code> from your thread, rather than looping on the main thread until there are no exceptions.</p>\n\n<p>Looping on the main thread defeats the purpose of using another thread because execution and therefore window event processing is blocked until the loop completes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-23T00:50:40.647",
"Id": "123609",
"ParentId": "4030",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T04:17:52.230",
"Id": "4030",
"Score": "6",
"Tags": [
"c#",
"multithreading",
"winforms",
"xpath"
],
"Title": "Returning a large number of values from a thread"
}
|
4030
|
<p>Below is what I have come up with for a router/dispatcher system for my personal framework I am working on. Can you please review and tell me any improvements that could be made? </p>
<p>The first part is an array of URI -> to class/method/id_number/page_number using regex. I have only included a partial list of routes, there will be at least 50 possible routes that will have to run the regex on. I am thinking that is pretty bad for performance, but it seems the best way I know of to do it, since I need to match page numbers and id numbers when they exists. </p>
<p>I am new to MVC so this is my first attempt and I am sure you guys can give me improvement on this, thanks for any tips or help!</p>
<p><code>.htaccess</code> file:</p>
<pre><code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?uri=$1 [NC,L,QSA]
</code></pre>
<p>Map array():</p>
<pre><code>/**
* Map URI to class/method and ID and Page numbers
* Must be an array
*/
$uri_route_map = array(
//forums
'forums/' => array(
'controller' => 'forums',
'method' => 'index',
'id_number' => '',
'page_number' => ''),
'forums/viewforum/(?<id_number>\d+)' => array(
'controller' => 'forums',
'method' => 'viewforum',
'id_number' => isset($id_number),
'page_number' => ''),
'forums/viewthread/(?<id_number>\d+)' => array(
'controller' => 'forums',
'method' => 'viewthread',
'id_number' => isset($id_number),
'page_number' => ''),
'forums/viewthread/(?<id_number>\d+)/page-(?<page_number>\d+)' => array(
'controller' => 'forums',
'method' => 'viewthread',
'id_number' => isset($id_number),
'page_number' => isset($page_number)),
// user routes
// account routes
// blog routes
// mail routes
// various other routes
);
</code></pre>
<p>Router class that reads and matches the Map array above</p>
<pre><code>/**
* Run URI against our Map array to get class/method/id-page numbers
*/
class Router
{
private $_controller = '';
private $_method = '';
public $page_number = '';
public $id_number = '';
public function __construct($uri, array $uri_route_map)
{
foreach ($uri_route_map as $rUri => $rRoute)
{
if (preg_match("#^{$rUri}$#Ui", $uri, $uri_digits))
{
//if page number and ID number in uri then set it locally
$this->page_number = (isset($uri_digits['page_number']) ? $uri_digits['page_number'] : null);
$this->id_number = (isset($uri_digits['id_number']) ? $uri_digits['id_number'] : null);
$this->_controller = $rRoute['controller'];
$this->_method = $rRoute['method'];
// just for debug and testing while working on it / will be removed from final code
echo '<hr> $page_number = ' . $this->page_number . '<br><br>';
echo '<hr> $id_number = ' . $this->id_number . '<br><br>';
echo '<hr> $controller = ' . $this->_controller . '<br><br>';
echo '<hr> $method = ' . $this->_method . '<br><br>';
break;
}else{
$this->page_number = '';
$this->id_number = '';
$this->_controller = '404';
$this->_method = '404';
}
}
}
public function getController()
{
return $this->_controller;
}
public function getMethod()
{
return $this->_method;
}
public function getPageNumber()
{
return $this->page_number;
}
public function getIDNumber()
{
return $this->id_number;
}
/**
* Call our class and method from values in the URI
*/
public function dispatch()
{
if (file_exists('controller' . $this->_controller . '.php'))
{
include ('controller' . $this->_controller . '.php');
$controllerName = 'Controller' . $this->_controller;
$controller = new $controllerName($this->getIDNumber(),$this->getPageNumber());
$method = $this->_method;
if (method_exists($this->_controller, $this->_method))
{
return $controller->$method();
} else {
// method does not exist
}
} else {
// Controller does not exist
}
}
}
</code></pre>
<p>Run it</p>
<pre><code>/**
* Testing the class
*/
$uri = isset($_GET['uri']) ? $_GET['uri'] : null;
$router = new Router($uri, $uri_route_map);
$router->dispatch();
?>
</code></pre>
|
[] |
[
{
"body": "<p>If you can limit your URI structure to using a delimiter - <code>/</code> comes to mind - you could avoid the regex.</p>\n\n<p>Here's a rough example (not with any configuration, but shows the concept):</p>\n\n<pre><code>$uri = 'forums/viewforum/1';\n$parts = explode('/', $uri);\n\n$controller = $parts[0];\n$method = $parts[1];\n$id = parts[2];\n</code></pre>\n\n<p>I'd take a look at the router implementations of some popular frameworks (my recommendation would be <a href=\"http://framework.zend.com/manual/en/zend.controller.router.html\">ZF's router</a>, but that's just me) - there's nothing wrong from learning how someone else tackled the same problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T04:37:00.953",
"Id": "4053",
"ParentId": "4031",
"Score": "7"
}
},
{
"body": "<p>Also check out 'Silex' and 'Slim' which are microframeworks which include routing to see how they tackle this problem. Personally I think that just having id_number and page_number is restrictive. Eventually you'll want more complexity (and potentially params) passed in each route.</p>\n\n<p>Silex for example maps each route to a closure, which is a pattern that I think works pretty well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T07:53:56.427",
"Id": "4068",
"ParentId": "4031",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4053",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T04:52:31.457",
"Id": "4031",
"Score": "8",
"Tags": [
"php",
"mvc",
".htaccess",
"url-routing"
],
"Title": "MVC router class"
}
|
4031
|
<p>I have got this working ok, I just think that it can be improved and reduce the amount of code. If anybody could help that would be brilliant. </p>
<pre><code>// Max Length Input
$('input[maxlength]').each(function() {
var maxCharLength = $(this).attr("maxlength");
if(maxCharLength < 0 || maxCharLength > 5000){
} else {
var charLength = $(this).val().length;
$(this).after("<span class='charCount clearBoth' id='charCount_"+$(this).attr("name").replace(".","_")+"'> " + charLength + " of " + maxCharLength + " characters used</span>");
$(this).keyup(function() {
var charLength = $(this).val().length;
$(this).next("span").html(charLength + ' of ' + maxCharLength + ' characters used');
if(charLength == maxCharLength ) {
$(this).next("span").html('<strong> Maximum of ' + maxCharLength + ' characters used.</strong>');
$(this).next("span").addClass("red");
} else { $(this).next("span").removeClass("red"); }
});
}
});
// Max Length textarea
$('textarea[maxlength]').each(function() {
var maxCharLength = $(this).attr("maxlength");
if(maxCharLength < 0 || maxCharLength > 5000){
} else {
var charLength = $(this).val().length;
$(this).after("<span class='charCount clearBoth'> " + charLength + " of " + maxCharLength + " characters used</span>");
$('textarea[maxlength]').keyup(function(){
var limit = parseInt($(this).attr('maxlength'));
var text = $(this).val();
var chars = text.length;
$(this).next("span").html(chars + ' of ' + limit + ' characters used');
if(chars > limit){
var new_text = text.substr(0, limit);
$(this).val(new_text);
$(this).next("span").html('<strong> Maximum of ' + limit + ' characters used.</strong>');
$(this).next("span").addClass("red");
} else { $(this).find("span").removeClass("red"); }
});
}
});
</code></pre>
|
[] |
[
{
"body": "<p>There are a few things I would suggest:<br>\n1. Replace you numbers with constants and revert the condition to get rid of 'else':</p>\n\n<pre><code>var minTextLength = 0;\nvar maxTextLength = 5000;\nif (maxCharLength >= minTextLength || maxCharLength <= maxTextLength){\n //Your code...\n }\n</code></pre>\n\n<p>2. Move the block of code:</p>\n\n<pre><code>$(this).next(\"span\").html('<strong> Maximum of ' + maxCharLength + ' characters used.</strong>');\n $(this).next(\"span\").addClass(\"red\");\n } else { $(this).next(\"span\").removeClass(\"red\"); }\n</code></pre>\n\n<p>To a separate function.</p>\n\n<p>And there are a couple of things that confuse me:<br>\n1. In 'Max Length textarea' you have:</p>\n\n<pre><code>$('textarea[maxlength]').keyup()\n</code></pre>\n\n<p>Is it correct? Becasue it means that you'll add a lot of handlers to all your textarea[maxlength].</p>\n\n<p>2\n. In your 'Max Length Input' you have:</p>\n\n<pre><code>if(charLength == maxCharLength )\n</code></pre>\n\n<p>Maybe it could be replaced with:</p>\n\n<pre><code>if(charLength > maxCharLength )\n</code></pre>\n\n<p>Depending on the answers to these questions, maybe it'll be possible to move the keyup handler to a separate function. And maybe even the whole code from both 'Max Length textarea' and 'Max Length Input'.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T19:04:59.923",
"Id": "4037",
"ParentId": "4036",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4037",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T14:38:36.857",
"Id": "4036",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Jquery Max character with character count for input and textarea"
}
|
4036
|
<p>I'm spec'ing out a API for a task scheduler and I would be thankful for your thoughts. This is what I've got so far:</p>
<pre><code>public void Configure(Context ctx) {
// Single tasks
ctx.Run(() => Tasks.First()).Every.Midnight;
ctx.Run(() => Tasks.Second()).Every.Day(8,0));
// Multiple tasks
ctx.Run(() => {
Tasks.Third();
Tasks.Fourth();
}).Every.Day(8,0);
// Triggers:
..Every.Hour(20/*Minute*/);
..Every.Minute(10/*Second*/);
..Every.Second();
}
</code></pre>
<p>The run method accepts an Action parameter.</p>
<p>Obviously, I need to support custom triggers to allow users to configure it exactly as they want. It could be done by implementing an interface like:</p>
<pre><code>interface ITask {
bool ShouldRun(DateTime currentDate);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T01:59:37.820",
"Id": "6043",
"Score": "1",
"body": "I wouldn't bother with all your various every overloads, if you want fluent style replace the everys with a single method `.AndReoccur(int numberOfTimes, Timespan interval)` also I'm pretty sure this site is supposed to be for compilable functioning code, maybe this fits on stackoverflow better?"
}
] |
[
{
"body": "<p>I'd like to be able to use a non-functional approach to running the api. Perhaps I'm a new developer and don't understand lambdas. Give me the option to go.</p>\n\n<pre><code>ctx.Run(//Task, or List of tasks, //How often, //Time to start, //Possible skip conditions - maybe skip weekends);\n\n//Utilize enums that they can use\nctx.Run(Task.First(), Frequency.Daily, Time.Midnight);\n\n//or pass a list of tasks perhaps\nList<Task> tasks;\nctx.Run(tasks, Frequency.Hourly, Time.Custom(hour, min, sec), Time.Weekends);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T02:51:01.830",
"Id": "4050",
"ParentId": "4038",
"Score": "0"
}
},
{
"body": "<p>Instead of rolling your own API for repetitions, I'd adopt the terminology and semantics of RFC 5545 RRULEs which is widely used within Calendaring applications</p>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc5545#section-3.8.5.3\" rel=\"nofollow noreferrer\">Section 3.8.5.3</a> thoroughly documents the syntax and behavior of RRULEs (Recurrence rules). They look like</p>\n<blockquote>\n<pre><code>RRULE:FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH\n</code></pre>\n</blockquote>\n<p>which means</p>\n<blockquote>\n<p>Weekly on Tuesday and Thursday for five weeks:</p>\n</blockquote>\n<p>so you could implement these semantics (or find an existing RFC 5545 library that does it) and your API might look very similar to the RRULE syntax:</p>\n<pre><code>ctx.Run(...).Freq(WEEKLY).Count(10).ByDay(TU, TH)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T22:39:55.390",
"Id": "4060",
"ParentId": "4038",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T20:30:33.773",
"Id": "4038",
"Score": "4",
"Tags": [
"c#",
"api",
"scheduled-tasks"
],
"Title": "Task scheduler API"
}
|
4038
|
<p>There's another exercise from Thinking in C++. <br />
This time it asks this:</p>
<blockquote>
<p>Write a program that uses two nested for loops and the
modulus operator (%) to detect and print prime numbers
(integral numbers that are not evenly divisible by any
other numbers except for themselves and 1).</p>
</blockquote>
<p>And this is what I think:</p>
<pre><code>// finds all prime numbers between 2 and a number given in input.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "How many prime numbers do you want to print? ";
int n;
cin >> n;
int i, j;
bool flag = true;
for(i = 2; i <= n; i++) {
for(j = 2; j <= i; j++) {
if((i % j) == 0) {
if(i == j)
flag = true;
else {
flag = false;
break;
}
}
}
if(flag)
cout << "Prime: " << i << endl;
}
}
</code></pre>
<p>It works perfectly, but I'd know what do you think about. Thanks for the feedback! </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:23:25.770",
"Id": "6040",
"Score": "4",
"body": "`for(j = 2; j <= i; j++)` should be `for(j = 2; j * j < i; j++)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:23:46.780",
"Id": "64481",
"Score": "0",
"body": "To check if n is a prime you only have to check divisibility by up to sqrt(n). You have excess computations."
}
] |
[
{
"body": "<p><code>for(j = 2; j <= i; j++)</code> should be <code>for(j = 2; j * j <= i; j++)</code>. You only need to test for divisors less than the square root of i (if there is a divisor greater than sqrt(i), there is one less than sqrt(i)).</p>\n\n<p>The loop should therefore read:</p>\n\n<pre><code>for(i = 2; i <= n; i++) \n{\n bool flag = true;\n\n for(j = 2; j * j <= i; j++) \n {\n if(i % j != 0) \n {\n flag = false;\n break;\n }\n }\n\n if (flag) cout << \"Prime: \" << i << endl;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:40:49.513",
"Id": "6041",
"Score": "0",
"body": "Your code doesn't works..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T02:32:41.030",
"Id": "6045",
"Score": "0",
"body": "@unNaturhal: Care to tell us anything more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T14:16:01.250",
"Id": "6058",
"Score": "0",
"body": "@alpha123: It prints 2, 3, 4, 5, 6, 8 if you give 10 in input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:26:08.840",
"Id": "4045",
"ParentId": "4043",
"Score": "0"
}
},
{
"body": "<p>Forgive me, I'm a C# developer, I like descriptive terms :)</p>\n\n<p>As Alexandre mentioned, the sqrt is key to minimize computations. Great heuristic. Another heuristic you can use is every other number will not be prime, as it will be divisible by 2. Then to expand on this heuristic, you can say that no odd numbers are divisible by even numbers and therefore may skip every other number as your divisible test number.</p>\n\n<pre><code>for(int mightBePrime = 3; mightBePrime <= upperLimitToCheck; mightBePrime += 2)\n{\n bool foundAPrime = true;\n for(int divisorToCheckPrime = 3; divisorToCheckPrime * divisorToCheckPrime <= mightBePrime ; divisorToCheckPrime += 2)\n {\n if(mightBePrime % divisorToCheckPrime == 0)\n {\n foundAPrime = false;\n break;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T08:44:53.063",
"Id": "6053",
"Score": "0",
"body": "+1 for best answer, though to be really pedantic, this does miss the number 2 :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T18:36:34.190",
"Id": "6065",
"Score": "0",
"body": "I remember doing some Euler projects where the modulus was actually inducing a fair amount of overhead. If your set is very large you may want to consider a simple `isOdd = num & 1`. That said... this was years ago and who's to say I wasn't stupidly running a debug build? A decent compiler should produce identical code for either... but you may want to check."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T01:25:30.780",
"Id": "4046",
"ParentId": "4043",
"Score": "5"
}
},
{
"body": "<p>If you're finding a single prime number, looping through all the numbers up to it's square root is good. But if you're trying to find <em>every</em> prime up to a certain limit, then do as follows. Keep a list of each prime you find, then, when checking a new number, only check it against the previously found primes, up to it's square root. So, something like this:</p>\n\n<pre><code>std::vector<int> primes;\nfor(int i=2; i<=n; ++i)\n{\n bool is_prime = true;\n int sq = sqrt((long double)i);\n for (int j=0; j<primes.size() && primes[j] <= sq; ++j)\n {\n if (i % primes[j] == 0)\n {\n is_prime = false;\n break;\n }\n }\n if (is_prime) primes.push_back(i);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T03:03:57.273",
"Id": "4051",
"ParentId": "4043",
"Score": "1"
}
},
{
"body": "<p>What I think about your code:</p>\n\n<p>This is sloppy coding.\nYou should not use it. It is best to fully qualify stuff from the std namespace. Its not that hard or long.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>I would put a \"\\n\" on the end of the line.\nIt makes the questions on the terminal look like the question is on one line and your answer is on the next which in my mind makes it easier to read.</p>\n\n<pre><code> cout << \"How many prime numbers do you want to print? \";\n</code></pre>\n\n<p>Single letter variables names is again slopy.<br>\nYour variable names should be descriptive. So readers can see your intention. As a side affect it makes looking for the variable easy. Especially if you use an editor that is scriptable and want to automate some task on the variable.</p>\n\n<pre><code> int n;\n cin >> n;\n</code></pre>\n\n<p>Personally I don't like the '{' at the end of the line. But I realize that is a style thing so I don;t care if other people do it like this.</p>\n\n<pre><code> for(i = 2; i <= n; i++) {\n</code></pre>\n\n<p>Other have already pointed out that the inner loop can be optimized a bit.</p>\n\n<pre><code> for(j = 2; j <= i; j++) {\n</code></pre>\n\n<p>This test should never be required.<br>\nIt just means that you are doing extra work.</p>\n\n<pre><code> if(i == j)\n</code></pre>\n\n<p>Try this:</p>\n\n<pre><code>#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <iostream>\n\nstruct PrimeTest\n{\n PrimeTest(int val)\n : value(val)\n {}\n bool operator()(int test) const { return value%test == 0;}\n int value;\n};\n\nint main()\n{\n std::vector<int> primes;\n int maxCount;\n\n std::cout << \"Check how many numbers?\\n\";\n std::cin >> maxCount;\n\n for(int primeTest = 2; primeTest <= maxCount; ++primeTest)\n {\n // There is a loop hidden inside here.\n if (std::find_if(primes.begin(), primes.end(), PrimeTest(primeTest)) == primes.end())\n { primes.push_back(primeTest);\n }\n }\n std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(std::cout, \", \"));\n}\n</code></pre>\n\n<p>But since the question explicitly asked for two loops:<br>\nYou can write the loop like this.</p>\n\n<pre><code> for(int primeTest = 2; primeTest <= maxCount; ++primeTest)\n {\n std::vector<int>::iterator loop = primes.begin();\n TestPrime test(primeTest);\n for(;loop != primes.end(); ++loop)\n {\n if (test(*loop))\n { break;\n }\n }\n if (loop == primes.end())\n { primes.push_back(primeTest);\n }\n }\n</code></pre>\n\n<p>Technically you don't need to test all the numbers less than the number you are testing. Some have pointed out the easy optimization of only testing up to the square root of the number. But an even better solution is to only test the primes below your number.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T09:27:10.847",
"Id": "6054",
"Score": "0",
"body": "Better still is to only test against primes up to the square root of the number. Then again, if you're going to find all the primes up to some limit, you should normally use the sieve of Eratosthenes (even though that doesn't fit the assignment)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T14:06:06.487",
"Id": "6057",
"Score": "0",
"body": "@Jerry: That is the next optimization. But only checking primes reduces the set of values by such a huge number compared to just checking upto the root of the value I though it was a great improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T22:29:46.200",
"Id": "6068",
"Score": "0",
"body": "There is no reason to fully quality everything in `std` for a simple throwaway program. That's ridiculous. Even then your advice is bad; just use `using std::cin`, you don't have to fully qualify it every time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:18:09.033",
"Id": "6070",
"Score": "0",
"body": "@Ed S: Sure you can be lazy. But habits become hard to break. You do not want to get in the habit of using bad practice because when you write a more complex application you don;t want to use bad habits or sloppy technique as this is going to cost you one day with a big break. I always fully qualify everything in standard. Its not as if it takes any more work. If it is a short program say less than a page I'll probably save typing anyways as I would have to use 5 objects in the standard namespace before it becomes more expansive than typing 'using namespace std;' (21 characters including)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:21:48.510",
"Id": "6072",
"Score": "0",
"body": "@Ed S: In fact in the above code it is 1 character shorter to prefix everything with std:: I also agree that pull things in selectively is also OK (as long as you scope the inclusion). So `using std::cin` but I rarely bother."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:22:04.393",
"Id": "6073",
"Score": "0",
"body": "I don't buy it. We're not retarded monkeys; we can determine when it is and is not ok to include an entire namespace."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:23:04.157",
"Id": "6075",
"Score": "0",
"body": "Uh huh, yet a lot more annoying at the same time. I can type `using namespace std;` a lot faster than all of those individual lines. This is just dogmatic and makes little sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:27:27.003",
"Id": "6076",
"Score": "0",
"body": "@Ed S: Sure I believe you are not a retarded monkey. Bu I am also sure you are not as precise as the compiler is. Polluting the global namespace is one of the first no-nos you will see on any coding standards. Obying this rule will save you much more than it costs you. Of course all rules have exceptions. But exceptions are for the skilled that know when to use them. Good advice for beginners is to stick with fully qualified objects until they learn how to do it correctly and the dangers of polluting the namespace."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T00:31:42.660",
"Id": "6078",
"Score": "0",
"body": "True, I definitely agree that people should know *when* it is acceptable before doing it, which in turn means that they understand (preferably from first hand experience) why it is a bad idea in general."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T06:42:51.973",
"Id": "4054",
"ParentId": "4043",
"Score": "4"
}
},
{
"body": "<p>The question at the beginning is misleading.\nn is an upper bound for the primes to be printed, not the number of primes.\nYou should change it to</p>\n\n<pre><code>cout << \"Enter an upper bound for the prime numbers to print: \"; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T08:01:43.557",
"Id": "4055",
"ParentId": "4043",
"Score": "3"
}
},
{
"body": "<p>Here is my Java code to create primes, which should be easily modified to match c++ needs:</p>\n\n<pre><code>public static boolean [] createPrimes (final int MAX)\n{\n boolean [] primes = new boolean [MAX];\n // make only odd numbers are candidates...\n for (int i = 3; i < MAX; i+=2)\n {\n primes[i] = true;\n }\n // ... except the 2\n primes[2] = true;\n\n // ... iterate in steps of 2\n for (int i = 3; i < MAX; i+=2)\n {\n /*\n If a number z is already eliminated, (like 9), \n because it is a multiple, (of 3), then all\n multiples of that number are already \n eliminated too.\n */\n if (primes[i])\n {\n int j = 2 * i;\n while (j < MAX)\n {\n if (primes[j])\n primes[j] = false;\n // in this inner loop *)\n j+=i;\n }\n }\n }\n return primes;\n}\n</code></pre>\n\n<p>In the inner loop, you even may jump in steps of i, because after eliminating multiples of 3*x (3*5, 3*7, 3*11, ...) you don't need to eliminate multiples like 5*3, the 3-times-something are already gone. The same if you reach 7: 7*3 is already gone as 3*7, and 7*5 as 5*7. Only multiples higher than 7 should be visited/tested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T13:00:45.400",
"Id": "4058",
"ParentId": "4043",
"Score": "0"
}
},
{
"body": "<p>In addition to everything already mentioned, you're not checking whether the user inputs a valid integer. As suggested by <a href=\"http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.3\" rel=\"nofollow\" title=\"the C++ FAQ\">the C++ FAQ</a>:</p>\n\n<pre><code>int max_prime;\nwhile ((std::cout << \"Enter an upper bound for the prime numbers to print: \")\n && !(std::cin >> max_prime)) {\n std::cout << \"That is not a valid number. \";\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T16:50:46.630",
"Id": "4089",
"ParentId": "4043",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4046",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-11T23:22:09.000",
"Id": "4043",
"Score": "3",
"Tags": [
"c++",
"primes"
],
"Title": "Prime number finder"
}
|
4043
|
<p>I'm an amateur programmer (self-taught). Anyway, this class provides a few methods to access Google's unofficial weather API. I'm having trouble on how to go about handling parsing errors in <code>parse_xml()</code> so any suggestions there would also be helpful.</p>
<pre><code><?php
class weather {
private $_location;
private $_url = 'http://www.google.com/ig/api?weather=';
private $_isParsed = false;
private $_wData;
public $lastError;
public function __construct( $location) {
// Set location
$this->_location = $location;
// urlencode doesn't seem to work so manually add the + for whitespace
$this->_url = preg_replace('/\s{1}/', '+',$this->_url .= $location);
$this->parse_xml($this->get_xml());
}
public function get_temp($type = "f") {
if (!$this->_isParsed)
return false;
// User specificed celsius, return celsius
if ($type == "c")
return $this->_wData['current']['temp_c'];
// return fahrenheit
return $this->_wData['current']['temp_f'];
}
public function get_condition() {
if (!$this->_isParsed)
return false;
// provide current conditions only
return $this->_wData['current']['condition'];
}
public function get_forecast_for_day($day) {
if (!$this->_isParsed)
return false;
return $this->_wData['forecast'][$day];
}
public function get_forecast_assoc() {
if (!$this->_isParsed)
return false;
return $this->_wData['forecast'];
}
public function get_cond_assoc() {
if (!$this->_isParsed)
return false;
return $this->_wData['current'];
}
public function dump_wData() {
if (!$this->_isParsed)
return false;
return $this->_wData;
}
public static function to_celsius($f) {
// Convert Fahrenheit to Celsius.
// I figured this would be quicker than trying to parse the XML.
return floor(((int)$f - 32) * (5 / 9));
}
private function get_xml() {
// Download raw XML to be parsed.
$ch = curl_init($this->_url);
// I don't know why I altered the useragent. It must have been for a good reason. Oh well.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rawXML = curl_exec($ch);
if (!$rawXML)
return false;
curl_close($ch);
return $rawXML;
}
private function parse_xml($xData) {
libxml_use_internal_errors(true);
try {
$weather = new SimpleXMLElement($xData);
} catch (Exception $err) {
// Set $lastError to getMessage()
$this->lastError = $err->getMessage();
return false;
}
// Select the current_conditions node ($cNode)
$cNode = $weather->weather[0]->current_conditions;
// ========= Set up our current conditions array ====================
// Tempreature - temp_f Fahrenheit, temp_c celsius - set as floats.
$this->_wData['current']['temp_f'] = (float)$cNode->temp_f->attributes()->data;
$this->_wData['current']['temp_c'] = weather::to_celsius($this->_wData['current']['temp_f']);
// Condition
$this->_wData['current']['condition'] = (string)$cNode->condition->attributes()->data;
// Condition Icon - icon url is not absolute, append google.com
$this->_wData['current']['icon'] = (string)"http://www.google.com" . $cNode->icon->attributes()->data;
// Wind Condition
$this->_wData['current']['wind'] = (string)$cNode->wind_condition->attributes()->data;
// ============= Set up our forecast array =============
$fNode = $weather->weather[0]->forecast_conditions;
// Iterate through each day of the week and create an assoc array.
foreach ($fNode as $forecast) {
// Get the day.
$day = (string)$forecast->day_of_week->attributes()->data;
// Insert an array of info for that day
$this->_wData['forecast'][$day] = array (
"high" => (float)$forecast->high->attributes()->data,
"low" => (float)$forecast->low->attributes()->data,
"icon" => (string)"http://www.google.com" . $forecast->icon->attributes()->data,
"condition" => (string)$forecast->condition->attributes()->data
);
} //foreach ($fNode as $forecast)
// Let the class know wData is ready for use.
$this->_isParsed = true;
} //private function parse_xml($xData)
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T17:00:39.890",
"Id": "6084",
"Score": "1",
"body": "amateur doesn't mean self-taught, it just means unpaid. There's plenty of us who went from amateur to professional self-taught :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T17:53:17.477",
"Id": "104263",
"Score": "0",
"body": "Google's Weather API is gone, but [Open Weather Map](http://openweathermap.org/API) looks like a good replacement."
}
] |
[
{
"body": "<p>I'm a C# developer myself but I like this altogether, very clean and easy to read and understand even though it's not a language I've worked in.</p>\n\n<p>The layout of the class is clean with the members and methods nicely ordered and clear to their purpose.</p>\n\n<p>The only suggestions I have are:\nseperate it into 2 classes, the one that has the gets, and the one that does the parsing. Make the <code>GoogleWeatherResponseParser</code> a member of your <code>GoogleWeatherDataAccess</code> and you can either construct the parser at construction, or a more testable approach is that it's handed to the constructor.</p>\n\n<p>If it's handed to the constructor, the consumer of the data access would construct the parser and be able to check if it was parsed successfully or not before handing it to the data access. Then the data access would only have to check at construction and throw an exception, never checking in the individual methods making them cleaner.</p>\n\n<p>Also, you could then write unit tests that hand in various versions of the <code>GoogleWeatherResponseParser</code> to the <code>GoogleWeatherDataAccess</code> at construction and verify that the data the data access hands out is as you expected. Not sure how common unit tests are in PHP, but they are immensely helpful in allowing you to change code knowing that you'll be notified if you broke something.</p>\n\n<p>Edit: Oh and you're dead right about doing the celsius calculation as opposed to the xml parse step.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T02:39:12.160",
"Id": "6206",
"Score": "0",
"body": "I disagree about splitting it into two objects, as it's already two objects. The actual parsing is done by the `SimpleXML` object, all the class has to be is a wrapper around that, allowing easy access to the data (easier than knowing where in the XML tree to find the data). I believe the real change should be navigating the tree when needed, and not all at once (in the `parse_xml` method). If the code did that, I think it would look like your two object suggestion, since the `SimpleXML` object would replace your suggested `GoogleWeatherResponseParser`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T11:10:05.047",
"Id": "6210",
"Score": "1",
"body": "@Tim I am unfamiliar with the php frameworks SimpleXML object, but my logic was based on the single responsibility principle and seperation of concerns, right now the one class is concerned with the http request, the response parsing, and the data serving to clients. My suggestion was there be one object for managing the request/parsing (which could use lazy loads for delayed execution) and one for data serving to clients, or in more standard terms a data provider and a data access, in which they do not need to know eachothers implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T00:11:08.903",
"Id": "6235",
"Score": "0",
"body": "@ Jimmy Hoffa - wasn't meaning to disagree with the principle, just that using SimpleXML already separates the two (and in this case, I find it enough)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T17:17:16.190",
"Id": "4071",
"ParentId": "4063",
"Score": "2"
}
},
{
"body": "<p><strong>Use methods to get the data</strong>, this is a kind of dependency injection and will allow you to test the code with out having to hit google's server everytime. It will also avoid the <code>if($this->_isParsed)</code> on all your functions.</p>\n\n<p>Additionally, move the 'parsing' - which is really just navigating the XML structure - to the functions that return the data. This removes your <code>parse_xml</code> function (which would now be just a function that creates the <code>SimpleXML</code> object), and allows you to throw exceptions only when requested data is missing/unexpected (or return just return false, if that's how you want your client to act).</p>\n\n<p>Here's some example code. </p>\n\n<p><em>I tend to use camelCase, I'm not trying to change your style, it's just second nature.</em></p>\n\n<pre><code><?php\nclass GoogleWeather{\n protected $api = 'http://www.google.com/ig/api?weather=';\n protected $xml;\n protected $response;\n protected $location;\n\n public function __construct( $location) {\n // Set location\n $this->location = $location;\n }\n\n public function setResponse($response)\n {\n $this->response = $response;\n }\n\n public function getResponse()\n {\n //if the xml hasn't been fetched, then fetch it\n if(empty($this->response)){\n $this->setResponse($this->fetchData());\n }\n return $this->response;\n }\n\n //was get_xml renamed to avoid confusion\n public function fetchData()\n {\n // Download raw XML to be parsed.\n $ch = curl_init($this->api . urlencode($this->location));\n\n // I don't know why I altered the useragent. It must have been for a good reason. Oh well.\n curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1');\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n $rawXML = curl_exec($ch); \n\n if (!$rawXML){\n //check the curl error for a better message\n throw new Exception('could not fetch data'); \n }\n curl_close($ch);\n return $rawXML;\n }\n\n public function getXml()\n {\n if(empty($this->xml)){\n try{\n $this->xml = new SimpleXMLElement($this->getResponse());\n } catch (Exception $e) {\n //there's no real recovery here, except maybe to retry fetching the data\n throw new Exception('bad response from from API');\n }\n\n //check for 'problem_cause' element\n if(isset($this->xml->weather->problem_cause)){\n throw new Exception('API responded with error');\n }\n }\n return $this->xml;\n }\n\n public function getCondition()\n {\n //make sure there's data\n if(!isset($this->getXml()->weather->current_conditions)){\n //you could throw an exception and assume any code using this is \n //calling it in a try block\n throw new Exception('could not find conditions');\n }\n\n return $this->getXml()->weather->current_conditions;\n }\n\n public function getTemp($type = 'f')\n {\n //validate type\n if(!in_array($type, array('f','c'))){\n throw Exception('invalid temp type: ' . $type);\n }\n\n $element = 'temp_' . $type;\n //make sure there's data\n if(!isset($this->getCondition()->{$element}['data'])){\n throw new Exception('could not find temp');\n }\n\n //cast as float and return\n return (float) $this->getCondition()->{$element}['data'];\n }\n}\n</code></pre>\n\n<p>You can avoid navigating the <code>SimpleXML</code> object multiple times for the same data using the same basic concept the other lazy loading functions use (<code>getXML()</code>, <code>getResponse()</code>). </p>\n\n<p>Instead of using object properties, I just put a static variable in the method - since the location can not change, there's no never a need to unset all the data. </p>\n\n<p>However, if the location could change, the same could be accomplished with <code>$this->data[$property]</code> - obviously resetting <code>$this->data</code> to <code>array()</code> every time the location is changed.</p>\n\n<p>Here's an improved <code>getTemp()</code>:</p>\n\n<pre><code> public function getTemp($type = 'f')\n {\n static $temp = array();\n\n //validate type\n if(!in_array($type, array('f','c'))){\n throw Exception('invalid temp type: ' . $type);\n }\n\n if(isset($temp[$type])){\n return $temp[$type];\n }\n\n $element = 'temp_' . $type;\n //make sure there's data\n if(!isset($this->getCondition()->{$element}['data'])){\n throw new Exception('could not find temp');\n }\n\n //cast as float and return\n $temp[$type] = $this->getCondition()->{$element}['data'];\n return $temp[$type];\n }\n</code></pre>\n\n<p>I'd be interested in seeing if there's any significant performance gained over navigating the <code>SimpleXML</code> object each time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T11:16:14.057",
"Id": "6211",
"Score": "0",
"body": "I don't know the overhead involved in querying into the SimpleXML object, I'm assuming it's not much, but just for safety I would lazy load in your getCondition and getTemp, have member level temp and condition, and first thing method does is check `if(isset($this->condition)) { return $this->condition; }` then set `$this->condition` at the end of getCondition() after parsing it out, otherwise this makes perfect sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T17:06:48.263",
"Id": "6219",
"Score": "0",
"body": "@Jimmy Hoffa Yeah, that could certainly be added. I'll try to update with that in a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T00:19:44.117",
"Id": "6236",
"Score": "0",
"body": "@Jimmy Hoffa updated with your suggestion (well, a variation of it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T17:41:15.467",
"Id": "104260",
"Score": "0",
"body": "\"Instead of using object properties, I just put a static variable in the method.\" **Warning:** Static local variables are shared across all instances of the class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T02:35:47.780",
"Id": "4161",
"ParentId": "4063",
"Score": "3"
}
},
{
"body": "<p>If I could make a few suggestions, both for readability and to avoid problems in the future.</p>\n\n<ol>\n<li>Indent from the class name.</li>\n</ol>\n\n<p>Instead of </p>\n\n<pre><code><?php\n class weather {\n private $_location;\n private $_url = 'http://www.google.com/ig/api?weather=';\n private $_isParsed = false;\n private $_wData;\n</code></pre>\n\n<p>write</p>\n\n<pre><code><?php\n class weather {\n private $_location;\n private $_url = 'http://www.google.com/ig/api?weather=';\n private $_isParsed = false;\n private $_wData;\n</code></pre>\n\n<p>2 Always use parenthesis with an if statement</p>\n\n<p>instead of </p>\n\n<pre><code>public function get_cond_assoc() {\n if (!$this->_isParsed)\n return false;\n return $this->_wData['current'];\n}\n</code></pre>\n\n<p>use</p>\n\n<pre><code>public function get_cond_assoc() {\n if (!$this->_isParsed)\n {\n return false;\n }\n return $this->_wData['current'];\n}\n</code></pre>\n\n<p>This may seem unnecessary since your construction is perfectly legal, but the first time you spend 2 hours hunting down a bug caused by not putting in the braces you'll thank me :)</p>\n\n<p>3 Dont typecast unnecessarily</p>\n\n<p>The (string) here is unnecessary and confusing.</p>\n\n<pre><code> // Condition Icon - icon url is not absolute, append google.com\n $this->_wData['current']['icon'] = (string)\"http://www.google.com\" .\n $cNode->icon->attributes()->data;\n</code></pre>\n\n<p>These are just a few pointers to make your code a bit more readable and less likely to cause you headaches in the future.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T20:44:40.053",
"Id": "4461",
"ParentId": "4063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4161",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T01:06:13.670",
"Id": "4063",
"Score": "7",
"Tags": [
"php",
"parsing",
"xml",
"api"
],
"Title": "Google Weather API wrapper"
}
|
4063
|
<p>Essentially I'm taking a number of checkboxes off of my view, adding them to a <code>Dictionary<string, bool></code>, and writing out the <code>Keys</code> of any checkbox that is checked.</p>
<p>I'm guessing there must be a better way of doing this.</p>
<pre><code>// We need to build a list of what the user would like more information on.
// First step is to add all of the Checkboxes to a `Dictionary<string, bool>`
Dictionary<string,bool> moreInfo = new Dictionary<string,bool>();
moreInfo.Add("Children's Programs", ccm.moreInfoChildren);
moreInfo.Add("Youth Programs",ccm.moreInfoYouth);
moreInfo.Add("Small Groups", ccm.moreInfoSmallGroups);
moreInfo.Add("Getting involved in Ministry",ccm.moreInfoMinistry);
moreInfo.Add("Receiving offering envelopes",ccm.moreInfoOfferingEnvelopes);
moreInfo.Add("Church Membership",ccm.moreInfoMembership);
moreInfo.Add("Baptism",ccm.moreInfoBaptism);
moreInfo.Add("Other (see notes)", ccm.moreInfoOther);
// Second step is to loop through the moreInfo `Dictionary<string, bool>` and build a string of results.
StringBuilder _moreInfo = new StringBuilder();
foreach (var info in moreInfo) {
_moreInfo.Append(info.Value ? info.Key + ", " : "");
}
// Third step is to determin if the user wants any information. If they do, we add that information to the email.
if(!string.IsNullOrEmpty(_moreInfo.ToString()))
{
builder.Append("I would like more information about ");
builder.Append(_moreInfo.ToString());
}
</code></pre>
<p>Here is the complete <code>Action</code>:</p>
<pre><code>[HttpGet]
[AllowCrossSiteJsonAttribute]
public JsonpResult CommunicateCard(CommunicateCardModel ccm)
{
if (ModelState.IsValid)
{
StringBuilder builder = new StringBuilder();
// ccm.name is a required field, so we don't have to check if it's empty.
builder.Append("Name: " + ccm.name + "\n");
// If these properties are empty, we don't want to include them in the built string.
builder.Append((!string.IsNullOrEmpty(ccm.address)) ? "Address: " + ccm.address + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.city)) ? "City: " + ccm.city + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.postalCode)) ? "Postal Code: " + ccm.postalCode + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.phone)) ? "Phone Number: " + ccm.phone + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.emailFrom)) ? "Email Address: " + ccm.emailFrom + "\n" : null);
builder.Append("\n");
builder.Append((!string.IsNullOrEmpty(ccm.information)) ? "Please " + ccm.information + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.christianity)) ? "I " + ccm.christianity + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.maritalStatus)) ? "I am " + ccm.maritalStatus + "\n" : null);
builder.Append("\n");
// pull together all of the checkboxes within the "Ministries" fieldset and generate a single string.
var pairs = new[]
{
// Tuple.Create(string, bool)
Tuple.Create("Children's Programs", ccm.moreInfoChildren),
Tuple.Create("Youth Programs", ccm.moreInfoYouth),
Tuple.Create("Small Groups", ccm.moreInfoSmallGroups),
Tuple.Create("Getting involved in Ministry", ccm.moreInfoMinistry),
Tuple.Create("Receiving offering envelopes", ccm.moreInfoOfferingEnvelopes),
Tuple.Create("Church Membership", ccm.moreInfoMembership),
Tuple.Create("Baptism", ccm.moreInfoBaptism),
Tuple.Create("Other (see notes)", ccm.moreInfoOther),
};
var moreInfo = String.Join(", ", pairs.Where(pair => pair.Item2).Select(pair => pair.Item1));
if (!String.IsNullOrEmpty(moreInfo))
{
builder.Append("I would like more information about ")
.Append(moreInfo);
}
builder.Append("\n");
builder.Append((!string.IsNullOrEmpty(ccm.guestReason)) ? "I am visiting today because " + ccm.guestReason + "\n" : null);
builder.Append((!string.IsNullOrEmpty(ccm.attendance)) ? "I am attending for my " + ccm.attendance + "\n" : null);
builder.Append("\n");
builder.Append((!string.IsNullOrEmpty(ccm.comments)) ? ccm.comments : null);
// initiate the email service and fire off an email
EmailService email = new EmailService();
email.to = ccm.emailTo;
email.from = ccm.emailTo;
email.replyTo = ccm.emailFrom;
email.subject = ccm.messageSubject;
email.messageBody = builder.ToString();
bool sent = email.send();
object result = null;
// Send a system error message via JSON back to the app if the email fails.
if (!sent)
{
result = new ErrorsModel { ErrorMessage = Server.GetLastError().Message };
}
// whether or not the email sent, we need to tell the app the result.
return this.Jsonp(result, sent);
}
// The ModelState is invalid, Loop through the ModelState and send a JSON string listing all the errors.
else
{
List<ErrorsModel> Errors = new List<ErrorsModel>();
foreach(ModelState modelState in ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
Errors.Add(new ErrorsModel { ErrorMessage = error.ErrorMessage });
};
};
return this.Jsonp(Errors, false);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Without knowing if you need the dictionary for later use, you can absolutely make the 2nd step better (and remove the trailing \", \" that would get added) by using String.Join with a lambda (don't forget to add the System.Linq using if it is not there):</p>\n\n<pre><code>// Second step is to loop through the moreInfo `Dictionary<string, bool>` and build a string of results.\nstring _moreInfo = String.Join(\", \", moreInfo.Where(m => m.Value).Select(m => m.Key).ToArray());\n</code></pre>\n\n<p>Then you can also drop the .ToString() on the IsNullOrEmpty check of _moreInfo and the append of _moreInfo in step 3.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T03:58:42.817",
"Id": "4065",
"ParentId": "4064",
"Score": "2"
}
},
{
"body": "<p>Your method has a lot of repetition to build your string often resulting in unnecessary calls to <code>Append()</code>. You should have used an <code>if</code> block for each of those writes instead of appending <code>null</code>. This also hides all the calls to <code>IsNullOrEmpty()</code> which is a detail you don't really want repeated so much. I'd break this into a couple of methods, one for each of the valid/invalid cases and one to help with writing the strings. Written this way, you have the option to use the same trick to quickly build the comma-separated list to write your content easier to do. I think you'll agree that it's a lot more easier to read.</p>\n\n<pre><code>[HttpGet]\n[AllowCrossSiteJsonAttribute]\npublic JsonpResult CommunicateCard(CommunicateCardModel ccm)\n{\n return ModelState.IsValid\n ? CommunicateValidCard(ccm)\n : CommunicateInvalidCard(ccm);\n}\n\nStringBuilder AppendNonWhiteField(StringBuilder builder, string format, string field)\n{\n if (!String.IsNullOrWhiteSpace(field))\n {\n builder.AppendFormat(format, field);\n }\n return builder;\n}\n\nJsonpResult CommunicateValidCard(CommunicateCardModel ccm)\n{\n StringBuilder builder = new StringBuilder();\n\n // ccm.name is a required field, so we don't have to check if it's empty.\n builder.Append(\"Name: \" + ccm.name + \"\\n\");\n\n // If these properties are empty, we don't want to include them in the built string.\n AppendNonWhiteField(builder, \"Address: {0}\\n\", ccm.address);\n AppendNonWhiteField(builder, \"City: {0}\\n\", ccm.city);\n AppendNonWhiteField(builder, \"Postal Code: {0}\\n\", ccm.postalCode);\n AppendNonWhiteField(builder, \"Phone Number: {0}\\n\", ccm.phone);\n AppendNonWhiteField(builder, \"Email Address: {0}\\n\", ccm.emailFrom);\n builder.AppendLine();\n\n AppendNonWhiteField(builder, \"Please {0}\\n\", ccm.information);\n AppendNonWhiteField(builder, \"I {0}\\n\", ccm.christianity);\n AppendNonWhiteField(builder, \"I am {0}\\n\", ccm.maritalStatus);\n builder.AppendLine();\n\n // pull together all of the checkboxes within the \"Ministries\" fieldset and generate a single string.\n var pairs = new[]\n {\n // Tuple.Create(string, bool)\n Tuple.Create(\"Children's Programs\", ccm.moreInfoChildren),\n Tuple.Create(\"Youth Programs\", ccm.moreInfoYouth),\n Tuple.Create(\"Small Groups\", ccm.moreInfoSmallGroups),\n Tuple.Create(\"Getting involved in Ministry\", ccm.moreInfoMinistry),\n Tuple.Create(\"Receiving offering envelopes\", ccm.moreInfoOfferingEnvelopes),\n Tuple.Create(\"Church Membership\", ccm.moreInfoMembership),\n Tuple.Create(\"Baptism\", ccm.moreInfoBaptism),\n Tuple.Create(\"Other (see notes)\", ccm.moreInfoOther),\n };\n var moreInfo = String.Join(\", \", pairs.Where(pair => pair.Item2).Select(pair => pair.Item1));\n AppendNonWhiteField(builder, \"I would like more information about {0}\\n\", moreInfo);\n\n AppendNonWhiteField(builder, \"I am visiting today because {0}\\n\", ccm.guestReason);\n AppendNonWhiteField(builder, \"I am attending for my {0}\\n\", ccm.attendance);\n builder.AppendLine();\n\n AppendNonWhiteField(builder, \"{0}\", ccm.comments);\n\n // initiate the email service and fire off an email\n EmailService email = new EmailService();\n email.to = ccm.emailTo;\n email.from = ccm.emailTo;\n email.replyTo = ccm.emailFrom;\n email.subject = ccm.messageSubject;\n email.messageBody = builder.ToString();\n\n bool sent = email.send();\n object result = null;\n\n // Send a system error message via JSON back to the app if the email fails.\n if (!sent)\n {\n result = new ErrorsModel { ErrorMessage = Server.GetLastError().Message };\n }\n\n // whether or not the email sent, we need to tell the app the result.\n return this.Jsonp(result, sent);\n}\n\nJsonpResult CommunicateInvalidCard(CommunicateCardModel ccm)\n{\n // The ModelState is invalid, Loop through the ModelState and send a JSON string listing all the errors.\n var errors = ModelState.Values\n .SelectMany(modelState =>\n modelState.Errors\n .Select(error => new ErrorsModel { ErrorMessage = error.ErrorMessage }))\n .ToList();\n return this.Jsonp(errors, false);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T16:34:27.953",
"Id": "6083",
"Score": "1",
"body": "There's no value in using a string builder for a single concatenation like this, use String.Concat or just the + (which overloads to String.Concat, so it's just a style difference). StringBuilder is for when you're going to append in a loop an unknown but plausibly significant number of strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T19:55:35.293",
"Id": "6088",
"Score": "1",
"body": "@Jimmy: Of course, but it was clear to me that this snippet of code wasn't fully complete. This could have (and was) a small part of a larger method where using the builder was relevant. Within this snippet alone, the builder definitely wouldn't have been necessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T04:10:43.907",
"Id": "4066",
"ParentId": "4064",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4066",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T03:15:18.073",
"Id": "4064",
"Score": "9",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-3"
],
"Title": "Conditional string building"
}
|
4064
|
<p>I'm looking for ways to improve this code (more readable, less redundant and maybe cleaner/faster).</p>
<p><em>The problem I needed to solve:</em></p>
<p>I was designated to implement a software that is going to validate an 96 column Excel file and if there is no error on it, create an XML file from it. In case there are any error in the excel file I have to display them to the user and indicate where the problem occurred.</p>
<p><em>How I attempted to solve the problem:</em></p>
<p>Since I knew the numbers of columns, I thought about making a class that represents an cell on the Excel file and include a string property to hold an possibly error description, by making that it'd make it easy to display the error log. So I actually created 2 collections of my class that is called <code>Cell</code>. One collection to hold all of Excel's cell values, and the other is the error log one.</p>
<p>Here is the <code>Cell</code> class code:</p>
<pre><code>public class Cell
{
public string Value { get; set; }
public int Row { get; set; }
public int Column { get; set; }
public string ErrorDescription { get; set; }
}
</code></pre>
<p>This is the <code>Cell</code>s collection:</p>
<pre><code>Range worksheetCells = sheet.get_Range(firstCell, lastCell);
private List<Cell> Cells = new List<Cell>();
foreach (Range item in worksheetCells)
{
Cells.Add(new Cell{ Value = item.Text, Row = item.Row, Column = item.Column});
}
</code></pre>
<p>For readability purposes, I create another 96 collections of <code>Cell</code>, one for each column:</p>
<pre><code>var Name = Cells.Where(c => c.Column == 1);
....
</code></pre>
<p>I've created 96 methods of validation one per column/collection:</p>
<pre><code>private void NameValidation(IEnumerable<Cell> excelColumn, List<Cell> log)
{
foreach (Cell item in excelColumn)
{
if (string.IsNullOrEmpty(item.Value))
{
item.ErrorDescription = "You need to fill up this Cell.";
}
else
{
if (item.Value.Length > 27)
{
item.ErrorDescription = "The MAX length of this field is 27 characters.";
}
}
if (!string.IsNullOrEmpty(item.ErrorDescription))
{
log.Add(item);
}
}
}
</code></pre>
<p>Basically that is what I have now. I haven't touch the XML file creation yet, but the reason why I've designed my code like this is that I can use the validation method to create the XML, instead of having to do another 96 <code>foreach</code> statements. I'd only create the XML file when after calling all the validation methods if the <code>log.count</code> return 0, so it is ok to generate the file.</p>
<p><em>What troubles my mind:</em></p>
<p>Do I really need to do 96 things all the time?</p>
<p>in 60% of the the validation methods I have to check for <code>string.IsNullOrEmpty(item.Value)</code> and copy and paste kills me, It makes me feel like I'm doing something wrong, you know?</p>
<p>In a few of those methods, the <code>item.value</code> is only mandatory if another cell is filled up. If it is, then the current cell is mandatory. That's why I didn't make a single method to validate when the field is mandatory, because it depends on other things. In 30% of the validation methods, I have to check for <code>item.Value.Length > "something"</code>.</p>
<p>Do you have any ideas on how to take some of those <code>if</code>/<code>else</code> out?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T20:38:55.170",
"Id": "6090",
"Score": "2",
"body": "Your presented code is fine, the parts that you say are a problem are in code you didn't present, I'm having a hard time understanding what extra code you made that you don't like as it is not displayed.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T21:17:02.790",
"Id": "6093",
"Score": "0",
"body": "See that var Name = Cells.Where(c => c.Column == 1) ? there are other 95 collections like this one, I'm not sure whether separating my code using these collection is good design or not, also there's other 95 methods like NameValidation, one for each column in the file, and sometimes they share common validations sometimes not. I don't know how to reduce the redundancy. Is it clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T22:17:13.927",
"Id": "6098",
"Score": "2",
"body": "I see, this is the perfect type of thing to raise on codereview. Though if you want to show where you're being repetitive in the future, show at least 2 of whatever is repeating so it's clear what repetitions you want abstracted out. :)"
}
] |
[
{
"body": "<p>If you find yourself repeating methods that often, then yes, you need to find a pattern that simplifies your work. That said, I think there would be a better solution than loading up collections of cells in columns. </p>\n\n<p>Take a look at this sample: <a href=\"http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/09654227-99a8-47d0-9d6c-c2ab0d293aba\">validate excel sheet</a></p>\n\n<p>Granted, the sample code at the other end of the link is validating an excel sheet prior to inserting into an Sql data store. But the gist is the same. </p>\n\n<p>I would query and hold in a <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx\">DataTable</a>. Properties can be set on each column that allow much easier validation of the data. In addition, you do not have to write code to manage the collections.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T21:21:13.167",
"Id": "6094",
"Score": "0",
"body": "I'll try that and see how that goes, thanks already."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T20:10:53.290",
"Id": "4074",
"ParentId": "4073",
"Score": "5"
}
},
{
"body": "<p>Consider using custom attributes.<br>\nHere is a possible variant:<br>\nCreate a class representing the data from the excel file and decorate it with attributes.</p>\n\n<pre><code> public class ExcelData\n {\n [ExcelColumn(\"Name\")]\n [Required]\n [MaxLength(27)]\n public string Name { get; set; }\n\n [ExcelColumn(\"NextColumn\")]\n [Required]\n public string NextColumn { get; set; }\n //...another 94 property.\n } \n</code></pre>\n\n<p>Then create a class that gets excel and returns a list of this data using ExcelColumn attribute.</p>\n\n<pre><code> public class ExcelParser\n {\n public IEnumerable<ExcelData> Parse(string fileName)\n {\n //Get file and return ExcelData, using ExcelColumn attribute.\n }\n }\n</code></pre>\n\n<p>Then create a class to convert this data to XML.</p>\n\n<pre><code>public class ExcelDataToXmlConverter\n {\n private ExcelDataValidator _validator = new ExcelDataValidator();\n\n public XDocument Convert(IEnumerable<ExcelData> excelData)\n {\n foreach (var data in excelData)\n {\n var errors = new Dictionary<string, List<string>>();\n if (_validator.IsValid(data, out errors))\n {\n //Convert the row to XML\n }\n else\n {\n //Do something with errors.\n }\n }\n } \n }\n\n public class ExcelDataValidator\n {\n //errors - is a list of errors where the key is the name of the field and value is the list of errors.\n public bool IsValid(ExcelData excelData, out Dictionary<string, List<string>> errors)\n {\n //Validate using different attributes: Required, MaxLength and so on.\n }\n }\n</code></pre>\n\n<p>Maybe you'll be able to use attributes for actual converting data to XML.<br>\nOf course it's only a very crude sketch, and only some parts of it may be useful for you, but I hope you've got the idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T21:36:03.887",
"Id": "6097",
"Score": "2",
"body": "Your hearts in the right place on coming up with validation patterns, but attributes cause reflection overhead that isn't necesary in this case"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T02:00:41.640",
"Id": "6103",
"Score": "0",
"body": "I like the custom attribute idea but how would I deal with property that depends on other property? like there are cases in which I need to verify if a certain column has value, if it has, than the current field I'm validating is required otherwise it is not. I also like the XML idea, I'll take a look at that too, thanks for answering."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T06:54:25.690",
"Id": "6107",
"Score": "0",
"body": "@Bsarkis: As for the dependent properties validation. For example you can do the folowing: Create an attribute CustomValidation and decorate with it a property that depends on another property.\nThen in the method ExcelDataValidator.IsValid just check this attribute. If it is on a property then use any custom code you like to validate it.\nAnd because of IsValid gets the whole row as a parameter, you can compare the value of this property to any other property in the row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T07:08:41.213",
"Id": "6108",
"Score": "0",
"body": "@Jimmy Hoffa: I know about the reflection overhead. But how much will it influence the perfomance in this particular case? Do you know? I've seen a couple of third-party libraries which use attributes to parse CSV files. I've implemented a couple myself. And I've never experienced performance problems with this approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T02:44:39.367",
"Id": "6724",
"Score": "1",
"body": "@Jimmy, totally disagree with the concern over performance. If reflection overhead is a problem, then obviously you should cache the results somewhere. It is *always* possible to make an attribute-based solution perform efficiently, though I agree the naive implementation that always uses `Attribute.GetAttribute` can be slow in certain situations. (In the *worst* case, an attribute-based solution should only be slow on the *very* first execution of the code -- types don't change and neither do their attributes, thus static caching will solve all the performance problems.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T13:47:13.950",
"Id": "6737",
"Score": "0",
"body": "@Kirk It's not invalid and caching could improve this, however manually going over each individual property could only be done in a loop if you were reflecting the properties each time, otherwise it would have to be hand written to have an early bound reference to each property which would make the code expansive. The alternative would be to emit IL based on the first reflection pass of the properties so the next pass wouldn't need to reflect the properties, but that is a bit much for a simple problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T14:40:24.620",
"Id": "6739",
"Score": "0",
"body": "@Jimmy, no idea why you would use IL. What we are talking about here is caching \"what needs to happen\" for each property. There are a ton of ways to model that behavior, and using Reflection.Emit would probably be the last idea I would try. All you need to do is grab the property infos (once!) and instantiate a class to model that property (once!). From then on, you grab that model from the cache dependent on the type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:04:16.160",
"Id": "6742",
"Score": "0",
"body": "@Kirk I guess I don't know how to dynamically \"instantiate a class to model\" something without emit. I would *not* do this with IL, was merely saying it's the only way I would know to do it. You must know something I don't. I am actually very curious to see something doing this without using the property info's as a key to the map, I can't think of a way to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:18:27.523",
"Id": "6743",
"Score": "0",
"body": "@Jimmy, the key to the `Dictionary` would be the `Type` object (since the properties of a type never change). However, I now see that the performance you are referring to is the cost of `PropertyInfo.GetValue` and not the cost of `Attribute.GetAttribute`. I agree that `PropertyInfo.GetValue` will be a bit slower than direct access. However, converting PropertyInfo access to early-bound access is fairly easy to do, but you are correct it requires a bit of IL. (but just once: create an extension method `Func<object, object> ToLambda(this PropertyInfo property) { ... }`)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T21:11:12.723",
"Id": "4075",
"ParentId": "4073",
"Score": "6"
}
},
{
"body": "<p>Edit: you may want the funcs to return a string rather than a bool as you have stated you want descriptive validation information, then instead of just iffing for boolean true, you would make the <code>if</code> in the <code>AllCellsAreValid</code>, you would <code>if(!string.IsNullOrEmpty(columnValidatorMap[cellToValidate.Column](cellToValidate)))</code></p>\n\n<p>Edit again: also, you're creating 96 lists you said I think? just create one list with every single cell regardless of column, and when you hand that list to the validator that checks all cells, it will just use the column member of Cell to find the correct validator in the dictionary.</p>\n\n<p>Try this, create a validator method for the various types of validation you will be doing and map them to the columns like so:</p>\n\n<pre><code> public static Func<Cell, bool> LengthValidator(int minLength, int maxLength)\n {\n return (Func<Cell, bool>)((cellParam) => { return (cellParam.Value.Length > minLength) && (cellParam.Value.Length < maxLength); });\n }\n\n public static Func<Cell, bool> NullnessValidator(bool shouldBeNull)\n {\n return (Func<Cell, bool>)((cellParam) => { return ((cellParam == null) == shouldBeNull); });\n }\n\n public static Func<Cell, bool> MultipleValidators(params Func<Cell, bool>[] validatorPredicates)\n {\n return (Func<Cell, bool>)((cellParam) =>\n {\n foreach(Func<Cell,bool> validator in validatorPredicates)\n {\n if(!validator(cellParam))\n {\n return false;\n }\n }\n return true;\n });\n }\n\n public static Dictionary<int, Func<Cell, bool>> columnValidatorMap = new Dictionary<int, Func<Cell, bool>>()\n {\n { 1, MultipleValidators(LengthValidator(1, 27), NullnessValidator(false)) },\n { 2, MultipleValidators(LengthValidator(1, 27), NullnessValidator(false)) }\n };\n\n public bool AllCellsAreValid(IEnumerable<Cell> cellsToValidate)\n {\n foreach(Cell cellToValidate in cellsToValidate)\n {\n if (!columnValidatorMap[cellToValidate.Column](cellToValidate))\n {\n return false; // or return some information if you want\n }\n }\n\n return true;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T21:54:04.817",
"Id": "4076",
"ParentId": "4073",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4074",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T19:37:29.810",
"Id": "4073",
"Score": "14",
"Tags": [
"c#",
"validation",
"excel"
],
"Title": "Validating Excel file columns"
}
|
4073
|
<p>Consider the following reproducible example: </p>
<pre><code># note that lh is a standard ts dataset that ships with R
lh
# fit an R model
ar.mle<-ar(lh,method="mle")
# now get the min AIC, this is the relevant line:
ar.mle$aic[ar.mle$aic==min(ar.mle$aic)]
</code></pre>
<p>This works fine and gives back the smallest AIC value and it's index, which is the suggested AR order. I feel I am repeating myself in this last line of code. Is there an easier way to obtain index and value?
I know I could use partial autocorrelations to determine the level, too. This is not a stats question, but an R indexing question. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T14:14:10.117",
"Id": "62788",
"Score": "0",
"body": "Try which([blahblah], arr.ind=TRUE)"
}
] |
[
{
"body": "<p>perhaps the function which.min() would do the trick?</p>\n\n<pre><code>which.min(ar.mle$aic)\n</code></pre>\n\n<p>it won't shorten your code all that much:</p>\n\n<pre><code>ar.mle$aic[which.min(ar.mle$aic)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T07:38:28.533",
"Id": "6110",
"Score": "0",
"body": "nice start tim :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T20:49:56.210",
"Id": "4084",
"ParentId": "4083",
"Score": "13"
}
},
{
"body": "<p>Well, it really doesn't return an index and value, what you get is a named value.</p>\n\n<pre><code>> ans <- ar.mle$aic[which.min(ar.mle$aic)]\n> names(ans)\n[1] \"3\"\n</code></pre>\n\n<p>The index itself is actually 4 (and is an integer); R indexes from 1.</p>\n\n<pre><code>> which.min(ar.mle$aic)\n3\n4\n> which.min(ar.mle$aic) == 4\n 3\nTRUE\n</code></pre>\n\n<p>(yes, this idea of tagging names to values is rather weird, coming from any other language)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T20:56:01.193",
"Id": "4085",
"ParentId": "4083",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4084",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T20:40:24.580",
"Id": "4083",
"Score": "5",
"Tags": [
"r"
],
"Title": "Is there a better way to get the index of a minimum?"
}
|
4083
|
<p>How could I improve this code?</p>
<pre><code>var to = "http://forum.";
if (!RedirectPermanent("http://www.", to))
if (!RedirectPermanent("http://blog.", to))
if (!RedirectPermanent("http://forum.", to))
if (!RedirectPermanent("http://tracker.", to))
if (!RedirectPermanent("http://wiki.", to))
RedirectPermanent("http://", to);
</code></pre>
<p>This is the method:</p>
<pre><code>private bool RedirectPermanent(string from,string to)
{
if (Request.Url.AbsoluteUri.StartsWith(from))
{
var domain = Request.Url.GetLeftPart(UriPartial.Authority).Replace(from, to);
Response.RedirectPermanent(string.Concat(domain, Request.RawUrl));
return true;
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>Went for this:</p>\n\n<pre><code>var arr = new[] { \"http://www.\", \"http://blog.\", \"http://forum.\", \"http://tracker.\", \"http://wiki.\", \"http://\" };\nvar to = \"http://forum.\";\n\nforeach (var from in arr)\n{\n if (RedirectPermanent(from, to))\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T23:20:21.813",
"Id": "6112",
"Score": "4",
"body": "Slight criticism, use better variable names. Expand it to `redirectSources`, `redirectTo` and `redirectFrom`. And in general, don't use contextual keywords as variable names such as `from`, even though safe, you should treat it like any other keywords and avoid it all together."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T16:32:52.990",
"Id": "4088",
"ParentId": "4087",
"Score": "5"
}
},
{
"body": "<p>As a variation:</p>\n\n<pre><code>var arr = new[] { \"http://www.\", \"http://blog.\", \"http://forum.\", \"http://tracker.\", \"http://wiki.\", \"http://\" }; \nvar to = \"http://forum.\";\n\nint i = 0;\n\nwhile ((!RedirectPermanent(from[i], to)) && i < arr.Length)\n{\n ++i; // reversed from i++\n if (i > arr.length) { break; }\n}\n</code></pre>\n\n<p>There are several reasons I prefer this over a <code>foreach</code>:</p>\n\n<ul>\n<li><p><code>foreach</code> has a performance cost to execute. An internal state machine iterator has to be instantiated. The <code>while</code> with a count limiter essentially does the same thing. While this is a performance tweak, IMO, it's still a better practice.</p></li>\n<li><p>code is not restricted/limited by the locked state of the iterated collection or the state machine iterator.</p></li>\n<li><p>IMO, using <code>foreach</code> with a body of <code>if-then-break</code> smells and reads like slang rather than proper grammar. ;)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T22:24:07.350",
"Id": "434163",
"Score": "0",
"body": "This may have been different 8 years ago, but nowadays a `foreach` loop over an _array_ produces IL bytecode that is quite similar to that for a `for` or `while` loop - in this case a `foreach` loop is even slightly faster. More importantly, it's less error-prone: your loop fails with an `IndexOutOfRangeException` if none of the redirects is successful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:55:36.500",
"Id": "434221",
"Score": "0",
"body": "A `foreach` loop does use an enumerator for other collection types, and that might be a bit slower. On the other hand, it works with any type that has an appropriate `GetEnumerator` method, it's easy to get right, and the intent is clear. The restrictions you mention are not inherent to `foreach`, they're an intentional safety mechanism in the enumerators of most BCL collection types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:47:19.877",
"Id": "434621",
"Score": "1",
"body": "Fair enough; I was only somewhat aware that optimizations had occurred in compiling `foreach` (and other loop/enumerator ops). As far as restrictions go, regardless of the purpose - safety, whatever - they are still restrictions and I agree with the need for safeguards. Added check for 'out of range'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:28:20.590",
"Id": "434666",
"Score": "0",
"body": "Your new out-of-range check is also broken..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-14T17:32:03.163",
"Id": "4092",
"ParentId": "4087",
"Score": "0"
}
},
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>That level of nesting hurts readability.</li>\n<li>There is a lack of re-usability for a common set of source urls to redirect.</li>\n<li>You have specified an ultimate fallback of <code>http://</code>. But what if we encounter <code>https://</code> or <code>ftp://</code>?</li>\n</ul>\n\n<h3>Alternative</h3>\n\n<p>As suggested by others, you want to loop a collection of input values and break on first match. The way I would do it is to provide a utility method. Use a <code>HashSet</code> to avoid duplicates.</p>\n\n<pre><code>private bool RedirectPermanent(HashSet<string> redirectSources, string redirectTo)\n{\n return redirectSources.Any(x => RedirectPermanent(x, redirectTo));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:31:30.287",
"Id": "224109",
"ParentId": "4087",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-14T16:28:56.053",
"Id": "4087",
"Score": "5",
"Tags": [
"c#",
".net",
"url"
],
"Title": "Issue a redirect, trying several string replacements for the domain"
}
|
4087
|
<p>Please review this connection pool. I tested it and it works but can we improve it from design or performance perspective?</p>
<pre><code>public class ConnectionPool {
private static final int MAX_SIZE=10;
private static final BlockingQueue<Connection> bq;
static{
bq= new ArrayBlockingQueue<Connection>(MAX_SIZE);
for(int i=0;i<MAX_SIZE;i++)
{
try {
bq.add(makeConnection());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("total size:" + bq.size());
}
public static Connection getConnection() throws InterruptedException
{
System.out.println("size before getting connection"+ bq.size());
Connection con=bq.take();
System.out.println("size after getting connection"+ bq.size());
return (con);
}
public static boolean releaseConnection(Connection con) throws InterruptedException
{
System.out.println("size before releasing connection"+ bq.size());
boolean bool =bq.add(con);
System.out.println("size after releasing connection"+ bq.size());
return (bool);
}
public static Connection makeConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "root");
connectionProps.put("password", "java33");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection("jdbc:" + "mysql" + "://"
+ "localhost" + ":" + "3306" + "/test", connectionProps);
System.out.println("Connected to database");
return conn;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T20:51:37.097",
"Id": "60212",
"Score": "0",
"body": "Like another poster, I highly suggest bonecp: http://jolbox.com/ You should have VERY good reasons to write your own db connection pool. Furthermore, Spring http://projects.spring.io/spring-framework/ has many high level object pooling constructs."
}
] |
[
{
"body": "<p>First of all I would suggest you to look at this library <a href=\"http://commons.apache.org/dbcp/\" rel=\"nofollow\">DBCP</a></p>\n\n<p>As for the code you have showed - It will be better to avoid using of static state and behavior in this class. The way to control number of instances of this class can be propagated to the client code using different approaches - injection for instance. As connection data may change better to encapsulate it in some class like Destination</p>\n\n<pre><code>class Destination(userName, password, host, port, dbName)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T07:39:53.753",
"Id": "4100",
"ParentId": "4090",
"Score": "3"
}
},
{
"body": "<p>Why do you need to load driver each time you call <code>makeConnection()</code>? I suggest to do it only once per class loading.\nConsider a case when <code>makeConnection()</code> will throw an exception every time you call it and <code>bq</code> will be empty. I suggest to throw a special exception in that case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:03:36.740",
"Id": "4103",
"ParentId": "4090",
"Score": "5"
}
},
{
"body": "<p>Overall: </p>\n\n<ul>\n<li>Are you sure that you want to keep a static number of connections? Why not keep a minimum set of connections and create new ones when needed? </li>\n<li>ConnectionPool shouldn't have static fields as signalpillar said. </li>\n<li>You don't check if the connections have timed out after a period of wait</li>\n<li>Loggers are nice -> you don't necessary have to remove all useful debug output when going to production</li>\n<li>You might want to have some sort of a timeout for the blocking queue depending on the application. Then you would poll rather than take from the queue. </li>\n</ul>\n\n<p>Static initializer: </p>\n\n<ul>\n<li>Is it sensible to catch exceptions per <code>makeConnection</code> - There's probably something wrong if any of them fail.</li>\n<li>You don't check if there really are 10 connections in the pool after initialization. </li>\n<li>What tt34 said. </li>\n</ul>\n\n<p>Method getConnection: </p>\n\n<ul>\n<li>return is not a method, parenthesis are not needed</li>\n<li>do you really want to throw an InterruptedException from your ConnectionPool?</li>\n</ul>\n\n<p>Method releaseConnection:</p>\n\n<ul>\n<li>The same as getConnection</li>\n</ul>\n\n<p>Method makeConnection: </p>\n\n<ul>\n<li>this could be perhaps renamed as connect or openConnection</li>\n<li>It would be better that the connection parameters are given as parameters rather hard-coding - you'll probably just testing at the moment but still </li>\n<li>You should not just ignore the ClassNotFoundException in <code>Class.forName(...)</code>: The program will fail again on the next instruction. Rethrow the exception or wrap it as a run-time exception if you do not want to show the ClassNotFoundException in the method signature</li>\n<li>Rather than concatenating multiple strings, consider using String.format </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:21:37.787",
"Id": "6353",
"Score": "1",
"body": "I understand all the suggestions except one. I dont understand why we cant create all the connections in a static block and have static methods to get and release the connections."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T06:19:22.433",
"Id": "6371",
"Score": "0",
"body": "The question is about (re)usability of the class. With static initializers and methods you make a decision that there shall be one and no more than one connection pool. This decision is better left to the client of the pool. Also consider testability - what limitations to testing ensues from static state? Thinking about different possibilities of how, where, when and why pool is used will lead to at least a few more arguments against the static approach."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:13:41.027",
"Id": "4104",
"ParentId": "4090",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T17:01:33.583",
"Id": "4090",
"Score": "7",
"Tags": [
"java",
"performance",
"jdbc"
],
"Title": "Connection pool in Java"
}
|
4090
|
<p>I'm working on a Cocoa project that uses OpenGL. I'm trying to keep things easily cross-platformable for later (which is the primary reason for my GL singleton; I hope to implement Linux versions of the <code>IRGL</code> methods that currently use <code>NSOpenGL...</code>). When doing Cocoa & OpenGL stuff, though, I'm never sure that I'm doing things the "right" way. What could I be doing better here? I've snipped out methods unrelated to GL or drawing.</p>
<p>Here is my NSView subclass:</p>
<pre><code>//
// IRLevelViewView
// Iris
//
// Created by Andy Van Ness on 3/15/11.
// Copyright 2011 Andy Van Ness. All rights reserved.
//
#import "IRGameEditView.h"
#import <OpenGL/gl.h>
#import "IRGL.h"
//snip
@implementation IRGameEditView
- (id)initWithFrame:(NSRect)frameRect
{
self = [super initWithFrame:frameRect];
if (self != nil)
{
//snip
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(surfaceNeedsUpdate:) name:NSViewGlobalFrameDidChangeNotification object:self];
}
return self;
}
- (void)initDisplayLink
{
GLint swapInt = 1;
[[[IRGL gl] glContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
CVDisplayLinkCreateWithActiveCGDisplays(&displayLink);
CVDisplayLinkSetOutputCallback(displayLink, &MyDisplayLinkCallback, self);
CGLContextObj cglContext = [[[IRGL gl] glContext] CGLContextObj];
CGLPixelFormatObj cglPixelFormat = [[NSOpenGLView defaultPixelFormat] CGLPixelFormatObj];
CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat);
CVDisplayLinkStart(displayLink);
}
- (void)initGL
{
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
[[IRGL gl] initShaders];
[self reshape];
[self setReadyForGL:YES];
}
static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext)
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
[(id)displayLinkContext setNeedsDisplay:YES];
[pool drain];
return kCVReturnSuccess;
}
- (void)lockFocus
{
[super lockFocus];
[[IRGL gl] activateContextForView:self];
}
- (void)drawRect:(NSRect)dirtyRect
{
if (![self isReadyForGL]) [self initGL];
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
[[self clock] updateTime];
CGFloat animator = (CGFloat)([[self clock] time] % 100000)/100000.0;
[[IRGL gl] setCurrentShader:IRIrisShader];
[[IRGL gl] setUniformGLVariable:@"animator" toFloat:animator];
[[IRGL gl] setUniformGLVariable:@"cameraCenter" toPoint:[[self camera] center]];
[[IRGL gl] setUniformGLVariable:@"cameraTileAspectRatio" toFloat:[[self camera] tileAspectRatio]];
[[IRGL gl] setUniformGLVariable:@"cameraZoom" toFloat:[[self camera] zoom]];
[[IRGL gl] setUniformGLVariable:@"cameraSize" toSize:[[self camera] size]];
[[self camera] loadCameraMatrix];
@synchronized([[self level] tileMap])
{
for (IRTileStack* currentStack in [[[self level] tileMap] tileStacksInIrisRect:[[self camera] irisFrame]])
{
[currentStack draw];
}
}
glFlush();
}
- (void)reshape
{
glViewport(0, 0, (GLsizei)[self frame].size.width, (GLsizei)[self frame].size.height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, [self frame].size.width, [self frame].size.height, 0, -2, 0);
glMatrixMode(GL_MODELVIEW);
}
- (BOOL)isOpaque { return YES; }
- (BOOL)isFlipped { return YES; }
- (void)setFrame:(NSRect)frameRect
{
[super setFrame:frameRect];
[[IRGL gl] activateContextForView:self];
[self reshape];
[self setNeedsDisplay:YES];
}
@synthesize automaticallyRedraws;
- (void)setAutomaticallyRedraws:(BOOL)newAutomaticallyRedraws
{
if (newAutomaticallyRedraws != automaticallyRedraws)
{
automaticallyRedraws = newAutomaticallyRedraws;
if (automaticallyRedraws)
{
[self initDisplayLink];
}
else
{
CVDisplayLinkRelease(displayLink);
}
}
}
- (void)surfaceNeedsUpdate:(NSNotification*)notification
{
[[[IRGL gl] glContext] update];
}
//snip
@end
</code></pre>
<p>And here is a singleton GL class:</p>
<pre><code>//
// IRGL.m
// Iris
//
// Created by Andy Van Ness on 8/9/11.
// Copyright 2011 Andy Van Ness. All rights reserved.
//
#import "IRGL.h"
@implementation IRGL
//snip
@synthesize currentShader;
- (void)setCurrentShader:(NSString *)newCurrentShader
{
if (![currentShader isEqualToString:newCurrentShader])
{
[currentShader release];
currentShader = [newCurrentShader copy];
}
if (!newCurrentShader)
{
glUseProgramObjectARB(0);
}
else
{
glUseProgramObjectARB([self shaderForKey:currentShader]);
}
}
- (void)initShaders
{
for (NSString* currentID in [NSArray arrayWithObjects:IRAllShaders])
{
[self addShaderWithID:currentID];
}
[self setInitialized:YES];
}
- (void)addShaderWithID:(NSString*)key
{
NSString* shaderSource = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:key ofType:@"fs"] encoding:NSUTF8StringEncoding error:nil];
if ([shaderSource length] > 0)
{
GLhandleARB shaderProgram = glCreateProgramObjectARB();
GLchar const* source = [shaderSource UTF8String];
GLint const length = [shaderSource length];
GLhandleARB shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
glShaderSourceARB(shader, 1, &source, &length);
glCompileShaderARB(shader);
glAttachObjectARB(shaderProgram, shader);
glLinkProgramARB(shaderProgram);
MOGLShaderInfoLog(shaderProgram);
[[self shaders] setObject:[NSValue valueWithPointer:shaderProgram] forKey:key];
[[self uniformVariablesByShader] setObject:[NSMutableDictionary dictionary] forKey:key];
}
else
{
MOLogWarning(@"Shader not found.");
}
}
- (GLhandleARB)shaderForKey:(NSString *)shaderKey
{
if (shaderKey == nil) return 0;
NSValue* shaderValue = [[self shaders] objectForKey:shaderKey];
if (!shaderValue) MOLogError(@"Shader %@ not found.",shaderKey);
return [shaderValue pointerValue];
}
- (GLint)uniformLocationForName:(NSString*)varName
{
NSNumber* uniformLocation = [[[self uniformVariablesByShader] objectForKey:[self currentShader]] objectForKey:varName];
if (!uniformLocation)
{
GLint var = glGetUniformLocationARB([self shaderForKey:[self currentShader]],[varName UTF8String]);
uniformLocation = [NSNumber numberWithInteger:var];
MOGLError();
if (var == -1)
{
MOLogError(@"Uniform %@ could not be found.",varName);
}
else
{
[[[self uniformVariablesByShader] objectForKey:[self currentShader]] setObject:uniformLocation forKey:varName];
}
}
return (GLint)[uniformLocation integerValue];
}
- (void)setUniformGLVariable:(NSString*)varName toFloat:(CGFloat)varValue
{
if ([self isInitialized])
{
glUniform1f([self uniformLocationForName:varName], varValue);
MOGLError();
}
}
//snip; bunches more methods like that one
- (void)activateContext
{
if (![self glContext])
{
NSOpenGLContext* newContext = [[NSOpenGLContext alloc] initWithFormat:[NSOpenGLView defaultPixelFormat] shareContext:nil];
[self setGLContext:newContext];
[newContext release];
MOGLError();
}
[[self glContext] makeCurrentContext];
MOGLError();
}
- (void)activateContextForView:(NSView*)view
{
[self activateContext];
[[self glContext] setView:view];
}
@end
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><code>CVDisplayLink</code> is asynchronous and in general <code>AppKit</code> is not threadsafe. </p></li>\n<li><p>Using <code>setNeedsDisplay</code>, which gets you a refresh at some point in the future, in the draw callback misses the point of display links, which is drawing something in sync with the screen refresh. </p></li>\n<li><p>You can drop the <code>ARB</code>, right? It's almost 2012.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T02:05:19.090",
"Id": "17853",
"Score": "0",
"body": "Great points--what do I do about #1? If I `-lockFocus` on my `NSView` directly and call my GL right in the callback, is that safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:01:21.230",
"Id": "17982",
"Score": "0",
"body": "I don't think lockFocus is what you want. Try CGLLockContext. See the the GLFullScreen sample code. It correctly uses an OpenGLView with a CVDisplayLink: http://developer.apple.com/library/mac/#samplecode/GLFullScreen/Listings/MyOpenGLView_m.html"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-04T07:43:11.293",
"Id": "6520",
"ParentId": "4093",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6520",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T19:36:14.263",
"Id": "4093",
"Score": "5",
"Tags": [
"objective-c",
"opengl",
"cocoa"
],
"Title": "OpenGL game edit view"
}
|
4093
|
<p>Wondering if this is fully in C++, and if not can someone help me tell the differences. This was submitted by me last semester, and received a good grade. I'm currently trying to ensure I can tell C++ and C apart.</p>
<pre><code>#include <fstream>
#include <stack>
#include <stdlib.h> //Not neccessary in C++
#define swap(type, a, b) {type t = a; a = b; b = t;}
using namespace std;
typedef struct {
int degree, *adjList, //arraySize = degree
nextToVisit, //0 <=nextToVisit < degree
parent, dfLabel, nodeName;
} GraphNode;
int numNodes, startNode = 1;
GraphNode *nodes;
void readGraph();
void depthFirstTraverse(int startNode);
int main() {
readGraph();
depthFirstTraverse(startNode);
}
void depthFirstTraverse(int startNode) {
int nextNode, dfLabels[numNodes], nextToVisit[numNodes], parents[numNodes], lastDFLabel = 0;
stack<int> stackArray;
for (int i = 0; i < numNodes; i++) dfLabels[i] = nextToVisit[i] = 0;
stackArray.push(startNode);
printf("startNode = %d, dfLabel(%d) = %d\n",startNode,startNode,1);
while (!stackArray.empty()) {
if (0 == dfLabels[stackArray.top()]) {
lastDFLabel++;
dfLabels[stackArray.top()] = lastDFLabel; }
if (nextToVisit[stackArray.top()] == nodes[stackArray.top()].degree) {
if (lastDFLabel < numNodes) {
printf("backtracking %d", stackArray.top());
stackArray.pop();
printf(" -> %d\n", stackArray.top()); }
else { printf("backtracking %d -> %d\n", stackArray.top(), startNode);
stackArray.pop(); }
}
else { nextNode = nodes[stackArray.top()].adjList[nextToVisit[stackArray.top()]];
nextToVisit[stackArray.top()]++;
if (0 == dfLabels[nextNode]) {
parents[nextNode] = stackArray.top();
printf("processing (%d, %d): tree-edge, dfLabel(%d) = %d\n",
stackArray.top(), nextNode, nextNode, lastDFLabel+1);
stackArray.push(nextNode); }
else if (dfLabels[nextNode] < dfLabels[stackArray.top()]) {
if (nextNode != parents[stackArray.top()])
printf("processing (%d, %d): back-edge\n", stackArray.top(), nextNode);
else printf("processing (%d, %d): tree-edge 2nd-visit\n", stackArray.top(), nextNode); }
else printf("processing (%d, %d): back-edge 2nd-visit\n", stackArray.top(), nextNode);
}
} for (int i = 0; i < 30; i++) printf("-");
}
void readGraph() {
char ignore;
ifstream digraph("digraph.data");
digraph >> numNodes;
nodes = new GraphNode[numNodes];
for (int i = 0; i < numNodes; i++) {
digraph >> nodes[i].nodeName >> ignore >> nodes[i].degree >> ignore;
nodes[i].adjList = new int[nodes[i].degree];
for (int j = 0; j < nodes[i].degree; j++) digraph >> nodes[i].adjList[j];
} digraph.close();
printf ("Input Graph:\nnumNodes = %d\n", numNodes);
for (int i = 0; i< numNodes; i++) {
printf("%d (%d): ", nodes[i].nodeName, nodes[i].degree);
for (int j = 0; j < nodes[i].degree; j++)
for (int k = 0; k < j; k++)
if (nodes[i].adjList[j] < nodes[i].adjList[k])
swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);
for (int j = 0; j < nodes[i].degree; j++) printf("%d ", nodes[i].adjList[j]);
printf("\n");
} for (int i = 0; i < 30; i++) printf("-");
printf ("\n");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T23:41:31.157",
"Id": "6113",
"Score": "1",
"body": "For C++ code, you're using an awful lot of C functions and paradigms. You usually could tell by the excessive use of `printf()`, pointers, for loops, lack of classes and so on. Good C++ would not rely on these constructs as much if at all using things in the STL and algorithm more. A bigger C++ guru will be able to explain these more thoroughly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T01:57:37.883",
"Id": "6115",
"Score": "0",
"body": "Originally it was different, but as I changed it to meet his demands, this was the result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T07:51:05.087",
"Id": "6120",
"Score": "1",
"body": "Martin is right: Your code is more C with some C++ features than C++. You are thinking \"functions with data\". In C++, you should think \"objects that hide their internals and know how to behave\". Encapsulation should be your main concern. Who told you this was a C++ code?"
}
] |
[
{
"body": "<p>using printf is C like.</p>\n\n<p>using a function like readGraph that does a lot of magic as well as printing things is C like.</p>\n\n<p>For this kind of thing to be C++ like, then you'd consider how to write these functions generically. Giving your graph an STL like feel. </p>\n\n<p>This code here is more about your attempts at learning traversal than writing a good useful function. For instance, the whole point of traversal is to do something with each node visited, here you have no facilities for injecting functionality as you reach each node.</p>\n\n<p>So a C++ approach, in the sense of a modern approach, would look quite different. This would be templated, it would accept lambdas or functors, it would use/provide iterators etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T01:40:56.963",
"Id": "4096",
"ParentId": "4095",
"Score": "6"
}
},
{
"body": "<p>It's still closer to C than C++ IMO.</p>\n<h3>First of two non C++ issues:</h3>\n<ol>\n<li><p>You don't encapsulate your classes. Your whole interface is public. Thus you are now doomed to forever maintain this interface for eternity. Additionally it allows other people to accidentally modify your structure. Use the C++ class system to encapsulate your objects and at least protect your objects from accidental miss use.</p>\n</li>\n<li><p>Your tree-traversal actually depends on the node object to track traversal. Now that's a bad design thing. You are basically binding yourself to an implementation and limiting the usability of your code. You should most defiantly look up the <code>Visitor Pattern</code>.</p>\n</li>\n</ol>\n<h3>The rest are C++ issues:</h3>\n<p>You are doing resource management manually:</p>\n<pre><code>nodes = new GraphNode[numNodes]; \n// STUFF\nnodes[i].adjList = new int[nodes[i].degree];\n</code></pre>\n<p>It would be better to use a std::vector at least that would be exception safe in controlling the resource:</p>\n<pre><code>std::vector<GraphNode> nodes(numNodes);\n</code></pre>\n<p>You are manually loading nodes. Should a node not know how to stream itself onto and off a stream?</p>\n<pre><code> digraph >> nodes[i].nodeName >> ignore >> nodes[i].degree >> ignore;\n</code></pre>\n<p>I would expect it to look like this:</p>\n<pre><code> digraph >> nodes[i];\n</code></pre>\n<p>Or even better create items and push them into the vector:<br />\nSince the only thing that seems to be in the file "digraph.data" seem to be GraphNodes then you could do something like this:</p>\n<pre><code>std::copy(std::istream_iterator<GraphNode>(digraph),\n std::istream_iterator<GraphNode>(),\n std::back_inserter(nodes) // Assuming nodes is a vector described above.\n );\n</code></pre>\n<p>This is not C++</p>\n<pre><code> printf("%d (%d): ", nodes[i].nodeName, nodes[i].degree);\n</code></pre>\n<p>The problem with the printf style is that it is not type safe. The main advantage C++ has over C is the exceptional type safety of the language. Use this to your advantage.</p>\n<p>This is so bad I nearly swallowed my tounge.:</p>\n<pre><code> swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);\n</code></pre>\n<p>You have #defined swap.</p>\n<ol>\n<li>Use all caps for macros.<br />\nThe reason is to make sure macros do not clash with any other identifiers.</li>\n<li>Macros are not type safe.<br />\nIf there was a conversion from this object to int the compiler will now happily do it.</li>\n<li>There is already a type safe macro as part of the standard library.<br />\nIf you want to override the default swap behavior you just need to rewrite your type specific version and Koenig lookup will automatically find it.</li>\n</ol>\n<p>Not a big deal but prefer pre-increment. The reason is it does not matter for POD types but for user defined types it does (or potentially does) matter. If a maintainer at a latter stage changes the type of the loop variable then you don't have to go and change any of the code the pre-increment is already the correct type.</p>\n<pre><code> for (int i = 0; i < 30; ++i)\n // ^^^^ Prefer pre-increment here\n</code></pre>\n<p>Don't declare multiple variables on the same line:</p>\n<pre><code>int nextNode, dfLabels[numNodes], nextToVisit[numNodes], parents[numNodes], lastDFLabel = 0;\n</code></pre>\n<p>Every coding standard is going to tell you not to do it. So get used to it. Technically there are a few corner cases that will come and hit you and putting each variable on its own line makes it easier to read. Also note it looks like you are initializing all values to zero. That's not happening so all of these (apart from the last one) are undefined.</p>\n<p>Also defining arrays with a non cost type is not technically allowed.</p>\n<pre><code>dfLabels[numNodes],\n</code></pre>\n<p>Some compilers allow it because it is C90 extension. But its not really portable. Use std::vector (or std::array) instead.</p>\n<p>Don't put code on the same line as the close braces.<br />\nI dobt anybody is going to like that style even the people that want to save vertical line space.</p>\n<pre><code>} for (int i = 0; i < 30; i++) printf("-");\n</code></pre>\n<p>And I prefer to put the statement the for loop is going to run on the next line so it is obvious what is happening (but I am not going to care that much about it).</p>\n<p>typedefing a structure is not needed in C++</p>\n<pre><code>typedef struct {\n // BLAH\n} GraphNode;\n</code></pre>\n<p>This is just</p>\n<pre><code>struct GraphNode\n{\n // BLAH\n};\n</code></pre>\n<p>When you loop over your containers you are using a C style (ie you are using an index). It is usually more conventionally to use an iterator style to index over a container (even a simple array). Thus if you ever choose to move to another style of container the code itself does not need to be changed. The iterator style makes the code container agnostic.</p>\n<p>Personally I don't think it is a big deal. In this limited context.</p>\n<pre><code> for (int j = 0; j < nodes[i].degree; j++)\n</code></pre>\n<p>You implement (badly) a sort function:</p>\n<pre><code> for (int j = 0; j < nodes[i].degree; j++)\n for (int k = 0; k < j; k++)\n if (nodes[i].adjList[j] < nodes[i].adjList[k]) \n swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);\n</code></pre>\n<p>Lets just say in both C/C++ you should probably use the built-in sorting algorithms:</p>\n<pre><code>std::sort(&nodes[i].adjList[0], &nodes[i].adjList[nodes[i].degree]);\n</code></pre>\n<p>Or am I reading your intention here incorrectly? Is it some sort of randomizing feature? Either way you should have probably documented this to explain what you are trying to achieve!</p>\n<h3>Here is a more C++ like version</h3>\n<pre><code>#include <vector>\n#include <map>\n#include <iterator>\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n\n\n\nclass GraphVisitor; // We will implement the `Visitor Pattern`\nclass Graph\n{\n public:\n class GraphNode\n {\n public:\n // Allows us to visit each node.\n // Don't need to track progress via modifying the node\n void accept(GraphVisitor& visitor);\n private:\n // The streaming operators are defined so we can freeze and thaw data to a stream\n friend std::istream& operator>>(std::istream& stream, Graph::GraphNode& node);\n friend std::ostream& operator<<(std::ostream& stream, Graph::GraphNode const& node);\n\n // The data is private nobody actually needs to see this\n int nodeName;\n std::vector<int> link;\n };\n\n // Graph knows how to implement depth first traversal.\n // External entities can't do this because that requires knowledge of the implementation\n void DepthFirstTraversal(size_t startNode);\n\n private:\n // The streaming operators are defined so we can freeze and thaw data to a stream\n friend std::istream& operator>>(std::istream& stream, Graph& node);\n friend std::ostream& operator<<(std::ostream& stream, Graph const & node);\n\n // The data is just the nodes\n std::vector<GraphNode> nodes;\n\n};\n// A visitor is easy\n// When you only have one node type.\n// So we just have one visit method.\nclass GraphVisitor\n{\n public:\n virtual ~GraphVisitor() {}\n virtual void visit(Graph::GraphNode& node, int name, std::vector<int> const& links) = 0;\n};\n\n// All the node does with the visitor is tell it that it can visit.\nvoid Graph::GraphNode::accept(GraphVisitor& visitor)\n{\n visitor.visit(*this, nodeName, link);\n}\n\n// Stream Nodes\nstd::ostream& operator<<(std::ostream& stream, Graph::GraphNode const& node)\n{\n stream << node.nodeName << ":" << node.link.size() << ":";\n std::copy(node.link.begin(), node.link.end(), std::ostream_iterator<int>(stream, " "));\n return stream;\n}\nstd::istream& operator>>(std::istream& stream, Graph::GraphNode& node)\n{\n char ignore;\n int count;\n\n stream >> node.nodeName >> ignore >> count >> ignore;\n\n for(std::istream_iterator<int> loop(stream); count != 0; --count, ++loop)\n { node.link.push_back(*loop);\n }\n // For some reason you sort your nodes so I am sorting them here.\n // Or I am reading your original code incorrectly.\n std::sort(node.link.begin(), node.link.end());\n return stream;\n}\n// Stream the whole graph.\n// This is simply the number of nodes followed by a list of nodes.\nstd::ostream& operator<<(std::ostream& stream, Graph const & graph)\n{\n stream << graph.nodes.size() << " ";\n std::copy(graph.nodes.begin(), graph.nodes.end(), std::ostream_iterator<Graph::GraphNode>(stream, " "));\n return stream;\n}\nstd::istream& operator>>(std::istream& stream, Graph& graph)\n{\n int nodeCount;\n stream >> nodeCount;\n\n // We could implement it like this.\n // As this would match your current file format nicely and if their\n // is anything after the nodes it still works. \n /*\n for(int loop=0;loop < nodeCount; ++loop) // I implemented it like this becuase \n {\n Graph::GraphNode node;\n stream >> node;\n graph.nodes.push_back(node);\n }\n */\n // But if there is nothing after the nodes it could be implemented like this:\n std::copy(std::istream_iterator<Graph::GraphNode>(stream),\n std::istream_iterator<Graph::GraphNode>(),\n std::back_inserter(graph.nodes)\n );\n}\n\n// A visitor object used by Graph::DepthFirstTraversal\n// It tracks which nodes it has already seen.\n// So you do not need to visit them again.\n// When a node says it can visit then just visit all the linked nodes.\n// If you get a call from a node that has already visited then just exit.\nclass DepthFirstVisitor: public GraphVisitor\n{\n public:\n DepthFirstVisitor(std::vector<Graph::GraphNode>& n)\n : nodes(n)\n {}\n private:\n virtual void visit(Graph::GraphNode& node, int name, std::vector<int> const& links)\n {\n if (visited[&node])\n { return;\n }\n\n visited[&node] = true;\n std::cout << "Visiting Node: " << name << "\\n";\n\n for(std::vector<int>::const_iterator loop = links.begin();loop != links.end();++loop)\n {\n nodes[*loop].accept(*this);\n }\n }\n std::map<Graph::GraphNode const*, bool> visited;\n std::vector<Graph::GraphNode>& nodes;\n};\n\n// Implementing the Depth First traversal is easy as calling the first node with the\n// the correct visitor object\nvoid Graph::DepthFirstTraversal(size_t startNode)\n{\n if (startNode >= nodes.size())\n { throw std::runtime_error("Failed");\n }\n DepthFirstVisitor visitor(nodes);\n nodes[startNode].accept(visitor);\n};\n\n\nint main()\n{\n Graph graph;\n\n std::ifstream digraph("digraph.data");\n digraph >> graph; // Very easy to load a graph.\n std::cout << graph << "\\n\\n\\n"; // Printing it out is also easy\n\n graph.DepthFirstTraversal(1); // start at node one instead of zero for some reason!!!!!.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T07:47:42.780",
"Id": "6119",
"Score": "1",
"body": "+1 for the thorough answer. `typedefing a structure is not needed in C++` : More important, if the structure is anonymous (and only has a typedef-ed name), it can't be forward declared!... Also, shouldn't the `startNode` parameter of `Graph::DepthFirstTraversal` be a size_t ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T22:54:39.167",
"Id": "6167",
"Score": "0",
"body": "@Martin Thanks. Very clear, and appreciate the example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T02:20:08.903",
"Id": "4097",
"ParentId": "4095",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "4097",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-14T23:24:15.043",
"Id": "4095",
"Score": "5",
"Tags": [
"c++",
"c",
"algorithm"
],
"Title": "depthFirstTraverse fully in C++?"
}
|
4095
|
<p>I'm primarily a C++/Java programmer, but I've recently started using Python at work and decided to write a Lottery Simulator at home. I wrote it to test out different combinations of lottery numbers against a set of winning numbers to calculate how much I would have won (I also run the lotto pool at work). The only major problem I've seen with the code is that it has a substantial memory leak that I just can't seem to track down. I've already plugged one large leak.</p>
<p>I'd really appreciate any help you can provide in tracking down the leak(s). The code is pretty large (655 lines), but a lot of it is comments & blank lines for readability. Also feel free to use the code yourself if you want, I'm not copyrighting it.</p>
<pre><code>#!/usr/bin/python
import random, ConfigParser, ast, copy
from optparse import OptionParser
# Global variables.
g_config = {} # Stores GameType config options.
g_prizes = {} # Stores prizes from config file.
g_prize_amounts = {} # Stores prize amounts from config file.
g_ticket_quick_picks = [] # Store an array of QuickPicks to use for tickets.
g_total_money_won = 0
g_total_tickets_won = 0
g_prizes_won = {} # Format: {'3':3, '3+1':2, '4':2 ...}
g_quick_pick_file = ''
g_how_many_tickets_played = 0
g_how_many_tickets_won = 0
class TicketNumbers( object ):
'''Represents the numbers of a ticket (or the 7 winning numbers).
@var numbers: A sorted array of 7 unique numbers from 1-49.'''
def __init__( self, numbers ):
'''Constructor.
@param numbers: The numbers for this ticket.'''
self.numbers = numbers
self._set_numbers( numbers )
def name( self ):
'''Return the name of this class type.'''
return "TicketNumbers"
def __str__( self ):
'''Returns a string of the number list.'''
str_nums = []
for i in range( len( self.numbers ) ):
str_nums.append( str( self.numbers[i] ) )
return ', '.join( str_nums )
def _set_numbers( self, numbers ):
'''Sets the numbers member variable and validates the numbers.
@param numbers: The numbers to assign.'''
global g_config
self.numbers = sorted( numbers )
if len( self.numbers ) != int(g_config['how_many_numbers']):
raise Exception( "You must have %d numbers, but found %d numbers: %s" % (g_config['how_many_numbers'], len( self.numbers ), str(self.numbers)) )
tmp = []
for num in self.numbers:
# Check if numbers are in range.
if ( num < int(g_config['min_number']) ) or ( num > int(g_config['max_number']) ):
raise Exception( "The numbers must be between %d & %d!" % (int(g_config['min_number']), int(g_config['max_number'])) )
# Check for duplicate numbers.
if num in tmp:
raise Exception( "You cannot have duplicate numbers! %d in %s" % (num, str( self.numbers )) )
tmp.append( num )
class PlayedTicket( TicketNumbers ):
'''Represents a ticket that was played.
@var amount_won: How much $$ this ticket won.'''
def __init__( self, numbers ):
'''Constructor.
@param numbers: The numbers for this ticket.'''
super( PlayedTicket, self ).__init__( numbers )
self.amount_won = {} # Map of Game Index to $$ won each play.
self.tickets_won = {} # Map of Game Index to Free Tickets won each play.
def name( self ):
'''Return the name of this class type.'''
return "PlayedTicket"
def compare_with( self, winning_numbers, game_index=None ):
'''Compares this ticket with the specified winning numbers and sets the amount_won & tickets_won members accordingly.
@param winning_numbers: The winning numbers to compare against.
@param game_index: (optional) The game index for this game. Defaults to 1 + the number of games recorded.
@return: A tuple of ($$ won, # free tickets won).'''
global g_config, g_prizes, g_prize_amounts, g_prizes_won, g_how_many_tickets_won
nums_correct = 0
bonus_correct = 0
amount_won = 0
tickets_won = 0
if game_index == None:
game_index = len( self.amount_won )
# Check each individual number of the ticket against the winning numbers.
for num in self.numbers:
if num in winning_numbers.numbers:
nums_correct = nums_correct + 1
elif num in winning_numbers.bonus_numbers:
bonus_correct = bonus_correct + 1
# Now see if we won anything.
for (key, value) in g_prizes.items():
main_nums = key[0]
bonus_nums = key[1]
if (main_nums == nums_correct) and ((bonus_nums == bonus_correct) or (bonus_nums == 0)):
if not g_prizes_won.has_key( value ):
g_prizes_won[value] = 0
g_how_many_tickets_won = g_how_many_tickets_won + 1
g_prizes_won[value] = g_prizes_won[value] + 1 # Increment map of how many times each prize won.
# We won. Now figure out what we won.
if g_prize_amounts[value] > amount_won:
amount_won = g_prize_amounts[value]
tickets_won = 0
elif g_prize_amounts[value] == -1:
amount_won = 0
tickets_won = 1
if amount_won or tickets_won:
if g_config['verbose']:
print( "Ticket %s won: $%d & %d Free tickets." % (str(self.numbers), amount_won, tickets_won) )
# Set and return the amount won.
self.amount_won[game_index] = amount_won
self.tickets_won[game_index] = tickets_won
return (amount_won, tickets_won)
class QuickPick( PlayedTicket ):
'''Represents a Quick Pick ticket.'''
def __init__( self, numbers ):
'''Constructor.
@param numbers: The numbers for this ticket.'''
super( QuickPick, self ).__init__( numbers )
self.amount_won = {} # Map of Game Index to $$ won each play.
self.tickets_won = {} # Map of Game Index to Free Tickets won each play.
def name( self ):
'''Return the name of this class type.'''
return "QuickPick"
class WinningNumbers( TicketNumbers ):
'''Represents the winning numbers + bonus number.
@var bonus_numbers: The bonus numbers.'''
def __init__( self, numbers, bonus_numbers=None ):
'''Constructor.
@param numbers: The winning numbers.
@param bonus_numbers: (optional) The bonus number(s). Defaults to empty list.'''
global g_config
bonus_numbers = bonus_numbers or []
super( WinningNumbers, self ).__init__( numbers )
self.bonus_numbers = []
if bonus_numbers:
self.bonus_numbers = sorted( bonus_numbers )
tmp = []
if len( bonus_numbers ) != int(g_config['how_many_bonus']):
raise Exception( "You must have %d bonus numbers!" % int(g_config['how_many_bonus']) )
for num in bonus_numbers:
if (num in tmp) or (num in self.numbers):
raise Exception( "You cannot have duplicate numbers!" )
tmp.append( num )
def __str__( self ):
'''Converts this class into a string.'''
ret = super( WinningNumbers, self ).__str__()
str_bnums = []
if len( self.bonus_numbers ):
for i in range( len( self.bonus_numbers ) ):
str_bnums.append( str( self.bonus_numbers[i] ) )
ret = ret + ' + ' + ', '.join( str_bnums )
return ret
def name( self ):
'''Return the name of this class type.'''
return "WinningNumbers"
def load_config( filename ):
'''Reads the config file to load program defaults.
@param filename: The filename of the config file.
@return: A ConfigParser object containing the parsed config file.'''
# Read the config file into the parser.
global g_config, g_prizes, g_prize_amounts
conf = ConfigParser.SafeConfigParser()
conf.read( filename )
if (not conf.has_section( 'GameType' )) or (not conf.has_section( 'Prizes' )):
raise Exception( "Invalid config file! [GameType] and/or [Prizes] sections are missing!" )
options = ['min_number', 'max_number', 'how_many_numbers', 'how_many_bonus', 'how_many_hand_picked_lines', 'how_many_quick_pick_lines', 'cost_per_ticket', 'quick_pick_pool_size', 'how_many_tickets_bought']
for option in options:
if not conf.has_option( 'GameType', option ):
raise Exception( "Invalid config file! '%s' option is missing!" % option )
g_config[option] = int( conf.get( 'GameType', option ) )
# Prizes section contains maps.
g_prizes = ast.literal_eval( conf.get( 'Prizes', 'prizes' ) )
g_prize_amounts = ast.literal_eval( conf.get( 'Prizes', 'prize_amounts' ) )
def load_tickets_conf( filename ):
'''Loads tickets from a config file.
@param filename: The filename to load the tickets from.
@return: A map of # of tickets to an array of Tickets.'''
# Read the config file into the parser.
conf.read( filename )
ticket_map = {}
# First read the 'all_groups' option that contains a list of all ticket groups.
if not conf.has_section( 'AllTicketGroups' ):
raise Exception( "Invalid config file! [AllTicketGroups] section is missing!" )
all_groups = parse_number_line( conf.get( 'AllTicketGroups', 'all_groups' ) )
# Then read each ticket group and add the tickets to the map.
for group in all_groups:
if not conf.has_section( str( group ) ):
raise Exception( "Invalid config file! [%d] section is missing!" % group )
tickets = []
for i in range( 1, group + 1 ):
if not conf.has_option( str( group ), str( i ) ):
raise Exception( "Invalid config file! There is no '%d' option under the [%d] section!" % (i, group) )
numbers = parse_number_line( conf.get( str( group ), str( i ) ) )
ticket = PlayedTicket( numbers )
tickets.append( ticket )
ticket_map[group] = tickets
return ticket_map
def load_tickets_txt( filename, ticket_class = PlayedTicket ):
'''Loads tickets from a text file.
@param filename: The filename to load the tickets from.
@param ticket_class: (optional) The class name for the type of tickets you want returned.
@return: A map of # of tickets to an array of Tickets.'''
global g_config
# Read the file into an array of lines.
fd = open( filename, 'r' )
lines = fd.readlines()
fd.close()
# Create the hand picked list of tickets.
ticket_list = parse_number_lines( lines, ticket_class )
number_of_tickets = len( ticket_list )
if ticket_class != QuickPick:
# Add the appropriate number of quick picks.
num_quick_picks = number_of_tickets * g_config['how_many_quick_pick_lines']
ticket_list.extend( quick_picks( num_quick_picks ) )
tickets = {number_of_tickets : ticket_list}
return tickets
def load_winning_numbers( lines ):
'''Loads the winning numbers from a CSV file and returns an array of WinningNumbers.
@param lines: The lines of the CSV containing the winning numbers.
@return: An array of WinningNumbers objects.'''
global g_config
numbers = []
winning_tickets = []
# Parse the string lines into arrays of numbers.
for line in lines:
numbers.append( parse_number_line( line ) )
how_many_numbers = g_config['how_many_numbers']
how_many_bonus = g_config['how_many_bonus']
# Create an array of WinningTickets.
for line in numbers:
if len( line ) != (how_many_numbers + how_many_bonus):
raise Exception( "Invalid winning numbers CSV file! There should be %d numbers, but we found %d!" % (how_many_numbers + how_many_bonus, len( line ) ) )
else:
nums = line[0:how_many_numbers]
bonus = line[-how_many_bonus:]
ticket = WinningNumbers( nums, bonus )
winning_tickets.append( ticket )
return winning_tickets
def parse_number_lines( lines, ticket_class = PlayedTicket ):
'''Parses an array of strings (comma delimited number lines).
@param lines: An array of strings (comma delimited number lines).
@param ticket_class: (optional) The class name for the type of tickets you want returned.
@return: An array of tickets of the type specified by ticket_class.'''
tickets = []
for line in lines:
numbers = parse_number_line( line )
tickets.append( ticket_class( numbers ) )
return tickets
def parse_number_line( line ):
'''Parses a string (comma delimited number line).
@param line: A string (comma delimited number line).
@return: An array of sorted numbers.'''
nums = line.split( ',' )
numbers = []
for num in nums:
numbers.append( int( num.strip() ) )
return sorted( numbers )
def quick_pick():
'''Returns a QuickPick ticket.
@return: A QuickPick ticket.'''
global g_config, g_quick_pick_file
random.seed()
numbers = []
while len( numbers ) < g_config['how_many_numbers']:
num = random.randrange( g_config['min_number'], g_config['max_number'], 1 ) # From 1 to 49, step by 1.
if not num in numbers:
numbers.append( num )
# If we're using a quick pick file, this function should never be called, so print this to let us know.
if g_config['verbose'] and g_quick_pick_file:
print( "Warning: You specified a quick pick file, but quick_pick() was called and returned: %s" % str(numbers) )
return QuickPick( numbers )
def quick_picks( number_of_tickets, quick_pick_list=None ):
'''Returns a list of QuickPick tickets.
@param number_of_tickets: The number of QuickPick tickets to generate.
@param quick_pick_list: (optional) Get as many quick picks from this list instead of generating new ones.
@return: A list of QuickPick tickets.'''
tickets = []
if quick_pick_list:
if len( quick_pick_list ) >= number_of_tickets:
tickets.extend( quick_pick_list[0:number_of_tickets] )
else:
tickets.extend( quick_pick_list )
for i in range( number_of_tickets - len( quick_pick_list ) ):
tickets.append( quick_pick() )
else:
for i in range( number_of_tickets ):
tickets.append( quick_pick() )
return tickets
def single_play( played_tickets, winning_numbers ):
'''Compares tickets to winning numbers and calculates what each ticket won.
The 'amount_won' member will be set for any tickets that won.
@param played_tickets: An array of PlayedTickets.
@param winning_numbers: A WinningNumbers object.
@return: A tuple of ($$ won, # free tickets won).'''
global g_total_money_won, g_total_tickets_won, g_config, g_how_many_tickets_played
total_money = 0
total_tickets = 0
num_tickets = len( played_tickets )
# Compare each ticket against the winning numbers.
for i in range( 0, num_tickets - 1 ):
ticket = played_tickets[i]
g_how_many_tickets_played = g_how_many_tickets_played + 1
if g_config['verbose']:
print( "[%s] = %s" % (played_tickets[i].name(), str(played_tickets[i])) )
(money_won, tickets_won) = ticket.compare_with( winning_numbers )
total_money = total_money + money_won
total_tickets = total_tickets + tickets_won
# Keep track of the totals won over all.
g_total_money_won = g_total_money_won + total_money
g_total_tickets_won = g_total_tickets_won + total_tickets
return (total_money, total_tickets)
def get_tickets( played_ticket_map, how_many_tickets, keys ):
'''Returns an array of tickets of the specified size, with as many hand_picked tickets as possible.
@param played_ticket_map: A map of # of tickets to array of PlayedTickets to choose from.
@param how_many_tickets: The number of tickets to be returned.
@param keys: The sorted list of keys in played_ticket_map.
@return: An array of tickets of the specified size, with as many hand_picked tickets as possible.'''
global g_ticket_quick_picks
tickets = []
# If any of the ticket pools have the exact number of tickets we need, use it; otherwise add quick picks
# to a ticket pool that's smaller than we need until we have the right number of tickets.
if how_many_tickets in keys:
tickets = copy.deepcopy(played_ticket_map[how_many_tickets] )
else:
# Find next ticket pool lower than how_many_tickets and add quick picks to fill up the rest.
last_key_index = -1
for i in keys:
if i > how_many_tickets:
break
last_key_index = i
if last_key_index == -1:
# Looks like we're using all quick picks.
print( "*** get_tickets() is adding all %d quick picks" % how_many_tickets ) # DEBUG
tickets = quick_picks( how_many_tickets, g_ticket_quick_picks )
else:
if (how_many_tickets - last_key_index) > 50:
print( "*** get_tickets() is adding %d quick picks" % (how_many_tickets - last_key_index) ) # DEBUG
tickets = copy.deepcopy( played_ticket_map[last_key_index] )
tickets.extend( quick_picks( how_many_tickets - last_key_index, g_ticket_quick_picks ) )
return tickets
def multiple_plays( played_ticket_map, quick_pick_list_const, winning_numbers, number_of_tickets ):
'''Compares tickets to an array of winning numbers and calculates what each ticket won over x number of games played.
The 'amount_won' member will be set for any tickets that won.
@param played_ticket_map: A map of # of tickets to array of PlayedTickets to choose from.
@param quick_pick_list_const: A list of QuickPick tickets to choose from.
@param winning_numbers: An array of WinningNumbers objects.
@param number_of_tickets: The usual number of tickets bought (assuming no extra or free tickets).
@return: A tuple of: (extra_tickets, extra_quick_picks, money_left_over)'''
global g_ticket_quick_picks, g_config
extra_tickets = 0
extra_quick_picks = 0
money_left_over = 0
amount_won = 0
tickets_won = 0
game_num = 0
keys = sorted( played_ticket_map.keys() )
# For each winning ticket, check if any of our tickets won.
for winning_ticket in winning_numbers:
total_tickets_won = 0
total_amount_won = 0
game_num += 1
if g_config['verbose']:
print( "Winning numbers are: %s" % winning_ticket )
# Check the hand picked tickets.
how_many_tickets = number_of_tickets + extra_tickets
tickets = get_tickets( played_ticket_map, how_many_tickets, keys )
# Play the numbers we picked.
(amount_won, tickets_won) = single_play( tickets, winning_ticket )
for ticket in tickets:
del ticket
del tickets
total_amount_won = total_amount_won + amount_won
total_tickets_won = total_tickets_won + tickets_won
# Check the quick picks.
how_many_quick_picks = (g_config['how_many_quick_pick_lines'] * number_of_tickets) + extra_quick_picks
# Make a copy of quick_pick_list_const.
quick_pick_list = quick_pick_list_const[0:len(quick_pick_list_const)]
# If the quick_pick pool isn't big enough, increase the pool size.
if len( quick_pick_list ) < how_many_quick_picks:
quick_pick_list.extend( quick_picks( how_many_quick_picks - len(quick_pick_list), g_ticket_quick_picks ) )
# Now play the quick picks.
(amount_won, tickets_won) = single_play( quick_pick_list[0:how_many_quick_picks], winning_ticket )
total_amount_won = total_amount_won + amount_won
total_tickets_won = total_tickets_won + tickets_won
# Now change the number of quick picks and extra money to reflect what we just won.
if g_config['verbose']:
print( "[Game %d]: We won: $%d, and %d Free Tickets.\n\n" % (game_num, total_amount_won, total_tickets_won) )
extra_tickets = int( (total_amount_won + money_left_over) / g_config['cost_per_ticket'] )
money_left_over = total_amount_won + money_left_over - (extra_tickets * g_config['cost_per_ticket'])
extra_quick_picks = total_tickets_won
return (extra_tickets, extra_quick_picks, money_left_over)
def main():
'''The start of the program.'''
global g_ticket_quick_picks, g_quick_pick_file, g_config, g_total_money_won, g_total_tickets_won, g_prizes_won, \
g_how_many_tickets_played, g_how_many_tickets_won
# Create the arg parser.
usage = """\
usage: %prog -c <config_file> -t <tickets_file> -w <winning_numbers_file> [-q <quick_pick_file>] [-o <quick_pick_output_file>] [-T] [-v]
or: %prog -c <config_file> -o <quick_pick_output_file> [-v]
-c, --config The main config file.
-t, --tickets The tickets config file.
-o, --output Will dump some quick pick numbers into this file.
-w, --winning-numbers The winning numbers csv file.
-d, --debug Debug mode.
-T, --text Read tickets_file as a text file instead of a config file.
-v, --verbose Enable verbose mode."""
parser = OptionParser( usage=usage )
parser.add_option( '-c', '--config', dest='config_file' )
parser.add_option( '-t', '--tickets', dest='tickets_file' )
parser.add_option( '-o', '--output', dest='output_file' )
parser.add_option( '-q', '--quick-pick', dest='quick_pick_file' )
parser.add_option( '-w', '--winning-numbers', dest='winning_numbers' )
parser.add_option( '-d', '--debug', action='store_true', dest='debug_mode' )
parser.add_option( '-T', '--text', action='store_true', dest='text_mode' )
parser.add_option( '-v', '--verbose', action='store_true', dest='verbose' )
(options, args) = parser.parse_args()
if len( args ):
parser.error( "The following arguments are unrecognized: %s" % str( args ) )
if (not options.config_file):
parser.error( "--config is a required parameter!" )
# Load the main config file.
load_config( options.config_file )
ticket_map = None
g_config['debug_mode'] = False
g_config['verbose'] = False
if options.debug_mode:
g_config['debug_mode'] = True
if options.verbose:
g_config['verbose'] = True
if g_config['verbose']:
# Print out current configuration.
print( "min_number = %s" % g_config['min_number'] )
print( "max_number = %s" % g_config['max_number'] )
print( "how_many_numbers = %s" % g_config['how_many_numbers'] )
print( "how_many_bonus = %s" % g_config['how_many_bonus'] )
print( "how_many_hand_picked_lines = %s" % g_config['how_many_hand_picked_lines'] )
print( "how_many_quick_pick_lines = %s" % g_config['how_many_quick_pick_lines'] )
print( "cost_per_ticket = %s" % g_config['cost_per_ticket'] )
print( "quick_pick_pool_size = %s" % g_config['quick_pick_pool_size'] )
print( "how_many_tickets_bought = %s" % g_config['how_many_tickets_bought'] )
print( "verbose mode = %s\n" % str(g_config['verbose']) )
# Load the quick pick pool from a file or generate the numbers.
quick_pick_pool = []
if options.quick_pick_file:
g_quick_pick_file = options.quick_pick_file
quick_pick_map = load_tickets_txt( options.quick_pick_file, QuickPick )
for key, val in quick_pick_map.items():
quick_pick_pool = val
else:
quick_pick_pool = quick_picks( g_config['quick_pick_pool_size'] )
if (options.output_file): # Just output some quick picks.
if ((options.tickets_file) or (options.winning_numbers) or (options.text_mode)):
parser.error( "--output cannot be used with --tickets or --winning-numbers or --text!" )
else:
# Just output some quick picks to a file.
fd = open( options.output_file, 'w' )
for quick_pick in quick_pick_pool:
fd.write( str( quick_pick ) + '\n' )
fd.close()
else: # Play the games.
# Move half the quick pick pool to g_ticket_quick_picks for use with normal tickets.
for i in range( (len(quick_pick_pool) / 2) ):
g_ticket_quick_picks.append( quick_pick_pool.pop(0) )
if (not options.tickets_file) or (not options.winning_numbers):
parser.error( "Incorrect number of arguments!" )
else:
# Load the tickets & winning numbers.
if options.text_mode:
ticket_map = load_tickets_txt( options.tickets_file )
else:
ticket_map = load_tickets_conf( options.tickets_file )
# Read the file into an array of lines.
fd = open( options.winning_numbers, 'r' )
lines = []
extra_tickets = 0
extra_quick_picks = 0
money_left_over = 0
while True:
for i in range( 1000 ):
line = fd.readline()
if not line:
break
lines.append( line )
if not lines:
break
winning_numbers = load_winning_numbers( lines )
# Start the simulation.
(extra_tickets, extra_quick_picks, money_left_over) = multiple_plays( ticket_map, quick_pick_pool, winning_numbers, g_config['how_many_tickets_bought'] )
del lines
lines = []
print( "After %d games, we won a total of $%d and %d Free Tickets ($%d)." % (len( winning_numbers ), g_total_money_won, g_total_tickets_won, (g_total_tickets_won * 5 + g_total_money_won)) )
print( "We played %d ticket lines and %d lines won." % (g_how_many_tickets_played, g_how_many_tickets_won) )
fd.close()
# Now display the results of all the games.
for (key, value) in sorted( g_prizes.items() ):
if g_prizes_won.has_key( value ):
print( " '%s' won, %d times." % (value, g_prizes_won[value]) )
if __name__ == "__main__":
main()
</code></pre>
<p>Here's a sample config file you can use (with the --config option) to run the program (I'll call this <strong>lotto.conf</strong>):</p>
<pre><code># Stores config info for the lotto simulation program.
[GameType]
min_number = 1
max_number = 49
how_many_numbers = 7
how_many_bonus = 1
how_many_hand_picked_lines = 1
how_many_quick_pick_lines = 2
cost_per_ticket = 5
quick_pick_pool_size = 10000
how_many_tickets_bought = 20
[Prizes]
# prizes = {(numbers matched, bonus matched) : $$ won, ...}
prizes = {(3, 0) : '3', (3, 1) : '3+1', (4, 0) : '4', (5, 0) : '5', (6, 0) : '6', (6, 1) : '6+1', (7, 0) : '7'}
# -1 means Free Ticket.
prize_amounts = {'3' : -1, '3+1' : 20, '4' : 20, '5' : 134, '6' : 6145, '6+1' : 325676, '7' : 15000000}
</code></pre>
<p>and a sample tickets file you can use (with the --tickets option), I'll call this <strong>tickets.conf</strong>:</p>
<pre><code>[AllTicketGroups]
all_groups = 7, 13
[7]
1 = 1, 2, 3, 4, 5, 6, 7
2 = 8, 9, 10, 11, 12, 13, 14
3 = 15, 16, 17, 18, 19, 20, 21
4 = 22, 23, 24, 25, 26, 27, 28
5 = 29, 30 ,31, 32, 33, 34, 35
6 = 36, 37, 38, 39, 40, 41, 42
7 = 43, 44, 45, 46, 47, 48, 49
[13]
1 = 1, 2, 3, 4, 5, 6, 7
2 = 8, 9, 10, 11, 12, 13, 14
3 = 15, 16, 17, 18, 19, 20, 21
4 = 22, 23, 24, 25, 26, 27, 28
5 = 29, 30 ,31, 32, 33, 34, 35
6 = 36, 37, 38, 39, 40, 41, 42
7 = 43, 44, 45, 46, 47, 48, 49
8 = 1, 3, 5, 7, 9, 11, 13
9 = 2, 4, 6, 8, 10, 12, 14
10 = 15, 17, 19, 21, 23, 25, 27
11 = 16, 18, 20, 22, 24, 26, 28
12 = 29, 31, 33, 35, 37, 39, 41
13 = 30, 32, 34, 36, 38, 40, 42
</code></pre>
<p>To generate a <strong>winning_numbers.csv</strong> file (to be used with the --winning-numbers option) edit the lotto.conf file and simply change the how_many_hand_picked_lines to equal 8 instead of 7 and set quick_pick_pool_size to the number of winning number lines you want to generate, then run:</p>
<blockquote>
<p>./lotto.py --config lotto.conf --output winning_numbers.csv</p>
</blockquote>
<p>Then to run the simulation, undo your changes to lotto.conf and run:
<strong>./lotto.py -c lotto.conf -t tickets.conf -w winning_numbers.csv</strong></p>
<p>But to make tests repeatable, I also added the ability to include a pre-generated set of Quick Picks in a file (which you can use on the command above with the -q option).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T06:20:05.973",
"Id": "6118",
"Score": "1",
"body": "Did not know you could leak in python (but then I am not that good at python). Would be interested in the bug you did fix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T16:39:46.853",
"Id": "6150",
"Score": "0",
"body": "@Martin, you can leak in any garbage collected language. GC languages just free objects which it is no longer possible to access. You can keep those objects around by having a reference to them such as in a list or dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T16:40:41.753",
"Id": "6151",
"Score": "0",
"body": "@Chris, how do you know you have a memory leak?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T17:33:52.963",
"Id": "6153",
"Score": "0",
"body": "@Winston Ewert: If they are in a list or a dictionary then they are not technically leaked (I would assume that if you got rid of the container the contained objects would eventually also be GC). Yes I understand that a loop of object with no external objects can potentially be leaked by a GC but I would hope that most modern GC could handle this situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T17:48:16.640",
"Id": "6155",
"Score": "0",
"body": "@Martin, the point is that objects can be kept in memory longer then you intended because you accidentally kept them referenced when you didn't mean to. These are called memory leaks even though in some sense, the memory isn't lost because its still accessible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T17:49:24.833",
"Id": "6156",
"Score": "0",
"body": "@Winston Ewert: OK That makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T21:37:52.580",
"Id": "6164",
"Score": "0",
"body": "You can't leak in the true sense in a managed language, but the result is of course the same; memory usage grows and the program cannot account for that as it stands."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T23:39:51.023",
"Id": "6168",
"Score": "0",
"body": "@Ed not completely true, unsafe blocks in C# can leak memory or many other things I'm sure, but I think in an interpreted language the script cannot leak memory- only the interpreter may, which python's probably does not. So I would agree I don't believe there could be a memory leak in python outside of a bug in the interpreter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T12:57:31.770",
"Id": "6188",
"Score": "0",
"body": "@Martin: Originally I loaded the entire Winning-numbers.csv file into memory; but when I tried it with a 300,000 line file, it filled up all my RAM and Page File, so I changed it to only load 1000 lines at a time. The thing I forgot to do was to set 'lines = []' after each iteration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T13:00:08.083",
"Id": "6189",
"Score": "0",
"body": "@Winston Ewert: I know I have a memory leak because when I watch the memory in the System Monitor while I'm running against a large dataset (300,000 winning number lines), my memory keeps going up. I had to increase my Virtual Machine's memory to 1.5GB to be able to run on a dataset that large."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T15:53:33.253",
"Id": "6194",
"Score": "0",
"body": "For tracing memory leaks have a look at: http://mg.pov.lt/objgraph/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-01T07:39:17.353",
"Id": "160282",
"Score": "0",
"body": "Use python conventions when writing python code. `g_*` `TicketNumbers( object ):` depict global by using SCREAMING_SNAKE_CASE and avoid using spaces like that inside parenthesis."
}
] |
[
{
"body": "<pre><code>#!/usr/bin/python\n\nimport random, ConfigParser, ast, copy\nfrom optparse import OptionParser\n\n# Global variables.\ng_config = {} # Stores GameType config options.\ng_prizes = {} # Stores prizes from config file.\ng_prize_amounts = {} # Stores prize amounts from config file.\ng_ticket_quick_picks = [] # Store an array of QuickPicks to use for tickets.\ng_total_money_won = 0\ng_total_tickets_won = 0\ng_prizes_won = {} # Format: {'3':3, '3+1':2, '4':2 ...}\ng_quick_pick_file = ''\ng_how_many_tickets_played = 0\ng_how_many_tickets_won = 0\n</code></pre>\n\n<p>In Python, it is recommended not have global variables. I usually only put constants at the global level, and according to python style guide they should be written WITH_ALL_CAPS. I'd move all of this data into some sort of object.</p>\n\n<pre><code>class TicketNumbers( object ):\n '''Represents the numbers of a ticket (or the 7 winning numbers).\n @var numbers: A sorted array of 7 unique numbers from 1-49.'''\n</code></pre>\n\n<p>Considering the fact that you later sort the number, why do specify that it should be sorted on input?</p>\n\n<pre><code> def __init__( self, numbers ):\n '''Constructor.\n @param numbers: The numbers for this ticket.'''\n\n self.numbers = numbers\n</code></pre>\n\n<p>You assign to numbers here, but _set_numbers also assigns to it. This one is pointless.</p>\n\n<pre><code> self._set_numbers( numbers )\n\n def name( self ):\n '''Return the name of this class type.'''\n return \"TicketNumbers\"\n</code></pre>\n\n<p>What's the point of this? If you want the name of the class use <code>obj.__class__.__name__</code></p>\n\n<pre><code> def __str__( self ):\n '''Returns a string of the number list.'''\n str_nums = []\n for i in range( len( self.numbers ) ):\n</code></pre>\n\n<p>There is almost never a need to use the range( len( container pattern. Just iterate over the numbers directly.</p>\n\n<pre><code> str_nums.append( str( self.numbers[i] ) )\n</code></pre>\n\n<p>There are a number of ways of writing this loop more simply:</p>\n\n<pre><code>str_nums = [str(number) for number in self.numbers]\nstr_nums = map(str, self.numbers)\n\n return ', '.join( str_nums )\n</code></pre>\n\n<p>Actually, the entire function can be written as:</p>\n\n<pre><code>return ', '.join(str(number) for number in self.numbers)\n\n\n def _set_numbers( self, numbers ):\n '''Sets the numbers member variable and validates the numbers.\n @param numbers: The numbers to assign.'''\n\n global g_config\n self.numbers = sorted( numbers )\n\n if len( self.numbers ) != int(g_config['how_many_numbers']):\n raise Exception( \"You must have %d numbers, but found %d numbers: %s\" % (g_config['how_many_numbers'], len( self.numbers ), str(self.numbers)) )\n</code></pre>\n\n<p>If you are validating user input, I suggest create a custom exception class. You should then catch this custom class and print just the error message instead of having python's default. Your error message should also give a better indication of where the numbers are from.</p>\n\n<pre><code> tmp = []\n</code></pre>\n\n<p>tmp is a terrible variable name, because all local variables are temporary.</p>\n\n<pre><code> for num in self.numbers:\n # Check if numbers are in range.\n if ( num < int(g_config['min_number']) ) or ( num > int(g_config['max_number']) ):\n</code></pre>\n\n<p>I recommend pulling configuration data into the correct types inside your configuration logic not in the rest of your code.</p>\n\n<pre><code> raise Exception( \"The numbers must be between %d & %d!\" % (int(g_config['min_number']), int(g_config['max_number'])) )\n # Check for duplicate numbers.\n if num in tmp:\n raise Exception( \"You cannot have duplicate numbers! %d in %s\" % (num, str( self.numbers )) )\n tmp.append( num )\n</code></pre>\n\n<p>I suggest splitting these check out into three seperate bits:</p>\n\n<pre><code>if min(self.numbers) < config.min_number:\n raise UserError(\"Too low!\")\nif max(self.numbers) > config.max_number:\n raise UserError(\"Too high!\")\nif len(set(self.numbers)) != len(self.numbers):\n raise UserError(\"duplicates!\")\n\n\nclass PlayedTicket( TicketNumbers ):\n '''Represents a ticket that was played.\n @var amount_won: How much $$ this ticket won.'''\n</code></pre>\n\n<p>A ticket isn't a special kind of TicketNumbers. The names suggest that a ticket should contain numbers.</p>\n\n<pre><code> def __init__( self, numbers ):\n '''Constructor.\n @param numbers: The numbers for this ticket.'''\n\n super( PlayedTicket, self ).__init__( numbers )\n self.amount_won = {} # Map of Game Index to $$ won each play.\n self.tickets_won = {} # Map of Game Index to Free Tickets won each play.\n\n def name( self ):\n '''Return the name of this class type.'''\n return \"PlayedTicket\"\n\n def compare_with( self, winning_numbers, game_index=None ):\n '''Compares this ticket with the specified winning numbers and sets the amount_won & tickets_won members accordingly.\n @param winning_numbers: The winning numbers to compare against.\n @param game_index: (optional) The game index for this game. Defaults to 1 + the number of games recorded.\n @return: A tuple of ($$ won, # free tickets won).'''\n</code></pre>\n\n<p>The name compare_with doesn't suggest that this method will modify the object's state. I suggest picking a number that will.</p>\n\n<pre><code> global g_config, g_prizes, g_prize_amounts, g_prizes_won, g_how_many_tickets_won\n nums_correct = 0\n bonus_correct = 0\n amount_won = 0\n tickets_won = 0\n\n if game_index == None:\n game_index = len( self.amount_won )\n\n # Check each individual number of the ticket against the winning numbers.\n for num in self.numbers:\n if num in winning_numbers.numbers:\n nums_correct = nums_correct + 1\n elif num in winning_numbers.bonus_numbers:\n bonus_correct = bonus_correct + 1\n</code></pre>\n\n<p>The numbers really function as sets not lists. That is, you can't have duplicates and the order doesn't matter. I suggest you change from using lists to using sets. Then you can just find the intersection of the ticket numbers and the winning number rather then needing a counting loop.</p>\n\n<pre><code> # Now see if we won anything.\n for (key, value) in g_prizes.items():\n main_nums = key[0]\n bonus_nums = key[1]\n</code></pre>\n\n<p>Use\n main_nums, bonus_nums = key</p>\n\n<pre><code> if (main_nums == nums_correct) and ((bonus_nums == bonus_correct) or (bonus_nums == 0)):\n</code></pre>\n\n<p>A dictionary is designed to enable fast lookup. You shouldn't be iterating over it. You should use:</p>\n\n<pre><code> value = g_prizes[(nums_correct, bonus_correct)]\n</code></pre>\n\n<p>To directly fetch the value for the prize you've won. </p>\n\n<pre><code> if not g_prizes_won.has_key( value ):\n g_prizes_won[value] = 0\n</code></pre>\n\n<p>Make g_prizes_won a <code>collections.defaultdict(int)</code> object. Then it will automatically act as though all unset values are zero and this piece of code will be unnecessary.</p>\n\n<pre><code> g_how_many_tickets_won = g_how_many_tickets_won + 1\n g_prizes_won[value] = g_prizes_won[value] + 1 # Increment map of how many times each prize won. \n</code></pre>\n\n<p>If you break those global variables into an object as I suggest, then a bunch of this should live in a method on that object.</p>\n\n<pre><code> # We won. Now figure out what we won.\n if g_prize_amounts[value] > amount_won:\n amount_won = g_prize_amounts[value]\n tickets_won = 0\n elif g_prize_amounts[value] == -1:\n amount_won = 0\n tickets_won = 1\n</code></pre>\n\n<p>You are picking the best prize of all the ones you qualify for. However, as mentioned before you should be able to directly fetch exactly the prize you are supposed to get without looping. So there is no need to get the best prize of the ones you've considered. </p>\n\n<pre><code> if amount_won or tickets_won:\n if g_config['verbose']:\n print( \"Ticket %s won: $%d & %d Free tickets.\" % (str(self.numbers), amount_won, tickets_won) )\n\n # Set and return the amount won.\n self.amount_won[game_index] = amount_won\n self.tickets_won[game_index] = tickets_won\n return (amount_won, tickets_won)\n\n\nclass QuickPick( PlayedTicket ):\n '''Represents a Quick Pick ticket.'''\n\n def __init__( self, numbers ):\n '''Constructor.\n @param numbers: The numbers for this ticket.'''\n\n super( QuickPick, self ).__init__( numbers )\n self.amount_won = {} # Map of Game Index to $$ won each play.\n self.tickets_won = {} # Map of Game Index to Free Tickets won each play.\n</code></pre>\n\n<p>The subclass already creates these, why are you creating them again </p>\n\n<pre><code> def name( self ):\n '''Return the name of this class type.'''\n return \"QuickPick\"\n</code></pre>\n\n<p>This class didn't do anything. </p>\n\n<pre><code>class WinningNumbers( TicketNumbers ):\n '''Represents the winning numbers + bonus number.\n @var bonus_numbers: The bonus numbers.'''\n\n def __init__( self, numbers, bonus_numbers=None ):\n '''Constructor.\n @param numbers: The winning numbers.\n @param bonus_numbers: (optional) The bonus number(s). Defaults to empty list.'''\n\n global g_config\n bonus_numbers = bonus_numbers or []\n super( WinningNumbers, self ).__init__( numbers )\n self.bonus_numbers = []\n if bonus_numbers:\n self.bonus_numbers = sorted( bonus_numbers )\n</code></pre>\n\n<p>There is no need to check if bonus_numbers is empty, just let it assign the empty sorted list.</p>\n\n<pre><code> tmp = []\n\n if len( bonus_numbers ) != int(g_config['how_many_bonus']):\n raise Exception( \"You must have %d bonus numbers!\" % int(g_config['how_many_bonus']) )\n\n for num in bonus_numbers:\n if (num in tmp) or (num in self.numbers):\n raise Exception( \"You cannot have duplicate numbers!\" )\n tmp.append( num )\n\n def __str__( self ):\n '''Converts this class into a string.'''\n ret = super( WinningNumbers, self ).__str__()\n\n str_bnums = []\n\n if len( self.bonus_numbers ):\n for i in range( len( self.bonus_numbers ) ):\n str_bnums.append( str( self.bonus_numbers[i] ) )\n\n ret = ret + ' + ' + ', '.join( str_bnums )\n\n return ret\n\n\n def name( self ):\n '''Return the name of this class type.'''\n return \"WinningNumbers\"\n\n\ndef load_config( filename ):\n '''Reads the config file to load program defaults.\n @param filename: The filename of the config file.\n @return: A ConfigParser object containing the parsed config file.'''\n\n # Read the config file into the parser.\n global g_config, g_prizes, g_prize_amounts\n conf = ConfigParser.SafeConfigParser()\n conf.read( filename )\n\n if (not conf.has_section( 'GameType' )) or (not conf.has_section( 'Prizes' )):\n</code></pre>\n\n<p>Too many parantehsis, use:</p>\n\n<pre><code> if not conf.has_section( 'GameType' ) or not conf.has_section( 'Prizes' ):\n\n raise Exception( \"Invalid config file! [GameType] and/or [Prizes] sections are missing!\" )\n\n options = ['min_number', 'max_number', 'how_many_numbers', 'how_many_bonus', 'how_many_hand_picked_lines', 'how_many_quick_pick_lines', 'cost_per_ticket', 'quick_pick_pool_size', 'how_many_tickets_bought']\n\n for option in options:\n if not conf.has_option( 'GameType', option ):\n raise Exception( \"Invalid config file! '%s' option is missing!\" % option )\n\n g_config[option] = int( conf.get( 'GameType', option ) )\n\n # Prizes section contains maps.\n g_prizes = ast.literal_eval( conf.get( 'Prizes', 'prizes' ) )\n g_prize_amounts = ast.literal_eval( conf.get( 'Prizes', 'prize_amounts' ) )\n</code></pre>\n\n<p>(Rest of code skipped.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T13:05:38.980",
"Id": "6190",
"Score": "0",
"body": "Wow, thanks Winston! I'll take a closer look at your suggestions when I get home and try them out. For some of your questions like the code comments... They're probably a little out of date, since the code changed a lot since my original version.\nEx. in the __init__() function I set self.numbers = numbers then later I added the _set_numbers() function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T03:59:08.400",
"Id": "6366",
"Score": "0",
"body": "I made some of the changes you suggested, and after looking into the compare_with() function (because of your \"The name compare_with doesn't suggest that this method will modify the object's state.\" comment) I found my memory leak. I was storing a huge amount of data in the self.amount_won and self.tickets_won member variables, and then never using them, so I just removed them. Now my program's memory and speed are constant. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T16:37:39.057",
"Id": "4125",
"ParentId": "4098",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "4125",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T03:07:49.667",
"Id": "4098",
"Score": "3",
"Tags": [
"python",
"memory-management",
"simulation"
],
"Title": "Memory leaks in lottery simulator"
}
|
4098
|
<p>I'm working on a small winforms app, the goal of which is to capture data and write to xml. I'm still a child where programming is concerned so could you guys please take a look and suggest changes as I'm pretty sure that this is not a good approach.
I'm using a masked-textbox for the invoice number which should only contain numbers. I'm trying not to use a <code>numupdown</code> for obvious reasons.</p>
<p>InputVars is a public class with empty string properties (<code>string value {get;set;}</code>)</p>
<pre><code> private bool TestVal(string testedVal)
{
if (!String.IsNullOrEmpty(testedVal))
{
return true;
}
else
{
return false;
}
}
private InputVars SetSemVars()
{
InputVars inVars = new InputVars();
if (TestVal(txtCapt.Text))
{
inVars.captured = txtCapt.Text;
}
else
{
MessageBox.Show("Please insert your name here");
txtCapt.Focus();
}
if (TestVal(mtxtInvoiceNumber.Text))
{
inVars.invoice = mtxtInvoiceNumber.Text;
}
else
{
MessageBox.Show("Please insert the invoice number here");
mtxtInvoiceNumber.Focus();
}
if(TestVal(cmbNetwork.SelectedIndex.ToString()))
{
inVars.network = cmbNetwork.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please select the network ");
cmbNetwork.Focus();
}
if(TestVal(cmbRegion.SelectedIndex.ToString()))
{
inVars.region = cmbRegion.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please select your office code here");
cmbRegion.Focus();
}
if(TestVal(cmbSupplier.SelectedIndex.ToString()))
{
inVars.supplier = cmbRegion.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please select the supplier here");
cmbSupplier.Focus();
}
return inVars;
}
</code></pre>
<p>I was playing around earlier and got this to work , just thought I'd share</p>
<pre><code> foreach (TextBox box in this.panel1.Controls.OfType<TextBox>())
{
if (String.IsNullOrWhiteSpace(box.Text))
{
box.Text = "Enter value here";
//or do a messagebox etc.
box.Focus();
return;
}
}
</code></pre>
<p>that`s loads and loads shorter and easier to read and makes sure that I don't forget a value... me gusta</p>
|
[] |
[
{
"body": "<ol>\n<li>Don't use String.IsNullOrEmpty to validate required values.</li>\n<li><p>You can create a method</p>\n\n<pre><code>private bool IsEmpty(string value, string errorMessage, Control controlToValidate)\n{\n if ((value ?? string.Empty).Trim().Length == 0)\n {\n MessageBox.Show(errorMessage);\n controlToValidate.Focus();\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<p>instead of TestVal.</p></li>\n<li>Consider using <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx\" rel=\"nofollow\">Validating event</a> for validating your controls and the <a href=\"http://www.dotnetperls.com/tag\" rel=\"nofollow\">Tag</a> property to associate error messages with the controls.</li>\n<li>Consider using <a href=\"http://www.codeproject.com/KB/dotnet/errorprovider.aspx\" rel=\"nofollow\">ErrorProviders</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:40:47.580",
"Id": "6122",
"Score": "0",
"body": "any specific reason for not using IsNullOrEmpty? I kinda figured that that's what it's for"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:52:58.607",
"Id": "6123",
"Score": "0",
"body": "IsNullOrEmpty will return false for a string containing only blank spaces. In general, a blank space is not a valid value for a reqired field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:27:52.927",
"Id": "6124",
"Score": "1",
"body": "how about using isNullOrWhiteSpace though? That gets around the blank space issue doesn't it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:39:44.083",
"Id": "6127",
"Score": "2",
"body": "@dreza: Yes, if it is a .Net 4 project then IsNullOrWhiteSpace is definitely the right solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T10:38:52.550",
"Id": "6271",
"Score": "0",
"body": "I kinda dislike the fact that a method named `IsEmpty` has to wait for a message box to be dismissed before returning the result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T11:05:28.397",
"Id": "6272",
"Score": "0",
"body": "@Sorin Comanescu: I don't like it either. But the method 'SetSemVars' is built this way and 'IsEmpty' is just a way to move some duplicate logic from it into one place. It's a way to improve the existing code. The better solution would be to rewrite it completely using event handlers (Validating or XXXChanged)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:19:07.787",
"Id": "4105",
"ParentId": "4101",
"Score": "3"
}
},
{
"body": "<p>Your testval method is completely unnecessary, just do your validation right in the method. I would create an eventhandler for each type of control's onchanged event, then you'd have one for combo boxes and one for text boxes. Have each control's tag property hold the invalid message for it to be displayed. Just set all text and combo boxes you want to validate for non-null/whitespace to have the same event handler to avoid code duplication.</p>\n\n<p>Something like so:</p>\n\n<pre><code>private void OnTextChanged(object sender, EventArgs e)\n{\n TextBox textBoxToValidate = sender as TextBox;\n if (string.IsNullOrWhiteSpace(textBoxTovalidate.Text))\n {\n MessageBox.Show(textBoxToValidate.Tag.ToString());\n textBoxToValidate.Focus();\n }\n}\n\nprivate void OnSelectedIndexChanged(object sender, EventArgs e)\n{\n ComboBox comboBoxToValidate = sender as ComboBox;\n if (string.IsNullOrWhiteSpace(comboBoxTovalidate.SelectedIndex.ToString()))\n {\n MessageBox.Show(comboBoxToValidate.Tag.ToString());\n comboBoxToValidate.Focus();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:18:40.527",
"Id": "6141",
"Score": "0",
"body": "I'll give it a shot but I'm pretty noobish"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T14:32:40.463",
"Id": "6143",
"Score": "0",
"body": "@Dani Just use the properties window in visual studio, select the control and scroll through properties to find the Tag property which you will put your error text in, and the SelectedIndexChanged event which you will put \"OnSelectedIndexChanged\" or whatever you name your event handler into and same for the text box, you just put the name of the method which has this signature `public void MethodName(object sender, EventArgs e)` into the event in the Properties window."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T10:15:09.707",
"Id": "6186",
"Score": "0",
"body": "I'll definitely try it out"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T12:53:54.057",
"Id": "4112",
"ParentId": "4101",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T08:15:54.273",
"Id": "4101",
"Score": "4",
"Tags": [
"c#",
"winforms"
],
"Title": "Is this validation sufficient to ensure that the vals are not empty?"
}
|
4101
|
<p>Not long ago I tried to get a game developer job (casual games). There was a task to write a simple game like this <a href="http://chainrxn.zwigglers.com/" rel="nofollow">one</a>. I was supposed to use an existing game engine (given in the task) and only create a game logic. After writing the solution I got the answer that my code has a bad style and not accepted for the review.</p>
<p><strong>BubbleGame.h</strong></p>
<pre><code>#ifndef __BUBBLEGAME_H__
#define __BUBBLEGAME_H__
using namespace std;
using namespace Render;
class Bubble
{
friend class BubbleGame;
typedef void (*pfnBubbleUpdate)(Bubble *bubble, float elapsedTime);
private:
FPoint m_velocity;
FPoint m_position;
Color m_color;
float m_workTime;
float m_radius;
bool m_isAlive;
bool m_isExploded;
pfnBubbleUpdate m_pfnBubbleUpdate;
ParticleEffect *m_particleTrail;
protected:
void PreventOutbound(float elapsedTime);
public:
static FRect Bound;
static float BornTime;
static float LiveTime;
static float FadeTime;
static float StartRadius;
static float DiffRadius;
static EffectsContainer Effects;
static void FinishAllEffects();
static bool IsIntersect(const Bubble *left, const Bubble *right);
static void FreeBubbleUpdate(Bubble *bubble, float elapsedTime);
static void BornBubbleUpdate(Bubble *bubble, float elapsedTime);
static void LiveBubbleUpdate(Bubble *bubble, float elapsedTime);
static void FadeBubbleUpdate(Bubble *bubble, float elapsedTime);
void Update(float elapsedTime);
void Reset();
bool IsAlive() const { return m_isAlive; }
bool IsExploded() const { return m_isExploded; }
void Explode();
};
class BubbleGame
{
private:
BubbleGame() { /* Never used */ };
BubbleGame(const BubbleGame& bubbleGame) { /* Never used */ };
vector<Bubble> m_bubbles;
vector<int> m_explodedIndices;
vector<int> m_freeIndicies;
Texture *m_bubbleTexture;
bool m_isActive;
int m_pointCount;
protected:
void Initialize();
void CheckInteractions(int explodedBubbleIndex);
void CheckInteractions();
void RemoveDeadBubblesIndices();
public:
BubbleGame(int pointCount, float bornTime, float liveTime, const FRect *bound);
~BubbleGame();
void Trigger(const IPoint& position);
void Update(float elapsedTime);
void Draw();
};
#endif // __BUBBLEGAME_H__
</code></pre>
<p><strong>BubbleGame.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include "BubbleGame.h"
FRect Bubble::Bound;
float Bubble::BornTime;
float Bubble::LiveTime;
float Bubble::FadeTime;
float Bubble::StartRadius;
float Bubble::DiffRadius;
EffectsContainer Bubble::Effects;
void Bubble::FinishAllEffects()
{
Bubble::Effects.Finish();
}
bool Bubble::IsIntersect(const Bubble *left, const Bubble *right)
{
float xDistance = abs(left->m_position.x - right->m_position.x);
float yDistance = abs(left->m_position.y - right->m_position.y);
float distance = sqrt(xDistance * xDistance + yDistance * yDistance);
float explodeDistance = left->m_radius + right->m_radius;
if (distance <= explodeDistance)
{
return true;
}
else
{
return false;
}
}
void Bubble::FreeBubbleUpdate(Bubble *bubble, float elapsedTime)
{
bubble->m_position.x += bubble->m_velocity.x * elapsedTime;
bubble->m_position.y += bubble->m_velocity.y * elapsedTime;
bubble->PreventOutbound(elapsedTime);
bubble->m_particleTrail->posX = bubble->m_position.x;
bubble->m_particleTrail->posY = bubble->m_position.y;
}
void Bubble::BornBubbleUpdate(Bubble *bubble, float elapsedTime)
{
bubble->m_workTime += elapsedTime;
if (bubble->m_workTime > Bubble::BornTime)
{
bubble->m_workTime = 0;
bubble->m_pfnBubbleUpdate = Bubble::LiveBubbleUpdate;
}
else
{
bubble->m_radius = (bubble->m_workTime / Bubble::BornTime) * Bubble::DiffRadius + Bubble::StartRadius;
}
}
void Bubble::LiveBubbleUpdate(Bubble *bubble, float elapsedTime)
{
bubble->m_workTime += elapsedTime;
if (bubble->m_workTime > Bubble::LiveTime)
{
bubble->m_workTime = 0;
bubble->m_pfnBubbleUpdate = Bubble::FadeBubbleUpdate;
}
}
void Bubble::FadeBubbleUpdate(Bubble *bubble, float elapsedTime)
{
bubble->m_workTime += elapsedTime;
if (bubble->m_workTime > Bubble::FadeTime)
{
bubble->m_workTime = 0;
bubble->m_isAlive = false;
bubble->m_pfnBubbleUpdate = NULL;
}
else
{
float progress = (1.0f - bubble->m_workTime / Bubble::BornTime);
bubble->m_radius = progress * (Bubble::DiffRadius + Bubble::StartRadius);
bubble->m_color.alpha = (unsigned char)(255 * progress);
}
}
void Bubble::PreventOutbound(float elapsedTime)
{
bool makeStep = false;
if (m_position.x < Bubble::Bound.xStart ||
m_position.x > Bubble::Bound.xEnd)
{
m_velocity.x = -m_velocity.x;
makeStep = true;
}
if (m_position.y < Bubble::Bound.yStart ||
m_position.y > Bubble::Bound.yEnd)
{
m_velocity.y = -m_velocity.y;
makeStep = true;
}
if (makeStep)
{
m_position.x += m_velocity.x * elapsedTime;
m_position.y += m_velocity.y * elapsedTime;
}
}
void Bubble::Update(float elapsedTime)
{
if (m_isAlive)
{
m_pfnBubbleUpdate(this, elapsedTime);
}
}
void Bubble::Reset()
{
m_velocity.x = Random(20.0f, 100.0f);
m_velocity.y = Random(20.0f, 100.0f);
m_velocity = m_velocity.Rotate(Random(0.0f, 2.0f * math::PI));
m_position.x = Random(Bubble::Bound.xStart, Bubble::Bound.xEnd);
m_position.y = Random(Bubble::Bound.yStart, Bubble::Bound.yEnd);
m_color.red = Random(255);
m_color.green = Random(255);
m_color.blue = Random(255);
m_color.alpha = 255;
m_workTime = 0.0f;
m_radius = Bubble::StartRadius;
m_isAlive = true;
m_isExploded = false;
m_pfnBubbleUpdate = Bubble::FreeBubbleUpdate;
m_particleTrail = Bubble::Effects.AddEffect("Trail");
m_particleTrail->posX = m_position.x;
m_particleTrail->posY = m_position.y;
m_particleTrail->Reset();
}
void Bubble::Explode()
{
m_isExploded = true;
m_particleTrail->Finish();
m_pfnBubbleUpdate = Bubble::BornBubbleUpdate;
ParticleEffect *effect = Bubble::Effects.AddEffect("Explode");
effect->posX = m_position.x;
effect->posY = m_position.y;
effect->Reset();
}
void BubbleGame::Initialize()
{
Bubble::FinishAllEffects();
m_bubbles.resize(m_pointCount);
m_explodedIndices.clear();
m_freeIndicies.clear();
for (int i = 0; i < (int)m_bubbles.size(); i++)
{
m_bubbles[i].Reset();
m_freeIndicies.push_back(i);
}
}
void BubbleGame::CheckInteractions(int explodedBubbleIndex)
{
vector<int>::iterator item = m_freeIndicies.begin();
while (item != m_freeIndicies.end())
{
if (Bubble::IsIntersect(&m_bubbles[*item], &m_bubbles[explodedBubbleIndex]))
{
m_bubbles[*item].Explode();
m_explodedIndices.push_back(*item);
item = m_freeIndicies.erase(item);
}
else
{
item++;
}
}
}
void BubbleGame::CheckInteractions()
{
vector<int>::iterator item = m_explodedIndices.begin();
while (item != m_explodedIndices.end())
{
CheckInteractions(*item);
item++;
}
}
void BubbleGame::RemoveDeadBubblesIndices()
{
vector<int>::iterator item = m_explodedIndices.begin();
while (item != m_explodedIndices.end())
{
if (!m_bubbles[*item].IsAlive())
{
item = m_explodedIndices.erase(item);
}
else
{
item++;
}
}
if (m_explodedIndices.size() == 0)
{
m_isActive = false;
Initialize();
}
}
BubbleGame::BubbleGame(int pointCount, float bornTime, float liveTime, const FRect *bound)
{
Bubble::Bound = *bound;
Bubble::BornTime = bornTime;
Bubble::FadeTime = bornTime;
Bubble::LiveTime = liveTime;
Bubble::StartRadius = 4.0f;
Bubble::DiffRadius = 20.0f;
m_pointCount = pointCount;
m_isActive = false;
m_bubbles = vector<Bubble>(pointCount);
m_bubbleTexture = Core::resourceManager.getTexture("Circle");
m_explodedIndices.reserve(pointCount + 1);
m_freeIndicies.reserve(pointCount + 1);
Initialize();
}
BubbleGame::~BubbleGame()
{
delete m_bubbleTexture; m_bubbleTexture = NULL;
}
void BubbleGame::Trigger(const IPoint &position)
{
if (!m_isActive)
{
m_isActive = true;
Bubble explodedBubble;
explodedBubble.Reset();
explodedBubble.m_position.x = (float)position.x + Bubble::DiffRadius;
explodedBubble.m_position.y = (float)position.y - Bubble::DiffRadius;
explodedBubble.Explode();
m_bubbles.push_back(explodedBubble);
m_explodedIndices.push_back((int)(m_bubbles.size() - 1));
}
}
void BubbleGame::Update(float elapsedTime)
{
for (int i = 0; i < (int)m_bubbles.size(); i++)
{
m_bubbles[i].Update(elapsedTime);
}
if (m_isActive)
{
CheckInteractions();
RemoveDeadBubblesIndices();
}
}
void BubbleGame::Draw()
{
Bubble::Effects.Draw();
m_bubbleTexture->Bind();
for (int i = 0; i < (int)m_bubbles.size(); i++)
{
if (m_bubbles[i].IsAlive())
{
Render::device.SetCurrentColor(m_bubbles[i].m_color);
Render::DrawRect(
(int)(m_bubbles[i].m_position.x - m_bubbles[i].m_radius),
(int)(m_bubbles[i].m_position.y - m_bubbles[i].m_radius),
(int)(m_bubbles[i].m_radius * 2.0f),
(int)(m_bubbles[i].m_radius * 2.0f));
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T12:28:27.730",
"Id": "6129",
"Score": "0",
"body": "I'm a C# dev and not familiar with C++ standard practices, but to me I'm thinking the 'style' is probably not the issue as it all appears clean and consistent. They probably had more issue with the design structure and you maybe did non-standard/unnecessary/dangerous things unknowingly (such as I would if I tried writing C++). Though maybe it's good style in C++ (I wouldn't know), I know the m_ will get you flogged outside of C++ for certain."
}
] |
[
{
"body": "<p>Two underscores reserved for compilers, so it is bad header guard: <code>#ifndef __BUBBLEGAME_H__</code></p>\n\n<p>Using <code>using namespace ...</code> directive in header is not recommended, you may use it in source file.</p>\n\n<p>Very much static variables, but i cant see, that you really need all these variables as static. You may create else one class (BubbleConfig, or smth like this) for bubble configuration and pass it to Bubble.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T12:20:54.293",
"Id": "4107",
"ParentId": "4102",
"Score": "1"
}
},
{
"body": "<p>You've forbid copying by closing copying constructor in private section, but what about </p>\n\n<blockquote>\n <p><code>const BubbleGame& operator=(const BubbleGame&)</code> ?</p>\n</blockquote>\n\n<p>It still allows to copy your BubbleGame object. Why is this bad? - You have a pointer to a texture here, which will be simply copied with the same address.</p>\n\n<p>The same is for the Bubble class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T12:51:59.837",
"Id": "4111",
"ParentId": "4102",
"Score": "0"
}
},
{
"body": "<p>I'll preface my review by saying: The grading of code style is very subjective.</p>\n\n<p>That said:</p>\n\n<ul>\n<li>You have a using namespace directive in your header file. Never do this.</li>\n<li>You have the <code>using namespace std;</code> directive in your header file. Never EVER do this.</li>\n<li>You have the access modifiers in the incorrect order, declare your access modifier sections in <code>public:</code>, <code>protected:</code>, then <code>private:</code>.</li>\n<li>Your public static member variables look like functions at a glance. Member variables should be declared with the first word in lowercase.</li>\n<li>You use a full if block to return <code>true</code> or <code>false</code>, just return the result of the expression: <code>return (x <= y)</code></li>\n<li>Your bracing style may not conform to company standards. Always check to see if your company has a code style document that must be followed.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T03:48:49.737",
"Id": "6173",
"Score": "0",
"body": "Thanks a lot. I never knew about the namespace directive issue in header files."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:26:30.937",
"Id": "4113",
"ParentId": "4102",
"Score": "4"
}
},
{
"body": "<p>\"Bad style\" can mean a lot of things, but the worst is, it is pretty subjective what is good and bad style. IMHO, unless they gave you some literature of what they consider \"good style\" by their policy, it was pretty unfair to disqualify you with such a reason. Furthermore, did they really mean code style or code design? There is a slight blur between the two at some places.</p>\n\n<p>Here are some things that you did but they <em>might</em> have not liked:</p>\n\n<ol>\n<li>Even though you only have two classes, you are already starting to play around with the 'friend' attribute. 'friend' is nice hack in a large project where a redesign is a no-go, but in a project of this scale people will wonder why you didn't just come up with a design that doesn't require 'friend'. After all, if you only have two classes and one has access to the private members of the other, why bother making them private at all?</li>\n<li>If you really want to go by The Book of OOP design, you should\nnot access member variables of other classes directly, but use\ngetter and setter methods instead. I often find this unnecessary and\nimpractical, but some just love it.</li>\n<li>You use static variables. Although they are mostly harmless with built-in type (eg. floats) as in your case, but more often than not, in complex projects and custom types you ARE going to run into hard-to-debug problems caused by static initialization order. I always design to avoid static variables, it simply saves a lot of headaches in the future.</li>\n<li>You have more than one class defined in the same header. Again, you can do it, but it is not considered \"clean\".</li>\n<li>It seems you have a Reset method on your bubbles, which you use to initialize them. You should probably call it from a constructor instead of relying on an external class to call Reset upon construction.</li>\n<li>Some also prefer initializer lists in constructors, since on large arrays of simple objects (like bubbles?) they can actually give you a better performance.</li>\n<li>What the others said are also true:\n<ol>\n<li>Prefixing member varibales with m_ is not to everybody's liking.\nSome do it simply with an underscore, some mark member variables by\ncasing differently, and some do not mark them at all.</li>\n<li>'using namespace' in a header is a bad idea, it will lead to name collisions and will mess up the auto-completion feature of IDEs.</li>\n<li>Avoid names reserved by the standard/compiler.</li>\n<li>If you want to prevent copying an objetc, you need to hide/rewrite both the copy constructor AND and the assignment operator. Only one will leave you prone to errors.</li>\n</ol></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T14:36:58.633",
"Id": "6145",
"Score": "1",
"body": "Few problems with the comments: Your concept of the friend is misguided [see here](http://programmers.stackexchange.com/questions/99589/what-is-friend-keyword-used-for/99595#99595). If you want to go by true OO Get/Set is bad design. It binds you public interface to an implementation. You r public interface should be actions that modify your object. If you are getting the members to do an action maybe that action should be part of the class. Not a good idea to use an underscore to prefix an identifier. Do you know what the next character can/can not be in a class context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T15:28:58.167",
"Id": "6147",
"Score": "0",
"body": "I agree on your concept of _ and getters/setters, I even said I am not a fan of the latter myself. I just wrote down what many others think. However, I do not think my concept of friend is misguided. I read the thread you linked to and it properly explains that it is to extend the public interface of existing classes. But if you are in charge of the class hierarchy design, you can design it so that you make the friend stuff actual part of the public interface. Most times this is possible. Since the original posted had this oppurtunity but didn't do so, I considered this a slight design error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T16:16:01.820",
"Id": "6148",
"Score": "1",
"body": "I agree with you characterization of the OP usage of friend as bad. I just think your `'friend' is nice hack in a large project` is an incorrect description of how friend should be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T04:06:22.457",
"Id": "6174",
"Score": "0",
"body": "Thanks for the excellent comments. Concerning some of your quotes: m_ is used in their sample code of engine and I decided to write my code in the same way. For me \"friend\" seems a nice solution for game development, where I want to give access only for inner classes, like the keyword \"internal\" in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T08:11:35.277",
"Id": "6181",
"Score": "0",
"body": "Just to clarify, 'internal' in C# is something completely different. It is used make methods/classes accessbile only to consumers in the same assembly. There is no such thing in C++, except for compiler-specific extensions for marking public/private interfaces in shared objects. 'friend' in C++ will make all members of the other class visible and will violate encapsulation and data hiding."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:30:32.860",
"Id": "4114",
"ParentId": "4102",
"Score": "6"
}
},
{
"body": "<p>Well. First of all look at your class <code>Bubble</code>. It includes logic (...Update methods) <strong>and</strong> presentation (Color, you hardcoded circle drawing) <strong>and</strong> metainfo (static variables). Mixing these things is bad because when you'll be asked for change Bubble to Diamond you'll have to change <strong>whole</strong> code, when you'll need to add even minor-little-tiny change you'll have to change <strong>loads</strong> of your code. You need to divide <code>Bubble</code> into several classes because it violates <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>. Also take a look at <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow\">Model-View-Controller</a></p>\n\n<p>No abstractions at all, only implementation. Code is hardly extensible.</p>\n\n<p><code>friend class BubbleGame;</code> Bad style because violates encapsulation. Nobody should even know what inside <code>Bubble</code>. It will be hard to find exact place <em>where <code>Bubble</code> object change it's state</em>.</p>\n\n<p><code>const</code> keyword not used at all. No const methods, no constant objects.</p>\n\n<p>Static variables. <code>using</code> in header file.</p>\n\n<p>Hmm, main violations described. So check out a \"Clean Code: A Handbook of Agile Software Craftsmanship\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:47:22.880",
"Id": "4116",
"ParentId": "4102",
"Score": "3"
}
},
{
"body": "<p>The whole deal with the m_pfnBubbleUpdate really has no place in a OOP design. Why do you want to replace class method in such way during run time? You should either make abstract Bubble class and derive different Bubble types from it, or use a single BubbleUpdate function doing different things depending on the Bubble's state.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T05:06:31.177",
"Id": "6175",
"Score": "0",
"body": "It isn't a nice way use a single method in this case. I will sink in many \"if\"s. I thought to define a method pointer, but a simple function pointer seems better in this task. And if you use too many OOP in game development your games will be suck because of performance issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T05:32:54.247",
"Id": "6176",
"Score": "1",
"body": "Well, you've got \"bad style\" answer so far, not a \"bad performance\" one. You don't usually use speed hacks in the job interview, code clarity and quality is much more important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T05:43:04.780",
"Id": "6177",
"Score": "0",
"body": "I think n-levels of if are even worse then to use function pointers. And I was given a game engine with not a good performance at all. It would be strange if I'd sent a low-performance solution and said them: \"You have a slow engine and I can't get a nice performance with your input data\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:26:06.120",
"Id": "6178",
"Score": "0",
"body": "What levels of if you are talking about? A simple switch statement would do just fine. My point is that performance means absolutely nothing if your code isn't even accepted for the review. As a side point, did you actually try to measure the real performance gain or you just think your solution is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:32:36.057",
"Id": "6179",
"Score": "0",
"body": "The first variant I made was with a single method where were many ifs. Then I made the variant that you can see above and after getting better performance I'd selected the second."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:51:38.397",
"Id": "4117",
"ParentId": "4102",
"Score": "0"
}
},
{
"body": "<p>The identifier __ BUBBLEGAME_H __ is reerved by the implementation in all contexts. The exact rules are complex <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">see here</a>. But shorthand never use double underscore never start an identifier with underscore (unless you know the exact rules and can remember them)</p>\n\n<p>Never put a using declaration in a header file:</p>\n\n<pre><code>using namespace std;\nusing namespace Render;\n</code></pre>\n\n<p>I prefer not to even put them in a source file. But absolutely never put them in the header file. Anybody that uses your header file is now pulling stuff into another namespace and they may nor realize this without reading the code.</p>\n\n<p>I don't think your usage of friend is very good. You are moving work from Bubble to Bubble Game that would be better encapsulated by the Bubble. In fact I think you can generalize Bubble with an interface so that other classes can be derived from the interface and still work with BubbleGame.</p>\n\n<p>Not sure why you have or need some many public static members.</p>\n\n<p>Why are you passing pointers here?</p>\n\n<pre><code>bool Bubble::IsIntersect(const Bubble *left, const Bubble *right)\n</code></pre>\n\n<p>Pass by const reference. You use pointers everywhere. Pointer are a big no-no as they can potentially be NULL (thus you should validate they are NULL).</p>\n\n<p>Use standard algorithms to help redability:</p>\n\n<pre><code>while (item != m_explodedIndices.end())\n{\n CheckInteractions(*item);\n item++;\n}\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code> std::for_each(m_explodedIndices.begin(), m_explodedIndices.end(), std::bind(CheckInteractions));\n</code></pre>\n\n<p>Manual resource management is a definite easy spot that this is not real C++ code (more loke C with classes). Learn to use RAII correctly. </p>\n\n<pre><code>delete m_bubbleTexture; m_bubbleTexture = NULL;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T14:31:44.817",
"Id": "4120",
"ParentId": "4102",
"Score": "7"
}
},
{
"body": "<p>For me the problem with your code is your use of</p>\n\n<pre><code>typedef void (*pfnBubbleUpdate)(Bubble *bubble, float elapsedTime);\n</code></pre>\n\n<p>and the associated functions:</p>\n\n<pre><code>static void XXXXBubbleUpdate(Bubble *bubble, float elapsedTime);\n</code></pre>\n\n<p>You should make them member functions, e.g.:</p>\n\n<pre><code>void Bubble::FreeBubbleUpdate(float elapsedTime)\n{\n m_position.x += m_velocity.x * elapsedTime;\n m_position.y += m_velocity.y * elapsedTime;\n PreventOutbound(elapsedTime);\n m_particleTrail->posX = m_position.x;\n m_particleTrail->posY = m_position.y;\n}\n</code></pre>\n\n<p>Instead of explicitly setting the pfn in your code, you should make the decision as to which function to call ONLY in your Update() function: I'd do it using a state member var, which makes debugging a lot easier:</p>\n\n<pre><code>enum BubbleState {\n BORN,\n ...\n NUM_STATES\n} m_state;\n</code></pre>\n\n<p>Now in Update() I'd use a switch to select the appropriate update member function:</p>\n\n<pre><code>switch (m_state) {\ncase BORN: BornBubbleUpdate(elapsedTime);\n...\n</code></pre>\n\n<p>or, if that led to performance issues, I'd make an array of pointers to member functions (see <a href=\"http://www.goingware.com/tips/member-pointers.html\" rel=\"nofollow\">http://www.goingware.com/tips/member-pointers.html</a>) and use the state's value as an index: </p>\n\n<pre><code>typedef void (Bubble::*UpdateFunc)(float elapsedTime);\nUpdateFunc m_UpdateFuncArray[NUM_STATES];\n...\n(*(m_UpdateFuncArray[m_state]))(elapsedTime);\n</code></pre>\n\n<p>The last example is almost like hand-coding run-time polymorphism -- a very similar thing goes on behind the scenes when you use RTTI.</p>\n\n<p>In a nutshell: There's nothing wrong with achieving polymorphism through function pointers, but you really ought to make them MEMBER function pointers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T11:13:14.170",
"Id": "4305",
"ParentId": "4102",
"Score": "1"
}
},
{
"body": "<p>A few tiny comments :</p>\n\n<p>In IsIntersect :</p>\n\n<ul>\n<li>You don't have to use abs for xDistance and yDistance as they will be squared before being used anyway.</li>\n<li>All the variables can be defined as const</li>\n<li>At the end, you can \"return (distance <= explodeDistance);\"</li>\n</ul>\n\n<p>In FadeBubbleUpdate :</p>\n\n<ul>\n<li>progress can be const</li>\n</ul>\n\n<p>And more generally :</p>\n\n<ul>\n<li>I LOVE this game!</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T18:08:28.377",
"Id": "7358",
"ParentId": "4102",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4114",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T08:54:28.393",
"Id": "4102",
"Score": "7",
"Tags": [
"c++",
"game"
],
"Title": "Simple chain reaction game"
}
|
4102
|
<p>How to write and design a simple (but still proper and secure) login class for PHP?</p>
<p>Currently I'm checking whether there is a login request (user entered data into login form) or the session is already existent and contains <code>$_SESSION['authenticated'] == TRUE;</code>. If both checks failed the user is not (properly) logged in. In code:</p>
<pre><code>class Auth {
private function __construct() {
// new login
if(isset($_POST['login'], $_POST['username'], $_POST['password']) && validCSRFToken()) {
$user = $_POST['username'];
$password = $_POST['password'];
if(($row = querySingle('
SELECT `id`, `password`
FROM `users` u
WHERE `nick` = "?"',
$user)))
// Crypt::hash checks the salted password
&& Crypt::hash($password, $row['password'])) {
// credential change (guest -> user) regenerate session id
session_regenerate_id(TRUE);
$_SESSION['authenticated'] = TRUE;
$_SESSION['userid'] = $row['id'];
$_SESSION['user'] = $user;
// prevent 'your browser has to re-send some data to display this page'
redirect($_SERVER['REQUEST_URI']);
} else {
$this->logout();
throw new AuthException('login failed. wrong user/password');
}
} else if($_SESSION['authenticated'] && $_SESSION['userid'] > 0 && !empty($_SESSION['user'])) {
// user already logged in, nothing to see here, move on
} else {
// not logged in!
throw new AuthException('not logged in. please login');
}
}
public function logout() {
$this->authenticated = FALSE;
$this->user = '';
$this->userid = 0;
$this->session->destroy();
$this->session->regenerate_id(TRUE);
}
}
</code></pre>
<p>An object of the <code>Auth</code> class has to be created on every page that requires authentication from users:</p>
<pre><code>try {
$auth = new Auth();
/*
* rest of the page
*/
} catch(AuthException $ex) {
// something went wrong during login
displayError();
displayLoginForm();
exit; // halt further execution of script
}
</code></pre>
<p>Is this the right way to do it? Do you see anything (seriously) flawed with this approach? Can users impersonate other users? Users getting logged out randomly? Users getting logged out by malicious attackers? (although CSRF checks are in place). I'm afraid, I might be missing something obvious.</p>
<p>Any improvements apreciated, thanks!</p>
<p>(Please don't suggest using a PHP framework like CodeIgniter, Zend Framework, Kohana, etc.)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:54:31.457",
"Id": "6130",
"Score": "0",
"body": "Have you tried using oAuth?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:06:49.790",
"Id": "6131",
"Score": "1",
"body": "Tip: Don't use exceptions to signal a standard case (auth failed), better have a auth state you can ask for (authenticated, unauthenticated)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:11:46.077",
"Id": "6132",
"Score": "0",
"body": "@hakre: I'm afraid some page forgets to check the auth state … thus the exception, that way it is garuanteed to abort the script"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:57:19.297",
"Id": "6133",
"Score": "0",
"body": "Seems perfectly valid to me. Is there a real question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:17:09.503",
"Id": "6134",
"Score": "0",
"body": "@nkittl: If that's the case, you should implement authentication on another layer probably. Just saying, you can use exceptions to gain something like a signal, however, keep in mind that it's not the right tool for the job. Might give you more problems than solutions in the end. Better check why some scripts are not checking authentication and think about twice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T12:59:19.920",
"Id": "6139",
"Score": "0",
"body": "I think you should consider checking for valid user in database even if you have valid session data. I had a very stupid problem once when deleted user was still \"logged in\" after he was deleted and one badly written query screwed our database a little."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:31:41.107",
"Id": "6142",
"Score": "0",
"body": "Forgot one more thing: usually you should check for $_POST variables after you check if user is already logged in($_SESSION), as it is very strange for a user to make double log in (and succesfull $_SESSION checks should be much more often, so making it first check will make your application slightly faster(as next checks will not be triggered), not that it matters, but still more logical). Just swap checks for $_SESSION and $_POST in your main IF tree."
}
] |
[
{
"body": "<p>At the first look, no big hole shines through. Some points that can be considered, on the order of appearance:</p>\n\n<ol>\n<li><p>Instead of directly using the <code>$_POST</code>, you can take these as parameters, thus making it look like more of an API. Example usage: when you want to directly log in people who have just registered. You will not be tied to some particular <code>$_POST</code> parameters.</p></li>\n<li><p><code>Crypt::hash ...</code>: Not seeing the interior of this, one can't comment much but from the looks, the salt seems constant, unless you are querying the users table again inside this. A different (and preferably with a length matching the password) salt for each user is generally the way to go in security-conscious developer environments.</p></li>\n<li><p>Similar to the #1, you can use a wrapper class for <code>$_SESSION</code> usage.</p></li>\n<li><p><code>else if($_SESSION['authenticated'] && $_SESSION['userid'] > 0 && !empty($_SESSION['user']))</code>: Instead of directly querying the <code>$_SESSION</code>, you can make another function like <code>$this->isLoggedIn()</code>, so you'd be more resistant to future session and log in changes (along with some other benefits).</p></li>\n<li><p><code>redirect($_SERVER['REQUEST_URI']);</code> Relying on a <code>$_SERVER</code> variable always looked insecure and unstable to me. You can use some checks here or use some of your internal navigation variables instead, in case you don't want to make it completely generic in this way.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:17:00.883",
"Id": "6135",
"Score": "0",
"body": "`Crypt::hash` uses a randomly generated user-unique salt (let's assume the usage of `crypt`). Wrapper class for session seems overhead to me, but was actually in use. 4) good point. 5) if the server was compromised then I've lost already, imo. the redirect call should probably be wrapped in a `refresh()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:36:36.823",
"Id": "6136",
"Score": "0",
"body": "But how `Crypt::hash` knows the specific salt for the user in question? It can generate random salts during registration, but what about log-in time, i.e. checking that salt?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:40:32.767",
"Id": "6137",
"Score": "0",
"body": "it's stored as part of the password. [`crypt`](http://php.net/crypt) does the same thing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:32:39.560",
"Id": "6180",
"Score": "0",
"body": "Ok, sorry for asking about something obvious :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T10:12:53.210",
"Id": "4110",
"ParentId": "4109",
"Score": "4"
}
},
{
"body": "<p>I'd also add validation of 'login', 'username' and 'password' before running the query.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T14:11:56.397",
"Id": "4119",
"ParentId": "4109",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T09:51:28.350",
"Id": "4109",
"Score": "5",
"Tags": [
"php",
"security"
],
"Title": "Writing a proper (and simple) auth/login class in PHP"
}
|
4109
|
<p>I have a form and need to be able to highlight/decorate fields as they gain focus (change their background color, border). I'm also decorating their corresponding 'labels'.</p>
<p>All works fine where it needs to: FF, Safari, IE 7, 8 and 9</p>
<p><strong>Problem 1</strong> cropped up with IE7 and changing background color of drop down box. There I had to resort to plain old JS to access the element and use 'onfocusin' and 'onfocusout' events otherwise it'd take 2 clicks to use the field.</p>
<p><strong>Problem 2</strong> was with Safari and how it handles 'focus' event with radio buttons. For that I'm using 'mouseenter' and 'mouseleave' events to change the color of their 'labels'.</p>
<p><strong>Is there a cleaner way of doing this?</strong> The caveats are I have no control of the HTML whatsoever and I can't use anything other than jQuery 1.4.3 That's all dictated by content management system I must work with.</p>
<p>Here's a complete 99.9% 'production' code example: <a href="http://jsfiddle.net/HenriPablo/YvDPa/3/" rel="nofollow">http://jsfiddle.net/HenriPablo/YvDPa/3/</a></p>
<p>Script in question:</p>
<pre><code>$(document).ready( function(){
/* PROFILE PAGE ONLY -> get rid of separator border on shipping addres block when editing any of the shipping addresses */
if( $('#formShippingAddress').length > 0 ){
$( 'table#block\\.crmshipping tbody tr td.block\\.crmshipping\\.text' ).css('border','none');
}
/* highlight input field labels when input field has focus */
/* see if event bubble - this is critical for handling decoration of select drop down boxes in IE7 */
if( $.support.changeBubbles){
var partialID = 'table[id^="page"]'
var focusable = $( partialID + ' input[type="text"], ' + partialID + ' input[type="password"], ' + partialID + ' select, ' + partialID + ' input[type="checkbox"]' );
var clickable = $( partialID + ' input[type="radio"]' );
focusable.focus( function( ){ decorate( $(this) ); })
focusable.blur( function( ){ decorate( $(this) ); })
clickable.mouseenter( function(){ decorate( $(this) ); })
clickable.mouseleave( function(){ decorate( $(this) ); })
} else { // bubbling support check
var i, d = document.getElementsByTagName('select')
for( i in d ){
d[i].onfocusin = function() {
this.style.backgroundColor = '#b4d5ec'
$(this).closest("td").prev().addClass('highlightLabel');
}
d[i].onfocusout= function() {
this.style.backgroundColor='#ffffff'
$(this).closest("td").prev().removeClass('highlightLabel');
}
} // for
$('table[id^="page"] input' ).focus( function( ){
decorate( $(this) )
})
$('table[id^="page"] input').blur( function( ){
decorate( $(this) );
})
} // handle IE7
function decorate( elm ){
elm.toggleClass('highlightField');
elm.closest("td").prev().toggleClass('highlightLabel');
} // decorator function
});
</code></pre>
<p>Many thanks in advance :-)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T13:52:48.167",
"Id": "6192",
"Score": "1",
"body": "The \"cleanest\" and probably easiest way would be to use the CSS `:focus` selector: `input:focus {background-color: red}`, which is widely supported, except IE7 and earlier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T16:22:18.317",
"Id": "6196",
"Score": "0",
"body": "that would, but can't happen under circumstances"
}
] |
[
{
"body": "<p>I'm not quite sure if this will do quite what you want, but here is my rehashing of the code:</p>\n\n<pre><code>$(document).ready(function() {\n $('table[id^=\"block\"] input, select').bind(\"focus blur\", function() {\n var $this = $(this);\n $this.closest(\"td\").prev().toggleClass('highlightLabel');\n $this.not(\"select\").toggleClass('highlightField');\n });\n});\n</code></pre>\n\n<p>You can see it in action <a href=\"http://jsfiddle.net/dg2d7/4/\" rel=\"nofollow\">here</a> on jsFiddle.</p>\n\n<p>As far as I can tell, the only thing I changed, behavior-wise, is that the select dropdown list does not have a background color when focused. IMO, it looks better that way, but you might prefer it with the background color.</p>\n\n<p>It seems to work the same on all the browsers I tested, but let me know if it doesn't and I'll look at it and see if I can fix it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T15:39:53.827",
"Id": "4122",
"ParentId": "4115",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T13:32:58.787",
"Id": "4115",
"Score": "2",
"Tags": [
"javascript",
"jquery-ui"
],
"Title": "jQuery and cross browser input fields focus handling"
}
|
4115
|
<p>I'm an iPhone Developer mainly, and I'm very new to web development - especially jQuery.</p>
<p>My task: I have three divs, which each contain a short biography about a certain person. (I have three people: liz, chris and michael). Those divs are hidden at the start of my code, because they all belong to the class <code>profile</code>. </p>
<p>I have three images which are displayed throughout, and have the IDs: (lizIMG, chrisIMG, michaelIMG). When an image is clicked, any other biographies' divs should be hidden, and the selected biography's div should be shown.</p>
<p>Also, I have a tooltip above each image, if a div is hidden, it will say: </p>
<blockquote>
<p>(Person Name) - Click to learn more</p>
</blockquote>
<p>If a div is displayed, it will say:</p>
<blockquote>
<p>(Person Name) - Click to hide</p>
</blockquote>
<p>I have fully working code, but the code is far too long for the desired task. It's quite annoying because I know exactly how I would do this in Objective-C, but not in jQuery. I'm guessing re-factoring it will involve functions, and possibly arrays?</p>
<p>I would like to make this shorter.</p>
<pre><code>$(document).ready(function() {
$('div.profile').hide(); // Hide all the profiles
$('#lizIMG').click(function() {
if ($("#lizDiv").is(":visible")) {
$('#lizTip').text('Click to learn more');
}
else {
$('#lizTip').text('Click to hide');
}
$('#lizDiv').slideToggle('slow');
$('#chrisDiv').hide('slow');
$('#chrisTip').text('Click to learn more');
$('#michaelDiv').hide('slow');
$('#michaelTip').text('Click to learn more');
});
$('#chrisIMG').click(function() {
if ($("#chrisDiv").is(":visible")) {
$('#chrisTip').text('Click to learn more');
}
else {
$('#chrisTip').text('Click to hide');
}
$('#chrisDiv').slideToggle('slow');
$('#lizDiv').hide('slow');
$('#lizTip').text('Click to learn more');
$('#michaelDiv').hide('slow');
$('#michaelTip').text('Click to learn more');
});
$('#michaelIMG').click(function() {
$('#lizDiv').hide('slow');
$('#lizTip').text('Click to learn more');
$('#chrisDiv').hide('slow');
$('#chrisTip').text('Click to learn more');
if ($("#michaelDiv").is(":visible")) {
$('#michaelTip').text('Click to learn more');
}
else {
$('#michaelTip').text('Click to hide');
}
$('#michaelDiv').slideToggle('slow');
});
$("#profiles img[title]").tooltip(); // Used to set text for the tooltips
});
</code></pre>
|
[] |
[
{
"body": "<p>Look at <a href=\"http://docs.jquery.com/UI/Accordion\" rel=\"nofollow\">JQuery Accordion</a></p>\n\n<p>Or if you don't want to use the Accordion then here is a variant:</p>\n\n<pre><code>function imgClickHandler(divBiographyId, divTooltipId){ \n var divBiographySelector = \"#\" + divBiographyId;\n var divTooltipSelector = \"#\" + divTooltipId;\n if ($(divBiographySelector).is(\":visible\")) {\n $(divTooltipSelector).text('Click to learn more');\n }\n else {\n $(divTooltipSelector).text('Click to hide');\n } \n $(divBiographySelector).slideToggle('slow');\n\n //.profileBiography - this css class you should add to lizDiv, chrisDiv, michaelDiv\n //.profileTip - this css class you should add to lizTip, chrisTip, michaelTip\n $(\".profileBiography\").not(divBiographySelector).hide('slow');\n $(\".profileTip\").not(divTooltipSelector).text('Click to learn more');\n }\n\n$(document).ready(function() {\n$('div.profile').hide(); // Hide all the profiles\nvar profiles = [{img: \"lizIMG\", biography: \"lizDiv\", tooltip: \"lizTip\"},\n {img: \"chrisIMG\", biography: \"chrisDiv\", tooltip: \"chrisTip\"},\n {img: \"michaelIMG\", biography: \"michaelDiv\", tooltip: \"michaelTip\"}];\n\n$.each(profiles, function(){\n var biographyId = this.biography;\n var tooltipId = this.tooltip;\n $(\"#\" + this.img).click(function(){\n imgClickHandler(biographyId, tooltipId);\n });\n }); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T17:28:06.953",
"Id": "6152",
"Score": "0",
"body": "great - but there's one thing wrong with your code, it doesn't hide the other two divs after adding one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T17:33:53.913",
"Id": "6154",
"Score": "0",
"body": "WOOPS! - forgot to set the CSS classes... I do apologise. Thank you for putting the effort into this - that's great code"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T16:34:08.900",
"Id": "4124",
"ParentId": "4123",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T15:59:08.893",
"Id": "4123",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"jquery"
],
"Title": "Three biographical profiles with photos"
}
|
4123
|
<p>I am writing a PHP application that works with a MySQL database. As I am fairly new to PHP I am looking for ways to improve my code. Below are two functions, <code>create_ct_query</code> and <code>create_ct_query2</code>. <code>create_ct_query2</code> is the result of my refactoring <code>create_ct_query</code>. I am fairly happy with it now, but am wondering how it looks to others.</p>
<pre><code><?php
// experiment with versions of create_ct_query
$lvb_id_ml=30; // lvb id
$lvb_name_ml=100; // competition name
$lvb_competitions_table =
array ("table_name" => "lvb_competitions",
"table_cols" =>
array (array ('id', $lvb_id_ml),
array ('name', $lvb_name_ml),
array ('age', 'INT')),
"primary_key" => array ('id', 'age'));
function varchar ($len) {
return "VARCHAR(" . $len . ")";
}
function primary_key ($item) {
return $item . " PRIMARY KEY";
}
// version currently in script
function create_ct_query ($tdesc) {
$ret_val = "CREATE TABLE " . $tdesc['table_name'] . " ( ";
foreach ($tdesc["table_cols"] as $row) {
if (is_numeric ($row[1])) {
$ret_val .= $row[0] . " " . varchar ($row[1]) . ", ";
} else {
$ret_val .= $row[0] . " " . $row[1] . ", ";
}
}
// add primary key constraint
$ret_val .= " CONSTRAINT pk_" . $tdesc["table_name"] .
" PRIMARY KEY (";
if (is_array ($tdesc['primary_key'])) {
$ret_val .= implode (",", $tdesc['primary_key']);
} elseif (is_string ($tdesc['primary_key'])) {
$ret_val .= $tdesc["primary_key"];
} else {
die ("Primary key not of right type in tdesc for " .
$tdesc['table_name'] . "\n");
}
$ret_val .= "))";
return $ret_val;
}
function create_ct_query2 ($tdesc) {
$ret_val = "CREATE TABLE " . $tdesc['table_name'] . " (";
$ret_val .= cols_desc ($tdesc['table_cols']) . ", ";
$ret_val .= primary_key_constraint ($tdesc['table_name'],
$tdesc['primary_key']) . "))";
return $ret_val;
}
// create the item description from the item
// Example:
// item_desc (array ('name', 10));
// 'name VARCHAR(10)'
// item_desc (array ('name', "INT"));
// 'name INT'
function item_desc ($item) {
return " " . $item[0] . " " .
(is_numeric($item[1]) ? varchar($item[1]) : $item[1]);
}
// create the column description part of table creation query
// Example:
// cols_desc (array (array ('id', 10), array ('id2', INT)));
// 'id VARCHAR(10), id2 INT'
function cols_desc ($table_cols) {
return implode (",", array_map ('item_desc', $table_cols));
}
// create the primary key constraint part of the table creation query
// primary_key_constraint ('name', 'id');
// CONSTRIANT pk_name PRIMARY KEY (id)
// primary_key_constraint ('name', array ('id', 'id2'));
// CONSTRAINT pk_name PRIMARY_KEY (id, id2)
function primary_key_constraint ($table_name, $primary_key_desc) {
return " CONSTRAINT pk_" . $table_name . " PRIMARY KEY (" .
(is_array($primary_key_desc) ?
implode (",", $primary_key_desc) :
$primary_key_desc);
}
echo create_ct_query ($lvb_competitions_table) . "\n\n";
echo create_ct_query2 ($lvb_competitions_table) . "\n\n";
</code></pre>
|
[] |
[
{
"body": "<p>Stylistically, it looks okay to me. But technically, you will want to embrace all your table and column names in backtick quotes, or else your queries will often fail if they are coming from user input. E.g. table and column names need backticks if they contain dashes, and also for a lot of other characters. See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/identifiers.html\" rel=\"nofollow\">description here</a>.</p>\n\n<p>On a second note, of course, you will want make sure that those variables that contain table and field names are properly filtered.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T09:31:11.967",
"Id": "4139",
"ParentId": "4129",
"Score": "1"
}
},
{
"body": "<p>Assuming you're protecting yourself from SQL Injection and the like, there are just a couple things that stand out to me:</p>\n\n<ul>\n<li>It doesn't seem clear to me why the closing parenthesis for your primary key constraint is in the create_ct_query2() function rather than in the primary_key_constraint() function.</li>\n<li>I believe the code would be far easier to read, test, and extend if it were built using objects rather than global functions.</li>\n<li>Since you are new to PHP, I think it is worth mentioning that single quotes and double quotes are treated differently. Knowing this, as a personal preference, I tend to use single quotes unless I intentionally need / want to use the added functionality of double quotes.</li>\n<li>While related to refactoring, I believe my other suggestions start to delve more in to the readability of things like create_ct_query(). This starts to feel a bit nit-picky, and almost a matter of style. For example, with create_ct_query(), it took me a minute to realize what \"<em>ct</em>\" meant. Only after looking inside the function and seeing the string being created did I realize what it did. I feel that something like \"get_create_table_query()\" or similar would be a bit more intuitive.</li>\n</ul>\n\n<p>Regarding documentation, I have found Eclipse and other tools to utilize the following style of doc-blocks. The @return is especially useful for code-completion of methods available on the returning object in my IDE. Documentation tools tend to have built-in support for other tags like @author as well.</p>\n\n<pre><code>/**\n * Description of someMethod()\n *\n * @param int $someInt\n * @param ObjectName $someObj\n * @return AnotherObj\n */\npublic function someMethod($someInt, ObjectName $someObj)\n{\n // ... \n\n return new AnotherObj();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T20:42:13.770",
"Id": "4153",
"ParentId": "4129",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T23:02:06.770",
"Id": "4129",
"Score": "1",
"Tags": [
"php",
"sql",
"mysql"
],
"Title": "Creating SQL queries for a MySQL database"
}
|
4129
|
<p>I wrote the following code to give an HTML element max width/height in its parent container.
I think I address the box model issues but I am wondering if anyone can see issues and or shortcomings.</p>
<p>Are there other solutions out there that accomplish this? I want to make sure I didn't re-invent the wheel.</p>
<pre><code>function heightBuffer(control) {
return parseInt((control.outerHeight(true)) - control.height());
}
function widthBuffer(control) {
return parseInt((control.outerWidth(true)) - parseInt(control.width()));
}
function MaxHeightInParent(control, minHeight, controlHeightsToSubtract) {
var h = parseInt(control.parent().height()) - heightBuffer(control);
if (controlHeightsToSubtract != null)
$.each(controlHeightsToSubtract, function(index, value) {
h = h - parseInt(value.outerHeight(true));
});
if (minHeight != null && h < minHeight) h = minHeight;
control.height(0);
control.css('min-height', h);
}
function MaxWidthInParent(control, minWidth, controlWidthsToSubtract) {
var w = parseInt(control.parent().width()) - widthBuffer(control);
if (controlWidthsToSubtract != null)
$.each(controlWidthsToSubtract, function(index, value) {
w = w - parseInt(value.outerWidth(true));
});
if (minWidth != null && w < minWidth) w = minWidth;
control.width(0);
control.css('min-width', w);
}
</code></pre>
<p>Note controlHeightsToSubtract / controlWidthsToSubtract are if you wish to pass an array of controls that share the containing element with the element you are attempting to maximize in Height/Width.</p>
|
[] |
[
{
"body": "<p>What is</p>\n\n<pre><code>parseInt((control.outerHeight(true)) - control.height());\n</code></pre>\n\n<p>supposed to achieve?</p>\n\n<p>The result of <code>-</code> is always going to be a number, so what this does is convert the number to a string and back to a number. This can only lose precision and waste time.</p>\n\n<p>Similarly, the use of parseInt on the first argument is also unnecessary</p>\n\n<pre><code>parseInt(control.parent().height()) - heightBuffer(control)\n</code></pre>\n\n<p>since</p>\n\n<pre><code>\"4\" - 1 === 3\n</code></pre>\n\n<p>In fact, the automatic conversion that <code>-</code> does is better than that done by <code>parseInt</code> since <code>parseInt</code> falls back to octal on some interpreters but not others.</p>\n\n<pre><code>\"10\" - 1 === 9\nparseInt(\"10\") - 1 === 9\n\"0x10\" - 1 === 15\nparseInt(\"0x10\") - 1 === 15\n\"010\" - 1 // throws reliably\nparseInt(\"010\") - 1 === 7 // on some and 9 on others\n</code></pre>\n\n<p>so I'd get rid of all the uses of <code>parseInt</code> as an operand to <code>-</code>.</p>\n\n<p>You seem to be setting <code>min-height</code> but the method is called <code>MaxHeight</code>. That confuses me.</p>\n\n<p>When you change the CSS</p>\n\n<pre><code>control.css('min-height', h)\n</code></pre>\n\n<p>you might want to specify units as in</p>\n\n<pre><code>control.css('min-height', h + \"px\")\n</code></pre>\n\n<p>I'm not sure how you're handling the widths of margins and borders on the controls. Is that important to you?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T16:07:39.307",
"Id": "4146",
"ParentId": "4130",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4146",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T01:48:26.117",
"Id": "4130",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Javascript to compute max width and height for a nested HTML element"
}
|
4130
|
<p>As an exercise in learning bash, I wrote this script designed to automate the process of populating a drive with uncompressed .aiff files copied directly from a CD. It saves me having to do a bunch of separate commands to create subdirectories, check before clobbering, etc.</p>
<p>It stores them in this fashion:</p>
<p>Root directory -> Artist -> Album -> Disc in the series (if necessary)</p>
<p>I wrote it to be run in bash on a Mac. Hence the "open" command.</p>
<ol>
<li><p>What best practices am I ignoring?</p></li>
<li><p>Is any of the logic unnecessarily complex? (Aside from the whole endeavor, which I suppose I could just do through the GUI... but where's the fun in that?)</p></li>
</ol>
<p>Specifically, I wonder about comparing the contents of an origin directory to a destination directory by outputting the destination's content to a text file and running an inverse grep search on it:</p>
<pre><code>for trackname in $(ls -1 /Volumes/$the_disc | grep -vf ~/.harvest/existing); do
</code></pre>
<p>Thanks for any feedback you can offer this newbie.</p>
<pre><code>#!/bin/bash
# > harvest.sh <
# Identifies audio CDs and copies their contents to my archive directory
# Written by parisminton for Concrete Daydreams.
# <parisminton@da.ydrea.ms>
vrs='v 0.7'
lastchange='8/15/11'
echo -e "\n--> Harvest $vrs $lastchange <--"
# ...change IFS to newline...
OLD_IFS=$IFS
IFS=$'\n'
i=0
tryagain="--> I can't find any more external volumes. Are you sure you inserted a CD or external drive?\n"
function y_or_n () {
until [ "$pick" == "y" -o "$pick" == "n" ]; do
echo -e "--> (Enter \"y\" or \"n\".)\n"
read pick
done
}
function collect () {
the_disc=$1
multi=null
ls /Volumes/$1
echo -e "\n--> What's the artist's name?\n"
read artist
echo -e "\n--> OK. We're storing music from $artist."
echo -e "\n--> Is \"$1\" the name of the album?"
pick=null
y_or_n
if [ "$pick" == "y" ]; then
echo -e "\n--> Excellent. $1 is the name of the album by $artist.\n"
album=$1
else
echo -e "\n--> What's the name of the album?\n"
read album
echo -e "\n--> Excellent. $album is the name of the album by $artist."
fi
echo -e "\n--> Is \"$album\" a multi-disc set?"
pick=null
y_or_n
if [ "$pick" == "y" ]; then
echo -e "\n--> Which disc is this? (\"1,\" \"Disc 1,\" \"The Love Below,\" \"etc...)\n"
read multi
if [[ "$multi" =~ ^[0-9]+$ ]]; then
multi="Disc $multi"
fi
fi
}
function archive () {
musicpath="/path/to/music/directory/"
if [ ! -e "$musicpath/$artist" ]; then
mkdir "$musicpath/$artist"
echo -e "\n--> I just created a folder named \"$artist.\""
else
echo -e "\n--> $artist already has a folder in the archive."
fi
cd "$musicpath/$artist"
if [ ! -e "$musicpath/$artist/$album" ]; then
mkdir "$musicpath/$artist/$album"
echo -e "\n--> I just created a folder named \"$album.\""
else
echo -e "\n--> The album \"$album\" already has a folder in the archive."
fi
cd "$musicpath/$artist/$album"
if [ "$multi" != null ]; then
if [ ! -e "$musicpath/$artist/$album/$multi" ]; then
mkdir "$musicpath/$artist/$album/$multi"
echo -e "\n--> I just created a folder named \"$multi.\""
else
echo -e "\n--> \"$multi\" already has a folder in the archive."
fi
cd "$musicpath/$artist/$album/$multi"
fi
mkdir ~/.harvest
ls -1 . > ~/.harvest/existing
tracktotal=$(ls -1 /Volumes/$the_disc | grep -cvf ~/.harvest/existing)
if [ $tracktotal -gt 0 ]; then
open .
trackcount=0
for trackname in $(ls -1 /Volumes/$the_disc | grep -vf ~/.harvest/existing); do
trackcount=$(($trackcount+1))
echo -e "\n--> Copying \"$trackname.\" This may take a minute or two..."
cp "/Volumes/$the_disc/$trackname" .
done
echo -e "\n--> Finished copying."
echo -e "\n--> $tracktotal tracks from the album \"$album\" by $artist have been saved to $(pwd)."
else
echo -e "\n--> Nothing copied. All the files on $album have already been archived.\n"
fi
rm -PR ~/.harvest
}
# ...compare the /Volumes list to the pre-defined list of internal volumes
# we know aren\'t the audio CD; any inverse matches are likely to be the
# CD we want to archive...
if [ "$(ls -1 /Volumes | grep -vf ~/.int_vols)" ]; then
for filename in $(ls -1 /Volumes | grep -vf ~/.int_vols); do
if [ -d "/Volumes/$filename" ]; then
fn[$i]=$filename
i=$(($i+1))
fi
done
if [ ${#fn[*]} -gt 1 ]; then
echo -e "\n--> I see more than one volume that might contain the music you want to archive:\n"
PS3="--> Which one do you want? (Type the number of your choice.) "
select disc in ${fn[*]}; do
echo -e "\n--> Cool. You selected $disc.\n"
break
done
collect $disc
archive
else
echo "\n--> Does the volume named \"${fn[0]}\" contain the music you want to archive?"
y_or_n
if [ "$pick" == "y" ]; then
collect ${fn[0]}
else
echo $tryagain
fi
fi
else
echo $tryagain
fi
# ...restore IFS...
IFS=$OLD_IFS
</code></pre>
|
[] |
[
{
"body": "<p>Some comments:</p>\n\n<ol>\n<li>You script does not work if you have spaces in the filenames, but I guess this cannot happen.</li>\n<li>You do not need to restore IFS as the script will be run in a subprocess, and will not impact parent environment.</li>\n<li>You could run <code>ls -1 /Volumes | grep -vf ~/.int_vols</code> only once, doing a <code>filenames=$(ls -1 /Volumes | grep -vf ~/.int_vols)</code> before the <code>if</code>.</li>\n<li>You could save the <code>-d</code> tests in the <code>for</code> loop by using <code>find /Volumes -mindepth 1 -maxdepth 1 -type d | cut -d \"/\" -f 3</code> instead of <code>ls -1 /Volumes</code>.</li>\n<li>You could save the entire <code>for</code> loop doing a <code>find /Volumes -mindepth 1 -maxdepth 1 -type d | cut -d \"/\" -f 3 | paste -s -d \" \" | read -a f</code></li>\n</ol>\n\n<p>The <code>cut -d \"/\" -f 3</code> does not work well if you change <code>/Volumes</code> by a directory that is not directly under <code>/</code>. I would use <code>sed -e s|.*/||</code> instead, but this introduces a new tool that you might not be familiar with.</p>\n\n<p>For the rest of the script, I do not know the structure of the data, so I cannot tell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T03:51:16.880",
"Id": "6237",
"Score": "0",
"body": "I appreciate the suggestions. I'm eager to learn sed. I'd heard about how powerful it is but never really had the context for being able to use it before now. The script actually does work with spaces in the filenames. I thought this was because I quoted the variables before they're expanded."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T10:12:58.730",
"Id": "4142",
"ParentId": "4131",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4142",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:09:05.410",
"Id": "4131",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Is this shell script for copying files sensible, readable?"
}
|
4131
|
<p>I know that nested namespaces are used in C++ very rarely. But I think it's a nice solution to exclude types from global scope and sometimes it helps to write programs faster when we use things like "IntelliSense" or search for documentation (maybe it's similar for C# developers).</p>
<p>I've tried to organize my simple 3D graphics engine library in this way. Here is its main header file:</p>
<pre><code>#ifndef RAZOR_H
#define RAZOR_H
#pragma warning (disable: 4482)
#include <Windows.h>
#include <fstream>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <gl\GL.h>
#include "Externals\wglext.h"
#include "Externals\gl3.h"
namespace Razor
{
namespace Framework
{
#include "DisplayOrientation.h"
#include "ButtonState.h"
#include "GameTime.h"
#include "Rect.h"
#include "Point.h"
#include "Color.h"
#include "Vector2.h"
#include "Vector3.h"
#include "Vector4.h"
#include "Matrix.h"
#include "GameWindow.h"
#include "Game.h"
namespace IO
{
#include "File.h"
}
namespace Input
{
#include "ButtonState.h"
#include "MouseState.h"
#include "Keyboard.h"
#include "Mouse.h"
#include "TouchPanel.h"
}
namespace Graphics
{
#include "PrimitiveType.h"
#include "VertexElementFormat.h"
#include "VertexElementUsage.h"
#include "VertexElement.h"
#include "VertexDeclaration.h"
#include "OpenGLExtensions.h"
#include "DepthFormat.h"
#include "BufferUsage.h"
#include "PresentationParameters.h"
#include "RenderTarget.h"
#include "OpenGLVersion.h"
#include "Viewport.h"
#include "Shader.h"
#include "VertexShader.h"
#include "FragmentShader.h"
#include "GeometryShader.h"
#include "ShaderContainer.h"
#include "VertexBuffer.h"
#include "GraphicsDevice.h"
#include "VertexBuffer.h"
#include "GraphicsDeviceManager.h"
}
}
}
#endif // RAZOR_H
</code></pre>
<p>What kind of problems can I get in the future if I organize my library in this way? Do you think this is really a bad style of coding?</p>
|
[] |
[
{
"body": "<p>I don't think there is anything inherently wrong with nested namespaces.</p>\n\n<p>I also disagree that it is rare. It is just not exposed directly.</p>\n\n<pre><code>std::tr1\nCompanyName::ProductName\nCompanyName::ProductName::Details\n</code></pre>\n\n<p>But like all features they can be abused so use judiciously. But saying that I see nothing wrong with your namespace hierarchy. <strong>BUT</strong> the way you are implementing it is a very bad idea.</p>\n\n<p>If I include the file \"File.h\" I expect everything included to be declared in the correct namespace. But the way you define it, it is now possible to include it in a way that puts the classes in the wrong namespace.</p>\n\n<p>Each header file should be designed so that it can not be used incorrectly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-18T20:54:33.887",
"Id": "8244",
"Score": "0",
"body": "+1 for that last line. Make your code as robust as possible, down to minute details."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:31:44.257",
"Id": "4133",
"ParentId": "4132",
"Score": "15"
}
},
{
"body": "<p>It's better, much more better to protect (you eventually protect) your names in the file scope, where they are declared. So, your using of namespaces protects names only in include scope, and what if I will try to include some of your headers and forget to frame it with a namespace? How will I even know what namespace to use?</p>\n\n<p>This topic correlates with header guards (which you use correctly here). Rule #24 from \"C++ Coding Standards: 101 Rules, Guidelines, and Best Practices\":</p>\n\n<blockquote>\n <p>Always write internal #include guards. Never write external #include\n guards</p>\n</blockquote>\n\n<p>BTW, very good book.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T10:20:36.410",
"Id": "6187",
"Score": "0",
"body": "Thanks for the nice commment. I didn't think of this issue in the beginning. it hadn't been supposed that I could've include headers from razor.h separably. Indeed I wanted to reduce #include directives in my code by including the only one razor.h file and then using only needed namespaces."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T09:31:41.933",
"Id": "4140",
"ParentId": "4132",
"Score": "2"
}
},
{
"body": "<p>There's nothing inherently wrong with nested namespaces, but note that namespaces are (in my opinion, and as far as I have read) intended to prevent name clashes, not to organise code. They are not rare -- there's boost, for example, which has plenty of nested namespaces, but as far as I've seen, they are usually used to split two (sub-)projects, so that developers don't need to worry about taking each other's names.</p>\n\n<p><strong>Note:</strong> When I say \"top-level namespace\", I mean <code>Razor</code>.</p>\n\n<p><strong>Other Note:</strong> You're including some files several times; I'm assuming those are copy-paste mistakes.</p>\n\n<p>Some ideas:</p>\n\n<ul>\n<li>The namespaces should be defined inside each individual header, not in some global header. Including this header everywhere is going to cost you a lot of compile time. It'll also mean that an error in a single header file will not allow you to build any of your project, which can be inconvenient.</li>\n<li>Do you really need a <code>Framework</code> namespace? It's just as big as your <code>Razor</code> namespace, so why bother with it? You could rename <code>Razor</code> to <code>RazorFramework</code>, and get the same effect. (If you decide to expand later, an <code>Addons</code> namespace may be more correct, anyway.)</li>\n<li>Is <code>File</code> really that important a class to get its own namespace? Moreover, will you use the same <code>File</code> class for reading and writing all files, or is that possible to change? Again, I'd put it in the top-level namespace if it's so general, but I suspect there's more design decisions to be made about that file, anyway.</li>\n<li><code>Graphics</code> looks like a good choice for a namespace, but then you shouldn't prefix the files with <code>Graphics</code>. While not necessary, it's nice when your namespace structure and header structure are similar, if not identical.</li>\n<li><code>Vertex</code> looks like a common prefix: perhaps putting all vertex-related things in a namespace of their own would avoid that. The same may go for <code>Buffer</code> and <code>Shader</code>, depending on how likely those are to clash.</li>\n<li>Functions and classes specific to OpenGL and DirectX are likely to be very similar, so having an <code>OpenGL</code> namespace and a <code>DirectX</code> namespace somewhere will let you use the same names for the same functionality in each.</li>\n</ul>\n\n<p>Also, not related to namespaces, but if you want to have uppercase file names in the includes, make sure your actual file names are uppercase, too -- things will compile fine on Windows, but mysteriously break on other platforms (if you ever port there).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T16:52:36.143",
"Id": "4263",
"ParentId": "4132",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T06:17:49.513",
"Id": "4132",
"Score": "9",
"Tags": [
"c++",
"library",
"windows",
"graphics",
"namespaces"
],
"Title": "Use of nested namespaces in 3D graphics engine library"
}
|
4132
|
<p>I have a <code>Sprite</code> class and an <code>AnimatedSprite</code> subclass, and I'd like to decouple these them and maintain substitutability, according to the Liskov Substitution Principle. I find that when dealing with pointers to Sprites I always use <code>GetFrameWidth</code> and <code>GetFrameHeight</code> instead of <code>GetWidth</code> and <code>GetHeight</code>just in case the pointer is actually pointing to an AnimatedSprite that requires just the frame width or height instead of the entire sprite sheet.</p>
<p>Sprite.h</p>
<pre><code>#ifndef CSPRITE_H
#define CSPRITE_H
#include <utility>
#include <allegro\fixed.h>
#include <allegro\fmaths.h>
#include <allegro\draw.h>
#include <allegro\file.h>
#include <allegro\datafile.h>
#include <allegro\color.h>
#include <string>
#include <vector>
#include "CBitmapCache.h"
class Sprite {
public:
static Sprite* CreateSprite(BITMAP* file, int centerX, int centerY);
static Sprite* CreateSprite(std::string file, int width, int height);
static Sprite* CreateSprite(std::string file, int width, int height, int centerX, int centerY);
static Sprite* CreateSprite(const Sprite& sprite);
virtual ~Sprite();
std::string* GetFilename() const;
virtual BITMAP* GetImage() const;
double GetX() const;
double GetY() const;
double GetZ() const;
Point GetPosition() const;
virtual int GetWidth() const;
virtual int GetHeight() const;
int GetFrameWidth() const;
int GetFrameHeight() const;
int GetCenterX() const;
int GetCenterY() const;
double GetRotation() const;
double GetScaleX() const;
double GetScaleY() const;
fixed GetScaleAsFixed() const;
int GetTint() const;
unsigned char GetTintIntensity() const;
unsigned char GetAlpha() const;
int GetRotationRadius() const;
void SetX(double x);
void SetY(double y);
void SetZ(double z);
void SetPosition(double x, double y);
void SetPosition(double x, double y, double z);
void SetPosition(const Point& position);
void SetCenterX(int x);
void SetCenterY(int y);
void SetScaleX(double x);
void SetScaleY(double y);
void SetRotation(double angle);
void SetTint(unsigned int tint);
void SetTintIntensity(unsigned char intensity);
void SetAlpha(unsigned char alpha);
void SetRadius(int radius);
Sprite& Clone(const Sprite& sprite);
/////////////////////////////////////////////////////////////////
// FOLLOWING METHODS ARE USED IN DERIVED ANIMATED SPRITE CLASS //
/////////////////////////////////////////////////////////////////
virtual int GetNumFrames() const;
virtual int GetNextFrameNum() const;
virtual int GetCurFrameNum() const;
virtual int GetPrevFrameNum() const;
virtual void Animate(int start, double deltaTime);
virtual void Animate(int start, int end, double deltaTime);
virtual int GetNumColumns() const;
virtual BITMAP** GetFrames() const;
virtual void SetFrames(std::vector<BITMAP*> _frames, int frameWidth, int frameHeight, int numCols);
virtual void SetFrames(BITMAP** frames, int frameWidth, int frameHeight, int numFrames, int numCols);
virtual bool CanLoop() const;
virtual void SetLoop(bool canLoop);
virtual void SetFrameRate(double deltaTime);
virtual double GetFrameRate();
virtual void DrawFrame(BITMAP* dest, int frame, int x, int y, bool transparent);
virtual BITMAP* GetFrame(int numFrame);
protected:
std::string* _file;
BITMAP* _image;
Point* _position;
std::pair<int, int> _dimensions;
std::pair<int, int> _frameDimensions;
std::pair<int, int> _center;
std::pair<double, double> _scaleDimensions;
double _angle;
int _radius;
int _tint;
unsigned char _tintIntensity;
unsigned char _alpha;
void CalcCenterFrame();
virtual void SetImage(BITMAP* image);
virtual void SetCurFrame(int frame);
Sprite(BITMAP* file, int centerX, int centerY);
Sprite(std::string file, int width, int height, int centerX, int centerY);
Sprite(const Sprite& sprite);
Sprite& operator=(const Sprite& rhs);
private:
};
#endif
</code></pre>
<p>AnimatedSprite.h</p>
<pre><code>#ifndef CANIMATEDSPRITE_H
#define CANIMATEDSPRITE_H
#include "CSprite.h"
#include <vector>
struct BITMAP;
class AnimatedSprite : public Sprite {
public:
static AnimatedSprite* CreateAnimatedSprite(BITMAP* file, int frameWidth, int frameHeight, int numFrames, int numCols, double frameRate, bool loop);
static AnimatedSprite* CreateAnimatedSprite(std::string file, int width, int height, int frameWidth, int frameHeight, int numFrames, int numCols, double frameRate, bool loop);
static AnimatedSprite* CreateAnimatedSprite(std::string file, int width, int height, int frameWidth, int frameHeight, int centerX, int centerY, int numFrames, int numCols, double frameRate, bool loop);
static AnimatedSprite* CreateAnimatedSprite(const AnimatedSprite& animatedSprite);
virtual ~AnimatedSprite();
virtual bool CanLoop() const;
virtual int GetNumFrames() const;
virtual int GetNextFrameNum() const;
virtual int GetCurFrameNum() const;
virtual int GetPrevFrameNum() const;
virtual int GetNumColumns() const;
virtual BITMAP* GetImage() const;
virtual BITMAP** GetFrames() const;
virtual void SetLoop(bool canLoop);
virtual void Animate(int start, double deltaTime);
virtual void Animate(int start, int end, double deltaTime);
AnimatedSprite& Clone(const AnimatedSprite& animatedSprite);
virtual void SetFrameRate(double deltaTime);
virtual double GetFrameRate();
virtual void SetFrames(std::vector<BITMAP*> _frames, int frameWidth, int frameHeight, int numCols);
virtual void SetFrames(BITMAP** frames, int frameWidth, int frameHeight, int numFrames, int numCols);
protected:
virtual void SetImage(BITMAP* image);
virtual BITMAP* GetFrame(int numFrame);
virtual void DrawFrame(BITMAP* dest, int frame, int x, int y, bool transparent);
virtual void SetCurFrame(int frame);
void GrabFrame(BITMAP* image, int width, int height, int startx, int starty, int columns, int numFrame);
AnimatedSprite(BITMAP* file, int frameWidth, int frameHeight, int centerX, int centerY, int numFrames, int numCols, double frameRate, bool loop);
AnimatedSprite(std::string file, int width, int height, int frameWidth, int frameHeight, int centerX, int centerY, int numFrames, int numCols, double frameRate, bool loop);
AnimatedSprite(const AnimatedSprite& animSprite);
AnimatedSprite& operator=(const AnimatedSprite& rhs);
private:
int _curFrame;
int _numFrames;
bool _loop;
int _numColumns;
BITMAP** _frames;
BITMAP* _frameImage;
double _frameRate;
};
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T09:30:46.013",
"Id": "6183",
"Score": "2",
"body": "I'd prioritize Single Responsibility Principle and Interface Segregation Principle before LSP in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T01:30:32.093",
"Id": "42166",
"Score": "0",
"body": "I concure, damn these classes do a lot. Reminds me of the bloaters code smell."
}
] |
[
{
"body": "<p><strong>Solution 1</strong>:</p>\n\n<ul>\n<li>have a texture/img class, with GetImgWidth/GetImgHeight. these return\nthe dimensions of the physical texture, so in case of a sprite sheet,\nthe size of the whole sheet</li>\n<li>make sprite extend image. getwidth/getheight return the size of the\nsprite, i.e. a single frame </li>\n<li>make animatedsprite extend sprite. getwidth/getheight return the size of a single frame.</li>\n</ul>\n\n<p>So if you only accept instances of class Sprite, you can be sure that you are always retrieving the right property, and you still have the chance to get the size of the whole image on a sprite sheet. This solution also easily extends to other techniques, like packed textures.</p>\n\n<p><strong>Solution 2</strong> (if you can live with the overhead):</p>\n\n<p>Use RTTI and ask for the type of object dynamically. Cast with dynamic_cast<>() and if it is an animated sprite instead of a simple sprite, call the appropriate methods. IMHO, this is not a nice solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T15:58:48.460",
"Id": "6195",
"Score": "0",
"body": "Solution 1 is essentially what the code already does. A sprite object is used to represent non-animating single-framed images and an animatedsprite object is used to represent either a collection of images or a series of frames...which after thinking aloud about that I'm going to separate those into two classes, a collection and animation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T09:30:40.433",
"Id": "6209",
"Score": "0",
"body": "The way I understood your original question is that you want to separate Sprite and AnimatedSprite, because you'd need to call GetHeight on Sprite and GetFrameHeight on AnimatedSprite. Now you're saying that the two classes you want to separate are two different kinds of AnimatedSprite. Given this, my first recommendation is not what your code is already doing. I recommended inserting an Image class with a different property to ask for the 'real' size of any image, and I changed the definition of GetHeight of AnimatedSprite."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T08:56:36.530",
"Id": "4138",
"ParentId": "4134",
"Score": "1"
}
},
{
"body": "<p>Looking over your code and comments, might I suggest a different strategy?</p>\n\n<p>AnimatedSprite could be thought of as a collection of individual sprites. Rather than deriving it from Sprite, use composition to resuse Sprite objects inside of an AnimatedSprite.</p>\n\n<p>If there is a genuine need to use both interchangeably (without knowing specifically whether you have a Sprite or AnimatedSprite) I would create an abstract class (interface) that collects the common methods and implement it in each of Sprite and AnimatedSprite.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T17:31:53.243",
"Id": "4150",
"ParentId": "4134",
"Score": "4"
}
},
{
"body": "<p>As others have mentioned.... I'd introduce more classes to make the interface simpler ( Image, Point, etc )</p>\n\n<p>Then extract an interface that both sprite and animated sprite use. </p>\n\n<p>But....maybe a whole different take on it...</p>\n\n<p>I'd first ask myself, do I really need a sprite and an animated sprite? Or is what I think of as a \"sprite\" just a single frame animated sprite?</p>\n\n<p>Therefore, just rename animatedsprite as sprite.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T03:46:35.170",
"Id": "4163",
"ParentId": "4134",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4150",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T07:16:35.687",
"Id": "4134",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"animation"
],
"Title": "Sprite and AnimatedSprite"
}
|
4134
|
<p>I have a basic cache set up. Whenever a user requests a bitmap, it fetches or loads it from disk if it isn't already loaded, significantly reducing load times.</p>
<p>Currently, the design explicitly tells the user that they are responsible for freeing the individual bitmaps when they are done. That's fine, but the biggest problem I notice right away is that the cache is created on first use. There's no way to <code>delete</code> it without having the user expressly call a Release method (which seems like a bad idea). They are forced not only to release each individual bitmap, but also the cache even though they never created it.</p>
<p>Should I create <code>Initialize</code> and <code>Release</code> methods strictly to <code>new</code> and delete the <code>std::map</code>?</p>
<p>(It's named <code>pool</code> in the code because the member name hasn't been updated as of this posting.)</p>
<p><strong>BitmapCache.h</strong></p>
<pre><code>#ifndef CBITMAPCACHE_H
#define CBITMAPCACHE_H
#include <allegro\file.h>
#include <allegro\gfx.h>
#include <allegro\draw.h>
#include <allegro\datafile.h>
#include <allegro\color.h>
#include <map>
#include <string>
struct BITMAP;
class BitmapCache {
public:
static BITMAP* GetBitmap(std::string filename);
static BITMAP* GetBitmap(BITMAP* file);
static std::string GetBitmapFilename(BITMAP* file);
static BITMAP* GetBlankBitmap(int width, int height);
protected:
private:
static std::map<std::string, BITMAP*>* _pool;
static void CleanCache();
};
#endif
</code></pre>
<p><strong>BitmapCache.cpp</strong></p>
<pre><code>#include "CBitmapCache.h"
#include <algorithm>
std::map<std::string, BITMAP*>* BitmapCache::_pool = NULL;
BITMAP* BitmapCache::GetBitmap(std::string filename) {
//Return NULL if a bad filename was passed.
if(filename.empty()) return NULL;
if(exists(filename.c_str()) == false) return NULL;
//Reduce incorrect results by forcing slash equality.
filename = fix_filename_slashes(&filename[0]);
//Create pool on first use.
if(_pool == NULL) _pool = new std::map<std::string, BITMAP*>();
//Clean the pool if it's dirty.
CleanCache();
//Search for requested BITMAP.
std::map<std::string, BITMAP*>::iterator _iter = _pool->find(filename);
//If found, return it.
if(_iter != _pool->end()) return _iter->second;
//Otherwise, create it, store it, then return it.
BITMAP* result = load_bmp(filename.c_str(), NULL);
if(result == NULL) return NULL;
_pool->insert(std::pair<std::string, BITMAP*>(filename, result));
return result;
}
BITMAP* BitmapCache::GetBitmap(BITMAP* file) {
if(file == NULL) return NULL;
if(_pool == NULL) new std::map<std::string, BITMAP*>();
CleanCache();
for(std::map<std::string, BITMAP*>::iterator _iter = _pool->begin(); _iter != _pool->end(); ++_iter) {
if(_iter->second != file) continue;
return _iter->second;
}
return NULL;
}
std::string BitmapCache::GetBitmapFilename(BITMAP* file) {
if(file == NULL) return std::string("");
if(_pool == NULL) return std::string("");
CleanCache();
for(std::map<std::string, BITMAP*>::iterator _iter = _pool->begin(); _iter != _pool->end(); ++_iter) {
if(_iter->second != file) continue;
return _iter->first;
}
return std::string("");
}
BITMAP* BitmapCache::GetBlankBitmap(int width, int height) {
//Smallest allowed size is 1x1.
if(width < 1 || height < 1) return NULL;
//Create pool on first use.
if(_pool == NULL) _pool = new std::map<std::string, BITMAP*>();
//Cleans the cache.
CleanCache();
//Partial Sequential Search for requested BITMAP.
if(_pool->empty() == false) {
for(std::map<std::string, BITMAP*>::iterator _iter = _pool->begin(); _iter != _pool->end(); ++_iter) {
//String keys sorted in ascending order.
//If key is not empty reached non-blank section.
if(_iter->first.empty() == false) break;
if(width == _iter->second->w && height == _iter->second->h) {
return _iter->second;
}
}
}
//Attempt to create bitmap, if failed, return NULL.
BITMAP* result = create_bitmap(width, height);
if(result == NULL) return NULL;
//Clear to black, store it, then return to caller.
clear_bitmap(result);
_pool->insert(std::pair<std::string, BITMAP*>("", result));
return result;
}
void BitmapCache::CleanCache() {
//Clean the pool of any NULL bitmaps that were deleted by caller.
for(std::map<std::string, BITMAP*>::iterator _iter = _pool->begin(); _iter != _pool->end(); ++_iter) {
if(_iter->second != NULL) continue;
_pool->erase(_iter);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You initialization is lazy, so there is no need for an explicit <code>Initialize</code>. A <code>Release</code> Method would be one option to clean the memory after usage and setting pool to NULL again. I guess your code is intended for single thread only so there are no real problems. Another option would be to use instances a your (then modified) class. In that way you give the user the control to use different Caches for different usages. The Cache deletes if it goes out of scope (local use) or if the user explicitly wants to.</p>\n\n<p>Personally I think it's rarely a good design to use Classes in a static way. If you find it neccessary to limit the number of instances, why not making it a Singleton instance?</p>\n\n<p>BTW I'd suggest a typedef for <code>std::map<std::string, BITMAP*></code> and <code>std::pair<std::string, BITMAP*></code> making the code a bit more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T07:55:06.377",
"Id": "4136",
"ParentId": "4135",
"Score": "0"
}
},
{
"body": "<p>Ahh, the wonderful world of game design - I assume that is what you are doing.\nIn my oppinion, the three most common solutions are (in order of my preference):</p>\n\n<ol>\n<li>Make the cache an object instead of a pointer to an object. This\nway it will automatically be destructed correctly when your\napplication ends. Disadvantage: No real way to shutdown the game and\n'reboot' without restarting the app, but unless you are switching\nlibraries or graphic backends, this is also not really needed.</li>\n<li>Leave everything as it is, don't worry. I know, the destructor won't\nrun, but upon application exit the OS will reclaim every bit of\nmemory anyway. However, DO NOT DO THIS IF there are 'important'\ntasks that need to be taken care of during cache destruction, like\n(i don't know) writing something back to disk. Note that this is\nonly viable if you want to discard the complete cache object (not\nonly its contents) only upon process termination, or else you are\ngoing to have serious memory leaks. Also do not do this if the application needs to continue execution for a long time after the your game has quit.</li>\n<li>In case neither 1) or 2) are viable, you are probably in the need to shut down your 'game\nengine' and start it back up again without terminating your app. In\nthis case, however you will have some method anyway to 'shut down\neverything'/'close engine'/'reinit'/call it whatever you want. Then\nsimply, this method can take care of releasing your cache.</li>\n</ol>\n\n<p>Note to solution 2: This 'solution' is dirty and if you are a good coder you really should properly destruct all objects even upon application exit, just like I always do. But to be honest, in this particular case you have almost nothing to gain from it. The only thing that I can think of is, if you are using a memory leak detector, properly terminating everything will spare you thousands of false warnings (which IS important IF you are using a leak detector). If you are not sure, forget about option 2) and do it right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-16T01:19:59.903",
"Id": "217400",
"Score": "0",
"body": "Hello from the World of Tomorrow! :D I've \"solved\" the issue by hooking into the `exit` function via `atexit` and my own cleanup function where I call `clear()` on the map. The cache has to be a friend of the cleanup function but that's a small price to pay."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T08:37:23.487",
"Id": "4137",
"ParentId": "4135",
"Score": "4"
}
},
{
"body": "<p>If I'm understanding what you're doing correctly, it seems like the callers should get a <code>shared_ptr</code> to the bitmap, while the cache keeps a <code>weak_ref</code>. That way, bitmaps will only exist while you are using them, and the cache will know when a bitmap stops being used (the <code>weak_ref</code> becomes invalid). However, this does lead to the overhead of <code>shared_ptr</code>, which may be unacceptable in a game.</p>\n\n<p>EDIT:</p>\n\n<p>I'm not sure why you'd <code>new</code> and <code>delete</code> the map; however, you could make people Release() each individual bitmap, and the map would then check for that while cleaning. This will incur very little overhead (one bool, plus a check and occasional delete when searching).</p>\n\n<p>In any case, just letting it be and never unloading bitmaps sounds like a very bad option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T18:51:54.890",
"Id": "4266",
"ParentId": "4135",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4137",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T07:29:15.113",
"Id": "4135",
"Score": "4",
"Tags": [
"c++",
"classes",
"cache",
"static"
],
"Title": "Static class member destruction in C++"
}
|
4135
|
<p>I needed a mutable priority queue (the priorities can be changed) for my currect project, and started by simply wrapping a class around a <code>std::vector</code> and make/push/pop_heap. However, it is not nearly fast enough, profiling shows ~70% of processing time is spent in the queue. I need some input on how to either fix the queue, or if there already exists something which can do this but better (there is a <code>mutable_queue</code> in boost, but in the "pending" directory, for instance).</p>
<pre><code>template <typename ValueT, typename KeyT>
class UnconsistentQueue {
struct Elem {
Elem(const ValueT& v_, const KeyT& p_) : v(v_), p(p_) {}
bool operator<(const Elem& rhs) const {
// Note that this is reversed, since we want a lowest-first prio queue
return rhs.p < p;
}
ValueT v;
KeyT p;
};
public:
typedef typename std::vector<Elem>::iterator iterator;
typedef typename std::vector<Elem>::const_iterator const_iterator;
void push(const ValueT& v, const KeyT& p) {
q.push_back(Elem(v, p));
std::push_heap(q.begin(), q.end());
}
void update(const ValueT& v, const KeyT& p) {
update(v, p, q.begin());
}
void update(const ValueT& v, const KeyT& p, const_iterator hint) {
iterator i = q.begin();
if(hint->v == v)
std::advance(i, std::distance<const_iterator>(q.begin(), hint));
else {
for(; i != q.end(); ++i) {
if(i->v == v)
break;
}
}
if(i != q.end()) {
i->p = p;
std::make_heap(q.begin(), q.end());
}
}
void pop() {
std::pop_heap(q.begin(), q.end());
q.pop_back();
}
const ValueT& top() const { return q.front().v; }
const KeyT& top_key() const { return q.front().p; }
const_iterator begin() const { return q.begin(); }
const_iterator end() const { return q.end(); }
const_iterator find(const ValueT& v) const {
const_iterator i;
for(i = q.begin(); i != q.end(); ++i) {
if(i->v == v)
break;
}
return i;
}
void remove(const ValueT& v) {
const_iterator i = find(v);
if(i != q.end()) {
q.erase(i);
std::make_heap(q.begin(), q.end());
}
}
bool empty() const { return q.empty(); }
void clear() { q.clear(); }
private:
std::vector<Elem> q;
};
</code></pre>
<p>In my project, the key type is encoded in this struct:</p>
<pre><code>template <typename CostType>
struct Key {
bool operator<=(Key<CostType> rhs) const {
return (k1 <= rhs.k1) || (k1 == rhs.k1 && k2 <= rhs.k2);
}
bool operator<(Key<CostType> rhs) const {
return (*this <= rhs) && !(rhs <= *this);
}
CostType k1;
CostType k2;
};
</code></pre>
<p>(The paper which defines the algorithm only defines a <code><=</code> operator, but I need a strict weak ordering, so I implemented it like this. Good?)</p>
<p>Below is the relevant part of the profiling results as generated by AMD CodeAnalyst</p>
<pre><code>CS:EIP Symbol + Offset 64-bit Timer samples
0xf156c0 Key<double>::operator<= 14.45
0xf1c350 std::_Adjust_heap<UnconsistentQueue<unsigned int,Key<double> >::Elem *,int,UnconsistentQueue<unsigned int,Key<double> >::Elem> 7.29
0xf140d0 Key<double>::operator< 6.91
0xf1d260 UnconsistentQueue<unsigned int,Key<double> >::Elem::operator< 6
0xf1c250 std::_Push_heap<UnconsistentQueue<unsigned int,Key<double> >::Elem *,int,UnconsistentQueue<unsigned int,Key<double> >::Elem> 5.64
0xf15910 std::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> > >::operator!= 4.56
0xf16570 std::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> > >::operator== 4.27
0xf15160 UnconsistentQueue<unsigned int,Key<double> >::find 4.01
0xf16130 std::vector<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> >::end 3.99
0xf1b0b0 std::_Make_heap<UnconsistentQueue<unsigned int,Key<double> >::Elem *,int,UnconsistentQueue<unsigned int,Key<double> >::Elem> 3.21
0xf16a90 std::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> > >::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem, 2.97
0xf15b50 std::_Tree<std::_Tmap_traits<unsigned int,double,std::less<unsigned int>,std::allocator<std::pair<unsigned int const ,double> >,0> >::_Lbound 2.93
0xf16540 std::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> > >::operator++ 2.41
0xf1c240 std::_Move<UnconsistentQueue<unsigned int,Key<double> >::Elem &> 1.86
0xf16500 std::_Vector_const_iterator<std::_Vector_val<UnconsistentQueue<unsigned int,Key<double> >::Elem,std::allocator<UnconsistentQueue<unsigned int,Key<double> >::Elem> > >::operator* 1.81
15 functions, 408 instructions, Total: 120448 samples, 72.33% of shown samples, 32.53% of total session samples
</code></pre>
|
[] |
[
{
"body": "<p>The standard already has a <a href=\"http://www.sgi.com/tech/stl/priority_queue.html\" rel=\"nofollow\">priority queue</a>.</p>\n\n<pre><code>std::priority_queue\n</code></pre>\n\n<p>Internally it uses std::vector<> (by default) but the elements in the vector are organized into a binary tree structure for faster sorting and organization. (ie element 0 is the root, element 1,2 are children of 0 etc).</p>\n\n<p>If you want to do this manually you can your own container and the following methods:</p>\n\n<ul>\n<li><a href=\"http://www.sgi.com/tech/stl/push_heap.html\" rel=\"nofollow\">Push Heap</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/pop_heap.html\" rel=\"nofollow\">Pop Heap</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/make_heap.html\" rel=\"nofollow\">Make Heap</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/sort_heap.html\" rel=\"nofollow\">Sort Heap</a></li>\n</ul>\n\n<p>The problem with the heap structure it only really supports removal of the head node. Once you start deleting nodes in the middle you need to re-build the heap manually (which seems to be your problem). According to the documentation re-building the map is linear (up-to 3n plus your linear traversal so 4n) so O(n).</p>\n\n<p>So it does not look like you really want a priority queue. What you really want to use is the std::map. This allows O(log(n)) insertion and deletion of elements anywhere in the map and the container is maintained in sorted order (using strict weak ordering). So you can iterate over the map in order if required.</p>\n\n<p>Also once elements are in the container there is no further copying of the elements. In the priority queue the elements were copied around the vector and if the copy construction of the key/value was expensive then other operation would suffer.</p>\n\n<p>Of course there will be a cost in using a map which is the extra memory it will use (a vector is very efficient in terms of memory usage).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T19:15:46.130",
"Id": "6199",
"Score": "0",
"body": "Hi! Thanks for reading. I can't use `std::priority_queue` as I need to change the priorities, and also remove elements which are not in the front. I think I'm using the std::push/pop/make_heap functions correctly in my code already, do you disagree? I'm not sure I understand why you'd say I'm keeping a list sorted, as I'm using a vector..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T21:03:35.640",
"Id": "6203",
"Score": "0",
"body": "@carlpett: Sorry misread your code. It seems fine. The costly part is when you insert and remove elements from the middle and call std::make_heap() to force the heap back into the correct shape. You may be able to do that more succinctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T07:14:13.033",
"Id": "6208",
"Score": "0",
"body": "@carlpett: Update answer with alternative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T12:28:34.763",
"Id": "6273",
"Score": "0",
"body": "Thank you for your input! However, I ended up using the `boost::d_ary_heap_indirect` class, which implemented the behaviour I wanted, and speeded up my algorithm with a factor 400 :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T18:55:06.180",
"Id": "4152",
"ParentId": "4148",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T17:10:02.807",
"Id": "4148",
"Score": "2",
"Tags": [
"c++",
"performance"
],
"Title": "Slow mutable priority queue"
}
|
4148
|
<p>We have some developers in house that believe it is best practice to use exception handing as flow control, as well as, thinking that catching and re-throwing exceptions is effective error handling. </p>
<p>In an effort to educated, I attempted to come up with a simple sample to demonstrate to them the negative effects of doing so. The code sample below is what I came up with. It consistently demonstrates that there is a penalty for gratuitous usage of try/catch blocks; but the effect is much greater than I had anticipated. I can't help but think I've done something very wrong in this sample. I would appreciate any suggestions of improvement.</p>
<p>In this sample, I am comparing the cost of catching and re-throwing an exception with just allowing the exception to bubble up. I needed to execute the methods in parallel to avoid waiting days for the code to execute on high values.</p>
<pre><code> static void Main(string[] args)
{
TimeSpan ts1 = new TimeSpan();
TimeSpan ts2 = new TimeSpan();
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; ++i)
{
Task a = new Task(() =>
{
Stopwatch watch1 = new Stopwatch();
watch1.Start();
function1(function2);
watch1.Stop();
ts1 += watch1.Elapsed;
});
a.Start();
tasks.Add(a);
Task b = new Task(() =>
{
Stopwatch watch2 = new Stopwatch();
watch2.Start();
function1(function3);
watch2.Stop();
ts2 += watch2.Elapsed;
});
b.Start();
tasks.Add(b);
}
while (!tasks.All(t => t.IsCompleted)) ;
Console.WriteLine("Watch1: " + ts1);
Console.WriteLine("Watch2: " + ts2);
Console.ReadLine();
}
static void function1(Action action)
{
try
{
action();
}
catch
{
}
}
static void function2()
{
try
{
int.Parse(null);
}
catch
{
throw;
}
}
static void function3()
{
int.Parse(null);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T21:41:38.870",
"Id": "6204",
"Score": "0",
"body": "You should also include a *proper* `try-catch` block that actually does something with a **specific** exception."
}
] |
[
{
"body": "<p>The while loop you are using is impacting performance. Sleep that check a bit beforehand to give your scenarios some time to think. </p>\n\n<pre><code>do { Thread.Sleep(3000); } while (!tasks.All(t => t.IsCompleted));\n</code></pre>\n\n<p>You may want to suggest some best practices reading to your team, throwing an exception should be reserved for an exceptional circumstance. Use of the throw for rethrowing an exception is correct to keep the stack trace information complete, but again, should be seldom and when they do finally bubble up to the top, the exception information should be captured in a way that they are not just ignored.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/409563/best-practices-for-exception-management-in-java-or-c\">https://stackoverflow.com/questions/409563/best-practices-for-exception-management-in-java-or-c</a></p>\n\n<p><a href=\"http://www.codethinked.com/how-do-you-deal-with-exceptions\" rel=\"nofollow noreferrer\">http://www.codethinked.com/how-do-you-deal-with-exceptions</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T23:11:19.817",
"Id": "4158",
"ParentId": "4155",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4158",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-16T20:50:25.210",
"Id": "4155",
"Score": "2",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Is This a Sufficient Demonstration of the Effects of Exception Handling"
}
|
4155
|
<p>This is the code that I'm using. I'm working on LINQ TO SQL and I'm using this model in my program:</p>
<p><a href="https://stackoverflow.com/questions/7072819/how-can-i-model-this-class-in-a-database/7072841#7072841">How can I model this class in a database</a></p>
<p>The person must have to enter the level, for example 1.2, 1.1.4, etc. The program must check if the level is available or busy. The function <code>ToIntArray</code> is an extension and consists of splitting the text and converting the resulting <code>string[]</code> to <code>int[]</code>.</p>
<p>The first condition, as you can see, is an inconsistency which I have in this post:</p>
<p><a href="https://stackoverflow.com/questions/7085713/problems-with-nullable-types-in-a-linq-function">Problems with nullable types in a LINQ function</a></p>
<pre><code>private void AddButton_Click(object sender, RoutedEventArgs e)
{
NorthwindDataContext cd = new NorthwindDataContext();
int[] levels = LevelTextBox.Text.ToIntArray('.');
string newGroupName = NameTextBox.Text;
Objective currentObjective = null;
int? identity = null;
for (int i = 0; i < levels.Length - 1; i++ )
{
int currentRank = levels[i];
if (identity == null)
{
currentObjective = (from p in cd.Objective
where p.Level == currentRank && p.Parent_ObjectiveID == null
select p).SingleOrDefault();
}
else
{
currentObjective = (from p in cd.Objective
where p.Level == currentRank && p.Parent_ObjectiveID == identity
select p).SingleOrDefault();
}
if (currentObjective == null)
{
MessageBox.Show("Levels don't exist");
return;
}
else
{
identity = currentObjective.ObjectiveID;
}
}
if (currentObjective != null)
{
if (levels.Last() == currentObjective.Level)
{
MessageBox.Show("Level already exists");
return;
}
}
else
{
var aux = (from p in cd.Objective
where p.Parent_ObjectiveID == null && p.Level == levels.Last()
select p).SingleOrDefault();
if (aux != null)
{
MessageBox.Show("Level already exists");
return;
}
}
var newObjective = new Objective();
newObjective.Name = NameTextBox.Text;
newObjective.Level = levels.Last();
newObjective.Parent_ObjectiveID = currentObjective == null ? null : (int?)currentObjective.ObjectiveID ;
cd.Objective.InsertOnSubmit(newObjective);
cd.SubmitChanges();
MessageBox.Show("The new objective has added successfully");
NameTextBox.Clear();
LoadObjectives();
}
</code></pre>
|
[] |
[
{
"body": "<p>A few comments: </p>\n\n<ol>\n<li>You should move this code from the <code>AddButton_Click</code> to some business logic class. </li>\n<li>Maybe you should add some validation of <code>LevelTextBox.Text</code>, before using its value. </li>\n<li><p>You should split this code into different methods. </p>\n\n<blockquote>\n <p>You have three responsibilities here: </p>\n \n <ol>\n <li>Find out if the level exists at all. </li>\n <li>Find out if the specified level already exists. </li>\n <li>Create a new level.</li>\n </ol>\n \n <p>The fact that all three actions use the same data doesn't mean you need to put them in one method. </p>\n</blockquote></li>\n<li><p>Maybe I get it wrong somewhere, but I can't understand how this code checks if the level already exists. I can't see how the code will ever get into the <code>MessageBox.Show(\"Level already exists\");</code> in both places.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T08:14:14.983",
"Id": "4168",
"ParentId": "4160",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T00:00:41.043",
"Id": "4160",
"Score": "3",
"Tags": [
"c#",
"linq",
"wpf"
],
"Title": "Determining if a level exists"
}
|
4160
|
<p>I know this is a pretty simple class for loading a config file into an object, and then accessing it's properties. I think config options should be lightweight and a class like this seems to adds a lot of overhead IMO but I really like being able to access the config properties with $config->propertyName. So do you see any room for improvement? Mainly performance improvements?</p>
<pre><code><?php
// config.class.php
/*
example usage
$config = Config::getInstance(PATH TO FILE, FILE TYPE);
echo $config->ip;
echo $config->db['host'];
example array file
<?php
return array(
'db' => array(
'host' => 'localhost',
'user' => 'user1',
'pass' => 'mypassword'),
'ip' => '123456',
)
*/
class Config
{
private static $_instance = null;
public $options = array();
/**
* Retrieves php array file, json file, or ini file and builds array
* @param $filepath Full path to where the file is located
* @param $type is the type of file. can be "ARRAY" "JSON" "INI"
*/
private function __construct($filepath, $type = 'ARRAY')
{
switch($type) {
case 'ARRAY':
$this->options = include $filepath;
break;
case 'INI';
$this->options = parse_ini_file($filepath, true);
break;
case 'JSON':
$this->options = json_decode(file_get_contents($filepath), true);
break;
//TO-DO add Database option for settings. Table = id, property, value
case 'DATABASE':
$this->options = json_decode(file_get_contents($filepath), true);
break;
}
}
private function __clone(){}
public static function getInstance($filepath, $type = 'ARRAY')
{
if (!isset(self::$_instance)) {
self::$_instance = new self($filepath, $type);
}
return self::$_instance;
}
/**
* Retrieve value with constants being a higher priority
* @param $key Array Key to get
*/
public function __get($key)
{
if (isset($this->options[$key])) {
return $this->options[$key];
}else{
trigger_error("Key $val does not exist", E_USER_NOTICE);
}
}
/**
* Set a new or update a key / value pair
* @param $key Key to set
* @param $value Value to set
*/
public function __set($key, $value)
{
$this->options[$key] = $value;
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Mainly performance improvements?</p>\n</blockquote>\n\n<p>There doesn't seem to be much oppurtunity for performance improvements. This class basically consists of (1) loading and parsing the configuration and (2) accessing data. For loading, parse_ini_file and json_decode are builtin methods so unless you write your own parser from scratch, you won't make this any faster. And accessing data is basically a single condition checking and an array lookup, not much to improve there either.</p>\n\n<p>However, here is a different kind of suggestion. You probably want to make sure that $filepath in the constructor is restricted to specific directories, for example your web root or better, a subfolder of that. That also means checking for attempts to escape from the restricted directory, e.g. $filepath does not have components like <code>../</code>. I can easily imagine an attack where a malicious user gets to place a custom php script in <code>/tmp</code> and then (if you have some other vulnerability in your other code) manages to call <code>new Config('/tmp/attack.php')</code>. Then you have an arbitrary maclicous script executing with the priviliges of your website. Ouch.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T12:10:34.307",
"Id": "4169",
"ParentId": "4162",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T02:51:06.613",
"Id": "4162",
"Score": "4",
"Tags": [
"php"
],
"Title": "PHP Config file loader class"
}
|
4162
|
<p>I feel a need to rewrite a rather large Python class that "does its job" but it looks somewhat terrible since it was pasted together while learning Python and the platform Google App Engine. It works so that there are no bugs towards user but readability and structure are poor. This is also the largest class of the whole project that posts entities to the datastore doing the basic function "ADD" for our entities and related blobs: </p>
<pre><code>class AdLister(FBBaseHandler, I18NHandler):
def post(self, view):
logging.info('in adlister post')
message = ''
challenge = self.request.get('recaptcha_challenge_field').encode('utf-8')
response = self.request.get('recaptcha_response_field').encode('utf-8')
remoteip = os.environ['REMOTE_ADDR']
cResponse = captcha.submit(
challenge,
response,
CAPTCHA_PRV_KEY,
remoteip)
if cResponse.is_valid==True:
isHuman=True
else:#failed anti-spam test and can try again
isHuman=False
data = AdForm(data=self.request.POST)
#Reprint the form
import util
template_values = {'logo':'montao' if util.get_host().endswith('.br') else 'koolbusiness','isHuman':isHuman,'form':data,'user_url': users.create_logout_url(self.request.uri) if users.get_current_user() else 'login','user' : users.get_current_user(),}
template_values.update(dict(current_user=self.current_user, facebook_app_id=FACEBOOK_APP_ID))
template_values.update(dict(capture=captcha.displayhtml(public_key = CAPTCHA_PUB_KEY, use_ssl = False, error = None)))
path = os.path.join(os.path.dirname(__file__), 'market', 'market_insert.html')
self.response.out.write(template.render(path, template_values))
return
from datetime import datetime
from i18n import FBUser
from twitter_oauth_handler import OAuthClient
import random
twenty = random.randint(1,5) > 3
def getGeoIPCode(ipaddr):
from google.appengine.api import memcache
memcache_key = "gip_%s" % ipaddr
data = memcache.get(memcache_key)
if data is not None:
return data
geoipcode = ''
from google.appengine.api import urlfetch
try:
fetch_response = urlfetch.fetch('http://geoip.wtanaka.com/cc/%s' % ipaddr)
if fetch_response.status_code == 200:
geoipcode = fetch_response.content
except urlfetch.Error, e:
pass
if geoipcode:
memcache.set(memcache_key, geoipcode)
return geoipcode
path = os.path.join(os.path.dirname(__file__), 'market', 'credit.html') #consume
lat=0
lng=0
try:
lat = self.request.POST.get('lat')#get lat,lt or latitude
lng = self.request.POST.get('lng')#get lng, ln or longitude
except Exception:
if False:#self.request.POST.get('montao_id'):
lat=-23.7126
lng=-46.6415
else:
pass
if False:#self.request.POST.get('montao_id'):
lat=-23.7126
lng=-46.6415
try:
ad = Ad(location=db.GeoPt(lat, lng))
ad.update_location()#also runs this at edits
except Exception:
ad = Ad()
import util
if util.get_host().find('koolbusiness') > 0:
url = 'www.koolbusiness.com'
if util.get_host().find('lassifiedsmarket') > 0:
url = 'classifiedsmarket.appspot.com'
if util.get_host().find('montao') > 0 or util.get_host().find('localhost') > 0:
path = os.path.join(os.path.dirname(__file__), 'market', 'market_ad_preview.html')
ad.url ='montao'
logo = 'montao'
if (util.get_host().find('acktuellt') > 0 or twenty):
asked_question = Question(question=self.request.get('title'), asker=db.IM("xmpp", 'classifiedsmarket.appspot.com'))#add urn
asked_question.put()
#path = os.path.join(os.path.dirnam e(__file__), 'market', 'market_ad_preview.html')
if (not twenty or util.get_host().find('acktuellt') > 0):
ad.published = False
path = os.path.join(os.path.dirname(__file__), 'market', 'credit.html')
ad.ip = self.request.remote_addr
ad.ipcountry = getGeoIPCode(self.request.remote_addr)
if users.get_current_user():
ad.user = users.get_current_user()
try:
ad.type = self.request.POST.get('type')
except Exception:
pass
ad.title = self.request.POST.get('title')
try:
ad.text = self.request.POST.get('text')
except Exception:
pass
try:
ad.currency = self.request.POST.get('currency')
except Exception:
pass
try:
ad.facebookID = int(self.current_user.id)
except Exception, ex:
logging.debug("failed creating facebookID object for user %s", str(ex))
pass
try:
client = OAuthClient('twitter', self)
info = client.get('/account/verify_credentials')
ad.twitterID = int(info['id'])
except Exception, ex:
logging.debug("creating twitter object for user failed %s", str(ex))
pass
try:
lat = self.request.POST.get('lat')#get lat,lt or latitude
lng = self.request.POST.get('lng')#get lng, ln or longitude
ad.geopt = db.GeoPt(self.request.POST.get('lat'),self.request.POST.get('lng'))#above
ad.geohash = Geohash.encode(float(lat),float(lng), precision=2)#evalu8 precision variable
except Exception:
pass
try:
ad.category = self.request.POST.get('cg')
except Exception:
logging.error(Exception)
if self.request.POST.get('company_ad')=='1':
ad.company_ad = True
try:
ad.url=url
except Exception:
pass
try:
ad.phoneview = self.request.get('phone_hidden',None) is not None
except Exception:
pass
try:
ad.place = self.request.POST.get('place')
ad.postaladress = self.request.POST.get('place')
except Exception:
pass
try:
ad.name = self.request.POST.get('name')
except Exception:
pass
try:
ad.email = self.request.POST.get('email')
except Exception:
pass
try:
ad.phonenumber = self.request.POST.get('phonenumber')
except Exception:
pass
ad.price = self.request.POST.get('price')
ad.save()
self.s = session.Session()
self.s['key'] = ad.key()
def create_image(number, self, file, ad):
logging.debug('creating image')
try:
file_name = files.blobstore.create()
with files.open(file_name, 'a') as f:
f.write(file)
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)
logging.debug('creating image')
img = Image(reference=ad)
logging.debug('creating image')
img.primary_image = blob_key
logging.debug('creating image')
img.put()
ad.put()
except Exception:
self.response.write(Exception)
#pass
#deprecate see http://stackoverflow.com/questions/5863305/storing-mime-type-with-blobstore
try:
filedata = file
im = Image(reference=ad)
im.full = filedata
im.small = images.resize(filedata, 640, 480)
tmp=images.Image(im.full)
if tmp.width > 80:
im.thumb = images.resize(filedata, 80, 100)#don't if already small
file_name = self.request.POST.get(number).filename
im.name = file_name
im.published = True
n = im.name.lower()
ext = 'jpg'
for e in ['jpeg','jpg','png','tif','tiff','gif','bmp']:
if n.endswith(e):
ext=e
im.full_ext=ext
im.small_ext=ext
im.thumb_ext=ext
im.save()
except Exception:
#self.response.write(Exception)
pass
#end deprecate
try:
create_image('file', self, self.request.POST.get('file').file.read(), ad)
except Exception:
pass
try:
create_image('file2', self, self.request.POST.get('file2').file.read(), ad)
except Exception:
pass
try:
create_image('file3', self, self.request.POST.get('file3').file.read(), ad)
except Exception:
pass
try:
create_image('file4', self, self.request.POST.get('file4').file.read(), ad)
except Exception:
pass
try:
create_image('file5', self, self.request.POST.get('file5').file.read(),ad)
except Exception:
pass
try:
ad.set_password(self.request.POST.get('password'))
except Exception:
size = 9
vowels='aeiou'
consonants='bcdfghjklmnpqrstvwxyz'
password=''
from random import randint
from random import choice
import random
minpairs = 4
maxpairs = 6
for x in range(1,random.randint(int(minpairs),int(maxpairs))):
consonant = consonants[random.randint(1,len(consonants)-1)]
if random.choice([1,0]):
consonant=string.upper(consonant)
password=password + consonant
vowel = vowels[random.randint(1,len(vowels)-1)]
if random.choice([1,0]):
vowel=string.upper(vowel)
password=password + vowel
newpasswd = password
ad.set_password(newpasswd)
ad.put()
key = ad.key()
matched_images=ad.matched_images
try:
im_from = db.IM("xmpp", 'classifiedsmarket.appspot.com')
except Exception:
pass
#"Added %s."
msg = _("Added %s.") % str(ad.title.encode('utf-8'))
self.response.out.write(template.render(path, {'url':util.get_host(),'message': msg ,'user':users.get_current_user(), 'ad.user':ad.user, 'ad':ad, 'matched_images': matched_images,}) )
</code></pre>
|
[] |
[
{
"body": "<p>My first impulse would be to take care of repeating </p>\n\n<pre><code>try:\n ...\nexcept Exceptiopn:\n pass\n</code></pre>\n\n<p>structures that take a lot of space e.g.</p>\n\n<pre><code>def value_of(self, param):\n try:\n return self.request.POST.get(param)\n except Exception:\n return None\n\n...\n\nad.email = self.value_of('email')\n</code></pre>\n\n<p>or even better (as provided by James Khoury): </p>\n\n<pre><code>ad.email = self.request.POST.get(param, None)\n</code></pre>\n\n<p>and </p>\n\n<pre><code>def create_images(self, ad, *files):\n for file in files:\n try:\n create_image(file, self, self.request.POST.get(file).file.read(),ad)\n except Exception: \n pass\n\n...\n\nself.create_images(ad, 'file1','file2','file3','file4','file5')\n</code></pre>\n\n<p>The second thing I would do is try to divide the long function to multiple functions that can be sensibly named. Possible functions include</p>\n\n<ul>\n<li>generate_password</li>\n<li>is_submitter_human</li>\n<li>create_facebook_id</li>\n<li>create_twitter_id</li>\n<li>geolocate</li>\n</ul>\n\n<p>When the basic functions have defined I would go on and try to write the post function in terms of higher abstractions that use the functions and let me read the intent of it as it was an executable comment. </p>\n\n<pre><code>def post(self, view): \n if not self.is_submitter_human():\n return\n self.geolocate()\n ad = self.create_ad()\n self.populate_ad_with_request_parameters(ad)\n self.connect_with_facebook(ad)\n self.connect_with_twitter(ad)\n self.create_images(ad)\n self.set_password(ad)\n self.save(ad)\n self.render(ad);\n</code></pre>\n\n<p><em>Disclaimer: I don't know Python</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T19:52:21.043",
"Id": "6223",
"Score": "0",
"body": "I agree. That was also my spontaneous reaction that Iäm wasting a lot of statement just making a try / except where it might not be needed. Thank you also for the other concrete advice and that you actually read the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T23:25:32.650",
"Id": "6266",
"Score": "2",
"body": "Why not instead of `def value_of(self, param):\n try:\n return self.request.POST.get(param)\n except Exception:\n return None\n` use `self.POST.get(param, None)` it does the same thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T09:06:40.527",
"Id": "6270",
"Score": "1",
"body": "In my defense: I did write a disclaimer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T13:52:16.830",
"Id": "6374",
"Score": "0",
"body": "Excellent review thanks to Aleksi and James. I needed this. :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T06:19:57.417",
"Id": "4165",
"ParentId": "4164",
"Score": "5"
}
},
{
"body": "<p>Start with writing unit and/or feature tests that capture the current behaviour. Then begin refactoring while making sure that the tests pass all the time.</p>\n\n<p>If you are not an experienced developer \"refactoring\" might be a bit vague; I'd then suggest to simply start with <em>removing duplication</em> in whatever form there is. Aleksi had a couple of examples of extracting methods. Start there.</p>\n\n<p>As you move stuff to methods you will soon see that there are different categories of methods that are used together. This is an indication that these should be moved to a separate classes to encapsulate that behaviour.</p>\n\n<p>Then read about the <a href=\"http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod\" rel=\"nofollow\">SOLID</a> principles and continue from there. Practice, practice, practice and think about what you are doing at all times. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T11:23:21.353",
"Id": "6213",
"Score": "0",
"body": "+1 I love refactoring code when I've got unit tests written for it, I get to leverage as many layers of new or removed abstraction as I want without any worry of screwing up the logic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T08:07:51.753",
"Id": "4167",
"ParentId": "4164",
"Score": "4"
}
},
{
"body": "<p>Have a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP-8</a>. Among the guidelines that it offers is that you get all your imports in the beginning of the file. There is even a tool named <a href=\"http://pypi.python.org/pypi/pep8\">pep8.py</a> that you should run on your code that alerts you of some of the unfollowing of those guidelines.</p>\n\n<p>One other note, on this line:</p>\n\n<pre><code>if cResponse.is_valid==True:\n</code></pre>\n\n<p><code>True</code> isn't needed at all. Just leave it as:</p>\n\n<pre><code>if cResponse.is_valid:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T15:28:43.123",
"Id": "4172",
"ParentId": "4164",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4165",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T04:25:04.247",
"Id": "4164",
"Score": "6",
"Tags": [
"python",
"google-app-engine"
],
"Title": "Add lister class"
}
|
4164
|
<p>I need a version of the mvc RouteValueDictionary that I can chain Add calls to, ie:</p>
<pre><code>new RouteValueDictionaryExtended()
.AddValue("controller", "Home")
.AddValue("action", "Index")
.AddValue("id", 3)
</code></pre>
<p>Is there a more description name I can use for this instead of just "Extended"? </p>
<pre><code> public class RouteValueDictionaryExtended : System.Web.Routing.RouteValueDictionary
{
public RouteValueDictionaryExtended() : base() { }
public RouteValueDictionaryExtended(object values) : base(values) { }
public RouteValueDictionaryExtended(System.Collections.Generic.IDictionary<string,object> dict) : base(dict) { }
public RouteValueDictionaryExtended AddValue(string key, object obj)
{
var newDict = new RouteValueDictionaryExtended(this);
newDict.Add(key, obj);
return newDict;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T14:12:34.320",
"Id": "6248",
"Score": "0",
"body": "Two questions:\n1. Maybe I miss something, but how does 'new RouteValues().WithValue(\"controller\", \"Home\").WithValue(\"action\", \"Index\");' returns 'RouteValues'? The return type of 'WithValue' method is 'DictionaryBuilder<RouteValueDictionary>', not 'RouteValues'. \n2. What stops you from using extension methods?"
}
] |
[
{
"body": "<p>If you need this class only to be able to chain 'Add' calls, maybe it would be better to just create an extension method:</p>\n\n<pre><code>public static class RouteValueDictionaryExtensions\n{\n public static RouteValueDictionary AddValue(this RouteValueDictionary routeValueDictionary, string key, object obj)\n {\n routeValueDictionary.Add(key, obj);\n return routeValueDictionary;\n }\n}\n</code></pre>\n\n<p>And use it like:</p>\n\n<pre><code> new RouteValueDictionary()\n .AddValue(\"controller\", \"Home\")\n .AddValue(\"action\", \"Index\")\n .AddValue(\"id\", 3);\n</code></pre>\n\n<p>If you still need a separate class and its only purpose is to add this chaining ability, then express it in the name like 'ChainableRouteValueDictionary' or 'FluentRouteValueDictionary'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T15:21:28.163",
"Id": "6215",
"Score": "0",
"body": "I don't think an extension method would work in my context, but I Fluent was exactly what I was looking for thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T15:15:55.293",
"Id": "4171",
"ParentId": "4170",
"Score": "5"
}
},
{
"body": "<p>I would actually recommend you to use the (Constructor) Builder pattern if you are only doing this for easier object initialization:</p>\n\n<pre><code>public class RouteValueDictionaryBuilder\n{\n private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();\n\n public RouteValueDictionaryBuilder WithValue(string key, object obj)\n {\n values_.Add(Tuple.Create(key, obj));\n return this;\n }\n\n public RouteValueDictionary Build()\n {\n var dict = new RouteValueDictionary();\n foreach (var value in values_)\n {\n dict.Add(value.Item1, value.Item2);\n }\n return dict;\n }\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>var dict = new RouteValueDictionaryBuilder()\n .WithValue(\"controller\", \"Home\")\n .WithValue(\"action\", \"Index\")\n .WithValue(\"id\", 3)\n .Build();\n</code></pre>\n\n<p>This avoids the higher coupling (inheritance) between the dictionary and its subclass, which is there only to help with initializing the dictionary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T07:31:40.383",
"Id": "4188",
"ParentId": "4170",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "4188",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T14:58:10.867",
"Id": "4170",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Is there a better name for this class?"
}
|
4170
|
<p>Would a join be quicker here? I tested a join and it's almost the same time! Basically its a ray casting mechanism that finds all properties in a square on GMaps, and then there's a javascript function that finds the point in polygon. So at any time, the records fetched could be in the tens of thousands. </p>
<p>The first statement finds all the postcodes in the latLongs, the second one finds all the properties in that postcode.</p>
<p>Bear in mind I just knocked this up very quickly, as the raycasting javascript took up most of my designated time</p>
<pre><code> $latlongs = explode("), ", $_GET['bounds']);
$first = ($latlongs[0]);
$first = substr($first, 2);
$second = $latlongs[1];
$second = substr(substr($second, 1),0, -2);
$first = explode(", ", $first);
$second = explode(", ", $second);
//$result = mysql_query("SELECT * FROM `postcodeGoogle` WHERE lat");
$lat1 = $first[0];
$lat2 = $second[0];
$long1 = $first[1];
$long2 = $second[1];
$resultE = "";
$result = mysql_query("SELECT * FROM `postcode`.`postcodeGoogle` WHERE (`lat` BETWEEN '$lat1' AND '$lat2') AND (`long` BETWEEN '$long1' AND '$long2')")or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$prop = mysql_query("SELECT * FROM `digital_hub`.`address_list` WHERE `postcode`='".$row['postcode']."'")or die(mysql_error());
echo $row['postcode'];
echo mysql_num_rows($prop);
while($propRow=mysql_fetch_assoc($prop)){
$resultE = $resultE."(".$row['lat'].", ".$row['long'].") || ";
}
}
$resultE = substr($resultE, 0, -4);
echo $resultE;
</code></pre>
|
[] |
[
{
"body": "<p>Personally I would go with a join even if they are currently the same speed.</p>\n\n<p>This way your code automatically gets upgraded when the DB gets upgraded (ie when a new index is added to the DB or they decide to partition the DB by latitude/longitude). In this situation if you are using a Join your code will automatically benefit from any improvement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T13:18:42.020",
"Id": "6247",
"Score": "0",
"body": "Ok thanks, changed it to a join now. I tested by doing the whole of kettering and wellingborough, results are: `load: 98796ms - parse: 0ms - display: 1ms`, and the memory size gets exhausted. I could up memory time, but I'd rather segment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T14:29:29.663",
"Id": "6249",
"Score": "0",
"body": "Although it's not technically an answer, I will mark yours as correct as noone else has put any, and I have made my code 100x quicker as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T18:14:18.840",
"Id": "4177",
"ParentId": "4173",
"Score": "1"
}
},
{
"body": "<pre><code><?php \n\ninclude(\"db.php\");\nmysql_select_db(\"digital_hub\");\n$latlongs = explode(\"), \", $_GET['bounds']);\n\n\n$first = ($latlongs[0]);\n$first = substr($first, 2);\n\n\n$second = $latlongs[1];\n$second = substr(substr($second, 1),0, -2);\n\n$first = explode(\", \", $first);\n$second = explode(\", \", $second);\n//$result = mysql_query(\"SELECT * FROM `postcodeGoogle` WHERE lat\");\n$lat1 = $first[0];\n$lat2 = $second[0];\n\n$long1 = $first[1];\n$long2 = $second[1];\n$resultE = \"\";\n$result = mysql_query(\"SELECT * FROM `digital_hub`.`address_list` INNER JOIN `postcode`.`postcodeGoogle` ON `digital_hub`.`address_list`.`postcode` = `postcode`.`postcodeGoogle`.`postcode` WHERE `postcode`.`postcodeGoogle`.`lat` >= '$lat1' AND `postcode`.`postcodeGoogle`.`lat` <= '$lat2' AND `postcode`.`postcodeGoogle`.`long` >= '$long1' AND `postcode`.`postcodeGoogle`.`long` <= '$long2'\")or die(mysql_error());\n\nwhile($row = mysql_fetch_assoc($result)){\n\n\n\n $resultE = $resultE.\"(\".$row['lat'].\", \".$row['long'].\") || \";\n\n}\n$resultE = substr($resultE, 0, -4);\necho $resultE;\n?>\n</code></pre>\n\n<p>I then indexed all columns that were used by this query, and upped memory limit to 512M. Works a treat.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T14:30:18.103",
"Id": "4189",
"ParentId": "4173",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T15:31:12.483",
"Id": "4173",
"Score": "0",
"Tags": [
"php",
"mysql"
],
"Title": "Make two MySQL statements & loop quicker"
}
|
4173
|
<p>I'm looking for a better way to create objects based off of a value of a string. </p>
<p>Consider the following:</p>
<p>Input file:</p>
<pre class="lang-none prettyprint-override"><code>//each Vehicle type has a list of different options
//whose length varies, I provided a simple case
van*2006*dodge*grand caravan*green~
car*2010*toyota*corolla*red~
truck*2005*toyota*tundra*black~
</code></pre>
<p>Classes:</p>
<pre><code>abstract class Vehicle: IVehicle{
public int Year;
public string Make;
public string Model;
...
}
class Van : Vehicle
{
...
}
class Car : Vehicle
{
...
}
class Truck : Vehicle
{
...
}
</code></pre>
<p>Program:</p>
<pre><code>static void Main(string[] args)
{
char delimiter = '*';
string fileToRead = "inventory.csv";
string currentLine = string.Empty;
List<IVehicle> inventory = new List<IVehicle>();
//Open file
using (StreamReader reader = new StreamReader(fileToRead))
{
//while you read each line
while ((currentLine = reader.ReadLine()) != null)
{
IVehicle temp;
//Tokenize the line
string[] parts = currentLine.Split(delimiter);
switch(parts[0])
{
case "van":
temp = new Van();
...
break;
case "car"
temp = new Car();
...
break;
case "truck"
temp = new Truck();
...
break;
}
inventory.add(temp);
}
}
...
}
</code></pre>
<p>My problem with the code is the switch statement. It feels messy and I'm looking for a better way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T16:09:08.147",
"Id": "6217",
"Score": "0",
"body": "What's a `Vechicle`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T03:07:06.800",
"Id": "83706",
"Score": "0",
"body": "have you considered Enum.Parse?"
}
] |
[
{
"body": "<p>You could use the abstract factory pattern and pass the vehicle type to the create method of the factory. That would definitely be cleaner and allow for easier exstensibility when someone wants to create a new type of vehicle (crossover, suv, etc).</p>\n\n<p>An example can be found <a href=\"http://dofactory.com/Patterns/PatternAbstract.aspx\" rel=\"nofollow\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T22:01:24.450",
"Id": "6230",
"Score": "0",
"body": "Scott explicitly asked to avoid the switch statement, but the factory pattern still requires it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T07:09:18.653",
"Id": "6242",
"Score": "2",
"body": "@ultimA: Who says that the factory pattern implementation can't accept the raw string as input and use reflection, as you do in your answer? AFAIK the factory pattern does not _require_ a switch statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T16:01:48.463",
"Id": "4175",
"ParentId": "4174",
"Score": "3"
}
},
{
"body": "<p>In .Net laguages you can easily instatiate any object given only the full name of the class (=namespace+class name).</p>\n\n<p>Here is a runnable example:</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\nnamespace Test\n{\n\n class MsgPrinter\n {\n public MsgPrinter()\n {\n System.Console.WriteLine(\"Hello!\");\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n MsgPrinter printer = assembly.CreateInstance(\"Test.MsgPrinter\") as MsgPrinter;\n Console.Read();\n }\n }\n}\n</code></pre>\n\n<p>So in your case it would break down to something like (of course, the names in your parameter file would need to exactly match the class names in your application):</p>\n\n<pre><code>...\nstring[] parts = currentLine.Split(delimiter);\nVehicle vehicle = Assembly.GetExecutingAssembly().CreateInstance(namespace_name+\".\"+parts[0]) as Vehicle;\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T12:52:38.727",
"Id": "6274",
"Score": "1",
"body": "(First-time visitor to this site) I used this as an opportunity to learn about a feature - reflection - that I'd had absolutely no experience with. I don't know what the protocol here is, so rather than add my code to your answer I put it on http://steven.vorefamily.net/using-reflection-to-read-a-text-file/ - if I should add it to @ultimA's answer instead, or if this is otherwise inappropriate, please let me know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T17:27:16.687",
"Id": "4176",
"ParentId": "4174",
"Score": "11"
}
},
{
"body": "<p>Here are a few tips:</p>\n\n<ol>\n<li>I would use regular expression (and specifically regular expression groups) to parse strings.</li>\n<li><p>Instead of a huge switch/case statement it is better to use a small IDictionary which contains all possible mappings from car type to constructor:</p>\n\n<pre><code> IDictionary<string, Func<IVehicle>> carBuilder = new Dictionary<string, Func<IVehicle>>();\n carBuilder.Add(\"van\", () => { return new Van(); });\n carBuilder.Add(\"car\", () => { return new Car(); });\n carBuilder.Add(\"truck\", () => { return new Truck(); });\n</code></pre></li>\n</ol>\n\n<p>And you can always get an instance of a Vehicle type using:</p>\n\n<pre><code>IVehicle vehicle = carBuilder[\"van\"]();\n</code></pre>\n\n<p>It is always better to clearly separate concerns:</p>\n\n<ul>\n<li><p>Introduce a DTO class called VehicleInfo which will contain all columns of a row in your csv file.</p></li>\n<li><p>Introduce a class for parsing csv file named VehicleInfoProvider which has a method:</p>\n\n<p>public IList GetVehicleInfos(string filePath)</p></li>\n</ul>\n\n<p>It will parse the file using the regular expression and fill all fields of a VehicleInfo class</p>\n\n<ul>\n<li><p>Another class that can build specific vehicles based on a VehicleInfo. Lets name it VehicleBuilder. It has a method:</p>\n\n<p>public IVehicle CreateVehicle(VehicleInfo info)</p></li>\n</ul>\n\n<p>This class would contain the dictionary and will be able to create all possible types of vehicle.</p>\n\n<ul>\n<li><p>Using a foreach statement you can parse file rows and create all instances:</p>\n\n<pre><code> IList<VehicleInfo> vehicleInfos = vehicleProvider.GetVehicleInfos(path);\n\n foreach (var vehicleInfo in vehicleInfos)\n {\n IVehicle vehicle = vehicleBuilder.CreateVehicle(vehicleInfo.VehicleType);\n inventory.Add(vehicle);\n }\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T07:49:07.370",
"Id": "4256",
"ParentId": "4174",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4176",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T15:34:15.730",
"Id": "4174",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Better way to create objects from strings"
}
|
4174
|
<p>My page contains: GridView1, GridView2, Button1, Button2, DropDownList1 I bind Gridviews to the table selected in dropdown like this:</p>
<pre><code>Dim results as DataTable
Select Case ddl1.SelectedValue
Case 0
Dim cl as ClassZero = new ClassZero()
results = cl.GetClassZeroNames()
Case 1
Dim cl as ClassOne = new ClassOne()
results = cl.GetClassOneNames()
Case 2
Dim cl as ClassTwo = new ClassTwo()
results = cl.GetClassTwoNames()
End Select
GridView1.DataSource = results
GridView1.DataBind()
</code></pre>
<p>Then I have two buttons with the following code:</p>
<pre><code>Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
Select Case ddl1.SelectedValue
Case 0
Dim cl as ClassZero = new ClassZero()
results = cl.RunInsert()
Case 1
Dim cl as ClassOne = new ClassOne()
results = cl.RunInsert()
Case 2
Dim cl as ClassTwo = new ClassTwo()
results = cl.RunInsert()
End Select
End Sub
</code></pre>
<p>And</p>
<pre><code>Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
Select Case ddl1.SelectedValue
Case 0
Dim cl as ClassZero = new ClassZero()
results = cl.RemoveFromZero()
Case 1
Dim cl as ClassOne = new ClassOne()
results = cl.RemoveFromOne()
Case 2
Dim cl as ClassTwo = new ClassTwo()
results = cl.RemoveFromTwo()
End Select
End Sub
</code></pre>
<p>For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?</p>
<p>RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T19:55:25.610",
"Id": "6224",
"Score": "0",
"body": "I don't think there is much different you can do here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T23:16:42.207",
"Id": "6232",
"Score": "0",
"body": "Is the title accurate? Multi-threading is involved? If so, that is important but you don't explain any of that in your question ..."
}
] |
[
{
"body": "<p>I like to use Dictionaries for stuff like this. So in your first instance you could create a <code>Dictionary<int,DataTable></code> and use that instead of the switch statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T19:23:29.740",
"Id": "4179",
"ParentId": "4178",
"Score": "0"
}
},
{
"body": "<p>The <code>switch-statement</code> has very little overhead. A Dictionary will clean it up but isn't as expressive as a switch statement. You still have to instance the dictionary and fill it with the values. </p>\n\n<p>I really don't see anything wrong with what your are doing. Some may nit-pick and recommend that the switch statement should be in another method. When you get down to it, these switch statements are probably the least of your concerns. Save those for when you really have nothing else to work on. </p>\n\n<p><strong>Update</strong><br>\nSeeing the update, the first thing I see is the same classes instantiated over and over ...and a couple of ways of dealing with this. </p>\n\n<p>Option 1:\nDo <code>ClassZero</code>, <code>ClassOne</code>, <code>ClassTwo</code> require a new instance every time? In other words, why not make them static. You won't have the instantiation code repeated. That would clean things up tremendously. </p>\n\n<p>Option 2:\nIf the classes must be instantiated every time, I would think about implementing 2 patterns: <a href=\"http://www.oodesign.com/factory-pattern.html\" rel=\"nofollow\">Factory</a> & <a href=\"http://www.oodesign.com/factory-pattern.html\" rel=\"nofollow\">Command</a> </p>\n\n<p>...There are plenty of examples on the internet and going into the design specifics. </p>\n\n<p>Using both of these patterns will move implementation from your UI logic to a business centric layer. For instance, I believe you could achieve something looking like this: </p>\n\n<pre><code>Dim cl as IDataClass = DataClassFactory.CreateDataClass(ddl1.SelectedValue);\n\nDim results as DataTable = cl.GetClassNames()\n\nGridView1.DataSource = results\nGridView1.DataBind()\n</code></pre>\n\n<p>Basically, then, in each of your button click events, you will create an <code>IDataClass</code> derived <code>ClassZero</code>, <code>ClassOne</code>, <code>ClassTwo</code>. </p>\n\n<p>IDataClass defines the method GetClassNames() which the sub-classes will implement independent of each other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T21:24:22.110",
"Id": "6225",
"Score": "0",
"body": "I can't agree that switch-statement has little overhead. In this particular example, when dll1 gets new value (4) we'll have to change code in 3 places. So, is think it's better to use Dictionary. It might be not so expressive as switch-statement, but it will allow you to change the code in one place only."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T21:39:23.193",
"Id": "6226",
"Score": "0",
"body": "Or you can change code in 3 dictionaries. Not much different. A different pattern, possibly the Command pattern would make this much better. But the OP hasn't provided enough code to be able to do much more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T05:59:47.440",
"Id": "6239",
"Score": "0",
"body": "Actually, by Dictionary I meant a class with delegates for every type of event handlers. So in event handler 'btn1_Click' you use it like _dllHandlers[ddl1.SelectedValue].RunInsert(). And for 'btn2_Click' event handler like _dllHandlers[ddl1.SelectedValue].RunRemove(). It also could be implemented as List of such classes, but it's minor details of the implementation. I could write a complete example, if this description is not clear."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T20:49:29.700",
"Id": "4180",
"ParentId": "4178",
"Score": "0"
}
},
{
"body": "<p>You could use delegates. Set delegates in the Change event of <code>ddl1</code>, then you can always call the same delegates in your button handlers. This way you only need a switch in <code>ddl1</code> Change event, and your button handlers will become much cleaner. However, even though this would make the code much more maintainable/readable, it'd probably be less efficient, though you still wouldn't be able to feel the difference in UI handlers.</p>\n\n<p><strong>Update:</strong> example added</p>\n\n<p>Something along these lines (not copy&paste):</p>\n\n<pre><code>Public Delegate Function CreateClassDelegate() As NumberClass\n\nPublic Class Form\n Public CreateClass As CreateClassDelegate\n\n Private Sub ddl1_SelectedValueChanged(sender As Object, e As EventArgs)\n Select Case Integer.Parse(TryCast(ddl1.SelectedItem, String))\n Case 0\n CreateClass = New CreateClassDelegate(AddressOf ClassZero.CreateClassZero)\n Exit Select\n Case 1\n CreateClass = new CreateClassDelegate(AddressOf ClassOne.CreateClassOne);\n Exit Select\n Case 2\n CreateClass = new CreateClassDelegate(AddressOf ClassTwo.CreateClassTwo);\n Exit Select\n End Select\n End Sub\n\n Private Sub btn1_Click(sender As Object, e As EventArgs)\n Dim cl As NumberClass = CreateClass()\n cl.GetNames()\n End Sub\n\n Private Sub btn2_Click(sender As Object, e As EventArgs)\n Dim cl As NumberClass = CreateClass()\n cl.RunInsert()\n End Sub\nEnd Class\n\nPublic MustInherit Class NumberClass\n Public MustOverride Function GetNames() As List(Of String)\n Public MustOverride Sub RunInsert()\n Public MustOverride Sub Remove()\nEnd Class\n\nPublic Class ClassZero\n Inherits NumberClass\n Public Overrides Function GetNames() As List(Of String)\n ...\n Return Nothing\n End Function\n Public Overrides Sub RunInsert()\n ...\n End Sub\n Public Overrides Sub Remove()\n ...\n End Sub\n\n Public Shared Function CreateClassZero() As ClassZero\n Return New ClassZero()\n End Function\nEnd Class\n\n' ... same as above for ClassOne, ClassTwo\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T22:11:24.527",
"Id": "4184",
"ParentId": "4178",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4184",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T19:00:52.993",
"Id": "4178",
"Score": "1",
"Tags": [
"asp.net",
"vb.net"
],
"Title": "Case statement in multiple methods"
}
|
4178
|
<p>The following code has a lot of conditionals. I am trying to write
it in a functional programming way.</p>
<pre><code>val basePrice = {
var b = 0.0
if (runtime > 120)
b += 1.5
if ((day == Sat) || (day == Sun))
b += 1.5
if (!isParquet)
b += 2
if (is3D)
b += 3
b
}
</code></pre>
<p>I think the following code would be a good approach, but maybe I am
complicating this too much.</p>
<pre><code>val basePrice = {
List((runtime > 120, 1.5),
(day == Sat || day == Sun, 1.5),
(!isParquet, 2.0),
(is3D, 3.0)).foldLeft(0.0)((acum, cond) =>
if (cond._1) acum + cond._2 else acum)
}
</code></pre>
<p>How would you write the first snippet of code using functional
programming?</p>
|
[] |
[
{
"body": "<p>Maybe a little bit more readable:</p>\n\n<pre><code>val basePrice = List((runtime > 120, 1.5), \n (day == Sat || day == Sun, 1.5),\n (!isParquet, 2.0),\n (is3D, 3.0)).collect{case (true, b) => b}.sum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T23:24:04.240",
"Id": "6233",
"Score": "0",
"body": "Scala noob here. Would this cause the list to be traversed twice? One for collect and another for sum? Or scala is aware of that and chains it properly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T06:46:15.163",
"Id": "6240",
"Score": "0",
"body": "I think it would be traversed twice, but I really hope you don't want to chain hundreds of these..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T05:02:58.693",
"Id": "7191",
"Score": "0",
"body": "Note that you can use `.view` on lists to make them lazy (and, hence, traversed once)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T21:57:31.707",
"Id": "4183",
"ParentId": "4181",
"Score": "2"
}
},
{
"body": "<p>Each condition is a function. It might be that you could write it more concisely, but I think the code is clearer if you do this:</p>\n\n<pre><code>def priceFunction(cond: => Boolean)(mod: Double => Double) = (_: Double) match {\n case x if cond => mod(x)\n case y => y\n}\n\nval modRuntime = priceFunction(runtime > 120)(_ + 1.5)\nval modWeekend = priceFunction(day == Sat || day == Sun)(_ + 1.5)\nval modParquet = priceFunction(!isParquet)(_ + 2.0)\nval mod3d = priceFunction(is3D)(_ + 3.0)\nval modifiers = List(\n modRuntime,\n modWeekend,\n modParquet,\n mod3d\n)\nval modifierFunction = modifiers reduceLeft (_ andThen _) \n\nval basePrice = modifierFunction(0.0)\n</code></pre>\n\n<p>The name of the identifiers here suck, and I could have written <code>val modifiers = modRuntime andThen modWeekend andThen modParquet andThen mod3d</code> without trouble. I choose putting them in a <code>List</code> because it shows how well it can scale.</p>\n\n<p>One could also make <code>PartialFunction</code> and chain them with <code>orElse</code>, for the cases where you want only the first condition.</p>\n\n<p>You see this kind of thing used in web frameworks, such as BlueEyes, Lift or Unfiltered, for example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T17:15:25.457",
"Id": "47947",
"Score": "0",
"body": "You've littered the code with one-shot vals, things which are unlikely to be directly re-used. Why not create a list of anonymous functions, at least? \"modifiers = List( priceFunction(runtime > 120)(_ + 1.5), priceFunction(day == Sat || day == Sun)(_ + 1.5). etc, etc )\". Frankly, I think simao's second example is as good as yours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-25T05:33:44.413",
"Id": "47977",
"Score": "1",
"body": "@itsbruce For two reasons. First, the identifier name helps one understand what the function is doing. Second, functions are syntactically noisy, so it's difficult to see where one ends and another starts in a list, whereas the `val` declarations make that obvious. The main question is: why _not_ declare them as `val`? It's not as if there would be any difference in memory usage or performance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T02:01:28.917",
"Id": "4186",
"ParentId": "4181",
"Score": "9"
}
},
{
"body": "<p>I like Daniel C. Sobral's answer. Anyway, in addition to the <code>List(...).sum</code> alternatives, there's:</p>\n\n<pre><code>val basePrice = {\n 0.0 +\n (runtime > 120 ? 1.5 | 0) +\n ((day == Sat) || (day == Sun) ? 1.5 | 0) +\n (!isParquet ? 2 | 0) +\n (is3D ? 3 | 0)\n}\n</code></pre>\n\n<p>Where <code>?|</code> is the <a href=\"https://stackoverflow.com/a/2706056/694469\">ternary operator</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-30T05:53:32.323",
"Id": "27955",
"ParentId": "4181",
"Score": "0"
}
},
{
"body": "<p>You can simply write it like this:</p>\n\n<pre><code>val basePrice = 0.0 +\n (if (runtime > 120) 1.5 else 0) +\n (if (day == Sat || day == Sun) 1.5 else 0) +\n (if (!isParquet) 2 else 0) +\n (if (is3D) 3 else 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T16:31:45.163",
"Id": "47940",
"Score": "0",
"body": "This is not more functional, just a slightly different way of writing the same code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-21T13:42:23.953",
"Id": "28782",
"ParentId": "4181",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4186",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-17T21:18:22.837",
"Id": "4181",
"Score": "2",
"Tags": [
"functional-programming",
"comparative-review",
"scala"
],
"Title": "Calculating a base price with surcharge conditions"
}
|
4181
|
<p>Currently I have this code:</p>
<pre><code>float tileX = (float)rectangle.X / (float)newTileSize;
float tileY = (float)rectangle.Y / (float)newTileSize;
int xOrigin = (int)Math.Round(tileX) * newTileSize;
int yOrigin = (int)Math.Round(tileY) * newTileSize;
// Same idea for the next 4 lines
float tileWidth = (float)rectangle.Width / (float)newTileSize;
float tileHeight = (float)rectangle.Height / (float)newTileSize;
int selectorWidth = (int)Math.Round(tileWidth) * newTileSize;
int selectorHeight = (int)Math.Round(tileHeight) * newTileSize;
</code></pre>
<p>The reason for the first two lines is because if I don't cast them as a float it does integer division and I was a floating point value instead so I can round it in the next two lines.</p>
<p>This code is fine <em>I guess</em> it just seems like there would be a better way to do it without so much casting. Just seems rather verbose if that makes any sense.</p>
<p>Thanks.</p>
|
[] |
[
{
"body": "<p>So you're looking for</p>\n\n<pre><code>int result = (int)Math.round((float)n/(float)d) * d;\n</code></pre>\n\n<p>(assuming you are only interested in the intermediate values for this particular calculation)</p>\n\n<p>Here's a test case with an alternative:</p>\n\n<pre><code>import junit.framework.TestCase;\n\npublic class TestModulo extends TestCase {\n\n private final static int d = 7;\n\n public void testModulo() throws Exception {\n for (int n = 0; n < 30; n++) {\n assertEquals(\"fails for \" + n, f2(n), f1(n));\n }\n }\n\n private int f1(int n) {\n return (int) Math.round((float) n / (float) d) * d;\n }\n\n private int f2(int n) {\n return ((n + d / 2) / d) * d;\n }\n\n}\n</code></pre>\n\n<p>You can solve your problem using only integer math.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T18:03:10.627",
"Id": "6251",
"Score": "0",
"body": "Much obliged =)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:56:03.150",
"Id": "4195",
"ParentId": "4192",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>The reason for the first two lines is because if I don't cast them as a float it does integer division and I was a floating point value instead so I can round it in the next two lines.</p>\n</blockquote>\n\n<p>Well, you only need to cast one side to get a float as the return value.</p>\n\n<pre><code>float tileX = (float)rectangle.X / newTileSize;\nfloat tileY = (float)rectangle.Y / newTileSize;\n</code></pre>\n\n<p>Because you are working with the <code>System.Drawing.Rectangle</code> type there is really no other way to go about it. All of the properties are <code>int</code>s, and you need to perform floating point arithmetic, so a cast is required. You could of course assign the <code>X</code> and <code>Y</code> values to a <code>float</code> first, but that doesn't save you anything. This is very common when working with graphics in WinForms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:57:46.683",
"Id": "4196",
"ParentId": "4192",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:03:32.393",
"Id": "4192",
"Score": "2",
"Tags": [
"c#",
"casting"
],
"Title": "A way to do this without a lot of variables and casting?"
}
|
4192
|
<p>I'm writing a perl script which reads logs from a file and looks for matches from another file before sending the matches off by email. The problem is, I'm dealing with files which could be changed (a log written to them by syslog) at any time. I discovered that files can be locked in perl, however I'm not sure if it is 100% secure yet. Here is the pertinent snippet:</p>
<pre><code> # Check for valid email
unless ($mailto =~ EMAIL_REGEX) {
die "Please supply a valid email"
}
# Build a rule from a key and an email
# Write it to LOGMAN_CONF
my $key_and_email = $keyword.":".$mailto."\n";
open (RULES, ">>", LOGMAN_CONF)
or die "Cannot open logman configuration file ".LOGMAN_CONF;
flock(RULES, LOCK_EX) or die "Can't lock ".LOGMAN_CONF;
print RULES $key_and_email;
close RULES;
# Check if CRONTAB_LOC needs a send entry
open (CRON, "<", CRONTAB_LOC)
or die "Cannot open crontab file ".CRONTAB_LOC;
flock(CRON, LOCK_SH) or die "Can't lock ".CRONTAB_LOC;
my @cronLines = <CRON>;
close CRON;
my $match = 0;
foreach my $line (@cronLines) {
if ($line eq CRON_ENTRY) {
$match = 1;
}
}
unless ($match == 1) {
open (CRON, ">>", CRONTAB_LOC)
or die "Cannot open crontab file ".CRONTAB_LOC;
flock(CRON, LOCK_EX) or die "Can't lock ".CRONTAB_LOC;
print CRON CRON_ENTRY;
close CRON;
}
</code></pre>
<p>Feel free to critique my style or structure, as this is my first contact with Perl.</p>
<p><strong>NB:</strong> There are a couple of constants used above which I haven't shown where they are defined. I could add them if anyone needs, but they are for the most part location to files.</p>
|
[] |
[
{
"body": "<p>Locking is advisory which mean unless syslog is also doing flock() before write (which is doubtful) your locking scheme will have no effect. Some operating systems like AIX do have manditory/enforced locking mechanisms but I don't believe they're standard at the filesystem level across any UNIX system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T21:20:23.453",
"Id": "6262",
"Score": "0",
"body": "Is there a way of knowing for sure if syslog flock()'s? I checked the man page and there was nothing that would indicate that it did or didn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T21:44:34.287",
"Id": "6263",
"Score": "0",
"body": "Test it. Write a perl app the flocks() the file and just waits forever. If you see new log lines appear then syslog doesn't use flock()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T22:01:51.467",
"Id": "6264",
"Score": "0",
"body": "I'm on OpenSuse and they don't use syslog for logging. So I'll have to try this tomorrow at work."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T20:24:18.083",
"Id": "4198",
"ParentId": "4197",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T19:08:41.127",
"Id": "4197",
"Score": "1",
"Tags": [
"perl",
"security",
"locking"
],
"Title": "Security concerns with locking files"
}
|
4197
|
<p>Ruby code below seems to be not so dry. Can you please help me reduce the code.</p>
<pre><code>self.value = case self.type
when 'fast'
Increment.first.max_hours * Incrementor.first.fast_completion_day
when 'super_fast'
Increment.first.max_hours * Incrementor.first.super_fast_completion_day
when 'ludicrous'
Increment.first.max_hours * Incrementor.first.ludicrous_completion_day
else
Increment.first.max_hours * Incrementor.first.budget_completion_day
end
</code></pre>
<p>I think we can use Ruby metaprogamming here to reduce the code. But I am not very good with ruby meta programming at the moment.</p>
|
[] |
[
{
"body": "<p>You can try:</p>\n\n<pre><code>day = case self.type\n when 'fast' then :fast_completion_day\n when 'super_fast' then :super_fast_completion_day\n when 'ludicrous' then :ludicrous_completion_day\n else :budget_completion_day\nend\n\nself.value = Increment.first.max_hours * Incrementor.first.send(day)\n</code></pre>\n\n<p>From a friend that knows more than me:</p>\n\n<pre><code>prefix = %w[ fast super_fast ludicrous ].include?(self.type) ? self.type : \"budget\"\nself.value = Increment.first.max_hours * Incrementor.first.send(:\"#{prefix}_completion_day\")\n</code></pre>\n\n<p>This is probably about as short and dry as you can get it. That said, I'm not sure that this is more clear/easy to read. I'd probably add a method to Incrementor like Incrementor#completion_day_for(type) that would take care of this logic for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T07:28:11.070",
"Id": "6269",
"Score": "0",
"body": "Thank you so much @Martin. Hope this is just a start for me to write better codes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T21:13:06.040",
"Id": "4207",
"ParentId": "4199",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4207",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T20:25:49.203",
"Id": "4199",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "ruby code case when not so dry"
}
|
4199
|
<p>I wrote the following function to determine whether a string ends with one of a few given options.</p>
<p>I'm sure it can be written more elegantly, probably avoiding the loop.</p>
<pre><code>bool EndsWithOneOf(string value, IEnumerable<string> suffixes)
{
foreach(var suffix in suffixes)
{
if value.EndsWith(suffix)
return true;
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:48:30.240",
"Id": "6253",
"Score": "0",
"body": "My previous answer was given multiple times, but this works too. Using a method group:\n\n bool EndsWithOneOf(string value, IEnumerable<string> suffixes)\n {\n return suffixes.Any(value.EndsWith);\n }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:50:13.150",
"Id": "6254",
"Score": "0",
"body": "@Abbas You can edit your current answer to include that if you like. No need to demote it to a comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:52:25.963",
"Id": "6255",
"Score": "0",
"body": "Ok thanks, didn't know that! :) I put it in my previous answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T00:06:20.617",
"Id": "6267",
"Score": "1",
"body": "You can't enumerate without... you know, enumerating. Any implementation will involve a loop, and there's nothing wrong with that. That's what loops are for... no pun intended =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-28T01:54:16.963",
"Id": "394386",
"Score": "0",
"body": "Could also try some [regex options depending on your use case](https://stackoverflow.com/a/2750758/1366033)"
}
] |
[
{
"body": "<p>You can LINQify it to improve readability:</p>\n\n<pre><code>bool endsWithOneOf = suffixes.Any(x => value.EndsWith(x));\n</code></pre>\n\n<p>Note that this doesn't \"avoid the loop\", since <code>Any()</code> will iterate through the suffixes (stopping when it hits a match.) But that's ok, since how else could you do it? You have an enumeration of suffixes, so to do anything with them, you must enumerate them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:49:05.110",
"Id": "6256",
"Score": "0",
"body": "That's what I've been looking for, thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:50:48.377",
"Id": "6257",
"Score": "0",
"body": "No prob! In general, if you have a `foreach` loop, you should try to \"Think LINQ\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:58:50.160",
"Id": "6258",
"Score": "0",
"body": "@dlev - I guess that would depend on how legible the code looks after you LINQ-ify it. Sometimes you sacrifice readability in those instances, which makes maintaining (probably by other developers) a little more challengeing (well, it becomes an obstacle...just a small one)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:59:51.273",
"Id": "6259",
"Score": "0",
"body": "@Matthew That's a good point. Personally, I've found that LINQ very often makes my code *more readable*, but there are certainly cases where that's not true."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T18:03:17.023",
"Id": "6260",
"Score": "0",
"body": "@dlev - I agree, I use it all over the place. I have encountered issues where other team members have initial struggled to understand what it is doing, but once they get the syntax, LINQ becomes second nature. In this case, with `suffixes.Any(...)` it is quite clear what the method is doing, moreso than the `foreach` variant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T18:07:27.667",
"Id": "6261",
"Score": "0",
"body": "@Matthew I know what you mean; LINQ does have a learning curve. Boy does it pay off, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T22:29:24.857",
"Id": "6265",
"Score": "2",
"body": "@Matthew: You should not have to don't dumb down your code just because a few people do not understand the syntax or the libraries. It's _their_ responsibility to keep up it and using LINQ as a part of a .NET 3.5+ application has become the norm. This reminds me of [this recent discussion](http://programmers.stackexchange.com/questions/101513) on [programmers.se]."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:44:58.207",
"Id": "4201",
"ParentId": "4200",
"Score": "15"
}
},
{
"body": "<pre><code>bool EndsWithOneOf(string value, IEnumerable<string> suffixes)\n{\n return suffixes.Any(suffix => value.EndsWith(suffix));\n}\n</code></pre>\n\n<p><strong>Edit:</strong> too late :D</p>\n\n<p><strong>Update</strong></p>\n\n<p>My previous answer was given multiple times, but this works too. Using a method group: </p>\n\n<pre><code>bool EndsWithOneOf(string value, IEnumerable<string> suffixes)\n{\n return suffixes.Any(value.EndsWith);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-03T16:17:00.793",
"Id": "325976",
"Score": "0",
"body": "+1 for reminding that you can use a method group."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:45:34.933",
"Id": "4202",
"ParentId": "4200",
"Score": "11"
}
},
{
"body": "<pre><code>static bool EndsWithOneOf(this string value, IEnumerable<string> suffixes)\n{\n return suffixes.Any(suffix => value.EndsWith(suffix));\n}\n</code></pre>\n\n<p>Two advantages here: </p>\n\n<ol>\n<li>use of extension method makes calling this method more straight\nforward (i.e. <code>mystring.EndsWithOneOf(mySuffixes);</code>)</li>\n<li>Use of linq allows for better readability (see declarative\nvs imperative programming)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:48:15.400",
"Id": "4205",
"ParentId": "4200",
"Score": "4"
}
},
{
"body": "<p>Regardless of how you do it, at some point in the execution of a method like that, there will be a enumeration.</p>\n\n<p>What you can do, is make the method more terse by using a LINQ method:</p>\n\n<pre><code>return suffixes.Any(s => value.EndsWith(s));\n</code></pre>\n\n<p>But is that any more readable than:</p>\n\n<pre><code>foreach (string suffix in suffixes) {\n if (value.EndsWith(suffix)) return true;\n}\nreturn false;\n</code></pre>\n\n<p>For <em>actual</em> method improvements, you should consider argument validation. What happens if value is <code>null</code>? Your current code will return in a <code>NullReferenceException</code>.</p>\n\n<p>Behaviourly would it be correct to throw an <code>ArgumentNullException</code> in this case? Or is the possible <code>null</code> value an automatic resultant value of false?</p>\n\n<p>You should also consider how your are comparing strings? Should you provide an overload that allows the caller to pass in an appropriate <code>CultureInfo</code> object? Or perhaps specify the <code>StringComparison</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:49:54.530",
"Id": "4206",
"ParentId": "4200",
"Score": "3"
}
},
{
"body": "<p>I dont think this is relevant given your question example, and therefore this answer may be pointless, but an alternative is that you can invert the comparison test to eliminate the enumeration.</p>\n\n<p>For example, if you were looking for file type extensions, then instead of comparing the filename against a collection of extensions (like has been solved already), you can build a single string containing all the extensions (plus maybe an extra token), and then search for the input filename type in that string.</p>\n\n<p>E.g. \".png.jpg.bmp.mov.mp3.\".contains(myFileExtension + \".\");</p>\n\n<p>I've used this approach a few times to unravel a loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T18:07:44.247",
"Id": "4339",
"ParentId": "4200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-18T17:43:01.227",
"Id": "4200",
"Score": "5",
"Tags": [
"c#",
"strings"
],
"Title": "Determining whether a string ends with one of a few given options"
}
|
4200
|
<p>There are some things I am not sure of from a professional standpoint about the "correct" way to write C++ code. I have been looking through source code produced by various opensource projects, as well as other code posted here and on Stack Overflow. </p>
<p>So let's just leave it at this. Let's say I am interviewing for company A over the phone. Not white board yet. They ask me to write the code below and turn it in a hour. This is a hypothetical situation, however it parallels how most "big" companies are interviewing nowadays. Would this code "get me the job"? If not, what would you change, or what can you coach me with so I can get a job programming?</p>
<pre><code>#include <iostream>
#include <queue>
#include <algorithm>
#include <iterator>
/*
* This program reads a sequence of pairs of nonnegative integers
* less than N from standard input (interpreting the pair p q to
* mean "connect object p to object q") and prints out pair
* representing objects that are not yet connected. It maintains an
* array id that has an entry for each object, with the property
* that id[p] and id[q] are equal if and only if p and q are
* connected.
*/
static const int N = 10;
int main( int argc, char *argv[ ] )
{
/*
* Ease the type of long types
*/
typedef std::ostream_iterator<int> output_data;
typedef typename std::vector<int>::iterator v_it;
/*
* Generate Test Data
*/
std::pair<int,int> pairs[12] = {
std::pair<int,int>( 3,4 ),
std::pair<int,int>( 4,9 ),
std::pair<int,int>( 8,0 ),
std::pair<int,int>( 2,3 ),
std::pair<int,int>( 5,6 ),
std::pair<int,int>( 2,9 ),
std::pair<int,int>( 5,9 ),
std::pair<int,int>( 7,3 ),
std::pair<int,int>( 4,8 ),
std::pair<int,int>( 5,6 ),
std::pair<int,int>( 0,2 ),
std::pair<int,int>( 6,1 )
};
/*
* Load Test Data onto Queue
*/
std::queue<std::pair<int,int> > queue;
for( int x=0;x<12;x++ )
{
queue.push( pairs[x] );
}
/*
* Data strucutre to represent nodes in graph.
* An index in the vector is an id for a node.
*/
std::vector<int> id;
/*
* Start the nodes as not being connected
*/
id.reserve( N );
for( int i = 0;i<N;i++ ) id.push_back( i );
std::cout << "p q\t";
/*
* Output the data
*/
copy( id.begin( ), id.end( ), output_data( std::cout, " " ) );
std::cout << std::endl;
std::cout << "------------------------------------";
std::cout << std::endl;
/*
* Algorithm to find out if wheter or not any two
* given pair p-q is connected. It does not show
* how they are connected.
*/
v_it start = id.begin( );
while( !queue.empty( ) )
{
std::pair<int,int> &pair = queue.front( );
int p = pair.first;
int q = pair.second;
int t = *(start+p);
if( t == *(start+q) )
{
}
else
{
for( v_it i = id.begin( ); i < id.end( ); i++ )
{
if( *(i) == t )
{
*(i) = *(start+q);
}
}
}
std::cout << p << " " << q << "\t";
copy( &id[0], &id[N], output_data( std::cout, " " ) );
std::cout << std::endl;
queue.pop( );
}
}
</code></pre>
<p>The output and arguments to gcc would look like this:</p>
<blockquote>
<pre><code>[mehoggan@desktop robert_sedgewick]$ g++ -o qf -Wall ./quick_find.cpp
[mehoggan@desktop robert_sedgewick]$ ./qf
p q 0 1 2 3 4 5 6 7 8 9
------------------------------------
3 4 0 1 2 4 4 5 6 7 8 9
4 9 0 1 2 9 9 5 6 7 8 9
8 0 0 1 2 9 9 5 6 7 0 9
2 3 0 1 9 9 9 5 6 7 0 9
5 6 0 1 9 9 9 6 6 7 0 9
2 9 0 1 9 9 9 6 6 7 0 9
5 9 0 1 9 9 9 9 9 7 0 9
7 3 0 1 9 9 9 9 9 9 0 9
4 8 0 1 0 0 0 0 0 0 0 0
5 6 0 1 0 0 0 0 0 0 0 0
0 2 0 1 0 0 0 0 0 0 0 0
6 1 1 1 1 1 1 1 1 1 1 1
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Looks good:</p>\n\n<p>Here typename is not required:</p>\n\n<pre><code>typedef typename std::vector<int>::iterator v_it;\n</code></pre>\n\n<p>So this:</p>\n\n<pre><code>typedef std::vector<int>::iterator v_it;\n</code></pre>\n\n<p>Here I would not specify the size:</p>\n\n<pre><code>std::pair<int,int> pairs[12] = {\n</code></pre>\n\n<p>This is because you have to manually validate that the element count matches the size (this can cause subtle errors). So rather just let the compiler work it out:</p>\n\n<pre><code>std::pair<int,int> pairs[] = { \n</code></pre>\n\n<p>Rather then specify the long winded and fully qualified type for the std::pair let the compiler deduce the type for you use std::make_pair.</p>\n\n<pre><code>std::pair<int,int> pairs[] = { \n std::make_pair( 3,4 ),\n std::make_pair( 4,9 ),\n</code></pre>\n\n<p>I would not use an empty main branch in an if statement.</p>\n\n<pre><code> if( t == *(start+q) ) \n {\n }\n</code></pre>\n\n<p>The one thing I would note is; that even though you may be using the standard library well, you are not writing encapsulated code.</p>\n\n<p>I would have written the code so that the test could have been applied to the code in the same way that real data could be applied to the code. This mean you have to define an interface to your algorithm. Think about what the inputs are (how real data and test data can be provided).</p>\n\n<p>Here you just have a loop inside main(). As a result you are not really showcasing your ability to write good encapsulated code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T08:35:29.093",
"Id": "4211",
"ParentId": "4209",
"Score": "8"
}
},
{
"body": "<p>The questions I would ask are:</p>\n\n<ol>\n<li>why <code>queue</code>? Do you really need the <code>push</code>/<code>pop</code> functionality?</li>\n<li>It seems you are familiar with the available algorithms, but I wonder if there is something you can use to replace the for loop in your search phase?</li>\n</ol>\n\n<p>Besides that (and Martin's fixes), I think your code is in good shape...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T08:47:21.240",
"Id": "4212",
"ParentId": "4209",
"Score": "4"
}
},
{
"body": "<p>I have a few more comments. I think you had a good idea adding typedefs to keep some of the names shorter and more meaningful, but I think I'd add even more than that.</p>\n\n<pre><code>typedef std::ostream_iterator<int> output_data;\ntypedef std::vector<int> graph;\n\n// As Martin said, `typename` isn't required (or really even allowed) here.\ntypedef graph::iterator v_it; \ntypedef std::pair<int, int> dt;\n</code></pre>\n\n<p>Since you have code to show <code>p</code>, <code>q</code> and <code>id</code> in a couple of different places, and it's important that they match up with each other, I'd move that into a little function named <code>display</code> or something on that order. In one place, you need to display the names <code>p</code> and <code>q</code>, and in others their values, so we want to make this a template parameterized on the types of <code>p</code> and <code>q</code>:</p>\n\n<pre><code>template <class T>\nvoid display(T p, T q, graph const &id) { \n std::cout << p << \" \" << q << \"\\t\";\n std::copy( id.begin( ), id.end( ), output_data( std::cout, \" \" ) );\n std::cout << '\\n';\n}\n</code></pre>\n\n<p>For example, when we use this from <code>main</code> to display the initial state, we use code something like this:</p>\n\n<pre><code>display('p', 'q', id);\nstd::cout << std::string(N*3, '-') << \"\\n\";\n</code></pre>\n\n<p>As a general rule, I prefer to create a vector already initialized, rather than creating, then filling it with data. Since filling a vector (or whatever) with a sequence of values is something that comes up all the time, I have a <code>sequence</code> class and <code>gen_seq</code> front end for exactly that purpose. It would probably be overkill to write <code>gen_seq</code> <em>just</em> for this purpose, but I think it's worth having around anyway, and when you do, you might as well use it. The header looks like this:</p>\n\n<pre><code>#ifndef GEN_SEQ_INCLUDED_\n#define GEN_SEQ_INCLUDED_\n\ntemplate <class T>\nclass sequence : public std::iterator<std::forward_iterator_tag, T>\n{ \n T val;\npublic:\n sequence(T init) : val(init) {}\n T operator *() { return val; }\n sequence &operator++() { ++val; return *this; }\n bool operator!=(sequence const &other) { return val != other.val; }\n};\n\ntemplate <class T>\nsequence<T> gen_seq(T const &val) {\n return sequence<T>(val);\n}\n#endif\n</code></pre>\n\n<p>With this, you can create and initialize <code>id</code> like this: </p>\n\n<pre><code>#include \"gen_seq\"\n\ngraph id(gen_seq(0), gen_seq(N));\n</code></pre>\n\n<p>I also keep a couple of macros around that are handy when you're initializing a vector from an array. There are templates that are (at least theoretically) better, but I've never quite gotten around to switching over to them. The macros look like this:</p>\n\n<pre><code>#define ELEMENTS_(x) (sizeof(x)/sizeof(x[0]))\n#define END(array) ((array)+ELEMENTS_(array))\n</code></pre>\n\n<p>With these, the <code>typedef</code>s above, and (as sort of suggested by @Nim) using a vector instead of a queue, initializing your test data looks like this:</p>\n\n<pre><code>dt pairs[] = { \n dt( 3,4 ), dt( 4,9 ), dt( 8,0 ), dt( 2,3 ), dt( 5,6 ), dt( 2,9 ), \n dt( 5,9 ), dt( 7,3 ), dt( 4,8 ), dt( 5,6 ), dt( 0,2 ), dt( 6,1 )\n};\n\nstd::vector<dt> data((pairs), END(pairs));\n</code></pre>\n\n<p>Instead of putting all the code to process the nodes into <code>main</code>, I'd move most of it out to a <code>process_node</code> function object. I'd also note that this:</p>\n\n<pre><code> for( v_it i = id.begin( ); i < id.end( ); i++ ) \n {\n if( *(i) == t )\n {\n *(i) = *(start+q);\n }\n }\n</code></pre>\n\n<p>...is essentially the same as <code>std::replace(id.begin(), id.end(), t, *(start+q));</code>. Taking that into account, <code>process_node</code> comes out looking something like this:</p>\n\n<pre><code>class process_node { \n graph &id;\npublic: \n process_node(graph &id) : id(id) {}\n\n void operator()(dt const &pair) { \n int p = pair.first;\n int q = pair.second;\n int o = id[p];\n int n = id[q];\n if(o != n) \n std::replace(id.begin(), id.end(), o, n);\n display(p, q, id);\n }\n};\n</code></pre>\n\n<p>Since we now have a vector to iterate through, and a function object to process each item, we can switch from an explicit loop to a standard algorithm:</p>\n\n<pre><code>std::for_each(data.begin(), data.end(), process_node(id));\n</code></pre>\n\n<p>[...and yes, for those find that unusual, this is a noteworthy day: I actually used <code>std::for_each</code> -- truly a rarity. ]</p>\n\n<p>That, however, brings up another point: there are still a few things about this code that don't excite me much. One, in particular, is that fact that it combines processing a node with displaying a row of results. We'd have to do a fair amount of extra work to avoid that, so I haven't bothered, but if we fixed that, <code>std::for_each</code> probably wouldn't be the right choice any more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T16:41:54.160",
"Id": "4222",
"ParentId": "4209",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T07:54:45.580",
"Id": "4209",
"Score": "6",
"Tags": [
"c++",
"interview-questions",
"mathematics",
"graph"
],
"Title": "Print pair representing objects from sequence of nonnegative integer pairs"
}
|
4209
|
<p>I am using code like this everywhere. How can I reduce such this code so that my Ruby code looks a lot cleaner?</p>
<pre><code>Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 266,:type => "fast" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 100,:type => "super_fast" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 50,:type => "ludicrous" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 900,:type => "budget" )
</code></pre>
|
[] |
[
{
"body": "<p>I found that I can use hash({}).each method to dry up the code. It is :</p>\n\n<pre><code>{\"fast\"=>266, \"super_fast\" => 100, \"ludicrous\" => 50, \"budget\" => 900}.each{ |key, value|\n Fabricate(:tl, :when =>Date.yesterday.to_s,:work => value,:type => key )\n}\n</code></pre>\n\n<p>If there is a better technique, please share it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T10:44:42.327",
"Id": "4213",
"ParentId": "4210",
"Score": "6"
}
},
{
"body": "<p>How about just defining a new facade method and calling that as many times as needed? You can put in some sanity checking on the arguments that way. Say for example, we had:</p>\n\n<pre><code>def fixture(attrs)\n raise ArgumentError unless Hash === attrs\n key = attrs.keys.first\n\n Fabricate(:tl, :when => Date.yesterday.to_s,\n :work => key.to_s, :type => attrs[key])\nend\n</code></pre>\n\n<p>Then you could create your objects like so,</p>\n\n<pre><code>fixture :ludicrous => 50\nfixture :super_fast => 100\nfixture :fast => 266\nfixture :budget => 900\n</code></pre>\n\n<p>You're still calling the same method multiple times, but I think it reads better that way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T21:46:58.520",
"Id": "6623",
"Score": "1",
"body": "I like the fixture. Much easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T03:06:18.780",
"Id": "6628",
"Score": "0",
"body": "I agree, more explicit while being clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T18:54:32.067",
"Id": "4421",
"ParentId": "4210",
"Score": "4"
}
},
{
"body": "<p>Tools like Fabricator are already designed to reduce duplication, while establishing a convention so that every example has exactly what it needs. Adding a <code>fixture</code> method adds another layer of indirection that makes it that much more challenging to understand what's supposed to be happening in an example. I'd recommend, instead, using Fabricator <em>as intended</em>.</p>\n\n<p>Let's say a <code>Person</code> needs to be 18 years or older to do certain things on a site. You'd set up a fabricator like this:</p>\n\n<pre><code>Fabricator(:person, :birthdate => Date.today - 18.years)\n</code></pre>\n\n<p>Now, in most examples you'd just say <code>Fabricate(:person)</code>, but in the example specifying that an underaged person is not allowed to do something you'd say:</p>\n\n<pre><code>Fabricate(:person, :birthdate => Date.today - 18.years + 1.day)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-21T21:28:50.417",
"Id": "8369",
"Score": "0",
"body": "This is absolutely the right way to do it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T14:57:59.120",
"Id": "4547",
"ParentId": "4210",
"Score": "4"
}
},
{
"body": "<p>I may be in the minority here but I have always been a fan of not DRYing test code. I think when you try to dry things you end up becoming less agile. Rather you want your tests to be as specific as possible to each case.</p>\n\n<p>I know this is not possible for example you may want to DRY up logging into the program, or navigating to an admin panel but drying up something like the accepted answer only does one thing to your code. Makes it less readable to your tests. That is make them less readable to a lay person or a new comer.</p>\n\n<p>That in my opinion is what tests are all about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-21T21:29:28.713",
"Id": "8370",
"Score": "1",
"body": "I've heard other people say this, but I think they're wrong. Removing repetition from test code usually leads to more readable test code in my experience."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T19:38:34.770",
"Id": "4566",
"ParentId": "4210",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4213",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T07:57:25.817",
"Id": "4210",
"Score": "5",
"Tags": [
"ruby",
"datetime",
"ruby-on-rails"
],
"Title": "Fabricate with work dates"
}
|
4210
|
<p>Here is my code, I use it to verify whether an input path is correct or not. I assume that the input path is encoded in <code>UTF8</code>. Is there any way to make it better?</p>
<pre><code>#define MAX_PATH_LEN MAX_PATH
#define IN
#define OUT
typedef int Bool_T;
static
int GetCharsNumInPath( IN const char * path )
{
int cnt;
int i;
int n = strlen( path );
for( i = 0; i < n; i++ )
{
if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )
cnt++;
}
return cnt;
}
Bool_T PathValid( IN const char * path )
{
if( path != NULL )
{
if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )
{
int i;
int n = strlen( path );
for( i = 0; i < n; i++ )
{
switch( path[i] )
{
// ? " / < > * |
// these characters can not be used in file or folder names
//
case '?':
case '\"':
case '/':
case '<':
case '>':
case '*':
case '|':
return false;
// Can meet only between a local disk letter and full path
// for example D:\folder\file.txt
//
case ':':
{
if( i != 1 )
{
return false;
}else{
break;
}
}
// Space and point can not be the last character of a file or folder names
//
case ' ':
case '.':
{
if( ( i + 1 == n ) || ( path[i+1] == PATH_SEPERATOR_CHAR ) )
{
return false;
}else{
break;
}
}
// two backslashes can not go straight
//
case PATH_SEPERATOR_CHAR:
{
if( i > 0 && path[i - 1] == PATH_SEPERATOR_CHAR )
{
return false;
}else{
break;
}
}
}
}
return true;
}else{ // if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )
LOG_ERROR( "PathValid FAILURE --> path is too long" );
return false;
}
}else{ // if( path != NULL )
// wrong argument
//
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T02:05:56.370",
"Id": "507983",
"Score": "0",
"body": "You need to check for invalid device names too, such as AUX, COM1, LPT1"
}
] |
[
{
"body": "<p>Personally if the preconditions to the function are not met then I like to return quickly and this not add to the nesting:</p>\n\n<pre><code>Bool_T PathValid( IN const char * path )\n{\n if( path != NULL )\n {\n // wrong argument\n return false;\n }\n\n if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )\n {\n LOG_ERROR( \"PathValid FAILURE --> path is too long\" );\n return false;\n }\n\n // Main Function body here.\n}\n</code></pre>\n\n<p>Of course in C you don't want to have too many return points from a function (as at each return point you need to close all open resources and tidy up. So in C (unlike C++) I find my code looking like this:</p>\n\n<pre><code><type> function(<Parameters>)\n{\n if (!<pre-condition1>)\n { return <errorStat1>;\n }\n\n if (!<pre-condition2>)\n { return <errorStat2>;\n }\n\n ....\n\n if (!<pre-condition-N>)\n { return <errorStat-N>;\n }\n\n\n <type> result = <initial Result>;\n <Set all Resource to NULL>\n\n // Code Which can generate errors>\n // If it does then set error state. and stop processing.\n // BUT DO NOT RETURN from this code.\n\n < Close all resource >\n return result;\n}\n</code></pre>\n\n<p>Your check for invalid characters is Windows specific. The OS will usually have a platform or OS specific set of functions for checking valid characters.</p>\n\n<ul>\n<li>Your set of invalid characters is not true for all platforms.</li>\n<li>The use of ':' as the second character is Windows only.\n<ul>\n<li>If it is there the first character should be 'A' - 'Z'</li>\n</ul></li>\n<li>Limiting the use of space is Windows only</li>\n<li>Are you sure about \".\" not being allowed as last character?</li>\n<li>On windows two '\\\\' can be used as the first two characters to indicate network resource.</li>\n<li>Windows has more than one path separator.\n<ul>\n<li>The old style '\\' (traditional backslash)</li>\n<li>The new style '/' (normal slash).</li>\n</ul></li>\n</ul>\n\n<p>In your function counting characters in the path. You basically traverse the string twice. Why not combine the two traversals into a single pass:</p>\n\n<pre><code>// int n = strlen( path );\n// Not requires (all this does is look for '\\0')\n\nfor( i = 0; path[i]; i++ )\n{ // ^^^^^^^ Test for '\\0' character\n\n if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )\n { cnt++;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:05:56.870",
"Id": "6348",
"Score": "1",
"body": "Regarding the multiple-returns and resource disposal, that would be a great opportunity to use the \"dreaded\" `goto` statement to handle all that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:10:58.067",
"Id": "6351",
"Score": "0",
"body": "@Jeff Mercado: On my last project that was actually the standard. But I just found it made the code more convoluted to read. Sorry but I can not even recommend it (goto) for this situation (It also one of the reason I left that team)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:54:50.477",
"Id": "6354",
"Score": "0",
"body": "At least IMO, this is one place that C++ (exception handling, to be specific) provides a major improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T04:35:52.363",
"Id": "6367",
"Score": "0",
"body": "@Martin, about traversing 2 times when counting num of characters good point, thanks). I'll edit, add some new checking and paste the second version of this function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T19:47:18.447",
"Id": "6900",
"Score": "0",
"body": "@Tux-D - Your user name is \"Tux\" and you left a team for the use of `goto` error handling? Better not look at those kernel sources... :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T20:35:09.373",
"Id": "6901",
"Score": "0",
"body": "@asveikau: In C using goto to move to a release section of a function to tidy up is good practice and perfectly valid . I left the team because they were applying these rules to C++ code. Where it is silly. Simple rule C is **NOT** C++ do not apply C coding standards to C++ or vice versa. In the kernal is written in C so the convention holds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T21:29:28.363",
"Id": "6903",
"Score": "0",
"body": "@Tux-D - A fair position to hold. I just found this lightly amusing, so my comment was meant to be taken in jest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-31T05:57:31.297",
"Id": "153965",
"Score": "0",
"body": "Been to an Intel conference recently and they said, code optimization wise, that is better to handle first the case that is most likely to happen and afterwards handle the others."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T17:10:25.910",
"Id": "4239",
"ParentId": "4214",
"Score": "3"
}
},
{
"body": "<p>Recognizing a path correctly is a bit more complex than you seem to realize (not surprising -- it's more complex than almost anybody seems to realize -- even quite a bit of Microsoft's software gets at least a few things wrong). I think I'd start by defining a grammar for what you're going to recognize. Since this seems to be based on Windows paths, I'd start with something like this:</p>\n\n<pre><code>path = local_path | share_path\n\nlocal_path = <drive> FSpath\n\ndrive = [A-Za-z] \":\"\n\nshare_path = \"\\\\\" share_name absolute_path\n\nFSpath = relative_path | absolute_path\n\nabsolute_path = path_sep relative_path\n\nrelative_path = { name path_sep } file_name\n\npath_sep = [\\/]\n\nshare_name = name\n\nname = [^?<>|\\*:]+\n\nfile_name = name <fork_name>\n\nfork_name = \":\" name\n</code></pre>\n\n<p>Here I've used <code><whatever></code> to mean that item is optional and <code>{whatever}</code> to mean it can be repeated arbitrarily. [Edit: also be aware that I just typed this in based on what I remember -- I could easily have missed something so it's even a bit more complex than I've shown.]</p>\n\n<p>Once you have that, it's pretty easy to write a small function for each of these to recognize that individual piece. To deal with optional parts of the path, I think I'd follow the convention of the function returning either the number of characters it matched from the input string, or else a pointer to the spot in the input string after the part it matched. Starting from the top, they'd look like:</p>\n\n<pre><code>bool path(char const *input) { \n return local_path(input) || share_path(input);\n}\n\nsize_t local_path(char const *input) { \n size_t drive_len = drive(input);\n return drive_len + FSpath(input+drive_len);\n}\n\nsize_t drive(char const *input) { \n if (isalpha(input[0]) && input[1] == ':\")\n return 2;\n return 0;\n}\n</code></pre>\n\n<p>This style will probably result in more total code (especially overhead for function headers and such) but it breaks the problem down into pieces that are each small and simple so it should be fairly easy to figure out what's happening at each step of the way, so if (for example) my understanding of the overall syntax for a path is wrong, it should be fairly easy to find exactly which code relates to the part I have wrong. Likewise, when/if Microsoft changes the rules to add or remove restrictions, it should be quite easy to do that and be sure you're getting the right result. Just for example, right now I have <code>share_name</code> defined as being exactly the same as any other directory/file name. In all honesty, I'm not sure that's really correct. A share name may be more restricted than a normal directory name, but I'm honestly not sure -- but if it is different, this style makes it really easy to find and correct. This also makes it easy to deal with things that are only allowed at specific points along the path, or have different rules at different points (e.g., ':' being used for two different purposes: preceded by a drive letter, or followed by a named file fork on NTFS).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:04:23.177",
"Id": "6347",
"Score": "0",
"body": "According to this `A:B:C:D:\\Plop` is a valid path. Need a slight tweak there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:06:18.120",
"Id": "6349",
"Score": "0",
"body": "In your comments: `[Whatever]` means optional, but here `[^?<>|\\*:]` you are using it to mean the RE any one of these"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T20:20:56.023",
"Id": "6352",
"Score": "0",
"body": "@Martin: Oops -- I defined `path` twice as two different things, and used `[]` twice to mean to different things as well. I'll edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T07:29:28.057",
"Id": "6373",
"Score": "0",
"body": "@Jerry Coffin, the path will come to my functions from the application explorer, so I think it is not so important to check all this things. The main purpose of this function is to check is the length of path is ok, and is file/folder name is correct, that's all. So what you suggest me to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T16:14:16.587",
"Id": "6378",
"Score": "0",
"body": "@akmal: If the path is comming from `application explorer` you already know the path is OK. If you want to validate it then you should either d exactly as Jerry has suggested to validate the path, or use a system call to validate the path. As Jerry explains doing it manually is harder than you think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T20:04:50.227",
"Id": "6385",
"Score": "0",
"body": "@akmal: I really see this one as pretty black and white. If you trust the source, trust it -- accept the data without validation. If you don't trust the source, validate it completely. Personally I don't see a lot of point in doing the job halfway though."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T19:45:39.577",
"Id": "4242",
"ParentId": "4214",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4239",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T13:53:41.580",
"Id": "4214",
"Score": "2",
"Tags": [
"c"
],
"Title": "Function to check whether a path is valid or not needs your critique"
}
|
4214
|
<p>I'm investigating some feature for the ScalaDoc tool, which would allow library writers to link to documentation created by third party tools like JavaDoc.</p>
<p>My idea is to have some (XML) configuration which specifies which package prefixes belong to which vendor and how to create a valid URL from the the class name, stored in the XML as regular expressions and format strings.</p>
<p>I only need one public method <code>getLink(entity: String): Option[String]</code> which either returns <code>Some(validURL)</code> or <code>None</code>, if the package name is not supported by the given configuration. Everything else can be changed as much as I want if it improves the code.</p>
<p>Consider this code:</p>
<pre><code>object ExternalReferences2 {
import java.util.regex._
import collection.mutable._
private object Mapping {
def fromXml(mapping: scala.xml.NodeSeq) = {
new Mapping(mapping \ "vendor" text, mapping \ "match" text, mapping \ "format" text)
}
}
private case class Mapping(vendor: String, matches: String, format: String) {
private val pattern = Pattern.compile(matches)
private var currentMatcher: Matcher = null
def hasValue(entity: String) = {
currentMatcher = pattern.matcher(entity);
currentMatcher.matches
}
def getValue = {
val range = 0 until currentMatcher.groupCount()
val groups = range
.map (currentMatcher.group(_))
.filterNot (_ == null)
.map (_.replace('.', '/'))
format.format(groups: _*)
}
}
private val config =
<external-links>
<mapping>
<vendor>OpenJDK</vendor>
<match>{ """^(javax?|sunw?|com.sun|org\.(ietf\.jgss|omg|w3c\.dom|xml\.sax))(\.[^.]+)+$""" }</match>
<format>{ "http://download.oracle.com/javase/7/docs/api/%s.html" }</format>
</mapping>
</external-links>
private def lookUp(entity: String) =
(config \ "mapping").view
.map(m => Mapping.fromXml(m))
.find(_.hasValue(entity))
.map(_.getValue)
private val links: Map[String, Option[String]] = Map[String, Option[String]]()
.withDefault(entry => {val result = lookUp(entry); links += ((entry, result)); result})
def getLink(entity: String) = links(entity)
}
</code></pre>
<p>How can I improve that code? </p>
<ul>
<li>The necessity to call <code>hasValue</code> before <code>getValue</code> is pretty bad, but I don't want to create the matcher twice.</li>
<li>Which environment variables do I have to use so that the tool can pick up the configuration from the current directory or from an arbitrary place with a command line switch?</li>
<li>Is there a better way to do simple caching than using <code>withDefault</code> to mutate the underlying map?</li>
<li>Any idea on how to improve <code>lookUp</code>?</li>
<li>Are there any ideas for better names? I'm not happy with <code>Mapping</code>, <code>Link</code>, <code>Reference</code> ... things are all over the place.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n <p>Any idea on how to improve lookUp?</p>\n</blockquote>\n\n<p><a href=\"https://gist.github.com/brikis98/5842766\" rel=\"nofollow\">Use a concurrent cache</a>. The point is, regardless how good or bad you lookup function is, nothing beats a cache-hit performance wise..</p>\n\n<blockquote>\n <p>Is there a better way to do simple caching than using withDefault to\n mutate the underlying map?</p>\n</blockquote>\n\n<pre><code>getOrElseUpdate(key, value)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T19:13:32.493",
"Id": "44464",
"ParentId": "4215",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T13:57:38.400",
"Id": "4215",
"Score": "5",
"Tags": [
"strings",
"regex",
"scala",
"xml",
"lookup"
],
"Title": "Processing XML configuration which stores regular expressions and format strings for a documentation tool"
}
|
4215
|
<p>I have a set of classes that abstract away calls to a set of web services. I have 6 classes in this particular group, 4 of which contain a simple function that, while small, is still duplicated. What happens is that if some exception or business rule violation happens in the service, they package it up as a fault object in the response. Otherwise, the fault object is null. As a result, the functions simply check to see if that object is not null and, if so, take the reason provided and throw an exception up the chain. So in one class, it might look like </p>
<pre><code>private void ThrowIfContainsFault(AlphaResponse response)
{
if (response.Fault != null)
{
throw new WhateverException(response.Fault.reasonText);
}
}
</code></pre>
<p>And then the other classes, the response object will be of a different type, but the <code>Fault</code> property is the same and the block of code is the same. </p>
<pre><code>private void ThrowIfContainsFault(BravoResponse response)
private void ThrowIfContainsFault(CharlieResponse response)
private void ThrowIfContainsFault(DeltaResponse response)
</code></pre>
<p>(<strong>Note</strong>: These class names are changed for readability, there is no common ancestor for these response objects.)</p>
<p>My first thought is that I could simply change the functions to receive the <code>Fault</code> object directly and forget the response object, and that's valid. But my overall concern is that while these methods literally do the same thing, the classes themselves are not particularly related, so introducing a common base hierarchy for a single (protected) method does not strike me as a suitable fit. </p>
<p>Here's my throwaway thought that I'm not even sure I like: </p>
<p>Define an empty interface that each class can "implement," then define an extension method against that interface. </p>
<pre><code>internal interface IFaultThrower
{
}
internal static class IFaultThrowerExtension
{
internal static void ThrowIfNotNull(this IFaultThrower thrower, Fault fault)
{
if (fault != null)
{
throw new WhateverException(fault.reasonText);
}
}
}
</code></pre>
<p>This would allow the related classes to get rid of their own private methods and invoke this common one.</p>
<pre><code> // this.ThrowIfContainsFault(response);
this.ThrowIfNotNull(response.Fault);
</code></pre>
<p>Again, not sure I like it, but I'm also not sure I like the same general idea creeping into multiple classes, either.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T18:18:54.013",
"Id": "6345",
"Score": "0",
"body": "Does AlphaResponse, BravoResponse etc all inherit the same interface or class or abstract class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T18:23:34.787",
"Id": "6346",
"Score": "0",
"body": "No, I've morphed the names of these service objects into something readable for presentation purposes, but they have no common ancestor (not counting `object`). An example of a real name might be something like `EckBarBrusselsproutResponse_Type94` (seriously)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T21:12:42.520",
"Id": "6355",
"Score": "0",
"body": "Is it possible to inherit from an `IResponse`? It would greatly simplify a lot of work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T21:26:34.010",
"Id": "6356",
"Score": "0",
"body": "@IAbstract - It's possible, I suppose, to use a partial class definition for each of the response objects. I just had another thought of perhaps adding an extension method directly for the `Fault` object and forgetting a fake inheritance approach entirely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-23T00:17:24.377",
"Id": "11080",
"Score": "0",
"body": "Which web service platform is this? ASMX, WCF, or other?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-23T03:20:17.827",
"Id": "11084",
"Score": "0",
"body": "@JohnSaunders, other. C# client, but Java service."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-23T03:52:53.077",
"Id": "11085",
"Score": "0",
"body": "\"Add Service Reference\" or \"Add Web Reference\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-23T14:48:28.377",
"Id": "11092",
"Score": "0",
"body": "@JohnSaunders, Service Reference."
}
] |
[
{
"body": "<p>If AlphaResponse, BravoResponse etc all inherit an interface \"IResponse\" then you could do this.</p>\n\n<pre><code>internal static class FaultThrowerExtension\n{\n internal static void ThrowIfContainsFault<T>(this T response) where T : IResponse\n {\n if (response.Fault != null) throw new WhateverException(fault.reasonText);\n }\n}\n</code></pre>\n\n<p>Update : \nAfter reading your comment that they don't have a common Interface you could then do this.\nThis is a lot more messey though.</p>\n\n<pre><code>internal static class FaultThrowerExtension\n{\n internal static void ThrowIfContainsFault<T>(this T response) where T : class\n {\n var type = typeof(T).FullName;\n\n foreach (var propertyInfo in PropertyInfoCache[type])\n {\n if (propertyInfo.Name == \"Fault\")\n {\n var fault = propertyInfo.GetValue(value, null);\n if (response.Fault != null) throw new WhateverException(fault.reasonText);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T18:26:40.707",
"Id": "4241",
"ParentId": "4216",
"Score": "0"
}
},
{
"body": "<p>I think it is a bad idea to introduce an empty interface to just add an extension method to it. You should think about an interface as a contract and not merely a way to introduce syntax sugar :)</p>\n\n<p>I believe instead of playing with extension methods it is enough to introduce a separate, helper, internal class whose only purpose would be to throw an exception if fault object is null:</p>\n\n<pre><code> internal class FaultResponseChecker\n {\n internal static void ThrowIfNotNull(Fault fault)\n {\n if (fault != null)\n {\n throw new WhateverException(fault.reasonText);\n }\n }\n }\n</code></pre>\n\n<p>If you, as I, don't like static methods, then you can use IoC container to inject IFaultResponseChecker into the constructor of every class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T15:24:50.630",
"Id": "6375",
"Score": "0",
"body": "This is practically line for line how I left it yesterday, except it's an extension method (`this Fault fault`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-08T15:18:31.720",
"Id": "18602",
"Score": "0",
"body": "As an update, we are presently doing a rearch of the project, and I am indeed electing to use composition instead of inheritance and also instead of a static method. Not using anything like an IoC container, although it does expose the fault handling dependency via the constructor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T08:03:17.460",
"Id": "4257",
"ParentId": "4216",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4257",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T16:03:45.810",
"Id": "4216",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Duplicated code in web service consumption"
}
|
4216
|
<p>I was applying for a position, and they asked me to complete a coding problem for them. I did so and submitted it, but I later found out I was rejected from the position. Anyways, I have an eclectic programming background so I'm not sure if my code is grossly wrong or if I just didn't have the best solution out there. I would like to post my code and get some feedback about it. Before I do, here's a description of a problem:</p>
<blockquote>
<p>You are given a sorted array of integers, say, <code>{1, 2, 4, 4, 5, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 13 }</code>. Now you are supposed to write a program (in C or C++, but I chose C) that prompts the user for an element to search for. The program will then search for the element. If it is found, then it should return the first index the entry was found at and the number of instances of that element. If the element is not found, then it should return "not found" or something similar. Here's a simple run of it (with the array I just put up):</p>
</blockquote>
<pre>
Enter a number to search for: 4
4 was found at index 2.
There are 2 instances for 4 in the array.
Enter a number to search for: -4.
-4 is not in the array.
</pre>
<p>They made a comment that my code should scale well with large arrays (so I wrote up a binary search). Anyways, my code basically runs as follows:</p>
<ul>
<li>Prompts user for input.</li>
<li>Then it checks if it is within bounds (bigger than a[0] in the array and smaller than the largest element of the array).</li>
<li>If so, then I perform a binary search.</li>
<li>If the element is found, then I wrote two while loops. One while loop will count to the left of the element found, and the second while loop will count to the right of the element found. The loops terminate when the adjacent elements do not match with the desired value. </li>
</ul>
<p>EX: 4, <strong>4</strong>, 4, 4, 4 </p>
<p>The <strong>bold 4</strong> is the value the binary search landed on. One loop will check to the left of it, and another loop will check to the right of it. Their sum will be the total number of instances of the the number four. </p>
<p>Anyways, I don't know if there are any advanced techniques that I am missing or if I just don't have the CS background and made a big error. Any constructive critiques would be appreciated!</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
/* function prototype */
int get_num_of_ints(
const int* arr,
size_t r,
int N,
size_t* first,
size_t* count
);
int main()
{
int N; /* input variable */
int arr[]={1,1,2,3,3,4,4,4,4,5,5,7,7,7,7,8,8,8,9,11,12,12}; /* sorted */
size_t r = sizeof(arr)/sizeof(arr[0]); /* right bound */
size_t first; /* first match index */
size_t count; /* total number of matches */
/* prompts the user to enter input */
printf( "\nPlease input the integer you would like to find.\n" );
scanf( "%d", &N );
int a = get_num_of_ints( arr, r, N, &first, &count );
/* If the function returns -1 then the value is not found.
Else it is returned */
if( a == -1)
printf( "%d has not been found.\n", N );
else if(a >= 0){
printf( "The first matching index is %d.\n", first );
printf( "The total number of instances is %d.\n", count );
}
return 0;
}
/* function definition */
int get_num_of_ints(
const int* arr,
size_t r,
int N,
size_t* first,
size_t* count)
{
int lo=0; /* lower bound for search */
int m=0; /* middle value obtained */
int hi=r-1; /* upper bound for search */
int w=r-1; /* used as a fixed upper bound to calculate the number of
right instances of a particular value. */
/* binary search to find if a value exists */
/* first check if the element is out of bounds */
if( N < arr[0] || arr[hi] < N ){
m = -1;
}
else{ /* binary search to find value if it exists within given params */
while(lo <= hi){
m = (hi + lo)/2;
if(arr[m] < N)
lo = m+1;
else if(arr[m] > N)
hi = m-1;
else if(arr[m]==N){
m=m;
break;
}
}
if (lo > hi) /* if it doesn't we assign it -1 */
m = -1;
}
/* If the value is found, then we compute left and right instances of it */
if( m >= 0 ){
int j = m-1; /* starting with the first term to the left */
int L = 0; /* total number of left instances */
/* while loop computes total number of left instances */
while( j >= 0 && arr[j] == arr[m] ){
L++;
j--;
}
/* There are six possible outcomes of this. Depending on the outcome,
we must assign the first index variable accordingly */
if( j > 0 && L > 0 )
*first=j+1;
else if( j==0 && L==0)
*first=m;
else if( j > 0 && L==0 )
*first=m;
else if(j < 0 && L==0 )
*first=m;
else if( j < 0 && L > 0 )
*first=0;
else if( j=0 && L > 0 )
*first=j+1;
int h = m + 1; /* starting with the first term to the right */
int R = 0; /* total number of right instances */
/* while loop computes total number of right instances */
/* we fixed w earlier so that it's value does not change */
while( arr[h]==arr[m] && h <= w ){
R++;
h++;
}
*count = (R + L + 1); /* total num of instances stored into count */
return *first; /* first instance index stored here */
}
/* if value does not exist, then we return a negative value */
else if( m==-1)
return -1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T16:16:34.690",
"Id": "6278",
"Score": "52",
"body": "As a starting advice: \"commnent less\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:49:03.653",
"Id": "6279",
"Score": "3",
"body": "Too bad you picked C. std::equal_range makes this one really easy."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T15:23:08.713",
"Id": "6281",
"Score": "1",
"body": "Couldn't three of the cases in that six-way bit be refactored into `if( L == 0 ) *first = m;`? And the first and last cases look like they could be collapsed also, so that leaves only three cases -- much nicer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:45:50.600",
"Id": "6282",
"Score": "20",
"body": "**This code is fine, absolutely fine.** Rest assured you didn't do anything godawful. The only worthwhile suggestion I've seen on this page is that the linear-time searches for the start and endpoints can be made log-time, but even that I would call nitpicking. You had exactly the right idea. Take heart, there are a lot of \"programmers\" who get FizzBuzz wrong in interviews (google it) and you're clearly not one of them. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-08T06:59:01.100",
"Id": "18564",
"Score": "0",
"body": "Please write a better title like: \"Critic required on searching an element in a sorted array.\" It helps other people to know what is it all about - without reading the big post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-23T14:23:11.650",
"Id": "179059",
"Score": "0",
"body": "Sorry about the job. but it looks like your program is worst case linear, so it could take a while. https://goo.gl/5xrjyk"
}
] |
[
{
"body": "<p>It's been a long while since I used C++, so I couldn't write it write now, but I know there were algorithms in the STL that would make very short work of this. Implementing your own binary search is probably a sign to the prospective employer that you're something of a beginner. The fact that you <em>can</em> implement it is good - but that you would choose to, when such algorithms are already implemented for you, might be discouraging to them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:30:41.943",
"Id": "6283",
"Score": "0",
"body": "Argh. I think there's a binary search algorithm but not a \"count the number of instances\" part. And more importantly it wouldn't return the 1st index as well. Anyways, I'll take another look. But thanks anyways! It will be something I have to think about for my next job app."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:33:01.653",
"Id": "6284",
"Score": "3",
"body": "Maybe, but then it is a trick question. If he'd used the STL, someone else would say that it proves he doesn't really understand the basic algorithms of CS and would be lost if he needed something that wasn't in the STL."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:33:06.037",
"Id": "6285",
"Score": "0",
"body": "I disagree. Most coding tests require that you do not use standard library functions. If I were the tester I would state that explicitly; using a std::vector does not tell me anything about what you can do."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:35:24.870",
"Id": "6286",
"Score": "1",
"body": "@Micky: If you are using C++, look at `std::lower_bound`. If the iterator returned by the search points to the value you searched for, you know that value is in the container. You can then walk forward and count the number of instances of that value in the container."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:43:28.010",
"Id": "6287",
"Score": "1",
"body": "@James: Or incorporate std::upper_bound, too, then subtract them. If my rusty STL is right, at least."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T11:23:26.240",
"Id": "6288",
"Score": "3",
"body": "Or just use `std::equal_range`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T14:05:20.843",
"Id": "6289",
"Score": "0",
"body": "Thanks, @UncleBens - that's what I meant when I said my STL was rusty; std::equal_range would make a simple one-liner of this whole question, I think. Good call."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T19:34:11.227",
"Id": "6290",
"Score": "0",
"body": "If you read his post, it was supposed to be implemented in either C++ or C, and he chose C. so any C++ specific comments wouldn't be relevant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T23:56:24.660",
"Id": "6291",
"Score": "0",
"body": "@Larry, you remind me why I stopped reading C *and* C++ newsgroups long, long ago."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:23:27.853",
"Id": "4224",
"ParentId": "4223",
"Score": "9"
}
},
{
"body": "<p>I would factor the binary search out as a separate procedure. </p>\n\n<p>Also, I would input the array, even if this is not called for, or factor it out into an input procedure that could be converted into something that reads from a file.</p>\n\n<p>I prefer camelCase convention, and more meaningful variable names.</p>\n\n<p>Your algorithm, however, seems fine. Have you thought about the possibility that the test was not a big factor in the hiring decision? Several applicants may have written equally good answers, and the decision made on other criteria.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:38:43.027",
"Id": "6292",
"Score": "0",
"body": "I thought about writing a while loop to input and sort the array. The problem description was agnostic as to whether I could assume it was already inputted & sorted. I should have been more careful on that point. You're probably right about the \"other factors\" point. I had to submit some essays regarding various topics--that could have played a role as well. I am just suspecting that I must have done something wrong with this part of the app since I have such a hodge podge CS background. I major in Math & Bio so I'm unsure about my CS skills. I don't know what to expect from employers. Thanks"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T19:29:15.357",
"Id": "6293",
"Score": "1",
"body": "Don't sweat it too much. It could even be something stupid, like he doesn't like the else{ and prefers else {. Or maybe the shirt you wore :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:25:01.423",
"Id": "4225",
"ParentId": "4223",
"Score": "8"
}
},
{
"body": "<p>It looks reasonable enough to me. Yes, maybe some STL methods might help. The only thing I would criticize is that you don't verify that the input is actually a number.</p>\n\n<p>Still I don't see enough here to reject you base don this assignment. Maybe it was another part of the interview. Or maybe they did not reject you - they accepted someone else. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:44:23.337",
"Id": "6294",
"Score": "2",
"body": "I totally agree with this. Rest assured you (Micky) didn't do anything godawful. The only worthwhile suggestion I've seen on this page is that the linear-time searches for the start and endpoints can be made log-time, but even that I would call nitpicking. You had exactly the right idea. There are a lot of \"programmers\" who get FizzBuzz wrong in interviews (google it) and you're clearly not one of them. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:27:27.407",
"Id": "4226",
"ParentId": "4223",
"Score": "10"
}
},
{
"body": "<p>Your code is too complex for what it should do. There are too many comments, variables poor named, and not a clear definitions of functions roles.\nSome code to show what I would expect as a response: </p>\n\n<pre><code>#include <stdio.h>\n\nint binary_search( const int value, const int *arr, size_t start, size_t end ){\n if( value < arr[start] || value > arr[end] ){\n return -1;\n }\n\n while(start <= end){\n int pivot = (start+end) >> 1; \n if(arr[pivot] == value){\n return pivot;\n }else if(arr[pivot] < value){\n start = pivot+1;\n } else if(arr[pivot] > value){\n end = pivot-1;\n } \n }\n return -1;\n}\n\nint get_occurences( int begin, const int *arr, size_t max){\n int counter = 1;\n int cursor = begin;\n while ( (cursor+1) < max && arr[cursor] == arr[cursor+1]) {\n counter++;\n cursor++;\n }\n cursor = begin;\n while ( (cursor-1) > 0 && arr[cursor] == arr[cursor-1]) {\n counter++;\n cursor--;\n }\n return counter;\n}\n\n\n#define MAX 22\nint main()\n{ \n int value;\n int arr_sorted []={1,1,2,3,3,\n 4,4,4,4,5,\n 5,7,7,7,7,\n 8,8,8,9,11,\n 12,12}; \n size_t arr_size = MAX; // works also the other way \n\n printf( \"\\nPlease input the integer you would like to find.\\n\" );\n scanf( \"%d\", &value );\n printf(\"Searching %d\\n\", value);\n int pos = binary_search( value, arr_sorted, 0, arr_size-1);\n\n if( pos == -1) { \n printf( \"%d has not been found.\\n\", value );\n } else{\n int howmany = get_occurences( pos, arr_sorted, arr_size);\n printf( \"The first matching index is %d.\\n\", pos );\n printf( \"The total number of instances is %d.\\n\", howmany );\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:34:12.660",
"Id": "6295",
"Score": "2",
"body": "While you can write a recursive binary search algorithm an iterative one is fine and if C is being used probably better."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:51:33.893",
"Id": "6296",
"Score": "0",
"body": "@fabrizioM: Can you suggest a (teaching) book, material or lecture note to correct my mistake?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:06:22.837",
"Id": "6297",
"Score": "0",
"body": "The code looks reasonably concise and understandable, so I doubt lack of recursion was a factor."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:12:46.573",
"Id": "6298",
"Score": "0",
"body": "@GregS is kind of personal preference. As a reviewer I would not accept that code. As a second thought I agree, recursion wasn't a factor."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:19:07.033",
"Id": "6299",
"Score": "1",
"body": "Your occurrences function does not work. binary search will not always return the first occurrence in the array, so you will need to search backward as well as forward."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:32:16.340",
"Id": "6300",
"Score": "0",
"body": "@SoapBox, thanks, I think I fixed that. (forgive me its 3:31 am here)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:42:10.847",
"Id": "6301",
"Score": "0",
"body": "@fabrizioM: Thank you taking the time to write up some more detailed code. Not a fun learning lesson but necessary. Just to recap. You described my problems with my code as follows: commenting, poor variable name selection, and the binary search algorithm wasn't written as cleanly as I should have?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:18:18.733",
"Id": "6302",
"Score": "0",
"body": "Recursion would make the code *worse* as it burns log(n) stack space unnecessarily. Recursion is pretty, recursion is elegant, recursion is not always better."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:28:29.777",
"Id": "4227",
"ParentId": "4223",
"Score": "19"
}
},
{
"body": "<p>I think the last part of your algorithm is sub-optimal. You could carry on your binary search to find the lowest and highest elements equal to the one you are looking for, and then subtract the addresses to find how many there are. </p>\n\n<p>This would scale better if there are many identical elements, but, more importantly for the interview question, it would make your algorithm simpler. For example, the \"6 outcomes\" code is pretty hairy, and having such a bunch of if-else is often considered a code smell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:36:53.453",
"Id": "6303",
"Score": "2",
"body": "Yes, for example if the array consists of only O(1) distinct elements, the algorithm degenerates to O(n) performance."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:50:03.163",
"Id": "6304",
"Score": "0",
"body": "@small_duck. Thanks. I felt the same way about the multiple if..else if statements I was making, but being pressed for time, I just did it the messy fashion I wrote up. Can you clarify your \"carry on your binary search..\" comment a bit more?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:22:34.747",
"Id": "6305",
"Score": "1",
"body": "If you did binary_search(requested_item-1) and binary_search(requested_item+1) and recorded the positions where those are (or the location where the search fails if they do not exist) then you could scan backwards/forwards from each until you located the element that you were actually looking for. You'd then have the first and last positions of it, which can be used to trivially count the number of instances. This is O(nlogn). There are a few sub-optimal cases, but I don't think they significantly effect the runtime."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T03:38:30.640",
"Id": "6306",
"Score": "0",
"body": "@SoapBox I might be missing something, but why would you go to the trouble of finding a different element and then linearly scanning until the end of that sequence, rather than just scan the original sequence?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T10:59:57.723",
"Id": "6307",
"Score": "2",
"body": "+1 SoapBox (although complexity would be O(log(n)), right?). Micky, the trick is to change your binary search in finding not just one element of the section, but the lowest of the range. Then you can logarithmically find the first and the last element the sequence, a simple subtraction giving you the length. In C++, the standard library has \"equal_range\", which does exactly this."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T01:29:29.657",
"Id": "4228",
"ParentId": "4223",
"Score": "19"
}
},
{
"body": "<p>Random observations:</p>\n\n<ul>\n<li><p>The binary search should be decoupled from \"find the longest run of identical elements containing this index.\"</p></li>\n<li><p>It's possible they want time logarithmic in the length of the run, rather than linear.</p></li>\n<li><p>I'd reject any candidate who submitted a six-way case analysis for a simple problem like finding a run. If you split that out as its own routine, you probably find a simpler way to do it like</p>\n\n<pre><code>for (first = m; first > arr && *first == arr[m]; first--)\n ;\nfor (last = m; last < arr+r-1 && *last == arr[m]; last++)\n ;\n</code></pre>\n\n<p>This code costs linear in the length of the run; if they want logarithmic it becomes a tricky little problem—but in my opinion, over the top as an interview problem.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:44:39.220",
"Id": "6308",
"Score": "0",
"body": "Thanks, I knew the multiple statements were not the best way to write it up, but I couldn't figure out how to do it any better with the time I was allotted. Btw, can you suggest a practical resource I could use to help me write better code?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T03:35:59.520",
"Id": "6309",
"Score": "0",
"body": "@Micky: There are lots of good books out there. For you I might recommend Jon Bentley's *Programming Pearls* since it is pretty focused on code and on thinking about code. Get the second edition."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:25:47.100",
"Id": "4229",
"ParentId": "4223",
"Score": "26"
}
},
{
"body": "<p>I would have a few concerns about hiring someone who submitted this for a code sample. Here is what I see.</p>\n\n<p>First, addressing overall design, the algorithm is suboptimal, and is worst case linear instead of worst case logarithmic, because it doesn't use a binary search to find the amount of elements, but a linear one.</p>\n\n<p>Second, (and this is what would have really killed it for me) the variable names. Most of these are either one or two letters, and the code is very unreadable because of it. Giving your variables descriptive names is important for maintainability.</p>\n\n<p>Third, ignoring standard libraries. Unless instructed not to use them, you should prefer standard libraries which have implementations of binary search (e.g. the stl or <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/\">bsearch</a>)</p>\n\n<p>Fourth, why have get_num_of_ints return -1 has a magic value feeling to me; better to just set count = 0 and check that.</p>\n\n<p>Fifth, get_num_of_ints is just far too long, and tries to do way too much. It badly needs to be broken up.</p>\n\n<p>Sixth (and this is a personal choice), I think C++, with the STL, is a far better choice in this instance.</p>\n\n<p>In the spirit of \"show, don't tell\", here is how I would have written the assignment (untested, uncompiled) (<strong>edited to match the required function signature</strong>):</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\n// This function signature is required:\nint get_num_of_ints(const int* searchBegin, size_t searchSize, int input,\n size_t* first, size_t* count) {\n const int* searchEnd = searchBegin + searchSize;\n const int* result = lower_bound(searchBegin, searchEnd, input);\n\n if (searchEnd == result || *result != input)\n return -1;\n\n *first = result - searchBegin;\n *count = upper_bound(result, searchEnd, input) - result;\n return 0;\n}\n\nvoid print_search_results(const int* searchBegin, size_t searchSize, int input) {\n size_t first;\n size_t count; \n\n if (get_num_of_ints(searchBegin, searchSize, input, &first, &count) < 0) {\n cout << input << \" is not in the array.\" << endl;\n return;\n }\n\n cout << input << \" was found at index \" << first << \". \"\n << \"There are \" << count << \" instances for \" << input << \" in the array.\"\n << endl;\n}\n\nbool read_input(int* input) {\n cout << \"Enter a number to search for: \";\n bool succeeded = cin >> *input;\n cout << endl; \n return succeeded;\n}\n\nint main (int argc, char** argv) {\n const int searchNumbers[] = {1, 2, 4, 4, 5, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 13};\n const int searchNumbersSize = sizeof(searchNumbers)/sizeof(searchNumbers[0]);\n\n while(1) {\n int input;\n if(!read_input(&input)) {\n count << \"Bad input, exiting\" << endl;\n return 1;\n }\n\n print_search_results(searchNumbers, searchNumbersSize, input);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:46:45.300",
"Id": "6310",
"Score": "0",
"body": "\"Fifth, get_num_of_ints is just far too long, and tries to do way too much. It badly needs to be broken up\" Hah! They told me I was supposed to write my solution with that function prototype. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T03:10:59.280",
"Id": "6311",
"Score": "2",
"body": "That does put some restriction on the interface, but you could still break up the internals; e.g., have a binary_search function instead putting those implementations inside of get_num_of_ints."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T23:30:51.637",
"Id": "6312",
"Score": "14",
"body": "A lot of these points can be found in code complete by Steve McConnell, it covers a lot of ground on coding style and has lots of references to dive deeper if needed."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:53:42.940",
"Id": "6313",
"Score": "5",
"body": "Despite being right about the computational complexity, I have to -1 this. Complaining about variable names in a short standalone piece of code is pretentious IMHO. I have no trouble keeping a small handful of short variable names in my head, and in fact find the reduced visual clutter makes it *much easier* to read and understand. Also while I agree with the idea of using standard library functions where possible in real code, it's not clear whether they were trying to test engineering knowledge or algorithmic ability here and it's safer to bet on the latter IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T18:56:04.480",
"Id": "8577",
"Score": "17",
"body": "@j_random_hacker: +1 to offset your -1. In the OP's code presented the variable names are horrendous, \"short standalone piece of code\" or otherwise. In very limited circumstances are short variable names okay such as loop counters, small functions (i.e., less than 8 lines). Favor read-time convenience over write-time convenience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-23T12:03:31.733",
"Id": "116316",
"Score": "0",
"body": "And I wouldn't hire you either (though I'm a bit young to hire anyone). This is suboptimal. Looking for a lower bound, you surely encounter a much better lower bound for the upper bound than `searchEnd` reducing the `[result, searchEnd]` interval. Knowing what stl can do is good if it doesn't prevent you to see what you miss in using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-11T16:04:02.340",
"Id": "298234",
"Score": "1",
"body": "Should use `std::equal_range` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:29:00.650",
"Id": "347737",
"Score": "3",
"body": "I almost withheld my +1 because of `using namespace std;` - that definitely warrants a conversation if I'm hiring!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T02:40:24.737",
"Id": "4230",
"ParentId": "4223",
"Score": "109"
}
},
{
"body": "<p>In addition to many of the other comments, the following:</p>\n\n<pre><code>m = (hi + lo)/2;\n</code></pre>\n\n<p>is the wrong way to find the middle index. This can overflow. You should do:</p>\n\n<pre><code>m = lo + (hi - lo) / 2;\n</code></pre>\n\n<p>Second, the line:</p>\n\n<pre><code>m=m;\n</code></pre>\n\n<p>has no effect, and can be eliminated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:52:57.357",
"Id": "6314",
"Score": "4",
"body": "True, but I doubt that anyone would fail to get a job because they forgot this bug."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:57:22.250",
"Id": "6315",
"Score": "6",
"body": "@Edan: I am not so sure. A \"simple\" question like this has multiple layers complexity. The interviewer may have asked this question to figure out the level of the applicant. And even if it wasn't the intension, writing correct code helps anyway. Maybe with a comment to the effect of \"do this instead of `(hi + lo)/2` to avoid overflow\" - and the interviewer would then realize that the applicant thought of something that the interviewer didn't! :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T08:51:35.110",
"Id": "6316",
"Score": "3",
"body": "I'm sure that bringing this up will score you huge points. But isn't this the bug that was discovered about 4 years ago to have been a bug in pretty much every implementation of binary search for the last 20 years? I'm just saying, if this was a bug in the Java library for 15 years before it was discovered, I wouldn't hold it against anyone not to think of it themselves."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T08:55:59.143",
"Id": "6317",
"Score": "1",
"body": "On the other hand, I did use this bug to show off to a University prof once... mentioning it will definitely get you points :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:14:57.867",
"Id": "6318",
"Score": "6",
"body": "@Edan Maor: It's even better than that -- according to http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html, Jon Bentley, a famous computer scientist, implemented a binary search in *Programming Pearls* that contained this bug. And if you wouldn't hire Bentley for a programming position, who would you hire?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-20T22:07:28.520",
"Id": "95904",
"Score": "0",
"body": "It's a stupid bug, imho. The code can always overflow, this just gives you a bit more of precision before it happens. In most cases the simple version would be easier to read and work just as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-20T22:11:21.123",
"Id": "95906",
"Score": "3",
"body": "@Thomas would you say the same if this bug was in a library?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-20T22:58:14.687",
"Id": "95913",
"Score": "0",
"body": "that's a very good point. For a library function I would expect it to work for the entire range of values available for array indexing."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T06:25:33.707",
"Id": "4231",
"ParentId": "4223",
"Score": "54"
}
},
{
"body": "<p>Was there a specific requirement that you do a binary search on the list? If there wasn't, why are you doing it? Unnecessarily overcomplicating a solution is one strike against you. * Edit: Whoops you said you had to do it this way in the question! Never mind, carry on * </p>\n\n<p>Why are you using single character variable names? There's plenty of room in the symbol table for more descriptive names. That's another strike.</p>\n\n<p>Too many comments. I can hear you all now: \"is he crazy??\". Seriously. The code should speak for itself as much as possible. Every time you start writing a comment think \"is there a way I could make the code clear enough to avoid this comment?\". That's strike three.</p>\n\n<p>Coding is as much communicating to other people as it is communicating to a machine. Your coding style should reflect that. <a href=\"http://rads.stackoverflow.com/amzn/click/0735619670\">Code Complete</a> is a great book with lots of useful coding style advice. Read the first few chapters and code up the solution again, applying the techniques he describes. Compare your two solutions while asking yourself \"which one would I rather maintain?\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T10:02:47.620",
"Id": "6319",
"Score": "4",
"body": "He's doing the binary search on the list because \"They made a comment that my code should scale well with large arrays.\" Properly executed, a binary search will handle this in O(lg(n)) time as opposed to the O(n) time required to just check through linearly. In this case, using a binary search isn't unnecessarily over-complicating the solution; it's using an appropriate level of complexity to get a significantly more efficient solution for the given requirements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T07:21:10.203",
"Id": "4232",
"ParentId": "4223",
"Score": "8"
}
},
{
"body": "<p>Is it just me, or am I the only one who would implement this in an entirely different fashion?</p>\n\n<p>Looking at the requirements of the problem:</p>\n\n<ol>\n<li>Determine if element is present</li>\n<li>If present return array index of first occurrence</li>\n<li>If present return number of occurrences</li>\n</ol>\n\n<p>You have to think outside the box on a problem like this. Specifically, I would implement a solution to this by dumping the array into a hash at the beginning of the program. The hash key is the number, and the value is a struct containing the index of the first occurance and the total occurance count. You set up this hash as part of the program start up / initilization and then any subsequent look ups by the user are always constant time operations - BigO(1).</p>\n\n<p>You would have no problem implementing this in C++ with the STL.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B_class%29\">unordered_map (C++)</a></p>\n\n<p>Binary Search is just the wrong solution to this problem.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Regarding the cost of setting up the hash:</p>\n\n<p>Setup is a constant cost incurred only once. While I won't say it doesn't matter, there are a limited number of cases where it does; usually when you have either very small data sets or you execute the algorithm a very small number of times. Other than that setup cost is amortized across all the executions of the algorithm. An algorithm that requires n setup but executes in BigO(1) still beats an algorithm that requires 0 setup but executes in BigO(log n) time unless you're executing it a very small number of times.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T11:39:59.950",
"Id": "6320",
"Score": "6",
"body": "\"Binary Search is just the wrong solution to this problem.\" - It appears the program is supposed to look just for one value when run. With a hash-table you'd have to look up several values to compensate for the expense of creating the table."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T12:34:05.813",
"Id": "6321",
"Score": "0",
"body": "@UncleBens: The OP says that one of the things they specifically asked for was a scalable solution. BigO(n) is significantly less scalable that BigO(1) even when setup time is fairly large."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T12:40:32.387",
"Id": "6322",
"Score": "3",
"body": "It really depends on the requirements. If you are asked to basically reimplement std::equal_range, as seems to be the case here, that is a function that accepts a sorted range and a value, then constructing a hash-table might not be an acceptable solution (because inevitably you'd have to create a new table for each look-up). - If the requirements were different and you knew you were working with the same array, then things might be different. - Also, constructing a std::map from a sorted array to perform binary search on it, seems like a complete waste of time and resources."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T12:56:03.053",
"Id": "6323",
"Score": "0",
"body": "@UncleBens: You're right - it all depends on the requirements :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T18:53:54.440",
"Id": "6324",
"Score": "2",
"body": "the setup would take O(n), that is worse than the O(log n) of binary search"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T20:05:35.177",
"Id": "6325",
"Score": "0",
"body": "@swegi: Setup is a constant cost incurred only once. While I won't say it doesn't matter, there are a limited number of cases where it does; usually when you have either very small data sets or you execute the algorithm a very small number of times. Other than that setup cost is amortized across all the executions of the algorithm. An algorithm that requires n setup but executes in BigO(1) still beats an algorithm that requires 0 setup but executes in BigO(log n) time unless you're executing it a very small number of times."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T22:20:19.890",
"Id": "6326",
"Score": "0",
"body": "The OP mentioned in a comment to my answer that they said the function should match the prototype \"int get_num_of_ints( const int* arr, size_t r, int N, size_t* first, size_t* count );\", which suggests they weren't looking for the hash solution (which certainly would be faster, depending on requirements)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:31:41.150",
"Id": "6327",
"Score": "2",
"body": "-1 for \"Binary search is just the wrong solution to this problem\". As UncleBens pointed out, either approach could be (much) faster depending on information we don't have -- that being how many searches will be performed, so this comment is unfounded. (There's also the fact that a hashtable will (at least) double memory requirements, since both keys and values must now be stored.) Will +1 if you get rid of this remark."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:35:04.200",
"Id": "6328",
"Score": "0",
"body": "In fact nothing in the problem description suggests performing more than 1 search, so I would assume a single search was being made. (The fact that the numbers are already sorted is another clue about the solution they are looking for.) In that case, a binary search will be dramatically faster for large n."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T07:22:51.620",
"Id": "4233",
"ParentId": "4223",
"Score": "14"
}
},
{
"body": "<p>This is what I would have turned in, simple clean and easy to read:</p>\n\n<p>I modified it to test the timing with an array of 300 Million ints and even on my older system it found the \"worst case\" values (the ones at the end of the array) in about a second (took 6 seconds to fill the array at startup).</p>\n\n<p>So IMHO all this binary search blather falls under the category of \"pre-mature optimization\" for this simple interview question. :-)</p>\n\n<p>Do the simplest thing that works. Write the code so people can <strong>read</strong> it and not have to <strong>decipher</strong> it. Of course, be prepared to discuss performance alternatives <strong>if needed</strong>.</p>\n\n<p>Latest edit: Addition of FindStartingPoint() function to optimize for speed.</p>\n\n<pre><code>/*****************************************************************\n Module: FindInts.cpp\n Author: Ron Savage\n Date: 03/13/2010\n\n Description:\n This program prompts the user for an integer, searches for it\n in a given sorted array of integers and prints the first location \n and number of matches in the array.\n\n Modification History:\n Date Init Comment\n 03/14/2010 RS Added a recursive FindStartingPoint function to\n find a good starting point for the linear search.\n 03/14/2010 RS Added a 300 million int array to test timing.\n 03/13/2010 RS Created.\n*****************************************************************/\n#include <stdafx.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stddef.h>\n\n/* function prototype */\nvoid FillArray( int* searchList, size_t listSize);\nint* FindStartPoint( int* searchList, size_t listSize, int numberToFind );\nsize_t FindMatches( int* searchList, size_t listSize, int numberToFind, size_t* firstMatchIndex, size_t* matchCount );\n\n/*****************************************************************\n Function: main()\n Author: Ron Savage\n Date: 03/13/2010\n\n Description:\n Entry point to the program.\n*****************************************************************/\nint main()\n {\n int userInput = 0;\n int *valueList = 0;\n\n // Allocate an array of 300 million ints\n size_t listSize = 300000000;\n if (valueList = (int*) malloc(listSize * sizeof(int)))\n {\n size_t firstMatchIndex = 0;\n size_t matchCount = 0;\n\n /* Fill the array with some values */\n FillArray(valueList, listSize);\n\n /* prompt the user to enter input */\n printf( \"\\nPlease input the integer you would like to find.\\n\" );\n scanf_s( \"%d\", &userInput );\n\n /* Search the list for the value entered */\n size_t iterations = 0;\n iterations = FindMatches( valueList, listSize, userInput, &firstMatchIndex, &matchCount );\n\n /* Display the results if found */\n if ( matchCount > 0 )\n {\n printf(\"\\n%d matches for [%d] were found, starting at index %d in %ld iterations.\\n\", matchCount, userInput, firstMatchIndex, iterations);\n }\n else\n {\n printf(\"\\nNo matches for [%d] were found.\\n\", userInput);\n }\n }\n else\n {\n printf(\"\\nCouldn't allocate memory for [%ld] ints.\\n\", listSize);\n }\n }\n\n/*****************************************************************\n Function: FindMatches()\n Author: Ron Savage\n Date: 03/13/2010\n\n Description:\n This function searches the searchList for the value entered\n by the user (numberToFind) and returns the first index and \n count of the matches.\n*****************************************************************/\nsize_t FindMatches( int* searchList, size_t listSize, int numberToFind, size_t* firstMatchIndex, size_t* matchCount )\n {\n // Set the default values if no matches are found\n *firstMatchIndex = 0;\n *matchCount = 0;\n\n // Find the start point of the number\n int* startPoint = FindStartPoint( searchList, listSize, numberToFind );\n\n // Loop through the list looking for matches, exit early if we pass the value in the sorted list.\n size_t searchIndex = 0;\n size_t searchInterations = 0;\n size_t startIndex = startPoint - searchList;\n for (searchIndex = startIndex; searchIndex < listSize; searchIndex++)\n {\n searchInterations++;\n\n if ( searchList[searchIndex] == numberToFind ) if ( ++(*matchCount) == 1 ) *firstMatchIndex = searchIndex;\n\n if ( searchList[searchIndex] > numberToFind ) break;\n }\n\n return(searchInterations);\n }\n\n/*****************************************************************\n Function: FindStartPoint()\n Author: Ron Savage\n Date: 03/14/2010\n\n Description:\n This function checks to see if the numberToFind is in the top\n or bottom half of the searchList, then recursively calls itself\n on each subsequently smaller sub-list until a starting point\n at or slightly before the first numberToFind is found.\n*****************************************************************/\nint* FindStartPoint( int* searchList, size_t listSize, int numberToFind )\n {\n // Check the value in the middle, to determine which half the number is in\n size_t middleIndex = listSize / 2;\n\n // Recurse into this function for just the first half of the list\n if ( searchList[middleIndex] >= numberToFind && middleIndex > 1 ) \n {\n return(FindStartPoint(searchList, middleIndex, numberToFind ));\n }\n\n // Recurse into this function for just the last half of the list\n if ( searchList[middleIndex] < numberToFind && middleIndex > 1 ) \n {\n return(FindStartPoint(&searchList[middleIndex], middleIndex, numberToFind ));\n }\n\n return(searchList);\n }\n\n/*****************************************************************\n Function: FillArray()\n Author: Ron Savage\n Date: 03/13/2010\n\n Description:\n This function fills the array with a sorted list of values.\n*****************************************************************/\nvoid FillArray( int* searchList, size_t listSize)\n {\n size_t searchIndex = 0;\n int value = 0;\n\n for (searchIndex = 0; searchIndex < listSize; searchIndex++)\n {\n searchList[searchIndex] = value++/100;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T09:54:46.607",
"Id": "6329",
"Score": "0",
"body": "This is just a linear search through the array requiring O(n) time. You can definitely do O(lg(n)) time for this using binary search. Given that in the original post, Micky wrote \"They made a comment that my code should scale well with large arrays,\" I feel like this would not at all be something that would make a good impression."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T21:42:53.453",
"Id": "6330",
"Score": "1",
"body": "I agree that the code should be readable, but a binary search algorithm can be readable too. Writing readable code does not mean writing the dumbest, least efficient thing that works. If the problem said to sort a huge array, would you choose bubble sort just because it's the simplest algorithm? That's essentially what you are doing here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T23:10:23.137",
"Id": "6331",
"Score": "0",
"body": "The point is do the simplest thing first (linear search). That took 5 minutes to code, and works easily for the up to 300 million int array I tested it with. If that's \"good enough\", i.e. their definition of \"large array\" is less than that - you're done. If not, refine the algorithm (spend more time on it) which I did with the latest edit since I was bored. :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:10:49.097",
"Id": "6332",
"Score": "2",
"body": "`// Allocate an array of 1 billion ints` next line:\n`size_t listSize = 300000000;` err... Your commenting scares me."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:57:45.867",
"Id": "6333",
"Score": "1",
"body": "@Ron Savage - If I were working on code as part of a job, I'd agree with you about doing the simplest thing first. But if you get asked a question in an interview, and they make a point of asking for it to scale with large arrays, it seems pretty clear to me that they want you to implement a binary search. The *least* I would do is ask them whether an O(n) solution would be appropriate for their requirements."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T03:37:59.750",
"Id": "6334",
"Score": "0",
"body": "I agree, I'd ask for clarification myself, to define what a \"large array\" means. Fixed the 1 billion ints comment, that's what I started with until I realized that my meager 2 gigs of memory with Win 7 and VS 2008 didn't have that much left over. :-)\nMost interview questions in my experience, are to see \"how you think\", not explicitly \"can you write a binary search\" - which can be picked up from google in few minutes."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T03:45:44.337",
"Id": "6335",
"Score": "0",
"body": "Also note, the FindStartPoint() function does implement the Binary Search algorithm - I just didn't realize that was the name for it. :-)\n(self taught programmer here)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:27:13.253",
"Id": "347734",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T18:37:00.420",
"Id": "451698",
"Score": "0",
"body": "BTW, `scanf_s()` doesn't invoke the constraint handler if `%d` conversion fails, so you still need to check its return value."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T08:27:59.873",
"Id": "4234",
"ParentId": "4223",
"Score": "8"
}
},
{
"body": "<p>I came up with a solution that is <span class=\"math-container\">\\$O(\\log n)\\$</span>. It involves a modified binary search that can be told to always take exactly log n comparisons (no early breaking if a match is found), and depending on a parameter, it will either keep trying to find the value to the left or to the right in the array until exhaustion.</p>\n\n<p>In this manner, we can run the binary search at most 2 times - no need to run it the second time if the first reports the value wasn't found - and give back the number of matches (last index - first index + 1). I pass in the <code>pos</code> variable as a pointer so we can effectively \"return\" 2 values - the number of matches, and the index of the first match in the run.</p>\n\n<pre><code>// returns the number of matches, and sets pos to the index of\n// the first match, or -1 if none found\nint findMatches(int array[], int size, int searchNum, int* pos)\n{\n *pos = binarySearch(array, size, searchNum, -1);\n // if it was found, pos points to a positive number\n if(*pos >= 0)\n {\n int lastIdx = binarySearch(array, size, searchNum, 1);\n return lastIdx - *pos + 1;\n }\n return 0;\n}\n</code></pre>\n\n<p>Then I've got a binary search method that takes an extra argument, <code>direction</code>, which indicates whether you want the first binary search index (0), the earliest (-1) or the last (+1).</p>\n\n<pre><code>int binarySearch(int array[], int size, int searchNum, int direction)\n{\n int left = 0;\n int right = size - 1;\n int center;\n int pos = -1;\n\n while(left <= right)\n {\n center = (right + left) >> 1;\n\n if(array[center] == searchNum)\n {\n pos = center;\n // break early if we want to find the exact match\n if(direction == 0) break;\n }\n\n // adding 1 to searchNum means we will find the last in the run\n if(array[center] < searchNum + ((direction > 0) ? 1 : 0))\n {\n left = center + 1;\n }\n else\n {\n right = center - 1;\n }\n }\n\n return pos;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:29:34.040",
"Id": "347738",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2010-03-14T11:04:20.470",
"Id": "4235",
"ParentId": "4223",
"Score": "10"
}
},
{
"body": "<p>In my experience, the</p>\n\n<pre><code>if (condition)\n consequence;\nstatementx;\n...\n</code></pre>\n\n<p>style is a land mine just waiting for another (or even the same) developer to extend it to:</p>\n\n<pre><code>if (condition)\n consequence1;\n consequence2;\nstatementx;\n...\n</code></pre>\n\n<p>Some of you might see what the problem is, but for most programmers, it is a virtually invisible bug because developers tend to interpret code by indentation even though the curly braces are missing, making consequence2 unconditional.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T22:17:14.073",
"Id": "6336",
"Score": "7",
"body": "+1 - Not sure why this got a down vote, I have seen way too many instances of exactly this happening to never personally not use brackets on an if statement. I agree, as developers we generally read code by indentation and not the presence of brackets."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-19T14:36:06.520",
"Id": "6337",
"Score": "12",
"body": "If only there was a language that used indentation to represent a nested block, then \"what the code looks like\" would always match \"what the code means\", as far as this answer goes."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:10:07.020",
"Id": "6339",
"Score": "6",
"body": "I agree with your advice, but I don't think this is important enough to justify not hiring someone. +0."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-04T10:12:59.580",
"Id": "6340",
"Score": "1",
"body": "@random_hacker I agree, by itself, it's no reason not to hire someone, but the question was a request to criticize the code and so I did: I described what I thought was bad practice and suggested a way to improve. It was quite a long time since I wrote some C code so I scan-read the code and provided the comments which sprang to mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T04:53:16.283",
"Id": "60950",
"Score": "0",
"body": "IMO, if your testing is crap enough to miss this mistake, you've got other problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:34:26.193",
"Id": "76289",
"Score": "11",
"body": "One such landmine, from 4 years in the future: Apple's SSL implementation skipped some security checks due to this problem. https://www.imperialviolet.org/2014/02/22/applebug.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:58:17.710",
"Id": "76437",
"Score": "1",
"body": "@Mike thanks for bringing it up. I guess the classics never go away..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-05T09:38:39.863",
"Id": "112876",
"Score": "0",
"body": "@Roger see http://en.wikipedia.org/wiki/Off-side_rule"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:09:29.783",
"Id": "347726",
"Score": "2",
"body": "Roger Pate was being facetious, right? Python, which had been out for ~9 years when he wrote his comment, uses indentation to represent a nested block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:26:30.387",
"Id": "347732",
"Score": "0",
"body": "@Snowbody, I assumed he was talking about Occam. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T20:50:40.287",
"Id": "347755",
"Score": "1",
"body": "@TobySpeight did you mean Caml/OCaml (dating from 1985)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T18:01:23.863",
"Id": "451696",
"Score": "1",
"body": "@Snowbody: no I meant [Occam](https://en.wikipedia.org/wiki/Occam_%28programming_language%29), from 1983. (Sorry I missed your comment earlier - I left for a New Year break, and it must have been lost in the pile when I returned!)"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T12:00:20.703",
"Id": "4236",
"ParentId": "4223",
"Score": "65"
}
},
{
"body": "<p>Another possibility is that the choice of C++ and C was a test in itself :) Maybe they were willing to settle for someone with C experience, but would have preferred someone with C++ experience, so that could have been a factor.</p>\n\n<p>If you are really curious, you could even contact them again and ask for some feedback. </p>\n\n<p>However, programming style is something that you should work on continuously, not just in preparation for an interview. You aren't going to change things much in that time. I would take a longer range view and try to get some C++, C#, and Java experience under your belt, maybe PHP or perl, or ruby or python, work continouously on programming better, maybe read a book or article on interviewing and resume writing, and keep applying.</p>\n\n<p>I really think maybe they just didn't like the shirt you were wearing :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-14T19:38:15.350",
"Id": "4237",
"ParentId": "4223",
"Score": "10"
}
},
{
"body": "<p>I came a bit late to this, but this is something like what I might expect to see in C++.</p>\n\n<pre><code>// Interface defined by the problem statement has been adjusted\nsize_t get_num_of_ints( const int* arr, size_t r, int N, size_t* first )\n{\n std::pair<const int *, const int *> range = std::equal_range(arr, arr+r, N);\n size_t count = range.second - range.first;\n if (count > 0 && first != 0)\n *first = range.first - arr;\n return count;\n}\n</code></pre>\n\n<p>I think the interface is broken as defined, so I've fixed it :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-19T23:07:39.463",
"Id": "6341",
"Score": "0",
"body": "Wow, now THAT is a solution. My hats off to you sir. That's the kind of eloquent and simple solution that you hope to see. Beats the solution I worked out on my own."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-02T17:39:44.500",
"Id": "6342",
"Score": "2",
"body": "Nice clean solution. But it's always hard to know whether they want to know (a) that you have good enough library knowledge to let `equal_range()` do all the work for you or (b) that you have the algorithmic abilities to code a non-broken binary search yourself, since both abilities are useful."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-03T02:51:47.793",
"Id": "6343",
"Score": "1",
"body": "Point taken about having the algorithmic chops to implement, but if that's what was required, why not just ask? Knowing the right tool to use for a job is something that can make us an order of magnitude more effective in practice."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-06-03T06:55:08.630",
"Id": "6344",
"Score": "1",
"body": "Absolutely agree, it's something I would always ask about if I could, and as the interviewer I would award some maturity points just for asking. I just got the feeling that this coding challenge was done offline and that may not have been an option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-14T19:27:22.000",
"Id": "347736",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-15T01:43:53.173",
"Id": "4238",
"ParentId": "4223",
"Score": "27"
}
},
{
"body": "<p>Slightly more than a nitpick, but probably not a big enough problem to rule you out:</p>\n\n<p>Why do you explicitly test the final <code>else</code> case in <em>three</em> exhaustive <code>if ... else</code> statements? Generally, either they should have another <code>else</code> statement to catch any possible unexpected case, or, in all these cases, you ought to comment out the final <code>if</code> clause:</p>\n\n<pre><code>if( a < 0) \n printf( \"%d has not been found.\\n\", N );\nelse //if(a >= 0)\n{ ...\n\n\nif(arr[m] < N)\n lo = m+1;\nelse if(arr[m] > N)\n hi = m-1;\nelse //if(arr[m]==N)\n{ ...\n\n if( j > 0 && L > 0 )\n *first=j+1;\n else if( j==0 && L==0)\n *first=m;\n else if( j > 0 && L==0 )\n *first=m;\n else if(j < 0 && L==0 )\n *first=m; \n else if( j < 0 && L > 0 )\n *first=0;\n else //if( j=0 && L > 0 )\n *first=j+1;\n</code></pre>\n\n<p>Note also the typo in that last condition.</p>\n\n<p>I did adjust the first condition to clearly ensure there's not an <code>else</code> case to add, and that is a valid option for the final case too, but as others have mentioned there's more consolidation available here anyway. </p>\n\n<p>BTW don't take my reusing your single statement then/else clauses as an endorsement of that; it just wasn't what I was intending to discuss.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-23T14:06:40.527",
"Id": "97809",
"ParentId": "4223",
"Score": "4"
}
},
{
"body": "<p>Your solution works, yet, as said in previous answers, it runs in worst case linear time. You can reduce it to worst-case logarithmic by rewriting two functions in the C++ standard library to C: namely, <a href=\"http://www.cplusplus.com/reference/algorithm/lower_bound/\" rel=\"nofollow noreferrer\">std::lower_bound</a> and <a href=\"http://www.cplusplus.com/reference/algorithm/upper_bound/\" rel=\"nofollow noreferrer\">std::upper_bound</a>. <code>std::lower_bound</code> will return the \"iterator\" (pointer in C, call it <code>const int* res</code>) to the first matching element (with value <code>N</code>). If there is no such, we will have <code>N != *res</code>. If the pointer is correct, perform <code>std::upper_bound</code> and the count of matching elements will be simply the difference between the result of <code>std::upper_bound</code> and <code>std::lower_bound</code>. Also, what comes to API, I suggest you insert the value of zero to <code>count</code> whenever there is no match. Putting all pieces together, you may obtain something like this:</p>\n\n<pre><code>#include <stdio.h>\n\nstatic const int* upper_bound(const int* begin,\n const int* end,\n const int value)\n{\n size_t count;\n size_t step;\n const int* iter;\n count = end - begin;\n\n while (count > 0)\n {\n iter = begin + (step = (count >> 1));\n\n if (*iter <= value)\n {\n begin = iter + 1;\n count -= step + 1;\n }\n else\n {\n count = step;\n }\n }\n\n return begin;\n}\n\nstatic const int* lower_bound(const int* begin,\n const int* end,\n const int value)\n{\n size_t count;\n size_t step;\n const int* iter;\n count = end - begin;\n\n while (count > 0)\n {\n iter = begin + (step = (count >> 1));\n\n if (*iter < value) /* upper_bound compares \"*iter <= value\" */\n {\n begin = iter + 1;\n count -= step + 1;\n }\n else\n {\n count = step;\n }\n }\n\n return begin;\n}\n\nvoid get_number_of_ints(const int* array,\n size_t array_length,\n int target_value,\n size_t* first_index,\n size_t* count)\n{\n const int* iter1;\n const int* iter2;\n\n iter1 = lower_bound(array, array + array_length, target_value);\n\n if (*iter1 != target_value)\n {\n /* No match. */\n *count = 0;\n return;\n }\n\n iter2 = upper_bound(array, array + array_length, target_value);\n *first_index = (size_t)(iter1 - array);\n *count = (size_t)(iter2 - iter1);\n}\n\nint main()\n{\n int N; /* input variable */\n int arr[]={1,1,2,3,3,4,4,4,4,5,5,7,7,7,7,8,8,8,9,11,12,12}; /* sorted */\n size_t r = sizeof(arr)/sizeof(arr[0]); /* right bound */\n size_t first; /* first match index */\n size_t count; /* total number of matches */\n\n /* prompts the user to enter input */\n\n printf( \"\\nPlease input the integer you would like to find.\\n\" );\n scanf( \"%d\", &N );\n\n get_number_of_ints(arr, r, N, &first, &count);\n\n if (count == 0)\n {\n printf(\"%d not found!\\n\", N);\n }\n else\n {\n printf(\"%d found at %zu, length %zu.\\n\", N, first, count);\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-07T14:26:08.563",
"Id": "184511",
"ParentId": "4223",
"Score": "2"
}
},
{
"body": "<p>Before we even look at the interface and algorithm, there's a few issues to address:</p>\n\n<ul>\n<li><p><code><string.h></code> and <code><stddef.h></code> aren't required, as far as I can see (note that <code><stdlib.h></code> must provide <code>size_t</code>, if that's why the latter was included).</p></li>\n<li><p><code>int main()</code> is a non-prototype definition; prefer <code>int main(void)</code> instead.</p></li>\n<li><p>There's no check that <code>scanf()</code> successfully converted a value. This lack of checking is a <strong>serious bug</strong>. If <code>scanf()</code> doesn't return 1 here, we need to take corrective action (consume input and prompt again, or just write a message to <code>stderr</code> and return <code>EXIT_FAILURE</code>).</p></li>\n<li><p>We attempt to print the results using <code>%d</code> with <code>size_t</code> values - we should be using <code>%zd</code> instead.</p></li>\n</ul>\n\n<p>As for the <code>get_num_of_ints()</code> function, there are many narrowing and sign-converting conversions hidden there, due to use of <code>int</code> variables which really ought to be <code>size_t</code> (don't just blindly convert, because subtraction will overflow when <code>r</code> is zero).</p>\n\n<p>To be honest, I don't understand why you're implementing your own binary search from scratch instead of simply using the Standard Library <code>bsearch()</code> for this.</p>\n\n<p>Oh, and the function name is highly misleading, as the return value is not the number of matches; it's the index of first match.</p>\n\n<hr>\n\n<p>I think all my other observations are mentioned in older answers; there's no point repeating those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T18:30:56.383",
"Id": "231567",
"ParentId": "4223",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2010-03-14T01:17:52.977",
"Id": "4223",
"Score": "149",
"Tags": [
"c",
"array",
"interview-questions",
"search",
"binary-search"
],
"Title": "Searching an element in a sorted array"
}
|
4223
|
<p>I have been working on a script for almost a month now, which takes in an XML file and uses it to either download or upload files from an ftp site. It also copies the files to a history directory for historical purposes.</p>
<p>This thing has to be flawless so any suggestions to make the script more stable, reliable, error free (should able to capture errors and continue with out ending the script just because one file was not found). Eventually there will be an email function to let me know of any errors and warnings. I will also me updating a database with information but more on that later here is the script and a sample XML file.</p>
<p><strong>Perl</strong></p>
<pre class="lang-perl prettyprint-override"><code>#! /usr/bin/perl -w
use DBI;
use strict;
use Switch;
use Net::FTP;
use Net::FTP::File;
use File::Copy;
use Getopt::Long;
use File::Basename;
use XML::Simple qw(:strict);
use Mail::Sender::Easy qw(email);
my ($e, $w, $p);
my (@files, @history);
my (%failed, %delete, %missing);
my ($config, $options, $xml, $ftp, $sbj, $msg, $error, $fi);
$options = GetOptions ("config=s" => \$config);
unless(-e $config){print "Could not find $config.\n";exit;}
$xml = XMLin($config, ForceArray=>0, KeyAttr=>[]);
if(exists $xml->{files}->{file}){
if (ref($xml->{files}->{file}) eq ""){
unless(-e $xml->{files}->{file}){$missing{$xml->{files}->{file}} = $!;next;}
if(lc($xml->{type}) eq "upload"){
push(@files, "$xml->{localpath}/$xml->{files}->{file}");
}
elsif(lc($xml->{type}) eq "download"){
push(@files, $xml->{files}->{file});
}
}
if(ref($xml->{files}->{file}) eq "ARRAY"){
if(lc($xml->{type}) eq "upload"){
foreach $fi ((@{$xml->{files}->{file}})){
unless(-e $fi){$missing{$fi} = $!; next;}
push(@files, "$xml->{localpath}/$fi");
}
}
elsif(lc($xml->{type}) eq "download"){
foreach $fi ((@{$xml->{files}->{file}})){
push(@files,$fi);
}
}
}
}
elsif(exists $xml->{files}->{regex}){
if(lc($xml->{type}) eq "upload"){
@files = glob("$xml->{localpath}/$xml->{files}->{regex}");
}
elsif(lc($xml->{type}) eq "download"){
@files = ();
}
}
else{print "No files specified\n";}
$ftp = Net::FTP->new($xml->{host});
if($@ ne ""){$e=1;}
unless ($ftp->login($xml->{user}, $xml->{password})){print $ftp->message;}
unless($ftp->cwd($xml->{serverpath})){print $ftp->message; exit;}
switch ($xml->{type}){
case "upload"{
foreach my $file (@files){
if(exists $xml->{name}){
unless($ftp->put($file, $xml->{name})){$failed{$file} = $ftp->message;next;}
}
else{
unless($ftp->put($file)){$failed{$file} = $ftp->message;next;}
}
push(@history, $file) if(exists $xml->{historypath});
}
}
case "download"{
if(scalar(@files) > 0){
foreach my $file (@files){
unless($ftp->exists($file)){$missing{$file} = "not found on server.";next;}
unless(exists $xml->{name}){$ftp->get($file, "$xml->{localpath}/$xml-> {name}");}
unless($ftp->get($file, "$xml->{localpath}/$file")){$failed{$file} = $ftp->message; next;}
}
}
elsif(scalar(@files) == 0){
@files = $ftp->ls($xml->{files}->{regex}) if($xml->{files}->{regex});
}
}
else{print "job type not defined.\n";}
}
$ftp->quit;
if( @history > 0 ){
if($xml->{date} == 0){
foreach my $h(@history){
unless(copy($h, "$xml->{historypath}/")){$delete{$h} = $!; next};
unlink($h) if($xml->{del} == 1);
}
}
elsif($xml->{date} == 1){
foreach my $h(@history){
(my $n, my $p, my $s) = fileparse($h, qr/\.[^.]*/);
use POSIX qw(strftime);
my $file = $n . "-" . strftime("%b-%e-%H-%M", localtime) . $s;
unless(copy($h,"$xml->{historypath}/$file")){$delete{$h} = $!; next;}
unlink($h) if($xml->{del} == 1);
}
}
}
while ((my $k, my $v) = each %missing){print "$k => $v\n";}
while ((my $k, my $v) = each %failed) {print "$k => $v\n";}
while ((my $k, my $v) = each %delete) {print "$k => $v\n";}
</code></pre>
<p><strong>XML</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="ISO-8859-1"?>
<site>
<job>zenadown</job>
<type>download</type>
<host>zena.leegin.com</host>
<ip>128.222.79.75</ip>
<user>leo</user>
<password>green97</password>
<serverpath>/leo</serverpath>
<localpath>/temp</localpath>
<historypath>/temp/leo</historypath>
<files>
<file>jo.png</file>
<file>jo2.png</file>
<file>jo3.png</file>
<file>jo4.png</file>
<file>Blogger.png</file>
</files>
<logfile>/zena/AUTOMIZE/leotest.txt</logfile>
<del>0</del>
<date>0</date>
</site>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Please indent consistently. It makes it easier for others to read your code, and it makes it easier for <em>you</em> to read your code, preventing mistakes. Seeing three close braces in a row lined up along the left side of the terminal makes me sad.</p></li>\n<li><p>Don't use Switch. Use <a href=\"http://search.cpan.org/perldoc/perlsyn#Switch_statements\">given/when</a>, or use if/elsif chains as you're doing elsewhere in your code, or use dispatch tables (hashes containing code references), or use OO methods called by name, but don't use Switch. It makes your code harder to debug, and sometimes it will cause your code to simply stop working.</p></li>\n<li><p>You're using <code>ForceArray => 0</code> and then switching on whether the values you find are arrayrefs or plain scalars, and writing a <em>lot</em> of duplicate code, in a situation where (as far as I can tell) you could simply use <code>ForceArray => 1</code> and shave off half of the code. Why?</p></li>\n<li><p>It's hard to tell at a glance what the code does or why, and that's a bad sign for reliability. Try splitting it up into functions along functional lines -- for example, one to parse the information you need from the XML file, one to perform uploads, one to perform downloads, and one to present the results to the user. Give each function documentation that says what it expects as input, what it produces as output, how it behaves in case of errors, etc. A program like yours should have no more than a dozen lines of code outside of functions. In fact, you should probably have half that many.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T19:45:05.770",
"Id": "6622",
"Score": "0",
"body": "Thank you hobbs for your words of wisdom. I am currently rewriting the script to account for some of your pointers. However I am not sure how I can shave the extra code by following your suggestion in point 3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T23:15:24.457",
"Id": "4245",
"ParentId": "4244",
"Score": "5"
}
},
{
"body": "<p>Adding to what @hobbs has said:</p>\n\n<ol>\n<li><p>Indentation: get <a href=\"http://metacpan.org/module/perltidy\" rel=\"nofollow\">perltidy</a> to help format your code.</p></li>\n<li><p><code>Switch</code> versus <code>given</code>/<code>when</code>: as long as your code has <code>use v5.10;</code> <code>given</code>/<code>when</code> makes for a better alternative than the Switch module. Also, <code>when</code> is also useful in <a href=\"http://perldoc.perl.org/functions/when.html\" rel=\"nofollow\"><code>for</code> loops</a>, and I can see some places in your code that could be made clearer using a few loops.</p></li>\n<li><p><code>XML::Simple</code> may not be even a good fit here. That module does provide a simple interface, but it is tailored more for reading XML config files than what looks like an XML response above. Maybe a combination of <code>XML::LibXML</code> (for parsing to DOM) and <code>XML::LibXML::XPathContext</code> (for navigating that DOM) would do better here, (not to mention <code>XML::LibXML</code> is faster, being built on top of libxml2.)</p></li>\n<li><p>Your script looks to be a controller of some sort: it takes XML input and decides on whether to upload or download files given the instructions parsed there. Might be better to break up the big parts into modules (say, one module for the XML parsing and another for file upload/download, and eventually one more for the mailer/error handler.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T20:28:05.667",
"Id": "4553",
"ParentId": "4244",
"Score": "1"
}
},
{
"body": "<p>The most obvious change you should make is to add some comments and, if you don't have it elsewhere, some documentation!</p>\n\n<p>Typical documentation is designed for the user - that might be an end user, or it might be another programmer who simply wants to use your code as a \"black box\" library. Comments are documentation for the programmer who needs to alter or debug your code. That person might be you a few months down the line, or it might be someone else. Good comments briefly describe the algorithm, so they provide additional information to the user-level documentation, which should describe the input and output.</p>\n\n<p>Even thought this is your code and you're intimately familiar with it, you'd be surprised how hard it can be to understand what it does after a few months away from it. Good comments and documentation mitigate this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-28T22:59:44.940",
"Id": "5047",
"ParentId": "4244",
"Score": "1"
}
},
{
"body": "<p>Use more descriptive variable names. Seeing the global variables <code>my ($e, $w, $p);\n</code> at the top of your script gave me the heebie-jeebies. Using <code>$i</code> as a counter in a short loop may be acceptable, otherwise you should use variable names which actually describe what they contain.</p>\n\n<p>As a general rule, I try to write a full description of the code that I'm going to write, then take the variable names from that description.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T00:07:58.650",
"Id": "10879",
"ParentId": "4244",
"Score": "1"
}
},
{
"body": "<p>Single letters are almost never good variable names.\ncase in point:<br>\n my ($e, $w, $p);<br></p>\n\n<p>There is not a single comment in this script, yet this script is highly complex and difficult to figure out. Try to explain a bit what you are doing each time.<br>\nTry to break the problem down into a few smaller problems and note those problems down. Often doing that leads to reuse of code.<br>\nThere is no design of this code, meaning nowhere can i see what it is that you are trying to do, and then how you intend to do it.\nNoting that down will make for an easy to read overview of what you are doing.\nThat would also be very helpful if ever the solution needs to be implemented in another programming language. Or if what you are doing needs to be explained to.. anyone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T11:18:45.097",
"Id": "13864",
"ParentId": "4244",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T22:35:40.547",
"Id": "4244",
"Score": "4",
"Tags": [
"xml",
"file-system",
"perl"
],
"Title": "Script for performing tasks with acquired XML files"
}
|
4244
|
<p>I'd appreciate any and all criticism about this code. I didn't have a particular use case in mind when I wrote it; I just wanted to try implementing linked lists. My comments are not very useful, I think. I'm not a very experienced programmer, so there's probably plenty of things I could improve or fix here.</p>
<p>Here is the header file:</p>
<pre><code>// llist.h
#ifndef LLIST_H_
#define LLIST_H_
struct LList;
typedef struct LList LList;
struct LLNode;
typedef struct LLNode LLNode;
struct LList {
LLNode *front, *back;
};
struct LLNode {
void *data;
LLNode *next;
};
LList* llist_new(LList **self);
void llist_add(LList *self, void *v);
void llist_remove(LList *self, LLNode *node);
void llist_insert(LLNode *node, void *v);
void llist_destroy(LList *self);
#endif
</code></pre>
<p>Here is the .c file:</p>
<pre><code>// llist.c
#include <assert.h>
#include <stdlib.h>
#include "llist.h"
// Initialize a new, empty LList, in dynamically allocated memory.
LList *llist_new(LList **self) {
*self = malloc(sizeof (LList));
if (self == NULL) { return NULL; }
(*self)->front = NULL;
(*self)->back = NULL;
return *self;
}
// Append a value to the LList. Creates a new node.
void llist_add(LList *self, void *v) {
LLNode *node = malloc(sizeof (LLNode));
assert(node != NULL);
node->data = v;
node->next = NULL;
// Put this node at the back of the list.
if (self->front != NULL) {
self->back->next = node;
self->back = node;
} else {
self->back = node;
self->front = node;
}
}
// Iterate over the LList to locate a node, and then remove it from the list.
void llist_remove(LList *self, LLNode *node) {
LLNode *iter_node = self->front;
LLNode *prev_node = NULL;
while (iter_node != NULL) {
if (iter_node == node) {
if (prev_node != NULL) { prev_node->next = iter_node->next; }
else { self->front = NULL; }
free(iter_node);
return;
}
prev_node = iter_node;
iter_node = iter_node->next;
}
}
// Insert a value after a particular node.
void llist_insert(LLNode *node, void *v) {
LLNode *next = node->next;
LLNode *new_node = malloc(sizeof (LLNode));
new_node->data = v;
new_node->next = next;
node->next = new_node;
}
void llist_destroy(LList *self) {
LLNode *iter_node = self->front;
while (iter_node != NULL) {
LLNode *next = iter_node->next;
free(iter_node);
iter_node = next;
}
free(self);
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>// Initialize a new, empty LList, in dynamically allocated memory.\nLList *llist_new(LList **self) {\n</code></pre>\n\n<p>Its odd to return the new list as a return value and by reference.</p>\n\n<pre><code> *self = malloc(sizeof (LList));\n if (self == NULL) { return NULL; }\n</code></pre>\n\n<p>Doing this check after you've already dereferenced self seems kinda pointless. Maybe you meant *self?</p>\n\n<pre><code> (*self)->front = NULL;\n (*self)->back = NULL;\n\n return *self;\n}\n\n\n// Append a value to the LList. Creates a new node.\nvoid llist_add(LList *self, void *v) {\n LLNode *node = malloc(sizeof (LLNode));\n assert(node != NULL);\n\n node->data = v;\n node->next = NULL;\n\n // Put this node at the back of the list.\n if (self->front != NULL) {\n</code></pre>\n\n<p>I'd add a comment to explain what having self->front NULL means.</p>\n\n<pre><code> self->back->next = node;\n self->back = node;\n } else {\n self->back = node;\n self->front = node;\n }\n}\n\n\n// Iterate over the LList to locate a node, and then remove it from the list.\nvoid llist_remove(LList *self, LLNode *node) {\n LLNode *iter_node = self->front;\n LLNode *prev_node = NULL;\n\n while (iter_node != NULL) {\n if (iter_node == node) {\n if (prev_node != NULL) { prev_node->next = iter_node->next; }\n else { self->front = NULL; }\n</code></pre>\n\n<p>I think putting the blocks on the same line like this makes it harder to read. I also think it fail if you delete the first node. </p>\n\n<pre><code> free(iter_node);\n return;\n }\n prev_node = iter_node;\n iter_node = iter_node->next;\n }\n\n}\n\n\n// Insert a value after a particular node.\nvoid llist_insert(LLNode *node, void *v) {\n LLNode *next = node->next;\n LLNode *new_node = malloc(sizeof (LLNode));\n\n new_node->data = v;\n new_node->next = next;\n</code></pre>\n\n<p>Why did you have the next local variable. It doesn't seem to have helped make the code clearer.</p>\n\n<pre><code> node->next = new_node;\n}\n\n\nvoid llist_destroy(LList *self) {\n LLNode *iter_node = self->front;\n\n while (iter_node != NULL) {\n LLNode *next = iter_node->next;\n free(iter_node);\n iter_node = next;\n }\n\n free(self);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T00:52:15.213",
"Id": "4248",
"ParentId": "4246",
"Score": "2"
}
},
{
"body": "<p>Seems good:</p>\n\n<p>In llist_new() I would not pass a parameter.<br>\nIt does not make the interface easier to use but it does add complexity to the tests.</p>\n\n<pre><code>LList *llist_new(LList **self) {\n</code></pre>\n\n<p>Just make it:</p>\n\n<pre><code>LList *llist_new()\n</code></pre>\n\n<p>Winsoton pointed out that checking self after the allocation was pointless.<br>\nWhich is true. But I think you were testing to see if the return value from malloc() was NULL. If this is the case then you have forgotten the de-reference here:</p>\n\n<pre><code>if (self == NULL) { return NULL; }\n</code></pre>\n\n<p>I think you wanted</p>\n\n<pre><code>if ((*self) == NULL) { return NULL; }\n// ^^ De-reference to check if malloc() worked.\n</code></pre>\n\n<p>Note: If you change the interface this problems go away since you don't have a ** parameter in the first place.</p>\n\n<p>In the llist_add() If you are going to assert() that the node was created you also need to make sure that the input parameter is valid. As the llist_new() can return NULL if malloc() fails. So you should probably assert on add if self is NULL (You should really chec kon all interfaces to make sure self is not NULL).</p>\n\n<pre><code>void llist_add(LList *self, void *v)\n{\n assert(self != NULL);\n\n LLNode *node = malloc(sizeof (LLNode));\n assert(node != NULL);\n</code></pre>\n\n<p>I agree with Winston that you should use more explicit indention on the <code>if</code> to make it readable:</p>\n\n<pre><code> if (prev_node != NULL)\n { prev_node->next = iter_node->next;\n }\n else\n { self->front = iter_node->next;\n } // ^^^^^^^^^^^^^^^^ Fix this\n</code></pre>\n\n<p>Also the assignment should not be to NULL, but should set the new head of the list.</p>\n\n<p>Also the interface to remove elements takes an LLNode pointer. But no other interface provides you with an LLNode pointer. So you are stuck in a chicken and egg situation and not able to use the interface.</p>\n\n<pre><code>void llist_remove(LList *self, LLNode *node) {\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T02:17:33.180",
"Id": "4251",
"ParentId": "4246",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T00:15:09.747",
"Id": "4246",
"Score": "3",
"Tags": [
"c",
"linked-list"
],
"Title": "Criticize my Linked List implementation"
}
|
4246
|
<p>I've been trying to learn different patterns of programming, and the "Chain of Responsibility" sort of eludes me. I've been told that my specific code snippet would be a good candidate for chain of responsibility, and I'm wondering if someone could show me how to get there?</p>
<pre><code>Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
''# Set a local variable for the HttpContext.Request. This is going to
''# be used several times in the subsequent actions, so it needs to be
''# at the top of the method.
Dim request = filterContext.HttpContext.Request
Dim url As Uri = request.Url
''# Now we get the referring page
Dim referrer As Uri = If(Not request.UrlReferrer Is Nothing, request.UrlReferrer, Nothing)
''# If the referring host name is the same as the current host name,
''# then we want to get out of here and not touch anything else. This
''# is because we've already set the appropriate domain in a previous
''# call.
If (Not referrer Is Nothing) AndAlso
(Not url.Subdomain = "") AndAlso
(Not url.Subdomain = "www") AndAlso
(referrer.Host = url.Host) Then
Return
End If
''# If we've made it this far, it's because the referring host does
''# not match the current host. This means the user came here from
''# another site or entered the address manually. We'll need to hit
''# the database a time or two in order to get all the right
''# information.
''# This is here just in case the site is running on an alternate
''# port. (especially useful on the Visual Studio built in web server
''# / debugger)
Dim newPort As String = If(url.IsDefaultPort, String.Empty, ":" + url.Port.ToString())
''# Initialize the Services that we're going to need now that we're
''# planning on hitting the database.
Dim RegionService As Domain.IRegionService = New Domain.RegionService(New Domain.RegionRepository)
''# Right now we're getting the requested region from the URI. This
''# is when a user requests something like
''# http://calgary.example.com, whereby we extract "calgary" out of
''# the address.
Dim region As Domain.Region = RegionService.GetRegionByName(url.Subdomain)
''# If the RegionService returned a region from it's query, then we
''# want to exit the method and allow the user to continue on using
''# this region.
If Not region Is Nothing Then
Return
End If
''# If we've made it this far, it means that the user either entered
''# an Invalid Region (yes, we already know the region is invalid) or
''# used www. or nothing as a subdomain. Up until this point, we
''# haven't cared if the user is authenticated or not, nor have we
''# cared what the full address in their address bar is. Now we're
''# probably going to start redirecting them somewhere.
''# First off we need to check if they're authenticated users. If they
''# are, we'll just send them on over to their default region.
If filterContext.HttpContext.User.Identity.IsAuthenticated Then
Dim userService As New Domain.UserService(New Domain.UserRepository)
Dim userRegion = userService.GetUserByID(AuthenticationHelper.RetrieveAuthUser.ID).Region.Name
filterContext.HttpContext.Response.Redirect(url.Scheme + "://" + userRegion + "." + url.PrimaryDomain + newPort + request.RawUrl)
End If
''# Now we know that the user is not Authenticated. So here we check for
''# www. If the host has www in it, then we just strip the www and
''# bounce the user to the original request.
If request.Url.Host.StartsWith("www") Then
Dim newUrl As String = url.Scheme + "://" + url.Host.Replace("www.", "") + newPort + request.RawUrl
''# The redirect is permanent because we NEVER want to see www in the domain.
filterContext.HttpContext.Response.RedirectPermanent(newUrl)
''# It's ok for an annonymous browser to view the "Details" of an
''# Event/User/Badge/Tag without being assigned to a regions. So
''# this is why we strip the www but don't redirect the visitor
''# directly over to the "Choose Your Region" view.
End If
''# If we've gone this far, we know the region is invalid, and the
''# user needs to be directed to a "choose your region" page. We're
''# not going to do the redirecting here because we want to allow for
''# browsing to specific Users/Tags/Badges/Events that are Region
''# Agnostic. But if a user tries to view an event listing of any
''# sort, we're going to fire them over to the "Choose Your Region"
''# page via a separate Attribute attached to only the Actions that
''# require it.
End Sub
</code></pre>
<p>Here's an uncommented C# version:</p>
<pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
Uri url = request.Url;
Uri referrer = (request.UrlReferrer != null) ? request.UrlReferrer : null;
if (((referrer != null)) && (!string.IsNullOrEmpty(url.Subdomain)) && (!(url.Subdomain == "www")) && (referrer.Host == url.Host)) {
return;
}
string newPort = url.IsDefaultPort ? string.Empty : ":" + url.Port.ToString();
Domain.IRegionService RegionService = new Domain.RegionService(new Domain.RegionRepository());
Domain.Region region = RegionService.GetRegionByName(url.Subdomain);
if ((region != null)) {
return;
}
if (filterContext.HttpContext.User.Identity.IsAuthenticated) {
Domain.UserService userService = new Domain.UserService(new Domain.UserRepository());
dynamic userRegion = userService.GetUserByID(AuthenticationHelper.RetrieveAuthUser.ID).Region.Name;
filterContext.HttpContext.Response.Redirect(url.Scheme + "://" + userRegion + "." + url.PrimaryDomain + newPort + request.RawUrl);
}
if (request.Url.Host.StartsWith("www")) {
string newUrl = url.Scheme + "://" + url.Host.Replace("www.", "") + newPort + request.RawUrl;
//'# The redirect is permanent because we NEVER want to see www in the domain.
filterContext.HttpContext.Response.RedirectPermanent(newUrl);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This method is not a good candidate for the Chain of Responsibility pattern, but it definitely can be implemented using it (just for the educational purpose):</p>\n\n<pre><code> public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n //Init\n var referrerRequestHandler = new ReferrerRequestHandler();\n var regionRequestHandler = new RegionRequestHandler();\n var authenticatedRequestHandler = new AuthenticatedRequestHandler(filterContext);\n var wwwRequestHandler = new WwwRequestHandler(filterContext);\n\n referrerRequestHandler.SetNextHandler(regionRequestHandler);\n regionRequestHandler.SetNextHandler(authenticatedRequestHandler);\n authenticatedRequestHandler.SetNextHandler(wwwRequestHandler);\n\n //Run\n var request = filterContext.HttpContext.Request;\n referrerRequestHandler.Redirect(request);\n }\n</code></pre>\n\n\n\n<pre><code> public abstract class RequestHandler\n {\n public void SetNextHandler(RequestHandler nextHandler)\n {\n _nextHandler = nextHandler;\n }\n\n public void Redirect(HttpRequestBase request)\n { \n bool handeled = HandleRedirect(request);\n if (!handeled)\n {\n if (_nextHandler != null)\n {\n _nextHandler.Redirect(request);\n }\n }\n }\n\n protected abstract bool HandleRedirect(HttpRequestBase request);\n\n private RequestHandler _nextHandler;\n }\n</code></pre>\n\n\n\n<pre><code> public class ReferrerRequestHandler : RequestHandler\n {\n protected override bool HandleRedirect(HttpRequestBase request)\n {\n Uri url = request.Url;\n Uri referrer = (request.UrlReferrer != null) ? request.UrlReferrer : null;\n if (((referrer != null)) && (!string.IsNullOrEmpty(url.Subdomain)) && (!(url.Subdomain == \"www\")) && (referrer.Host == url.Host))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n</code></pre>\n\n\n\n<pre><code> public class RegionRequestHandler: RequestHandler\n {\n protected override bool HandleRedirect(HttpRequestBase request)\n {\n Domain.IRegionService RegionService = new Domain.RegionService(new Domain.RegionRepository());\n Domain.Region region = RegionService.GetRegionByName(url.Subdomain);\n if ((region != null))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n</code></pre>\n\n \n\n<pre><code> public class AuthenticatedRequestHandler: RequestHandler\n {\n public AuthenticatedRequestHandler(ActionExecutingContext filterContext)\n {\n _filterContext = filterContext;\n }\n\n protected override bool HandleRedirect(HttpRequestBase request)\n {\n Uri url = request.Url;\n string newPort = url.IsDefaultPort ? string.Empty : \":\" + url.Port.ToString();\n if (_filterContext.HttpContext.User.Identity.IsAuthenticated)\n {\n Domain.UserService userService = new Domain.UserService(new Domain.UserRepository());\n dynamic userRegion = userService.GetUserByID(AuthenticationHelper.RetrieveAuthUser.ID).Region.Name;\n _filterContext.HttpContext.Response.Redirect(url.Scheme + \"://\" + userRegion + \".\" + url.PrimaryDomain + newPort + request.RawUrl);\n return true;\n }\n else\n {\n return false;\n }\n } \n\n private readonly ActionExecutingContext _filterContext;\n }\n</code></pre>\n\n\n\n<pre><code> public class WwwRequestHandler : RequestHandler\n {\n public WwwRequestHandler(ActionExecutingContext filterContext)\n {\n _filterContext = filterContext;\n }\n\n protected override bool HandleRedirect(HttpRequestBase request)\n {\n Uri url = request.Url;\n if (request.Url.Host.StartsWith(\"www\"))\n {\n string newUrl = url.Scheme + \"://\" + url.Host.Replace(\"www.\", \"\") + newPort + request.RawUrl;\n //'# The redirect is permanent because we NEVER want to see www in the domain.\n _filterContext.HttpContext.Response.RedirectPermanent(newUrl);\n return true;\n }\n else\n {\n return false;\n }\n }\n private readonly ActionExecutingContext _filterContext;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T15:28:18.633",
"Id": "6376",
"Score": "0",
"body": "Thanks for that. Can you explain why it's not a good candidate for CoR?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T16:03:18.270",
"Id": "6377",
"Score": "1",
"body": "Just compare the amount of code in your original implementation and CoR implementation. Your original variant is much more compact. And we don't gain any advantages by using CoR. Moreover, CoR makes it even worse: 1. The code becomes too complicated. 2. If you need to add a new 'handler' in the original variant it will take only a couple of lines of code. With the CoR you'll have to add a class and change the code in two places. Designe patterns are useful, but they should be used really carefully or else you'll end up with overcomplicated code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T17:08:10.487",
"Id": "6379",
"Score": "0",
"body": "Good call... Like I said, a friend just told me this would be a good example to learn from."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T15:21:07.147",
"Id": "4261",
"ParentId": "4250",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4261",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T02:00:40.930",
"Id": "4250",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
"asp.net",
"vb.net"
],
"Title": "Refactor IF into Chain of Responsibility Pattern"
}
|
4250
|
<p>I have a set of Class methods which is :</p>
<pre><code>class << self
def increment_value
self.first.increment_value
end
def max_work_hours_per_day
self.first.max_work_hours_per_day
end
def fast_completion_day
self.first.fast_completion_day
end
def super_fast_completion_day
self.first.super_fast_completion_day
end
def ludicrous_completion_day
self.first.ludicrous_completion_day
end
def budget_completion_day
self.first.budget_completion_day
end
end
</code></pre>
<p>Since all the methods call self.first.atttibute where attribute is the same name as function name. I think we can reduce this to a single method. Something like method_missing is there in Ruby , but since I am not very good at meta programming , I am seeking advise here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T04:38:31.220",
"Id": "6368",
"Score": "1",
"body": "[This](http://ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html) and [this](http://ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html) look like reasonabl nice ways to handle delegation in Ruby."
}
] |
[
{
"body": "<p>Ruby already has a module which allows you to forward specific methods to a given object in its standard library: <a href=\"http://ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html\">the Forwardable module</a>.</p>\n\n<p>Using it you can write code like this:</p>\n\n<pre><code>class << self\n extend Forwardable\n\n def_delegators :first, :increment_value, :max_work_hours_per_day #...\nend\n</code></pre>\n\n<p>I think spelling out the methods you want to forward like this is preferable to simply forwarding everything as it won't accidentally forward something you don't want to forward. It also does not affect the error message when calling a method that does not exist.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T10:24:54.400",
"Id": "4327",
"ParentId": "4253",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "4327",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T03:16:05.957",
"Id": "4253",
"Score": "7",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "using method missing to reduce the code in ruby"
}
|
4253
|
<p>This function checks if a file name is valid or not. I think it's not good enough for integration (not optimized, maybe I forgot about some checks), so need your comments.</p>
<pre><code>static
int ReservedName( const char * name )
{
char * reservedFileNames[] = { "CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
char * reservedFileNamesWithDot[] = { "CON.", "PRN.", "AUX.", "NUL.",
"COM1.", "COM2.", "COM3.", "COM4.", "COM5.", "COM6.", "COM7.", "COM8.", "COM9.",
"LPT1.", "LPT2.", "LPT3.", "LPT4.", "LPT5.", "LPT6.", "LPT7.", "LPT8.", "LPT9." };
int i;
int n = sizeof( reservedFileNames ) / sizeof( reservedFileNames[0] );
for( i = 0; i < n; i++ )
{
if( stricmp( reservedFileNames[i], name ) == 0 )
{
return 1;
}else{
if( strnicmp( reservedFileNamesWithDot[i], name, strlen( reservedFileNamesWithDot[i] ) ) == 0 )
{
return 1;
}
}
}
return 0;
}
static
int GetCharsNumInPath( IN const char * path )
{
int i, cnt;
for( i = 0; path[i]; i++ )
{
if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )
cnt++;
}
return cnt;
}
int ValidName( const char * name )
{
if( name != NULL )
{
if( GetCharsNumInPath( path ) <= MAX_PATH )
{
if( ! ReservedName( name ) )
{
int i;
int n = strlen( path );
for( i = 0; i < n; i++ )
{
switch( path[i] )
{
// ? " / < > * |
// these characters can not be used in file or folder names
//
case '<':
case '>':
case '/':
case '\\':
case '\"':
case '?':
case '*':
case '|':
return 0;
case ' ':
case '.':
{
if( ( i + 1 == n ) )
{
return 0;
}else{
continue;
}
}
}
}
return 1;
}else{ // if( ! ReservedName( name ) )
return 0;
}
}else{ // if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )
return 0;
}
}else{ // if( name != NULL )
return 0;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Every one has their own side of the holy war about where the '{' should be.</p>\n\n<p>But one thing everybody agrees upon is that you must be consistent.<br>\nIn your code you align the open and close (which I think is perfect) apart from when you use else</p>\n\n<pre><code> }else{\n</code></pre>\n\n<p>Stay with the same style as the rest of your code</p>\n\n<pre><code> }\n else\n {\n</code></pre>\n\n<p>If your 2 arrays are supposed to be identical then you should probably not have two different arrays. You should probably use a single array and use code to get the extra functionality. Otherwise you head into a maintenance problem where every addition to one array must be mirrored by an addition to the other array (and you must validate they are the same).</p>\n\n<pre><code>char * reservedFileNames[] = { \"CON\", \"PRN\", \"AUX\", \"NUL\",\n \"COM1\", \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", \"LPT9\" };\n\n size_t wordLen = strlen( reservedFileNames[i]);\n if( stricmp( reservedFileNames[i], name, wordLen) == 0 ) \n {\n if (name[wordLen] == '\\0') // The strings are technically equal\n { return 1;\n }\n if (name[wordLen] == '.') // The string has a bad prefix.\n { return 1;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T04:41:31.067",
"Id": "6430",
"Score": "0",
"body": "I will think about using \"else\", as you showed. About code you showed, I think I will do like this. There is some errors. in return part, there must be `return 1;` instead of `return s;` Thank you for your answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T16:26:32.427",
"Id": "4262",
"ParentId": "4258",
"Score": "2"
}
},
{
"body": "<p>I'm not sure what you're using this for, but my advice: Don't bother validating the filename. Just open the file. The system knows the rules better than you do, and by adding too much validation you can cause problems down the line.</p>\n\n<p>On Windows these rules are especially complex. Frankly you will never find them all. Here's a few you missed, off the top of my head:</p>\n\n<ul>\n<li>Filenames may contain unicode characters. You are using <code>char*</code>. Unless you're using UTF-8 and passing all your filenames to <code>MultiByteToWideChar</code> before they reach a file API, you're ruling out a lot of potential valid paths based on that. (Not to mention the way these filenames get mapped to Unicode is now subject to the user's language settings, which one can argue is a bad thing in its own right...)</li>\n<li><code>MAX_PATH</code>. You're assuming that all paths will fit in a buffer of that size. On Windows you can actually have a path longer than <code>MAX_PATH</code> if it starts with <code>\\\\?\\</code>; also things like <code>\\\\?\\C:\\foo</code> are valid paths.</li>\n<li>Names containing trailing spaces or dots, which you seem to be filtering on, are also valid and distinct if the path begins with <code>\\\\?</code>. Without that prefix, trailing dots and spaces get truncated.</li>\n<li>Paths under <code>\\\\.\\</code>, <code>\\\\?\\GLOBALROOT</code>.</li>\n</ul>\n\n<p>Not to mention, these rules could potentially be subject to change. Note that Win9X had different rules than NT. What if such a change occurs again and breaks your logic? Don't bother duplicating these rules in your code; don't second-guess the filesystem either. Just pass the name to <code>CreateFile</code>.</p>\n\n<p>(Aside: If your filename happens to come from an untrusted source, then it probably is fair to be overly restrictive...)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T17:25:04.390",
"Id": "4310",
"ParentId": "4258",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4262",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T11:01:42.053",
"Id": "4258",
"Score": "2",
"Tags": [
"c",
"strings",
"validation"
],
"Title": "Function to validate a file name"
}
|
4258
|
<p>I'm attempting to create a function that will give me a "fish" at random, though a bias random depending on the weight value for the "fish".</p>
<pre><code>var FISH = {
"level1": [
//["name", xp, weight]
["Shrimp", 10, 95],
["Sardine", 20, 85],
["Herring", 30, 75],
["Anchovies", 40, 65],
["Mackerel", 40, 55]
]
};
function randomRange(min, max) {
return Math.random() * (max - min) + min;
}
function getRandomFish(level) {
var fishForLevel = FISH[level],
numberOfFish = fishForLevel.length,
chance = randomRange(0, 100);
if (numberOfFish > 1) {
var fish = fishForLevel[Math.floor(randomRange(0, numberOfFish))];
if (chance <= fish[2]) {
return fish;
} else {
return getRandomFish(level);
}
} else {
return fishForLevel[0];
}
}
</code></pre>
<p>Example of outcome: <a href="http://jsfiddle.net/qAvAs/" rel="nofollow">http://jsfiddle.net/qAvAs/</a></p>
<p>If this could be made more efficient, how would one do so?</p>
|
[] |
[
{
"body": "<p>I'd suggest you select a random number that's from 0 to the total weight of your fish. Then, each fish can have a piece of that random range according to it's weight which gives it the weighting you want. This ends up giving each fish a number of buckets that corresponds to it's weighting value and then you pick a random number from 0 to the total number of buckets and find out who's bucket the random number landed in. </p>\n\n<p>It's the same idea as turning each weighting number into a percentage change and then picking a random number from 0 to 99.</p>\n\n<p>This code should do that:</p>\n\n<pre><code>var FISH = {\n \"level1\": [\n //[\"name\", xp, weight] \n [\"Shrimp\", 10, 95],\n [\"Sardine\", 20, 85],\n [\"Herring\", 30, 75],\n [\"Anchovies\", 40, 65],\n [\"Mackerel\", 40, 55]\n ]\n};\n\n\nfunction getRandomFish(level) {\n var fishForLevel = FISH[level];\n var fishTotalWeight = 0, fishCumWeight = 0, i;\n // sum up the weights\n for (i = 0; i < fishForLevel.length; i++) {\n fishTotalWeight += fishForLevel[i][2];\n }\n var random = Math.floor(Math.random() * fishTotalWeight);\n // now find which bucket out random value is in\n\n for (i = 0; i < fishForLevel.length; i++) {\n fishCumWeight += fishForLevel[i][2];\n if (random < fishCumWeight) {\n return(fishForLevel[i]);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T17:52:17.487",
"Id": "6380",
"Score": "0",
"body": "I like this. Certainly seems more efficient then what I was using. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T17:22:56.890",
"Id": "4265",
"ParentId": "4264",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T17:11:32.013",
"Id": "4264",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"random"
],
"Title": "JavaScript: Weighted Random Generator"
}
|
4264
|
<p>I'm coming from a Python background(look at indentation :) ) and trying to learn basics of C++. I wrote a simple prime generator, I know there is better algorithms, but I want advices about coding style, inconsistencies, or better language use.</p>
<p>Here is my main.cpp:</p>
<pre><code>#include <iostream>
#include "PrimeGenerator.h"
using namespace std;
int main(){
PrimeGenerator *generator;
generator = new PrimeGenerator();
for(int i=0;; i++){
generator->addPrime();
cout<<generator->getPrimes()->back()<<endl;
}
delete generator; #I know this is unnecessary at the end of program, but I think it is a better practice.
return 0;
}
</code></pre>
<p>And PrimeGenerator.h:</p>
<pre><code>#pragma once
#include <list>
#include <iostream>
typedef std::list<unsigned long long int> PrimeList;
class PrimeGenerator{
PrimeList *primes;
public:
PrimeGenerator();
~PrimeGenerator();
PrimeList *getPrimes();
void addPrime();
};
PrimeGenerator::PrimeGenerator(){
primes = new PrimeList;
primes->push_back(2);
primes->push_back(3);
}
PrimeGenerator::~PrimeGenerator(){
delete primes;
}
void PrimeGenerator::addPrime(){
unsigned long long int num = primes->back()+2;
while(true){
bool isPrime = true;
for(auto it=primes->begin(); it!=primes->end(); ++it){
if(*it > (num / 2))
break;
if((num % *it) == 0){
isPrime = false;
break;
}
}
if(isPrime){
primes->push_back(num);
break;
}
num += 2;
}
}
PrimeList *PrimeGenerator::getPrimes(){
return primes;
}
</code></pre>
|
[] |
[
{
"body": "<p>You don't need to manage resources manually. \nYou are declaring a pointer to the new PrimeGenerator instance and releasing it at the end of the main function, but what happens if one of the calls inbetween (for example, addPrime()) fails? You end up with a memory leak.</p>\n\n<p>Instead of </p>\n\n<pre><code>PrimeGenerator *generator;\ngenerator = new PrimeGenerator();\n....\ndelete generator;\n</code></pre>\n\n<p>why don't you use </p>\n\n<pre><code>PrimeGenerator generator;\n....\n</code></pre>\n\n<p>You don't need to use pointers in the PrimeGenerator class either.</p>\n\n<pre><code>class PrimeGenerator\n{\n\n PrimeList primes;\n\n public:\n PrimeGenerator();\n\n const PrimeList& getPrimes() const {return primes;}\n void addPrime(); \n};\n\nstd::ostream& operator<<(std::ostream& stream, PrimeList const& value)\n{\n for (PrimeList::const_iterator it = value.begin(); it != value.end; it++)\n { \n stream << *it << endl;\n }\n\n return stream;\n}\n\nPrimeGenerator::PrimeGenerator()\n{\n primes.push_back(2);\n primes.push_back(3);\n}\n\nint main()\n{\n PrimeGenerator generator;\n\n for(int i = 0; i < 100; i++)\n {\n generator.addPrime();\n }\n cout << generator.getPrimes();\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:42:51.733",
"Id": "6387",
"Score": "0",
"body": "Thank you. Am I understand right if I don't use pointers, will those objects destroyed at the end of their scope? If this is true, when should I use pointers, or `new` and `delete`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:56:51.970",
"Id": "6389",
"Score": "2",
"body": "Yes, the objects you've constructed will be destroyed at the end of the function you've constructed them in. As for the pointers, you should avoid using them in C++ unless it is absolutely necessary for some reason."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:09:36.897",
"Id": "4269",
"ParentId": "4267",
"Score": "6"
}
},
{
"body": "<p>Your indentation style is unusual for C++. There are a variety of styles used in C++, I recommend you take a look at them, <a href=\"http://en.wikipedia.org/wiki/Indent_style\">http://en.wikipedia.org/wiki/Indent_style</a>, pick one you like. As it is you are combing elements of several styles. We don't need more indentation styles, so use a standard one, don't invent your own.</p>\n\n<pre><code>#include <iostream> \n#include \"PrimeGenerator.h\"\n\nusing namespace std;\n</code></pre>\n\n<p>Many people use this, but I recommend against it. It looks doing a <code>from std import *</code> in python. I think its better to just use the prefix.</p>\n\n<pre><code>int main(){\n PrimeGenerator *generator;\n generator = new PrimeGenerator();\n</code></pre>\n\n<p>You can combine this into one line:</p>\n\n<pre><code>PrimeGenerator * generator = new PrimeGenerator();\n</code></pre>\n\n<p>You can also avoid using a pointer altogether and write:</p>\n\n<pre><code>PrimeGenerator generator;\n\n\n for(int i=0;; i++){\n</code></pre>\n\n<p>I think you are missing the middle element, as it is this is an infinite loop</p>\n\n<pre><code> generator->addPrime();\n cout<<generator->getPrimes()->back()<<endl;\n</code></pre>\n\n<p>I'd add spaces around the <<</p>\n\n<pre><code> }\n\n delete generator; #I know this is unnecessary at the end of program, but I think it is a better practice.\n</code></pre>\n\n<p>If you use the pointerless version I suggested, it will automatically be destroyed at the end of main.</p>\n\n<pre><code> return 0;\n }\n\n#pragma once\n</code></pre>\n\n<p>This may not work on all compilers, so be careful.</p>\n\n<pre><code>#include <list>\n#include <iostream>\n\ntypedef std::list<unsigned long long int> PrimeList;\n</code></pre>\n\n<p>List is a linked list, unlike lists in python which are resizable arrays. Linked lists are almost always the wrong choice as a datastructure. Perhaps a vector would be better? Vectors act like python lists. unsigned long long int can be written as unsigned long long. You also repeat it often enough creating a typedef might be a good idea.</p>\n\n<pre><code>class PrimeGenerator{\n\n PrimeList *primes;\n</code></pre>\n\n<p>Don't make this a pointer. Just use the object directly.</p>\n\n<pre><code> public:\n\n PrimeGenerator();\n ~PrimeGenerator();\n\n PrimeList *getPrimes();\n void addPrime();\n };\n\nPrimeGenerator::PrimeGenerator(){\n primes = new PrimeList;\n</code></pre>\n\n<p>If you avoid make primes a pointer like I suggest, this is unneccesary.</p>\n\n<pre><code> primes->push_back(2);\n primes->push_back(3);\n }\n\nPrimeGenerator::~PrimeGenerator(){\n delete primes;\n }\n</code></pre>\n\n<p>If you avoid making primes a pointer like I suggest, this is unneccesary.</p>\n\n<pre><code>void PrimeGenerator::addPrime(){\n\n unsigned long long int num = primes->back()+2;\n\n while(true){\n bool isPrime = true;\n\n for(auto it=primes->begin(); it!=primes->end(); ++it){\n\n if(*it > (num / 2)) \n break;\n</code></pre>\n\n<p>This limitation isn't obvious, a comment explaining would be good. </p>\n\n<pre><code> if((num % *it) == 0){\n</code></pre>\n\n<p>Operator precedence rules were defined to make sense, use them.</p>\n\n<pre><code> isPrime = false;\n break;\n }\n }\n\n if(isPrime){\n primes->push_back(num);\n break;\n }\n\n num += 2;\n }\n }\n</code></pre>\n\n<p>Your logic can be simplified:</p>\n\n<pre><code>bool isPrime = false;\nunsigned long long int num = primes->back();\nwhile(!isPrime)\n{\n num += 2;\n\n for(auto it = primes->begin(); it != primes->end(); it++)\n {\n if(*it > num / 2)\n {\n break;\n }\n\n if( num % *it == 0 )\n {\n isPrime = false;\n break;\n }\n }\n}\nprimes->push_back(num);\n</code></pre>\n\n<p>I try to avoid using break when possible. Basically, I try to restrict to cases where it is skipping the rest of the loop as an optimisation. If the breaks were removed, the code would be valid but slower.</p>\n\n<pre><code>PrimeList *PrimeGenerator::getPrimes(){\n return primes;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:56:39.480",
"Id": "6388",
"Score": "0",
"body": "Thank you. But, is there a way to skip the break's with that logic? And also, one more question, using \"auto\" is bad for my learning(backward compatiblity isn't a problem for me), or code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:59:56.550",
"Id": "6390",
"Score": "0",
"body": "@utdemir, sorry, I didn't understand either of your questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T23:06:17.123",
"Id": "6391",
"Score": "1",
"body": "You said \"I try to avoid using break when possible.\". How? And I used `auto it = primes->begin()` in code, should I explicitly define iterator's type?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T01:39:10.673",
"Id": "6392",
"Score": "0",
"body": "@utdemir, I showed how to eliminate one the breaks in your example. I think the other breaks are fine. That's a perfectly fine use of auto. The auto syntax was introduce partially to avoid having to write out types like that iterator."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T22:22:44.693",
"Id": "4270",
"ParentId": "4267",
"Score": "6"
}
},
{
"body": "<p>It seems to me that prime number generation is really best represented as an algorithm. Rather than giving the client access to the class' internals I'd also prefer to send the results to an iterator. Finally, I'd prefer to producing a set of results over producing one result at a time.</p>\n\n<p>As such, it seems like the interface should be something like:</p>\n\n<pre><code>template <class FwdIt>\nvoid gen_primes(size_t num, FwdIt out);\n</code></pre>\n\n<p>If you wanted, for example, to generate the first 100 primes, you'd call it something like this:</p>\n\n<pre><code>std::vector<int> primes(100);\n\ngen_primes(100, primes.begin());\n</code></pre>\n\n<p>Note that since it reuses the data in the output, it does require a <em>forward</em> iterator, not an output iterator, so you couldn't (for example) use <code>std::back_inserter(primes)</code>.</p>\n\n<p>Although I'd probably incorporate most of (for example) @Winston Ewert's suggestions, internally the code could remain at least <em>reasonably</em> close to what you already have.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T15:38:39.130",
"Id": "4309",
"ParentId": "4267",
"Score": "2"
}
},
{
"body": "<p>I think the object-oriented design could be improved. </p>\n\n<ul>\n<li><code>PrimeGenerator</code> is a tool to generate a linked list. Once you return a pointer to it, who knows what the caller will do with its contents? The caller could alter the list in a way that breaks subsequent calls to <code>.addPrime()</code>.</li>\n<li>Primes are a notionally infinite list, so your class should try to create the illusion of an infinite list. Requiring the user to call <code>.addPrime()</code> is a chore that breaks that illusion.</li>\n</ul>\n\n<p>It would be better if <code>PrimeList</code> were a self-managing read-only list of prime numbers, like this:</p>\n\n<pre><code>class PrimeList {\n public:\n PrimeList();\n\n // Returns the nth prime number\n // (primelist[0] is 2, primelist[1] is 3, etc.)\n unsigned long long operator[](size_t nth);\n\n private:\n std::vector<unsigned long long> knownPrimes;\n\n void findMorePrimes();\n};\n</code></pre>\n\n<p>Then your implementation of <code>operator[]</code> could call <code>findMorePrimes()</code> as needed behind the scenes.</p>\n\n<p>The notion of an infinite list also frees you from the expectation that you should only add one prime number at a time to the list. Then, you would have the flexibility to find batches of prime numbers at a time, with likely improvements in performance.</p>\n\n<p><em>Answer self-plagiarized from <a href=\"https://codereview.stackexchange.com/a/32275/9357\">here</a>.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T01:08:46.413",
"Id": "37792",
"ParentId": "4267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4270",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-20T19:36:11.553",
"Id": "4267",
"Score": "8",
"Tags": [
"c++",
"beginner",
"primes"
],
"Title": "Prime generator"
}
|
4267
|
<p>I made this sketch in Processing (basically Java) that consists of a bunch of particles moving around a Perlin Noise field. Each particle is aware of the position of one other particle and this creates a rope like effect. The sketch is intended to be aesthetic, like a screensaver, and I in that way it might be difficult to judge the efficiency of the code. </p>
<p>Nevertheless, I'm hoping that there is something that I'm doing wrong stylistically that could be pointed out.</p>
<pre><code> int emergenceInterval = int(random(75, 100));
float a, freq = 0.05;
float alphDelta, alphAccel, alphSpringing = 0.0009, alphDamping = 0.98, alphX, maxAlph;
int pAmt = int(random(2000, 4000));
Particle p[] = new Particle[pAmt];
void setup() {
background(0);
size(1000, 500);
for (int i = 0; i < pAmt; i++) {
p[i] = new Particle(random(width), random(height), i);
}
}
void draw() {
if(frameCount % emergenceInterval == 0) {
if(maxAlph == .05) maxAlph = 1;
else maxAlph = .05;
}
a += freq;
fill(50, findAlpha() * 255);
rect(0, 0, width, height);
runParticles();
}
void runParticles() {
for (Particle _p : p) {
Particle lastP = _p;
if (_p.index != 0) lastP = p[_p.index - 1];
_p.update(450, lastP.pos, abs(pow(sin(radians(a)), 3)));
point(_p.pos.x, _p.pos.y);
_p.vel.x = 1;
}
}
float findAlpha() {
if (!(alphAccel < 0)) alphDelta = width - alphX;
else alphDelta = 0 - alphX;
alphDelta *= alphSpringing;
alphAccel += alphDelta;
alphAccel *= alphDamping;
alphX += alphAccel;
float alph = (alphX * (maxAlph * abs(pow(sin(radians(a)), 2))))/width;
if(alphX > width) alphAccel *= -1;
else if(alphX < 0) alphAccel *= -1;
return alph;
}
class Particle {
int index;
float theta;
float stride;
float maxSpeed = 5;
float maxChaos = 10;
PVector accel, vel, pos;
Particle(float startX, float startY, int index) {
this.index = index;
accel = new PVector(0, 0);
vel = new PVector(0, 0);
pos = new PVector(startX, startY);
}
void update(float stride, PVector target, float chaos) {
this.stride = stride;
stroke(50*(noise(pos.x)),0,50*(noise(pos.x)), noise(pos.x, pos.y) * 255);
accel = noiseDir(chaos);
accel.add(followDir(target));
if (pos.x > width) pos.x = 0;
if (pos.y > height) pos.y = 0;
if (pos.y < 0) pos.y = height;
vel.add(accel);
float speed = noise(pos.x, pos.y) * maxSpeed;
vel.limit(speed);
pos.add(vel);
}
PVector noiseDir(float chaos) {
theta = abs(noise(pos.x, pos.y)) * 180;
float x = pos.x + stride * cos(theta);
float y = pos.y + stride * sin(theta);
PVector dir = new PVector(x - pos.x, y - pos.y);
dir.normalize();
dir.mult(chaos * maxChaos);
return dir;
}
PVector followDir(PVector target) {
PVector dir = new PVector(target.x - pos.x, target.y - pos.y);
dir.normalize();
dir.mult(5);
return dir;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T05:57:54.720",
"Id": "6394",
"Score": "0",
"body": "Is this code complete? If this is in Java why are there a bunch of functions and variables defined in the middle of nowhere that are not inside a class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T10:17:44.067",
"Id": "6396",
"Score": "0",
"body": "In Processing there are self contained setup() and draw() functions so you can create programs really quickly. It's based on Java but I'm not sure of the details."
}
] |
[
{
"body": "<p>Some small observations:</p>\n\n<pre><code>//maybe it works here, but generally you should use Math.abs(a-b) < epsilon \n//with a very small epsilon instead a == b for double comparision\nif(maxAlph == .05) maxAlph = 1;\nelse maxAlph = .05; \n-->\nmaxAlph = (maxAlph == .05) ? 1 : 0.05; \n\nif(alphX > width) alphAccel *= -1;\nelse if(alphX < 0) alphAccel *= -1;\n-->\nif(alphX > width || alphX < 0) alphAccel *= -1;\n\nif (!(alphAccel < 0)) alphDelta = width - alphX;\nelse alphDelta = 0 - alphX;\n-->\nalphDelta = (alphAccel >= 0) ? width - alphX : -alphX;\n</code></pre>\n\n<p>And why is theta a member variable? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T20:45:09.073",
"Id": "6449",
"Score": "0",
"body": "I'm not sure I understand why theta wouldn't be a member variable. Do you think you could clarify that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T07:22:43.077",
"Id": "6458",
"Score": "1",
"body": "@Miles: As far as I can see `theta` is used only in `noiseDir`, where it could be a local variable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T10:31:12.137",
"Id": "4273",
"ParentId": "4271",
"Score": "1"
}
},
{
"body": "<p>(1). From the point of style I'd recommend you not to mix the level of details in a function. For example.</p>\n\n<p>Instead of writing something like this:</p>\n\n<pre><code>void setup() {\n background(0);\n size(1000, 500); \n for (int i = 0; i < pAmt; i++) { // this is bad\n p[i] = new Particle(random(width), random(height), i);\n }\n}\n</code></pre>\n\n<p>You should write something like this. The same is applicable for other functions.</p>\n\n<pre><code>void setup() {\n background(0);\n size(1000, 500); \n fillArray(); // there goes the loop and it's load easier to read.\n}\n</code></pre>\n\n<p>(2). As for naming conventions I'd recommend you to use a verb as a first part for the function's name. Code like this looks unusual.</p>\n\n<pre><code>background(0);\nsize(1000, 500); \n</code></pre>\n\n<p>(3). You should be consistent with names for your variables. For example in your update() function you can see a mix of full and short names like stride, target, chaos vs accel, vel, pos. It really makes me think a lot more about names than I should.</p>\n\n<p>(4).If you have to call this \"normalize()\" method a lot after construction of the object I'd recommend to think about adding this method to consturctor for example with the flag called \"shouldNormalize\".</p>\n\n<pre><code>PVector dir = new PVector(x - pos.x, y - pos.y);\ndir.normalize();\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>PVector dir = new PVector(x - pos.x, y - pos.y, true); \n//or make it to normalize the vector by default and pass false when you don't need it\n//but I guess that you should normalize it quite often after creation \n</code></pre>\n\n<p>(5). I would strongly recommend to make Particle class immutable. It would save you from a lot of hacks like this and make your code cleaner:</p>\n\n<pre><code> void update(float stride, PVector target, float chaos) {\n this.stride = stride;\n ... } \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T20:43:12.333",
"Id": "6448",
"Score": "0",
"body": "I understand your first point, but I'm not positive what level of details means. \n\nDoes it mean that if a function deals with high level areas like setting the size of the program specific things like filling an array should be done in other more specialized functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T10:08:30.333",
"Id": "6459",
"Score": "1",
"body": "Yes. It's very hard to read a code that jumps from high level abstractions to the low level and back."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T08:16:36.543",
"Id": "4301",
"ParentId": "4271",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4301",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T05:17:38.843",
"Id": "4271",
"Score": "6",
"Tags": [
"animation",
"processing"
],
"Title": "Particles moving around a Perlin Noise field"
}
|
4271
|
<p>I was wondering if anyone would be so kind as to look at this code I've written for practice. Tell me what am I doing wrong, where can I optimize, anything.</p>
<p>What this code does is (in terminal) draw a bunch of random 1's and 0's, but I added an effect kinda like a lattice. The bulk of this I got help on here.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main (int argc, char *argv[]){ //check for whitch effect to print
switch(*argv[1]){
case '1': lattus();break;
case '2': normal();break;
default: printf("1 = lattus effect | 2 = static effect\n");break;
}
}
char *randstring (char *buffer, int length){ //genertate a random number
int i = length;
while(--i >= 0) {
buffer[i] = (rand() % 2) ? '1' : '0';
}
buffer[length] = 0;
return buffer;
}
int normal(){ // normal drawing of 1's and 0's
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int width = w.ws_col;
int height = w.ws_row; //get terminal width and height
char buffer[width*height + 1]; //create a buffer big enough to hold one draw to the screen
int i = 25;
while(i-- >= 0) {
printf("%s\n", randstring(buffer, width*height)); //draw to screen
usleep(90000);
}
system("clear"); //clear screen
}
int lattus (void){
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int width = w.ws_col; //get the terminal width
char buffer1[width + 1]; //create 3 buffers for each segment
char buffer2[width + 1]; //each big enough to hold the width of the terminal
char buffer3[width + 1];
int first = 1; //how many before the space
int second = width - 8; //how many in the middle of the space
int third = 1; //how many at the end of the space
int i = 1000; //draw 1000 lines
int on = 0; //switch for growing and shrinking
while(i-- >= 0){
usleep(9000);
if(first == 1 && third == 1 && second == width - 8 | second == width - 9){ //is it at min?
if(second % 2 == 0){ //is it an even number (had problems with buffer if it was odd)
second = second - 2;
}else{
second = second - 3;
}
first ++;
third ++;
on = 0; //keep growing
}else if(first == (width - 8) / 2 && third == (width - 8) / 2 && second == 2){ //untill it gets to max
if(second % 2 == 0){
second = second + 2;
}else{
second = second + 1;
}
third --;
first --;
on = 1; //start shrinking
}else if(on == 0){ //else if suppost to grow, grow
second = second - 2;
third ++;
first ++;
}else if(on == 1){ //else if suppost to shrink shrink
second = second + 2;
third --;
first --;
}else{
break;
}
printf("%s %s %s\n", randstring(buffer1, first), randstring(buffer2, second), randstring(buffer3, third)); //print it out
}
system("clear"); //clear screen
}
</code></pre>
|
[] |
[
{
"body": "<p>A few pointers:</p>\n\n<p>First, variable length arrays are only allowed in C99:</p>\n\n<pre><code>char buffer1[width + 1];\n</code></pre>\n\n<p>If the code is to be strictly ANSI C, one would make an pointer to an array and use a function like <code>malloc</code> or <code>calloc</code> to allocate some memory for the array:</p>\n\n<pre><code>char* buffer = malloc(sizeof(char) * (width + 1));\n</code></pre>\n\n<p>(Then, if necessary, the <code>buffer</code> would be initialized, or <code>calloc</code> used instead to initialize and allocate at once.)</p>\n\n<p>Second, code readability:</p>\n\n<pre><code>if(second % 2 == 0){\n second = second - 2;\n}else{\n second = second - 3;\n}\n</code></pre>\n\n<p>Could be better written as:</p>\n\n<pre><code>if (second % 2 == 0) {\n second = second - 2;\n} else {\n second = second - 3;\n}\n</code></pre>\n\n<p>It may seem like nitpicking, but it does make it easier for people to read your code and understand what is going on. Coding is a form of communication as well -- make it easier for others to read, and it others will be able to better understand what you're trying to achieve.</p>\n\n<p>The <code>switch</code> statement could be similarly improved:</p>\n\n<pre><code>switch(*argv[1]){\n case '1': lattice();break;\n case '2': normal();break;\n default: printf(\"1 = lattice effect | 2 = static effect\\n\");break;\n}\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>switch(*argv[1]) {\n case '1':\n lattice();\n break;\n case '2':\n normal();\n break;\n default:\n printf(\"1 = lattice effect | 2 = static effect\\n\");\n}\n</code></pre>\n\n<p>Also, adding line breaks between certain blocks of statement which perform one task may improve readability.</p>\n\n<p>There seems to be copious use of <code>while</code> loops, but I don't see a single <code>for</code> loop -- <code>for</code> loops are probably more useful for performing \"counter\"-type activities, such as performing repetitions for a certain number of iterations:</p>\n\n<pre><code>int i;\nfor (i = 0; i < 100; i++) {\n /* Action to perform 100 times */\n}\n</code></pre>\n\n<p>The basic structure of a <code>for</code> loop is as follows:</p>\n\n<pre><code>for (initial-condition; loop-condition; expression-on-each-iteration) {\n /* Action to perform on each iteration. */\n}\n</code></pre>\n\n<p>(Note: The name for the conditions are not official names, I just made them up to describe what they're for.)</p>\n\n<p>The <code>initial-condition</code> is what to do when the <code>for</code> loop first begins. Many times, this is used to initialize a counter variable to some value. For example, <code>i</code> is set to <code>0</code>.</p>\n\n<p>The <code>loop-condition</code> is an expression that is evaluated at the beginning of each iteration which determines whether the loop should continue. If the expression is true, then the loop is performed, but if false, then the loop terminates.</p>\n\n<p>The <code>expression-on-each-iteration</code> is something that is performed at the beginning of each iteration of the loop, if that iteration is to take place. Commonly, this is part is used to increment the counter used to control the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:22:46.757",
"Id": "6402",
"Score": "0",
"body": "thanks, one of my goals is to be very ANSI C strict. sorry about readability, i probably should have gone through and indented a bit better. as for the switch i had it in that formatt before, but i was having trouble getting it to work, (totally just learned about argc and argv) i was trying to pass argc to the switch and ended up trying everything, including changing the format to that of some example code to fix it. also i just added some comments."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:26:55.610",
"Id": "6403",
"Score": "0",
"body": "Don't be apologetic! Actually, your code is fairly well-indented :) Definitely better than how I started out. You seem to be on a good start, so keep it up :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:37:55.913",
"Id": "6404",
"Score": "0",
"body": "thank you, for your words of compassion. :) really thanks, your comments really helpful, I'll have to go lookup why fors are better than whiles for counting."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:50:57.387",
"Id": "6405",
"Score": "0",
"body": "@austin, I've added a little bit on the for loop as an edit."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T12:03:50.167",
"Id": "6406",
"Score": "1",
"body": "Also:\n\nif (second % 2 == 0) {\n second = second - 2;\n} else {\n second = second - 3;\n}\n\ncould be made more concise:\n\nif (second % 2 == 0) {\n second -= 2;\n} else {\n second -= 3;\n}"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2009-06-21T11:09:06.863",
"Id": "4276",
"ParentId": "4275",
"Score": "14"
}
},
{
"body": "<p>I would suggest to check if <code>argc</code> is indeed 1 or greater, before trying to refer to it in <code>argv[1]</code></p>\n\n<pre><code>int main (int argc, char *argv[])\n{\n if(argc != 1)\n {\n printf(\"1 = lattice effect | 2 = static effect\\n\");\n return 1;\n }\n switch(*argv[1]) {\n</code></pre>\n\n<p>I have bad memories of unchecked pointers :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:18:32.100",
"Id": "6407",
"Score": "0",
"body": "yeah, i just added that quick because i knew what to expect there, but i shall remember."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T11:15:12.513",
"Id": "4277",
"ParentId": "4275",
"Score": "11"
}
},
{
"body": "<p>Also, avoid <code>system()</code>. It's evil. Instead of <code>system(\"clear\")</code>, provide your own. Use</p>\n\n<pre><code>write (1, \"\\033[2J\", 4);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T14:39:49.980",
"Id": "6409",
"Score": "1",
"body": "Why is this better? Is that a valid sequence for every terminal type? \"man clear\" would seem to suggest otherwise."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T14:44:27.737",
"Id": "6410",
"Score": "0",
"body": "Maybe not -- I don't do much with the terminal. My apologies. Anyway, system() isn't particularly bad in this case, but it can lead to big security problems if you get in the habit of doing it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2009-06-21T14:26:46.883",
"Id": "4279",
"ParentId": "4275",
"Score": "2"
}
},
{
"body": "<p>ANSI C89 requires procedures to be declared before they are used. Which compiler are you using? gcc at least will complain about this. If you are using gcc and aiming for C89 compatibility try using the compiler options \"-Wall -ansi -pedantic\" to make the compiler more verbose.</p>\n\n<p>If you move your \"main\" procedure to the bottom of the code, you will solve that problem. Alternatively, you could provide signatures for lattuce and normal above main like so</p>\n\n<pre><code>int lattus (void);\n</code></pre>\n\n<p>Looking at this line</p>\n\n<pre><code> if(first == 1 && third == 1 && second == width - 8 | second == width - 9){ //is it at min?\n</code></pre>\n\n<p>Should that be a boolean OR after -8?</p>\n\n<pre><code> if(first == 1 && third == 1 && second == width - 8 || second == width - 9){ //is it at min?\n</code></pre>\n\n<p>Some parenthesis around the boolean operators would make things clearer there.</p>\n\n<p>You are using C++-style // comments which are not supported by C89. They can be re-written like this:</p>\n\n<pre><code> if(first == 1 && third == 1 && second == width - 8 || second == width - 9){ /* is it at min? */\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2009-06-21T14:38:05.397",
"Id": "4280",
"ParentId": "4275",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4276",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2009-06-21T11:01:15.753",
"Id": "4275",
"Score": "13",
"Tags": [
"c",
"random",
"console",
"ascii-art"
],
"Title": "Draw random 1's and 0's"
}
|
4275
|
<pre><code>if(env['REQUEST_METHOD'] == 'POST')
$post = {}
post = env['rack.input'].read.split('&')
post_split = Array.new
post.each{|x| post_split << x.split('=')}
post_split.each{|x|
$post[x[0]] = x[1]
}
end
</code></pre>
<p>What would be a nice way to do this? I have a string like:</p>
<pre><code>"a=b&c=d"
</code></pre>
<p>and i'm trying to get it into a hash like</p>
<pre><code>{:a=>'b',:c=>'d'}
</code></pre>
<p>This code works but it is just terrible, and I can't access the keys with</p>
<pre><code>$post[:a]
</code></pre>
<p>only </p>
<pre><code>$post['a']
</code></pre>
|
[] |
[
{
"body": "<p>better way of such parsing is not to reinvent the wheel and use existing ruby functionality</p>\n\n<pre><code>require \"cgi\"\npost = CGI.parse \"a=b&c=d\"\n# => {\"a\"=>[\"b\"], \"c\"=>[\"d\"]}\n</code></pre>\n\n<p>hash values are arrays here, but it makes sense, as you can have several vars in your query string with the same name</p>\n\n<p>for the second part of your question (accessing the keys as symbols) you can use .with_indifferent_access method provided by ActiveSupport (it is already loaded if you use rails)</p>\n\n<pre><code>post.with_indifferent_access[:a]\n# => [\"b\"]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:39:38.343",
"Id": "4393",
"ParentId": "4282",
"Score": "5"
}
},
{
"body": "<p>The Rack gem has a built-in function to parse the query. If your project depends on <code>rack</code> (e.g. it's a Rails app), then you can use it.</p>\n\n<pre><code>Rack::Utils.parse(\"a=b&c=d\")\n# { :a => 'b', :c => 'd' }\n</code></pre>\n\n<p>If your project doesn't depend on <code>rack</code>, you can copy the method in your code.</p>\n\n<pre><code>DEFAULT_SEP = /[&;] */n\n\n# Stolen from Mongrel, with some small modifications:\n# Parses a query string by breaking it up at the '&'\n# and ';' characters. You can also use this to parse\n# cookies by changing the characters used in the second\n# parameter (which defaults to '&;').\ndef parse_query(qs, d = nil)\n params = {}\n\n (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|\n k, v = p.split('=', 2).map { |x| unescape(x) }\n if cur = params[k]\n if cur.class == Array\n params[k] << v\n else\n params[k] = [cur, v]\n end\n else\n params[k] = v\n end\n end\n\n return params\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T08:03:28.803",
"Id": "103676",
"Score": "0",
"body": "Seems in the newer versions `parse` is remove and now one need to call `parse_query` instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T20:24:56.167",
"Id": "4457",
"ParentId": "4282",
"Score": "5"
}
},
{
"body": "<p>If you can do without symbol keys, the following builds a Hash without any external dependencies:</p>\n\n<p>s = \"a=b&c=d\"</p>\n\n<p>Hash[*s.split(/=|&/)] => {\"a\"=>\"b\", \"c\"=>\"d\"} </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T08:40:50.833",
"Id": "103688",
"Score": "0",
"body": "Will fail for `\"a=b&c=\"`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T02:56:52.907",
"Id": "4570",
"ParentId": "4282",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T15:00:38.020",
"Id": "4282",
"Score": "5",
"Tags": [
"beginner",
"ruby",
"strings",
"array"
],
"Title": "Split post string into hash"
}
|
4282
|
<pre><code>(cn.PublishEnd == null || cn.PublishEnd < DateTime.Now)
</code></pre>
<p>vs</p>
<pre><code>(cn.PublishEnd ?? DateTime.MinValue < DateTime.Now)
</code></pre>
<p>Which is more readable?
I'm inclined towards the second form, but something tells me I'm wrong.</p>
<p>Context:</p>
<pre><code>namespace Damnation.Website.Main.Business.Extensions
{
public static class CommunityNews
{
public static IEnumerable<DAL.CommunityNews> Published(this ObjectSet<DAL.CommunityNews> table)
{
return table.Where(cn => cn.PublishStart > DateTime.Now && DateTime.Now > (cn.PublishEnd ?? DateTime.MinValue)).OrderByDescending(cn => cn.PublishStart);
}
}
}
</code></pre>
<p><em>Types</em></p>
<pre><code>DateTime PublishStart
DateTime? PublishEnd
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:45:43.883",
"Id": "6415",
"Score": "0",
"body": "In light of seeing Ivan's answer, I think we'll need a bit more context like, what's that actual type of `cn.PublishEnd`? If it happened to be of type `bool?` (very odd), then that would invalidate my answer and would need clarification. Is this going to be a part of a conditional and you use the value somewhere? Other things will change as well in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:50:12.477",
"Id": "6417",
"Score": "0",
"body": "It's `DateTime?`, I'll update with the full snippet."
}
] |
[
{
"body": "<p>Within a conditional, it would depend largely on the type of the object. In general, I'd favor the first form, particularly if it is a non-string reference type that doesn't offer a nice default value. Otherwise if it was a <code>string</code> or nullable structure, I would prefer the second.</p>\n\n<p>I'd be very careful instantiating new objects only for doing a comparisons like this. It's rather wasteful, especially if you have many comparisons and the object isn't very cheap to instantiate since it's being thrown away.</p>\n\n<p>In this case, it is a nullable (<code>DateTime?</code> apparently) so it would be cleanest IMHO using the second.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T16:22:16.200",
"Id": "4284",
"ParentId": "4283",
"Score": "3"
}
},
{
"body": "<p>As for me, the first form is more readable because it clearly describe the condition. It's easy to read and understand. The second form is a little confusing. The first thought I had was: What is the DateTime.Zero? Is this a default value for PublishEnd? If yes then why not to use the DateTime.MinValue? Maybe it's not a default value and I get it wrong somewhere? Of course these thoughts took only seconds but nevertheless.\nIn general I think that ?? should be used to return the default value with expected type. The default value of the PublishEnd should be of DateTime type. But the second form distorts the meaning of ?? and returns bool type instead, and it’s confusing. </p>\n\n<p><strong>Edited:</strong>\nIf you want to read is like you said: \"if now is greater than (end date or earliest date)\"\nthen you should write it like:</p>\n\n<pre><code>(DateTime.Now > cn.PublishEnd ?? DateTime.MinValue)\n</code></pre>\n\n<p>And this, third form is better than first and second.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:24:40.440",
"Id": "6412",
"Score": "0",
"body": "it's DateTime.MinValue, I mistyped it. I find it easy to read as \"if now is greater than (end date or earliest date)\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:36:06.817",
"Id": "6413",
"Score": "0",
"body": "Yes, this part is easy to read, but for me it's confusing because it is not plainly connected to PablishEnd. It's connected to PablishEnd by means of operator that has specific purpose. Once again - it's only my opinion. I prefere plain code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:38:47.977",
"Id": "6414",
"Score": "0",
"body": "Hmm, I didn't realize there wasn't a `Zero` property of `Datetime`. Hopefully he intended to use the .NET `DateTime` and not some custom class, it'd be bad form to name a type the same as one in the `System` namespace. Also good point at the end, I forgot that the `??` operator has lower precedence than comparison operators. But the intent is clear, any decent IDE would help correct that rather quickly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:21:57.030",
"Id": "4287",
"ParentId": "4283",
"Score": "4"
}
},
{
"body": "<p>Usualy I solve problems like this with introducing a class DateTimeRange which has a method Contains(DateTime date).</p>\n\n<p>In your case I would rewrite the conditional statement and put it into the CommunityNews class</p>\n\n<pre><code>public class CommunityNews\n{\n public bool IsPublished(DateTime checkingDate)\n {\n if (this.PublishStart <= checkingDate)\n {\n return false;\n }\n\n return this.PublishEnd.HasValue\n ? checkingDate < this.PublishEnd.Value\n : true;\n }\n}\n</code></pre>\n\n<p>Then your search method would become as clear as possible:</p>\n\n<pre><code> public static IEnumerable<DAL.CommunityNews> Published(this ObjectSet<DAL.CommunityNews> table)\n {\n return table.Where(cn => cn.IsPublished(DateTime.Now)).OrderByDescending(cn => cn.PublishStart);\n }\n</code></pre>\n\n<p>P.S. In general I would consider using cn.PublishEnd ?? DateTime.MinValue < DateTime.Now in a check statement as a bad practice, because to me ?? is more about return and not about checking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T06:39:19.603",
"Id": "4299",
"ParentId": "4283",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T15:57:08.873",
"Id": "4283",
"Score": "7",
"Tags": [
"c#",
"datetime",
"linq",
"comparative-review",
"null"
],
"Title": "Enumerating new articles whose publication start date has passed"
}
|
4283
|
<p>I need to get this program reviewed. It is counting the lines of code in all files in the
given directory. </p>
<p>I'm new to python and need some advice on pretty much everything.</p>
<pre><code>#!/usr/bin/python
import os
import sys
def CountFile(f):
counter = 0
f = open(f, "r")
for line in f.read().split('\n'):
counter = counter + 1
f.close()
return counter
def CountDir(dirname):
counter = 0
for f in os.listdir(dirname):
fa = os.path.join(dirname, f)
if os.path.isdir(fa):
dcount = CountDir(fa)
counter = counter + dcount
else:
fcount = CountFile(fa)
counter = counter + fcount
return counter
print CountDir(sys.argv[1])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T21:15:54.457",
"Id": "68626",
"Score": "2",
"body": "What was wrong with `wc -l *`?"
}
] |
[
{
"body": "<p>You can iterate over a file object line by line without calling <code>.read()</code> or <code>.split('\\n')</code>\nThat should save you a bunch of function calls.</p>\n\n<p>Maybe the built in <code>sum()</code> function would be faster? </p>\n\n<pre><code>counter = sum(1 for line in f)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T18:49:16.400",
"Id": "4288",
"ParentId": "4286",
"Score": "2"
}
},
{
"body": "<p>First a small nitpick: in python the prevailing naming convention for function names is all lowercase, with words separated by underscores. So <code>CountFile</code> should be <code>count_file</code>, or even better would be something like <code>count_lines</code>, since <code>count_file</code> doesn't really explain what the function does.</p>\n\n<p>Now in <code>CountFile</code>, you read the file using <code>f.read()</code> then <code>split</code> on newlines. This isn't really necessary -- for one thing because file objects have a method called <code>readlines</code> which returns a list of the lines, but more importantly because file objects are iterable, and iterating over them is equivalent to iterating over the lines. So <code>for line in f.read().split('\\n'):</code> is equivalent to <code>for line in f:</code>, but the latter is better because when you call <code>read()</code> you actually read the entire contents of the file into memory, whereas <code>for line in f:</code> reads the lines one at a time. It's also the idiomatic way to go about reading a file line by line.</p>\n\n<p>If you're not concerned about memory, however, then because <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">flat is better than nested</a> you can do away with the explicit for loop and just call <code>len</code> on your list of lines. The entire function could be <code>return len(open(f, 'r').readlines())</code> (but this isn't really advisable in the general case because of the memory thing). You could also use a <a href=\"http://docs.python.org/reference/expressions.html#generator-expressions\" rel=\"nofollow\">generator expression</a> and write <code>return sum(1 for line in f)</code>.</p>\n\n<p>Now notice that in <code>CountFile</code>, you write <code>f = open(f, \"r\")</code> to open a file, then later you write <code>f.close()</code> -- this kind of pattern is what <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-343\" rel=\"nofollow\">context managers and the <code>with</code> statement</a> were introduced for. The context manager protocol is already conveniently implemented for file objects, so you could write:</p>\n\n<pre><code>counter = 0\nwith open(f, 'r') as f:\n for line in f:\n counter += 1\n</code></pre>\n\n<p>And you wouldn't need to explicitly close the file. This may not seem like such a big deal in this case, and it isn't really, but <code>with</code> statements are a convenient way to ensure you that you only use resources (like files, or database connections, or anything like that) just as long as you need to. (Also, allocating and later freeing a resource might be a lot more involved than just calling <code>open</code> and <code>close</code> on it, and you might have to worry about what happens if something goes wrong while you're using the resource (using <code>try... finally</code>)... Hiding that behind a <code>with</code> statement makes for much more readable code because you can focus on what you're trying to accomplish instead of details like that.)</p>\n\n<p>Your <code>CountDir</code> function looks mostly okay. You might look into using <a href=\"http://docs.python.org/library/os.html#os.walk\" rel=\"nofollow\"><code>os.walk</code></a> instead of <code>os.listdir</code> so you won't need to check for directories -- it would look something like</p>\n\n<pre><code>for root, _, files in os.walk(dirname):\n for f in files:\n count += CountFile(os.path.join(root, f))\n</code></pre>\n\n<p>(The <code>_</code> doesn't have any special meaning, it just by convention means that we won't be using that variable.) Another advantage of <code>os.walk</code> is that by default it doesn't follow symlinks, whereas <code>listdir</code> doesn't care, so if you don't explicitly check for symlinks you might end up counting things twice.</p>\n\n<p>If you stick with <code>os.listdir</code>, you could still make your code a bit cleaner by using a <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-308-conditional-expressions\" rel=\"nofollow\">conditional expression</a>, which would look like:</p>\n\n<pre><code>counter += CountDir(fa) if os.path.isdir(fa) else CountFile(fa)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T19:04:45.220",
"Id": "4289",
"ParentId": "4286",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4289",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T17:53:12.863",
"Id": "4286",
"Score": "4",
"Tags": [
"python"
],
"Title": "Program to count the number of lines of code"
}
|
4286
|
<p>I have written this implementation of Huffman coding. Please suggest ways to make this code better, i.e. more Pythonic.</p>
<pre><code>from collections import Counter
#####################################################################
class Node(object):
def __init__(self, pairs, frequency):
self.pairs = pairs
self.frequency = frequency
def __repr__(self):
return repr(self.pairs) + ", " + repr(self.frequency)
def merge(self, other):
total_frequency = self.frequency + other.frequency
for p in self.pairs:
p[1] = "1" + p[1]
for p in other.pairs:
p[1] = "0" + p[1]
new_pairs = self.pairs + other.pairs
return Node(new_pairs, total_frequency)
#####################################################################
def huffman_codes(s):
frequency_table = Counter(s)
initial_table = []
for k, v in frequency_table.items():
initial_table.append([k, v])
initial_table = sorted(initial_table, key = lambda p : p[1])
# print(initial_table)
table = []
for entry in initial_table:
ch = entry[0]
freq = entry[1]
table.append(Node([[ch, ""]], freq))
# print(table)
while len(table) > 1:
first_node = table.pop(0)
second_node = table.pop(0)
new_node = first_node.merge(second_node)
table.append(new_node)
table = sorted(table, key = lambda n : n.frequency)
# print(table)
return dict(map(lambda p: (p[0], p[1]), table[0].pairs))
#####################################################################
print(huffman_codes('yashaswita'))
</code></pre>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T14:44:01.500",
"Id": "6418",
"Score": "2",
"body": "Also, if you want to compare methods, there is an early version of a Huffman coding module I wrote as an exercise [on pastebin](http://pastebin.com/QEK3WdbE). The core is the same as what I ended up with, but it ended up getting significantly refactored and simplified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T01:42:24.023",
"Id": "6424",
"Score": "1",
"body": "\"pythonic\" rocks"
}
] |
[
{
"body": "<p><strike>Generally, loops aren't encouraged in python, since it is interpreted rather than compiled, thus the loop body will be \"recompiled\" at every iteration.</strike></p>\n\n<p>using map/reduce is one good way to avoid loops. another is using the <code>for.. in</code>, e.g.:</p>\n\n<pre><code>initial_table=[[k, v] for k, v in frequency_table.items()]\n</code></pre>\n\n<p>and similarly for your 2nd for loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T13:13:21.223",
"Id": "6419",
"Score": "5",
"body": "Loops aren't encouraged in Python? The loop body will be recompiled at every iteration? That's completely and totally wrong. You actual advice for how to write it is fine, but the first paragraph is __entirely wrong__. -1 if you don't edit this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T13:27:05.797",
"Id": "6420",
"Score": "0",
"body": "Sorry, that's what i've been taught. I guess I was told wrong, then. Good to know, thanks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T13:33:01.807",
"Id": "6421",
"Score": "1",
"body": "Python code is bytecompiled once, before it's executed. The names in the loop are looked up again on every iteration, because Python is a dynamic language and you could be changing what they mean; this is also generally true for a list comprehension. With `map`, the function you call repeatedly is only looked up once, however. The Python interpreter does a good job optimizing list comprehensions though (and they tend to be a bit faster than explicit loops) so `map` usually doesn't help much."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T13:12:08.283",
"Id": "4291",
"ParentId": "4290",
"Score": "3"
}
},
{
"body": "<p>Really does belong on codereview.</p>\n\n<ol>\n<li><p>Use four space indentation. This is the <a href=\"http://www.python.org/dev/peps/pep-0008/\">Python standard</a>, and will make any code more \"Pythonic\". <strong>Edit:</strong> You're following PEP-8 in all other respects as far as I can tell, so if you like two space indentation, it's not a big deal. Your code is very easy to read.</p></li>\n<li><p>You don't need to sort every time; you don't even need a fully sorted list. Python has a datatype for this -- it's called <a href=\"http://docs.python.org/library/heapq.html\"><code>heapq</code></a>. Use it's <code>heappush</code> and <code>heappop</code> methods, so you don't have to sort every time. You can actually write a single line loop to do the tree building. Read what that page says about priority queues -- it's what you're using.</p></li>\n<li><p>You don't need anything like </p>\n\n<pre><code>return dict(map(lambda p: (p[0], p[1]), table[0].pairs))\n</code></pre>\n\n<p>just</p>\n\n<pre><code>return dict(table[0].pairs)\n</code></pre>\n\n<p>does exactly the same thing.</p></li>\n<li><p>If you <em>really</em> want to minimize lines, everything before the <code>while</code> can be written as one line:</p>\n\n<pre><code>table = sorted((Node([[p[0], \"\"]], p[1]) for p in Counter(s).iteritems()), key = lambda n : n.frequency)\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T13:12:39.053",
"Id": "4292",
"ParentId": "4290",
"Score": "6"
}
},
{
"body": "<p>I agree with <code>agf</code> except for point 4.\nThis is my try on your code:</p>\n\n<pre><code>from collections import Counter\nimport heapq\n\nclass Node(object):\n def __init__(self, pairs, frequency):\n self.pairs = pairs\n self.frequency = frequency\n\n def __repr__(self):\n return repr(self.pairs) + \", \" + repr(self.frequency)\n\n def merge(self, other):\n total_frequency = self.frequency + other.frequency\n for p in self.pairs:\n p[1] = \"1\" + p[1]\n for p in other.pairs:\n p[1] = \"0\" + p[1]\n new_pairs = self.pairs + other.pairs\n return Node(new_pairs, total_frequency)\n\n def __lt__(self, other):\n return self.frequency < other.frequency\n\ndef huffman_codes(s):\n table = [Node([[ch, '']], freq) for ch, freq in Counter(s).items()]\n heapq.heapify(table)\n while len(table) > 1:\n first_node = heapq.heappop(table)\n second_node = heapq.heappop(table)\n new_node = first_node.merge(second_node)\n heapq.heappush(table, new_node)\n return dict(table[0].pairs)\n\nprint(huffman_codes('yashaswita'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T14:18:26.280",
"Id": "6422",
"Score": "2",
"body": "Nice, (I'm out of votes), but you actually did exactly what I did in #4 except for not needing to sort because you added the `heapq`, and better variable naming."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T14:10:23.720",
"Id": "4293",
"ParentId": "4290",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "4293",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T12:58:13.197",
"Id": "4290",
"Score": "8",
"Tags": [
"python",
"algorithm"
],
"Title": "Is there a better way to implement this Huffman Algorithm in Python?"
}
|
4290
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.