body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I need to call an <code>upsert</code> to my Category table in PostgreSQL. My current solution uses the <code>exec_query</code> API in ActiveRecord, using binding.</p>
<p>What I got so far looks like this:
<strike>
</p>
<pre><code>VERIFY_CATEGORY_SQL = <<SQL
WITH sel AS (SELECT id FROM categories WHERE name=$1 AND source=$2),
ins AS (INSERT INTO categories (name, source, created_at, updated_at) SELECT
$3, $4, 'now', 'now' WHERE NOT EXISTS (SELECT * from sel) RETURNING id)
select id from ins union all select id from sel
SQL
</code></pre>
<p></strike>
</p>
<pre><code>VERIFY_CATEGORY_SQL = <<SQL
WITH sel AS (SELECT id FROM categories WHERE name=$1 AND source=$2),
ins AS (INSERT INTO categories (name, source, created_at, updated_at) SELECT
$1, $2, now(), now() WHERE NOT EXISTS (SELECT * from sel) RETURNING id)
select id from ins union all select id from sel
SQL
</code></pre>
<pre class="lang-ruby prettyprint-override"><code>def verify_category_existence(name, source)
ActiveRecord::Base.connection.exec_query(VERIFY_CATEGORY_SQL, 'SQL',
[[nil, name], [nil, source]]).first['id'].to_i
end
</code></pre>
<p><strong>Notes</strong></p>
<ol>
<li>In order to make this work I needed to add <code>prepared_statements: true</code> attribute to my <code>database.yml</code> file.</li>
<li><strike>Although I need to reuse my <code>name</code> and <code>source</code> parameters, I can't and have to duplicate them as parameters <code>$1, $3</code> and <code>$2, $4</code> respectively</strike> (Apparently this works fine...)</li>
<li>The method call seems a bit hackish, and I believe maybe it was not meant as a public method, and only intended for internal uses (hence the awkward <code>[[nil, x]...]</code> syntax and the <code>'SQL'</code> parameter, which apparently is for logging purposes)</li>
</ol>
<p>What do you think of this solution? </p>
<p>Do you know of a better way to do this?</p>
<p><strong>Edit:</strong></p>
<p>I've received great responses to the SQL/Postgresql side of my solution, but I would love to also hear from our rubyists regarding the Ruby/ActiveRecord part of the solution - is this way correct? is there a better solution?</p>
<p><strong>Edit:</strong></p>
<p>Just found out that using <code>'now'</code> produced unexpected results - timestamp values were re-used rather than calculated on each insert. Changed it to <code>now()</code>, and it works better.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T10:41:50.150",
"Id": "70826",
"Score": "1",
"body": "In regular `PostgreSQL` you could just re-use `$1` and `$2`; try it with `PREPARE` then `EXECUTE` in `psql`. So if you can't here, it's a Rails or Pg gem limitation. My main concern is that your insert-if-not-exists implementation is subject to race conditions; concurrently running statements will both insert rows. You'll need `SERIALIZABLE` isolation to prevent that (test and make sure that's enough, I think it is), or you'll need to `LOCK TABLE ... IN EXCLUSIVE MODE` first. See http://stackoverflow.com/q/17267417/398670"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T12:21:52.610",
"Id": "70832",
"Score": "0",
"body": "@CraigRinger, could you explain how to use `SERIALIZABLE`? Could you show me an example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T12:43:40.353",
"Id": "70833",
"Score": "0",
"body": "take a look at the link I provided, it has references to safe approaches to upsert. For `SERIALIZABLE`, see http://www.postgresql.org/docs/current/static/transaction-iso.html . It's important to understand that if you use serializable isolation, it'll cause an *error* when you encounter a race condition, so your code must handle errors and retry the transaction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T12:56:21.313",
"Id": "70834",
"Score": "0",
"body": "Do I need to use `SERIALIZABLE` if I have a unique constraint on the relevant columns? Won't it be enough? If so, I should still expect a unique exception, and retry, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T13:34:27.547",
"Id": "70836",
"Score": "0",
"body": "Your approach has been tried, many times before. You are not the first to think of it. The links I provided explain why it does not work in a concurrent environment. Here is the most important one. Read this. http://www.depesz.com/2012/06/10/why-is-upsert-so-complicated/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T13:55:16.420",
"Id": "70837",
"Score": "0",
"body": "Thanks! I've read the post you mentioned. Maybe I misunderstood it, but if there are no DELETEs, race condition will result in _one_ of the transactions to fail on insert, in which case a retry will solve the issue. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T03:01:46.133",
"Id": "70886",
"Score": "0",
"body": "If you have a unique constraint on (source, name) it's probably OK, see answer. But in that case, why do it such a complicated way? Just run the insert, and if it fails, select the ID of the existing row. If there's no unique constraint, you will get double inserts."
}
] |
[
{
"body": "<p>Statement, formatted readably:</p>\n\n<pre><code>WITH \nsel AS (\n SELECT id FROM categories WHERE name=$1 AND source=$2\n),\nins AS (\n INSERT INTO categories (name, source, created_at, updated_at )\n SELECT $1, $2, 'now', 'now'\n WHERE NOT EXISTS (SELECT * FROM sel) \n RETURNING id\n)\nSELECT id FROM ins\nUNION ALL\nSELECT id FROM sel;\n</code></pre>\n\n<p>Dummy table:</p>\n\n<pre><code>CREATE TABLE categories (\n id serial not null PRIMARY KEY,\n name text not null,\n source text not null,\n created_at timestamp,\n updated_at timestamp,\n UNIQUE(name, source)\n);\n</code></pre>\n\n<p>Demo, with three concurrent <code>psql</code> sessions:</p>\n\n<ul>\n<li>Session1: <code>PREPARE q(text,text) AS WITH ...</code></li>\n<li>Session2: <code>PREPARE q(text,text) AS WITH ...</code></li>\n<li>Session0: <code>BEGIN;</code></li>\n<li>Session0: <code>LOCK TABLE categories IN ACCESS EXCLUSIVE MODE;</code></li>\n<li>Session1: <code>EXECUTE q('n', 's');</code></li>\n<li>Session2: <code>EXECUTE q('n', 's');</code></li>\n<li>Session0: <code>ROLLBACK;</code></li>\n</ul>\n\n<p>One session will report:</p>\n\n<pre><code>regress=> EXECUTE q('n', 's');\n id \n----\n 1\n(1 row)\n</code></pre>\n\n<p>and one will report:</p>\n\n<pre><code>regress=> EXECUTE q('n', 's');\nERROR: duplicate key value violates unique constraint \"categories_name_source_key\"\nDETAIL: Key (name, source)=(n, s) already exists.\n</code></pre>\n\n<p>So it might be OK if you have a unique constraint on <code>(name, source)</code> and are willing to retry errors, but if you don't have that unique constraint:</p>\n\n<pre><code>ALTER TABLE categories DROP CONSTRAINT categories_name_source_key;\n</code></pre>\n\n<p>then you'll get a double insert, because your <code>SELECT</code> for IDs can run on both sessions before either session executes the <code>INSERT</code>.</p>\n\n<p>If you have a unique constraint, there's no point wasting your time with all this hoop jumping. You're better off just running the <code>insert</code> and if it fails, querying for the ID of the existing row.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:49:46.813",
"Id": "70903",
"Score": "0",
"body": "I do have a unique constraint, but since the call is made many times a second, and the DB is on another machine, I'd prefer to make one round-trip to the server. I will add a retry to my code though. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T02:57:20.487",
"Id": "41306",
"ParentId": "41277",
"Score": "5"
}
},
{
"body": "<p>This is not so much an <code>UPSERT</code> as an insert-if-not-exists. Nevertheless, the PostgreSQL manual <a href=\"http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE\" rel=\"nofollow\">suggests using a procedure</a>:</p>\n\n<pre><code>CREATE TABLE category\n( id SERIAL\n, name TEXT\n, source TEXT\n, UNIQUE (name, source)\n);\n\nCREATE FUNCTION insert_category_if_not_exists(n TEXT, s TEXT) RETURNS SETOF category AS\n$$\n BEGIN\n BEGIN\n INSERT INTO category (name, source) VALUES (n, s);\n EXCEPTION WHEN unique_violation THEN\n -- The row already exists; proceed...\n END;\n RETURN QUERY SELECT * FROM category WHERE category.name=n AND category.source=s;\n END;\n$$\nLANGUAGE plpgsql;\n\nSELECT * FROM insert_category_if_not_exists('rose', 'evian');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:40:17.223",
"Id": "41308",
"ParentId": "41277",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41306",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T07:16:20.767",
"Id": "41277",
"Score": "5",
"Tags": [
"ruby",
"sql",
"postgresql",
"active-record"
],
"Title": "How to properly call an \"upsert\" using parameterized raw SQL to Postgresql in ActiveRecord?"
}
|
41277
|
<blockquote>
<p>Rewrite <code>readlines</code> to store lines in an array supplied by main, rather than calling <code>alloc()</code> to maintain storage. How much faster is the program?</p>
</blockquote>
<p>Here is my solution:</p>
<pre><code>int readlines(char **lineptr, char *storage, int maxlines, int storage_size) {
int len;
int nlines;
nlines = 0;
while((len = _getline(storage, MAXLEN))) {
if(nlines >= maxlines || !(storage_size - len)) {
return -1;
}
else {
storage[len - 1] = '\0';
lineptr[nlines] = storage;
storage += len; // next free space in the buffer supplied by main
storage_size -= len;
nlines++;
}
}
return nlines;
}
</code></pre>
<p>Now, the function takes 2 more arguments: a pointer to the array that will store all the read lines and its size. There is no need now to use another array to store the line temporary, I just can pass portions of the <code>storage</code> to <code>getline</code>.</p>
<p>The condition <code>!(storage_size - len)</code> verifies if there is enough space in <code>storage</code> to store the line that was just read. At each iteration <code>storage</code> is incremented to point to the next free space in the array and the value of the variables <code>storage_size</code> is reduced.</p>
<p>(This exercise can be found at page 124 in K&R.)</p>
|
[] |
[
{
"body": "<p>I don't know what <code>_getline</code> is; perhaps it's something like <a href=\"http://www.gnu.org/software/libc/manual/html_node/Line-Input.html\" rel=\"nofollow\">the file-input function described here</a>.</p>\n\n<hr>\n\n<p>This looks strange ...</p>\n\n<pre><code>int nlines;\n\nnlines = 0;\n</code></pre>\n\n<p>I think that C now (like C++) allows you to delay defining a local variable until you initialize it. So there's no need to declare your variables at the top of the function.</p>\n\n<hr>\n\n<p>Passing <code>MAXLEN</code> is probably wrong: because if <code>(MAX_LEN > storage_size)</code> then you give <code>_getline</code> the opportunity to write past the end of the buffer.</p>\n\n<p>Allowing a buffer overrun is a bug.</p>\n\n<p>Instead you could do something like:</p>\n\n<pre><code>int n_lines = 0;\n\nfor (;;)\n{\n // define local buffer inside function\n char buffer[MAX_LEN];\n int line_length = _getline(buffer, MAXLEN);\n if (line_length == 0)\n break;\n if (n_lines >= maxlines)\n return -1;\n if (line_length > storage_size)\n return -1;\n buffer[line_length - 1] = '\\0';\n // copy local buffer to passed-in buffer\n strcpy(storage, buffer);\n lineptr[n_lines] = storage;\n storage += line_length;\n storage_size -= line_length;\n ++n_lines;\n}\n\nreturn n_lines;\n</code></pre>\n\n<p>Or you can read directly into the passed-in buffer, to avoid <code>strcpy</code> and avoid defining <code>MAXLEN</code>:</p>\n\n<pre><code>int line_length = _getline(buffer, storage_size);\nif (line_length == storage_size)\n{\n // fail unless there's nothing more to read\n char temp[1];\n if (0 != _getline(temp, 1))\n return -1;\n}\n</code></pre>\n\n<hr>\n\n<p>I'm not sure what this statement does ...</p>\n\n<pre><code>storage[len - 1] = '\\0';\n</code></pre>\n\n<p>... if the end-of-line marker is a two-character \"\\r\\n\" sequence (which it is on Windows).</p>\n\n<hr>\n\n<p>You could possibly edit your variable names; if you're going to use_underscores as you did for storage_size, then perhaps:</p>\n\n<ul>\n<li>maxlines -> max_lines</li>\n<li>len -> line_length</li>\n<li>lineptr -> lines or lines_array</li>\n<li>nlines -> num_lines or line_number or line_counter</li>\n</ul>\n\n<p>The least obvious variable name was <code>len</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T22:38:28.960",
"Id": "41297",
"ParentId": "41280",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41297",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T10:03:13.523",
"Id": "41280",
"Score": "7",
"Tags": [
"c",
"beginner",
"pointers"
],
"Title": "Storing lines in an array"
}
|
41280
|
<p>I've written a custom binding for KnockoutJS which renders <code><select></code> elements with <code><optgroup></code> children.</p>
<p>When run, this binding adds <code><optgroup></code> and <code><option></code> DOM elements.</p>
<p>In order to make the binding two-way I obviously need to 'record' the observables for each of those newly-added DOM elements. I've done this using</p>
<pre><code>ko.utils.domData.set(option, "data", thisOption);
</code></pre>
<p>and then in order to retrieve the observable (or plain object) I call</p>
<pre><code>ko.utils.domData.get(node, "data");
</code></pre>
<p>This works fine. However, in Knockout's native bindings I can call <code>ko.dataFor(element)</code> and retrieve the observable, yet this doesn't work in my custom binding.</p>
<p>Can anyone tell me if I've gone about this the right/wrong way? And if wrong, how do I 'record' data that <code>ko.dataFor</code> can retrieve?</p>
<p>Furthermore, my custom binding accepts a parameter which is the property that the selected element's observable is assigned to (in exactly the same way that Knockout's <a href="http://knockoutjs.com/documentation/options-binding.html" rel="nofollow">native <code>options</code> binding</a> uses the 'value' parameter). So in that same change-handler I retrieve this property using the same methodology as above - <em>i.e.</em> using <code>ko.utils.domData...</code></p>
<p>Is this the correct approach for assigning a selected value to another observable in a change handler?</p>
<pre><code>ko.bindingHandlers.groupedOptions = {
"init": function (element, valueAccessor, allBindings) {
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor(),
property = ko.utils.domData.get(element, "property");
ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
if (node.selected) {
var data = ko.utils.domData.get(node, "data");
if (typeof(property) === "function") {
property(data);
} else if (typeof(property) === "string") {
var vm = ko.dataFor(element);
if (vm !== null) {
vm[property] = data;
}
}
}
});
});
},
"update": function(element, valueAccessor) {
// Get the parameters
var h = ko.utils.unwrapObservable(valueAccessor());
var groups = h["groups"],
groupsCollection,
groupsLabel = "Label", // the convention for this property
optionsCollProp = "Options", // the convention for this property
optionsTextProp = "Text", // the convention for this property
optionsValProp = "Value", // the convention for this property
optionsValue = null;
if (typeof (groups) === "undefined" || !groups) {
throw "The \"groupedOption\" binding requires a \"groups\" object be specified.";
} else {
groupsCollection = groups["coll"];
}
if (!groupsCollection) {
throw "The \"groupedOption\" binding's \"groups\" object requires that a collection (array or observableArray) be specified.";
}
if (typeof (groups["label"]) === "string" && groups["label"].length) {
groupsLabel = groups["label"];
}
if (typeof (groups["options"]) === "object") {
var options = groups["options"];
if (typeof (options["coll"]) === "string" && options["coll"].length) {
optionsCollProp = options["coll"];
}
if (typeof (options["text"]) === "string" && options["text"].length) {
optionsTextProp = options["text"];
}
if (typeof (options["value"]) === "string" && options["value"].length) {
optionsValProp = options["value"];
}
}
var selectedItem = h["value"],
selectedValue = ko.unwrap(selectedItem);
if (typeof(selectedItem) === "function") {
ko.utils.domData.set(element, "property", selectedItem); // this records the subscribing property, i.e., the property which stores the selected item
} else if (typeof(selectedItem) === "string") {
// this caters for the situation whereby the subscribing property is not an observable
ko.utils.domData.set(element, "property", selectedItem); // this records the name of the subscribing property, i.e., the property which stores the selected item
}
// find how many elements have already been added to 'element'
var childCount = 0,
children = element.childNodes,
childMax = children.length;
for (var c = 0; c < childMax; c++) {
if (children[c].nodeType != 3) {
childCount++;
}
}
// Default <option> element
// if 'element' is currently empty then add the default <option> element
if (!childCount) {
var defaultText = h["optionsCaption"];
if (defaultText && typeof(defaultText) === "string" && defaultText.length) {
var defaultOption = document.createElement("option");
defaultOption.innerHTML = defaultText;
element.appendChild(defaultOption);
}
} else {
// if 'element' is not empty then decrement realChildren by 1, which represents the default <option> element
childCount--;
}
// now it's time to loop through each <optgroup>
// in this loop, i is set to the the index in the collection which marks the start of the newly-added items, skipping items already added (which were counted above)
var coll = ko.utils.unwrapObservable(groupsCollection);
childMax = coll.length;
for (; childCount < childMax; childCount++) {
var groupLabel = ko.utils.unwrapObservable(coll[childCount][groupsLabel]);
// if there is no label for this <optgroup> then don't add the <optgroup>
if (!groupLabel || !groupLabel.length) {
continue;
}
var optGroup = document.createElement("optgroup");
optGroup.setAttribute("label", groupLabel);
// loop through each <option>
// determine whether the <option>s collection is an array or an observableArray
var options = ko.utils.unwrapObservable(coll[childCount][optionsCollProp]);
for (var j = 0, jMax = options.length; j < jMax; j++) {
var thisOption = options[j],
optionText = ko.utils.unwrapObservable(thisOption[optionsTextProp]);
// if there is no text for this <option> then don't add the <option>
if (!optionText || !optionText.length) {
continue;
}
var option = document.createElement("option");
option.innerHTML = optionText;
// add the 'value' attribute if it exists
var val = ko.utils.unwrapObservable(thisOption[optionsValProp]);
if (val && val.length) {
option.setAttribute("value", val);
}
// if this is the same object as the 'value' parameter then indicate so
if (thisOption === selectedValue) {
option.setAttribute("selected", "selected");
}
// add the observable to this node so that we may retrieve this data in future
ko.utils.domData.set(option, "data", thisOption);
// now add this <option> to the parent <optgroup>
optGroup.appendChild(option);
}
element.appendChild(optGroup);
}
return true;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T14:22:26.123",
"Id": "70839",
"Score": "0",
"body": "Furthermore, it sounds like your code is not working the way you want it to. Please only submit working code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T16:12:44.773",
"Id": "70853",
"Score": "1",
"body": "Ok, I've now added the JS in question. @konijn - yes it is working as expected. My question asks \"if I've gone about this the right/wrong way?\" and later \"Is this the correct approach\". What made you think it wasn't working?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T17:58:56.440",
"Id": "70862",
"Score": "0",
"body": "@avi: *'yet this doesn't work in my custom binding.'*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T07:38:58.283",
"Id": "70910",
"Score": "0",
"body": "@konijn - my question is clearly asking for advice, not a solution. If you have nothing to suggest or no guidance to offer then you don't need to return to this post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T22:15:43.427",
"Id": "71021",
"Score": "0",
"body": "Just a note cause it was bothering me a bit reading your code `typeof` isn't a function and is usually written `typeof x` instead of `typeof(x)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:01:49.917",
"Id": "71231",
"Score": "0",
"body": "Ok, I'll take that on-board. I think I probably used the function-like call because I'm primarily a C# developer, but I'm happy to change it if `typeof x` is more prevalent in JavaScript."
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>You use the following type of coding a ton:<br></p>\n\n<pre><code>var groupsLabel = \"Label\";\n...\nif (typeof (groups[\"label\"]) === \"string\" && groups[\"label\"].length) {\n groupsLabel = groups[\"label\"];\n}\n</code></pre>\n\n<p>You could consider using a helper function for that </p>\n\n<pre><code>function getStringValue( s , defaultValue )\n{\n return (typeof s === \"string\" && s.length) ? s : defaultValue;\n}\n</code></pre>\n\n<p>Then you can </p>\n\n<pre><code> var groupsLabel,\n optionsCollProp, \n optionsTextProp, \n optionsValProp, \n optionsValue, \n\n groupsLabel = getStringValue( groups.label, \"Label\" );\n\n if (typeof (groups[\"options\"]) === \"object\") {\n var config = groups[\"options\"];\n optionsCollProp = getStringValue( config.coll , \"Options\" );\n optionsTextProp = getStringValue( config.text , \"Text\" );\n optionsValProp = getStringValue( config.value, \"Value\" ); \n }\n</code></pre>\n\n<p>Note that I also changed <code>options[\"something\"]</code> to <code>options.something</code> which is the preferred style in JavaScript.</p></li>\n<li>You use <code>var options</code> twice, the meaning of <code>options</code> is different in the 2 usages, I would use <code>config</code> instead the first time as in my counter proposal above this point.</li>\n<li>You do not use <code>var value = valueAccessor()</code> as far as I can tell</li>\n<li>You do not use <code>optionsValue = null;</code> as far as I can tell</li>\n<li>Some variables are perhaps too Spartan <code>vm</code> -> <code>viewModel</code> ?</li>\n<li><code>.nodeType != 3</code> <- This could use a line of comment, given the otherwise excellent level of commenting</li>\n</ul>\n\n<p>As for your actual question, I see nothing wrong with your approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:33:25.763",
"Id": "71014",
"Score": "0",
"body": "default is a reserved word by the way and you have some syntax errors like `getStringValue( groups[\"label\"]), \"Label\" );`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T09:42:46.970",
"Id": "71075",
"Score": "0",
"body": "Those are great comments, @konijn. I've implemented them all except for the first one, regarding the `getStringValue` function: the problem here is, if the `groups[\"options\"] !== \"object\"` then the default values are never set. `groups[\"options\"]` is an optional parameter, so it could feasably be `!== \"object\"` and in that case the defaults wouldn't be set. But other than that, great suggestions - thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:56:13.263",
"Id": "41359",
"ParentId": "41281",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T10:55:40.410",
"Id": "41281",
"Score": "4",
"Tags": [
"javascript",
"knockout.js"
],
"Title": "Knockout custom binding"
}
|
41281
|
<p>I wanted to fiddle around with the <code>BackgroundWorker</code> and <code>Task</code> classes, to see how I would implement a given task with these two techniques.</p>
<p>So I created a new WinForms project, and implemented a simple UI; two sections, each with a <code>ProgressBar</code>, and <kbd>Start</kbd> + <kbd>Cancel</kbd> buttons:</p>
<p><img src="https://i.stack.imgur.com/PYNOk.png" alt="MainForm at startup. Two progressbars, each with an enabled "Start" and a disabled "Cancel" button." /></p>
<p>I implemented a <em>DoSomething</em>-type "service":</p>
<pre><code>public class SomeService
{
public void SomeMethod()
{
Thread.Sleep(1000);
}
}
</code></pre>
<p>But that's irrelevant. The form's code-behind is where I put all the code this post is all about:</p>
<h3>Constructor</h3>
<p>The form's constructor is essentially the entry point here (program.cs is ignored), so I put the obvious fields in first, and initialized them in the constructor:</p>
<pre><code>public partial class Form1 : Form
{
private readonly SomeService _service;
private readonly BackgroundWorker _worker;
public Form1()
{
_service = new SomeService();
_worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
_worker.DoWork += OnBackgroundDoWork;
_worker.ProgressChanged += OnBackgroundProgressChanged;
_worker.RunWorkerCompleted += OnBackgroundWorkerCompleted;
InitializeComponent();
CloseButton.Click += CloseButton_Click;
StartBackgroundWorkerButton.Click += StartBackgroundWorkerButton_Click;
CancelBackgroundWorkerButton.Click += CancelBackgroundWorkerButton_Click;
StartTaskButton.Click += StartTaskButton_Click;
CancelTaskButton.Click += CancelTaskButton_Click;
}
private void CloseButton_Click(object sender, EventArgs e)
{
CancelBackgroundWorkerButton_Click(null, EventArgs.Empty);
CancelTaskButton_Click(null, EventArgs.Empty);
Close();
}
</code></pre>
<h3>#region BackgroundWorker</h3>
<p><strong>Button.Click handlers</strong></p>
<p>These are the event handlers for the <kbd>Start</kbd> and <kbd>Cancel</kbd> buttons' <code>Click</code> event:</p>
<pre><code> private void StartBackgroundWorkerButton_Click(object sender, EventArgs e)
{
StartBackgroundWorkerButton.Enabled = false;
_worker.RunWorkerAsync();
}
private void CancelBackgroundWorkerButton_Click(object sender, EventArgs e)
{
CancelBackgroundWorkerButton.Enabled = false;
_worker.CancelAsync();
}
</code></pre>
<p><strong>BackgroundWorker.DoWork handler</strong></p>
<p>Here we are. The "work" here, will be to call our "time-consuming operation" 5 times, reporting progress as we go, and assigning the <code>DoWorkEventArgs.Cancel</code> as needed:</p>
<pre><code> private void OnBackgroundDoWork(object sender, DoWorkEventArgs e)
{
//CancelBackgroundWorkerButton.Enabled = true; // this call fails the background task (e.Error won't be null)
Invoke((MethodInvoker)(() => { CancelBackgroundWorkerButton.Enabled = true; }));
var iterations = 5;
for (var i = 1; i <= iterations; i++)
{
if (_worker.CancellationPending)
{
e.Cancel = true;
return;
}
_service.SomeMethod();
if (_worker.CancellationPending)
{
e.Cancel = true;
return;
}
_worker.ReportProgress(100 / (iterations) * i);
}
Thread.Sleep(500); // let the progressbar animate to display its actual value.
}
</code></pre>
<p><strong>ProgressChanged handler</strong></p>
<p>This handler assigns the new value to the <code>ProgressBar</code> control owned by the UI thread:</p>
<pre><code> private void OnBackgroundProgressChanged(object sender, ProgressChangedEventArgs e)
{
// BGW facilitates dealing with UI-owned objects by executing this handler on the main thread.
BackgroundWorkerProgressBar.Value = e.ProgressPercentage;
if (BackgroundWorkerProgressBar.Value == BackgroundWorkerProgressBar.Maximum)
{
CancelBackgroundWorkerButton.Enabled = false;
}
}
</code></pre>
<p><strong>WorkerCompleted handler</strong></p>
<p>If I get the <code>BackgroundWorker</code> right, this is where we can determine whether the thing has succeeded, failed with an error or was cancelled:</p>
<pre><code> private void OnBackgroundWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("BackgroundWorker was cancelled.", "Operation Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("BackgroundWorker operation failed: \n{0}", e.Error), "Operation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("BackgroundWorker completed.", "Operation Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ResetBackgroundWorker();
}
private void ResetBackgroundWorker()
{
BackgroundWorkerProgressBar.Value = 0;
StartBackgroundWorkerButton.Enabled = true;
CancelBackgroundWorkerButton.Enabled = false;
}
#endregion
</code></pre>
<hr />
<h3>#region Task</h3>
<p>I don't get to write this kind of code very often, so I'm very interested in this part. I declared a private field and handled the <code>Click</code> event like this:</p>
<pre><code> CancellationTokenSource _cancelTokenSource;
private void StartTaskButton_Click(object sender, EventArgs e)
{
StartTaskButton.Enabled = false;
_cancelTokenSource = new CancellationTokenSource();
var token = _cancelTokenSource.Token;
var task = Task.Factory.StartNew(DoWork, token);
task.ContinueWith(t =>
{
switch (task.Status)
{
case TaskStatus.Canceled:
MessageBox.Show("Async task was cancelled.", "Operation Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case TaskStatus.Created:
break;
case TaskStatus.Faulted:
MessageBox.Show(string.Format("Async task failed: \n{0}", t.Exception), "Operation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case TaskStatus.RanToCompletion:
MessageBox.Show("Async task completed.", "Operation Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
case TaskStatus.Running:
break;
case TaskStatus.WaitingForActivation:
break;
case TaskStatus.WaitingForChildrenToComplete:
break;
case TaskStatus.WaitingToRun:
break;
default:
break;
}
ResetTask();
_cancelTokenSource = null;
});
}
</code></pre>
<p><strong>DoWork Action</strong></p>
<p>Instead of inlining the <code>DoWork</code> method, I wrote it as a <code>private void</code> parameterless method:</p>
<pre><code> private void DoWork()
{
// CancelTaskButton.Enabled = true; // fails the background thread.
Invoke((MethodInvoker)(() => { CancelTaskButton.Enabled = true; }));
var iterations = 5;
for (var i = 1; i <= iterations; i++)
{
_cancelTokenSource.Token.ThrowIfCancellationRequested();
_service.SomeMethod();
_cancelTokenSource.Token.ThrowIfCancellationRequested();
var progress = 100 / (iterations) * i;
Invoke((MethodInvoker)(() => { TaskProgressBar.Value = progress; }));
if (i == iterations)
{
Invoke((MethodInvoker)(() => { CancelTaskButton.Enabled = false; }));
}
}
Thread.Sleep(500); // let the progressbar animate to display its actual value.
}
</code></pre>
<p><strong>Cancellation</strong></p>
<p>In the <code>Click</code> handler for the <kbd>Cancel</kbd> button, I called <code>Cancel()</code> on the token source:</p>
<pre><code> private void CancelTaskButton_Click(object sender, EventArgs e)
{
CancelTaskButton.Enabled = false;
// token source is null if Close button is clicked without task started
if (_cancelTokenSource != null)
{
_cancelTokenSource.Cancel();
}
}
private void ResetTask()
{
Invoke((MethodInvoker)(() =>
{
TaskProgressBar.Value = 0;
StartTaskButton.Enabled = true;
CancelTaskButton.Enabled = false;
}));
}
#endregion
</code></pre>
<hr />
<p><img src="https://i.stack.imgur.com/UNChp.png" alt="Both jobs can be cancelled." /></p>
<p>Of course this is just an exercise. The question is, is it well conducted? Are there suspicious patterns in the coding style?</p>
<p><strong>In the BGW code</strong>, I don't like that I'm accessing <code>_worker.CancellationPending</code>, but it works (the <code>CancellationPending</code> property must be <em>thread-safe</em> then). Is this correct usage?</p>
<p><strong>In the TPL code</strong>, I don't like that <code>switch (task.Status)</code> block. That can't be the best way to go about it?!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T22:13:01.367",
"Id": "70877",
"Score": "1",
"body": "BTW, you might be interested in [Stephen Cleary's *Task.Run vs BackgroundWorker* series](http://blog.stephencleary.com/2013/09/taskrun-vs-backgroundworker-conclusion.html) (unless you already read that and it was what prompted this)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T22:36:13.977",
"Id": "70879",
"Score": "1",
"body": "Thanks! It's actually aimed at showing a fellow reviewer how to deal with progressbar in C# / WinForms - I hope it does a not-so-bad job at it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T22:45:45.000",
"Id": "70880",
"Score": "2",
"body": "I originally wanted the task code to `.ContinueWith` and show the appropriate message box, but couldn't get it to work, so I resorted to switching on `task.Status`."
}
] |
[
{
"body": "<p>It does show very good example for the progressbar in WinForms. \nHere are my code-review outputs for you.</p>\n\n<ul>\n<li>Closebutton_Click calls the other click \"handlers\". This is not the common way. Implement another method and call it from those handlers.</li>\n<li>I couldnt understand the logic why are you asking the cancellation before and after invoking the DoSomething(). </li>\n<li>Reduce synchronization. Try to \"synchron\" your threads at once. Optimize method invocation delegate for progressbar.value and the canceltaskbutton.enabled.</li>\n<li>Your .ContinueWith approach is good. But always eliminate 'switch’s from your code. Here would be a dictionary very handy. You can define your status-action set before hand and .ContinueWith status keyed action. This would reduce the complexity and increase the readability of your code.</li>\n<li><p>On the OnBackgroundWorkerCompleted method, the Else-if should be separated from the first if-expression. (Again complexity and readability) Please see following code.</p>\n\n<pre><code>if (e.Error != null)\n{\n // Handle Error and call reset.\n return; \n}\n\nif (e.Cancelled)\n{\n // Handle cancel and call reset.\n return;\n}\n\n\nif (e.Result == null)\n{\n // No Result\n}\nelse\n{\n // Result\n}\n\n// reset ...\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T00:27:08.167",
"Id": "70884",
"Score": "1",
"body": "+1 Nice review. The 2nd cancellation check is to avoid updating the progressbar if cancellation is pending. Without it the user has to wait for the progressbar animation to complete before they get the \"Operation Cancelled\" message box."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T00:22:19.073",
"Id": "41302",
"ParentId": "41295",
"Score": "6"
}
},
{
"body": "<ol>\n<li>I think the <code>OnXxxxxx</code> naming for event handlers is more common, so <code>StartBackgroundWorkerButton_Click</code> should probably be <code>OnStartClicked</code> or something. Either way, you should choose single naming notation and stick to it.</li>\n<li><pre><code>private void CloseButton_Click(object sender, EventArgs e)\n{\n CancelBackgroundWorkerButton_Click(null, EventArgs.Empty);\n CancelTaskButton_Click(null, EventArgs.Empty);\n Close();\n}\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>private void CloseButton_Click(object sender, EventArgs e)\n{\n CancelBackgroundWorker();\n CancelTask();\n Close();\n}\n\nprivate void CancelBackgroundWorkerButton_Click(object sender, EventArgs e)\n{\n CancelBackgroundWorker();\n}\n</code></pre></li>\n<li><pre><code>if (BackgroundWorkerProgressBar.Value == BackgroundWorkerProgressBar.Maximum)\n{\n CancelBackgroundWorkerButton.Enabled = false;\n}\n</code></pre>\n\n<p>I think this is a bad idea. If you want do disable a cancel button when bgw finished working - then you should do so in appropriate event handler (and you already do!). Doing so depending on progress bar state is a lousy solution.</p></li>\n<li><p>I don't get this <code>switch</code> hate i see everywhere. Yes, you can replace it with <code>Dictionary</code>, yes, it will look more <a href=\"http://b.vimeocdn.com/ts/402/654/40265458_640.jpg\" rel=\"nofollow\">fabulous</a>. But frankly, there is no difference what so ever in such simple case. I would even prefer a <code>switch</code> (or <code>if-else</code>) solution, because it does not force me to go look for actual mapping somewhere else. <code>switch</code> is there for a reason and it is certainly not something you should \"always eliminate\". What you can do is remove empty <code>case</code>s, the <code>default:</code> operator should deal with those. </p></li>\n<li><pre><code> if (i == iterations)\n {\n Invoke((MethodInvoker)(() => { CancelTaskButton.Enabled = false; }));\n }\n</code></pre>\n\n<p>You can simply call <code>Invoke</code> outside the loop.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T22:50:19.170",
"Id": "71026",
"Score": "1",
"body": "Behavioral mappings via switch-case should be \"eliminated\". There are many reasons for that. Readability, [Complexity](http://en.wikipedia.org/wiki/Cyclomatic_complexity), Extensibility, ... The statement 'always' might be to much though :) [See also this](http://stackoverflow.com/questions/7264145/if-less-programming-basically-without-conditionals)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:33:38.370",
"Id": "71217",
"Score": "1",
"body": "@Kaan, well, yes and no. I do agree that `Dictionary` is more extendable and flexible solution. If you require those two - then by all means - go for it. I this code sample it is not the case though. I do not think that `switch` is less readable than dictionaries. Its the opposite, imho. And i fail to see how does complexity differs between the two approaches. In general i think that the sipliest solution is the best (YAGNI, right?). But nowadays, i guess, its all about building frameworks :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:52:42.523",
"Id": "41328",
"ParentId": "41295",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41302",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T21:09:29.680",
"Id": "41295",
"Score": "13",
"Tags": [
"c#",
"asynchronous",
"winforms",
"task-parallel-library"
],
"Title": "BackgroundWorker vs TPL ProgressBar Exercise"
}
|
41295
|
<p>Is it possible to write this in fewer lines of code?</p>
<p>If you input an integer it will output it as an ordinal number if it is less than 100. The below code works perfectly, but I'm wondering if it could be written more succinctly.</p>
<pre><code>def ordinal(self, num):
"""
Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.
"""
self.num = num
n = int(self.num)
if 4 <= n <= 20:
suffix = 'th'
elif n == 1 or (n % 10) == 1:
suffix = 'st'
elif n == 2 or (n % 10) == 2:
suffix = 'nd'
elif n == 3 or (n % 10) == 3:
suffix = 'rd'
elif n < 100:
suffix = 'th'
ord_num = str(n) + suffix
return ord_num
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T03:41:44.447",
"Id": "70887",
"Score": "0",
"body": "Off topic (As this is a python question, not .net), But https://github.com/MehdiK/Humanizer has extension methods to do this kind of thing nicely e.g., `1.Ordinalize() == \"1st\"` or `\"21\".Ordinalize() == \"21st\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-17T12:28:34.067",
"Id": "369298",
"Score": "0",
"body": "Yes, it's possible: `using num2words; def ordinal(num): num2words(num, to=ordinal_num, lang=en)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-31T17:03:44.710",
"Id": "398686",
"Score": "0",
"body": "*Fewer lines of code*\" is rarely a worthwhile objective; **clear** and **efficient** usually trump **short**."
}
] |
[
{
"body": "<p>You can simplify the repeated <code>n == 1 or (n % 10) == 1</code>, as well as special-case test for <code>11th</code>, <code>12th</code>, and <code>13th</code>, by using a <a href=\"https://stackoverflow.com/a/394814/49942\">ternary expression</a>;</p>\n\n<p>So:</p>\n\n<pre><code>i = n if (n < 20) else (n % 10)\nif i == 1:\n suffix = 'st'\nelif i == 2:\n suffix = 'nd'\nelif i == 3:\n suffix = 'rd'\nelif n < 100:\n suffix = 'th'\n</code></pre>\n\n<p>I think you can also use a dictionary:</p>\n\n<pre><code>suffixes = { 1: \"st\", 2: \"nd\", 3: \"rd\" }\ni = n if (n < 20) else (n % 10)\nif 0 < i <= 3:\n suffix = suffixes[i]\nelif n < 100:\n suffix = 'th'\n</code></pre>\n\n<p>Or use <a href=\"http://www.tutorialspoint.com/python/dictionary_get.htm\" rel=\"nofollow noreferrer\">dictionary get</a> which lets you supply a default value:</p>\n\n<pre><code>suffixes = { 1: \"st\", 2: \"nd\", 3: \"rd\" }\ni = n if (n < 20) else (n % 10)\nsuffix = suffixes.get(i, 'th')\n</code></pre>\n\n<p>Maybe you can reduce it to one line of code:</p>\n\n<pre><code>suffix = { 1: \"st\", 2: \"nd\", 3: \"rd\" }.get(n if (n < 20) else (n % 10), 'th')\n</code></pre>\n\n<p>(Beware the above may be buggy because I don't know Python).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T23:35:55.327",
"Id": "41300",
"ParentId": "41298",
"Score": "8"
}
},
{
"body": "<pre><code>def ordinal(self, num):\n \"\"\"\n Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.\n \"\"\"\n</code></pre>\n\n<p>Its suspicious that this seems to be a method rather than a free standing function. </p>\n\n<pre><code> self.num = num\n</code></pre>\n\n<p>Why are you storing the input here? Given the purpose of this function that seems odd.</p>\n\n<pre><code> n = int(self.num)\n</code></pre>\n\n<p>Its doubtful that this is a good idea. What are you converting from? Converting to int should be really be done closer to whether this number came from.</p>\n\n<pre><code> if 4 <= n <= 20:\n</code></pre>\n\n<p>You've made this case larger than necessary, many of those would be correct even with out this test, and its not clear what so special about the range 4-20.</p>\n\n<pre><code> suffix = 'th'\n elif n == 1 or (n % 10) == 1:\n</code></pre>\n\n<p>You don't need the or. If n == 1, then that the second condition will be true anyways.</p>\n\n<pre><code> suffix = 'st'\n elif n == 2 or (n % 10) == 2:\n suffix = 'nd'\n elif n == 3 or (n % 10) == 3:\n suffix = 'rd'\n elif n < 100:\n suffix = 'th'\n</code></pre>\n\n<p>What happens if suffix is >= 100? You'll get an error.</p>\n\n<pre><code> ord_num = str(n) + suffix\n return ord_num\n</code></pre>\n\n<p>You don't need to split this across two lines.</p>\n\n<p>Here is my version:</p>\n\n<pre><code># much code can be improved by using a datastructe.\nSUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}\ndef ordinal(num):\n # I'm checking for 10-20 because those are the digits that\n # don't follow the normal counting scheme. \n if 10 <= num % 100 <= 20:\n suffix = 'th'\n else:\n # the second parameter is a default.\n suffix = SUFFIXES.get(num % 10, 'th')\n return str(num) + suffix\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:57:45.513",
"Id": "70893",
"Score": "0",
"body": "You are right about this looking like a method. I actually had this as part of a class. I just pulled it out and pasted it here. I should have functionalized it. Sorry about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:29:13.407",
"Id": "70902",
"Score": "0",
"body": "The n was used to simplify and reduce the number of characters from \"self.num\" to \"n\". 4 to 20 is special because it is a big block of 'th' suffixes. I actually saw that in an example I found in a tutorial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T06:41:08.703",
"Id": "70906",
"Score": "0",
"body": "This is perfect! I've already incorporated it into my script and it worked great."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:54:22.177",
"Id": "70940",
"Score": "2",
"body": "here it is in one line (the implementation is identical): `ordinal = lambda n: str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(10<=n%100<=20 and n or n % 10, 'th')`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:25:46.047",
"Id": "70972",
"Score": "1",
"body": "It's worth mentioning that opinions vary on doing calculations in the `return`. Many people (myself included) tend to prefer returning only results, although the shorter the function the less it tends to matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T01:56:40.713",
"Id": "71033",
"Score": "2",
"body": "@DSM, out of curiosity, why? From my perspective it seems that assigning to a local just to return seems pointless."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T00:16:08.347",
"Id": "41301",
"ParentId": "41298",
"Score": "27"
}
}
] |
{
"AcceptedAnswerId": "41301",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T22:41:01.643",
"Id": "41298",
"Score": "21",
"Tags": [
"python"
],
"Title": "Producing ordinal numbers"
}
|
41298
|
<p>While trying to teach myself C, I decided to take a stab at writing this Tic-Tac-Toe program on a 4x4 board. It will be great if somebody could review it and let me know of some ways of refining this.</p>
<pre><code>#include <stdio.h>
#include <stddef.h>
typedef struct {
int xpos;
int ypos;
} BRDPOS;
void printBoard(int brd_size,char board[][brd_size]){
int i,j;
for(i = 0;i < brd_size;i++){
for(j = 0;j < brd_size;j++){
if(j == 0) printf("| ");
printf("%c |",(char)board[i][j]);
if(j == (brd_size - 1)){
printf("\n");
}
}
}
}
BRDPOS getPosition(int brd_size,char board[][brd_size]){
//Enter Positions X and Y
BRDPOS pos;
int x,y;
do{
printf("Enter the x-position:");
scanf("%d",&x);
printf("\nEnter the y-position:");
scanf("%d",&y);
printf("\n");
}while(board[x][y] != ' ');
pos.xpos = x;
pos.ypos = y;
return pos;
}
void updateBoard(int brd_size,char board[][brd_size],BRDPOS pos,int player){
if(player == 0){
board[pos.xpos][pos.ypos] = 'X';
}else{
board[pos.xpos][pos.ypos] = 'O';
}
}
int isWinningPosition(BRDPOS position,int brd_size,char brd[][brd_size],int player){
char posChar = (player == 0)? 'X':'Y';
int xPos = position.xpos;
int yPos = position.ypos;
char yStatus = brd[0][0];
char majDiag = brd[0][0];
char minDiag = brd[0][brd_size-1];
int xstatus = 0;
int ystatus = 0;
int majdiag = 0;
int mindiag = 0;
int i,j,k,l;
for(i=0;i< brd_size;i++){
if(brd[xPos][yPos] == brd[xPos][i]){
xstatus = 1;
}else{
xstatus = 0;
break;
}
}
//Check if the horizontal has the same characters
for(j=0;j<brd_size;j++){
if(brd[xPos][yPos] == brd[j][yPos]){
ystatus = 1;
}else{
ystatus = 0;
break;
}
}
//Check if the major diagonal has the same characters
if(xPos == yPos){
for(k=0;k < brd_size;k++){
if(majDiag == brd[k][k]){
majdiag = 1;
}else{
majdiag = 0;
break;
}
}
}
//Check if the minor diagonal has the same characters
if(xPos == (brd_size - 1 - yPos)){
for(l = 1;l < brd_size;l++){
if(minDiag == brd[l][(brd_size-1) - l]){
mindiag = 1;
} else {
mindiag = 0;
break;
}
}
}
return xstatus|ystatus|majdiag|mindiag;
}
int main()
{
//Flag to indicate the current player 0 for A, 1 for B. Default to A
int player = 0;
//Flag to indicate the winner, -1 for no winner, 0 for A, 1 for B
int winner = -1;
//Counter to indicate the total number of turns
int counter = 0;
//Tic-Tac-Toe board
char board[4][4];
int i,j;
for(i = 0;i<4;i++){
for(j = 0;j<4;j++){
board[i][j] = ' ';
}
}
//Keep iterating until a winner is found and the cell count is less than 16
while((winner == -1) && (counter < 16)){
//Print the tic-tac-toe board
printBoard(4,board);
//Ask position to place the X for player 1
//getPosition keeps asking for the position until a legal position has been entered
printf("Enter positions for PlayerA:\n");
BRDPOS positionA = getPosition(4,board);
//Update board with positionA
printf("Updating the board:\n");
updateBoard(4,board,positionA,0);
//Check if the updated position is a winning position
if(isWinningPosition(positionA,4,board,0)){
//Mark player A as the winner
printf("Marking player A as the winner \n");
winner = 0;
break;
}
//update the move counter
counter++;
//print updated board
printBoard(4,board);
//Ask position to place the 'O' for player 2
printf("Enter position for PlayerB:\n");
BRDPOS positionB = getPosition(4,board);
//Update board with positionB
updateBoard(4,board,positionB,1);
//Check if the updated position is a winning position
if(isWinningPosition(positionB,4,board,1)){
winner = 1;
break;
}
//update the move counter
counter++;
}
//print the final board configuration
printBoard(4,board);
switch(winner){
case -1: printf("The game is a draw!\n");
break;
case 0: printf("Player 1 has won the game\n");
break;
case 1: printf("Player 2 has won the game\n");
break;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:49:24.847",
"Id": "70889",
"Score": "1",
"body": "The `struct` name should only *start* with an uppercase letter. Having the entire name in caps makes it appear as a macro."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:51:38.803",
"Id": "70892",
"Score": "0",
"body": "Does this code work as intended? The board isn't showing up properly for me when I run this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:58:33.207",
"Id": "70895",
"Score": "0",
"body": "@syb0rg Works for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:00:31.043",
"Id": "70897",
"Score": "0",
"body": "@200_success Odd. I'll work with it anyways I guess :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T08:54:05.263",
"Id": "70914",
"Score": "0",
"body": "@syb0rg It crashes [here](http://coliru.stacked-crooked.com/a/99c6a6e7f2432c66)."
}
] |
[
{
"body": "<h2>General:</h2>\n\n<p>I myself am writing a <a href=\"https://codereview.meta.stackexchange.com/q/1471\">Tic-Tac-Toe game of sorts</a>, so I am go to try to not give my code away too much. For a self-taught beginning C programmer, this code looks good. However, it looks like you were over thinking things a bit based on how long your code is.</p>\n\n<hr>\n\n<h2>What you did well on:</h2>\n\n<ul>\n<li><p>You kept your dependencies at a minimum (for the most part).</p></li>\n<li><p>You attempt to use comments to describe what your thought process is and how the program works.</p></li>\n<li><p>You used <code>typedef</code> with your <code>struct</code> properly.</p></li>\n<li><p>You used a <code>switch</code> instead of multiple <code>if-else</code> test conditions (very good!).</p></li>\n</ul>\n\n<hr>\n\n<h2>Things you could improve on:</h2>\n\n<ul>\n<li><p>You unnecessarily <code>#include <stddef.h></code>.</p></li>\n<li><p>You aren't using the characters that correspond with a Tic-Tac-Toe game.</p>\n\n<blockquote>\n<pre><code> char posChar = (player == 0)? 'X':'Y';\n</code></pre>\n</blockquote>\n\n<p>I don't see any reason to not use the <code>X</code>'s and <code>O</code>'s. We want to be as user-experience friendly as possible to lowering the initial learning curve for first time users.</p>\n\n<pre><code>char posChar = (player == 0) ? 'X' : 'O';\n</code></pre></li>\n<li><p>Your name of the <code>typedef struct</code> is not how the usual programmer would name it.</p>\n\n<blockquote>\n<pre><code> typedef struct {\n int xpos;\n int ypos;\n } BRDPOS;\n</code></pre>\n</blockquote>\n\n<p>Right now you are using the naming standards that coincide with naming a macro. Here is how I would name a similar struct.</p>\n\n<pre><code>typedef struct\n{\n int xPos;\n int yPos;\n} BoardPosition;\n</code></pre></li>\n<li><p>You have some unused variables: <code>posChar</code>, <code>yStatus</code>, and <code>player</code>. Get rid of them.</p></li>\n<li><p>I would <code>#define</code> your board size at the top.</p>\n\n<pre><code>#define ROWS 4\n#define COLS 4\n</code></pre></li>\n<li><p>You always set some variables in a function to your <code>struct</code> values.</p>\n\n<pre><code> int xPos = position.xpos;\n int yPos = position.ypos;\n</code></pre>\n\n<p>I'm not seeing the purpose of using these local variables at all. I would remove them and use the direct <code>struct</code> values in their place.</p></li>\n<li><p>Initialize variables in your <code>for</code> loop, not outside of them.<sup>(C99)</sup></p>\n\n<pre><code>for (int row = 0; row < ROWS; row++)\n</code></pre></li>\n<li><p>Your comments are sporadic. Also, some areas have too many comments.</p>\n\n<blockquote>\n<pre><code> //Ask position to place the X for player 1\n //getPosition keeps asking for the position until a legal position has been entered\n printf(\"Enter positions for PlayerA:\\n\");\n BRDPOS positionA = getPosition(4,board);\n</code></pre>\n</blockquote>\n\n<p>Here is an example of where I think you are saying too much with your comments. Some code can speak for itself. However, in other areas you have no comments at all.</p>\n\n<blockquote>\n<pre><code> return xstatus|ystatus|majdiag|mindiag;\n</code></pre>\n</blockquote>\n\n<p>Some people may not know what the bitwise operator <code>|</code> does. You should comment more in areas like these that may be more confusing to newer developers.</p></li>\n<li><p>You could use the function <code>puts()</code> in place of your <code>printf()</code>.</p>\n\n<blockquote>\n<pre><code> printf(\"Enter position for PlayerB:\\n\");\n</code></pre>\n</blockquote>\n\n<p>Using <code>puts()</code> is a bit better in my mind. Then you don't have to worry about the <code>\\n</code> character at the end.</p>\n\n<pre><code>puts(\"Enter position for PlayerB: \");\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:05:22.720",
"Id": "71009",
"Score": "0",
"body": "btw. out of interest, does it make sense to play this kind of 4x4 tic tac toe game? I think this is very easy not to let someone win here. (For learning purposes I know it's ok, I am asking for the sake of playing)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T22:35:13.593",
"Id": "71023",
"Score": "0",
"body": "@hanalbuseltes I think it makes sense to play, sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T07:00:18.720",
"Id": "71067",
"Score": "0",
"body": "@syb0rg - Thanks for taking the time to provide a detailed review. Learned quite a bit from your and 200_success's review."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:43:22.677",
"Id": "41309",
"ParentId": "41304",
"Score": "15"
}
},
{
"body": "<p>I see no major memory-handling or parameter-passing errors, which is pretty good for a self-taught C novice.</p>\n\n<hr>\n\n<p>First, let the compiler do the reviewing…</p>\n\n<blockquote>\n<pre><code>$ clang -Wall -g -o tictactoe cr41304.c \ncr41304.c:47:10: warning: unused variable 'posChar' [-Wunused-variable]\n char posChar = (player == 0)? 'X':'Y';\n ^\ncr41304.c:50:10: warning: unused variable 'yStatus' [-Wunused-variable]\n char yStatus = brd[0][0];\n ^\ncr41304.c:103:9: warning: unused variable 'player' [-Wunused-variable]\n int player = 0;\n ^\n3 warnings generated.\n</code></pre>\n</blockquote>\n\n<p><code>yStatus</code> is particularly bad: having variables named <code>yStatus</code> and <code>ystatus</code> in the same function is confusing.</p>\n\n<hr>\n\n<p>The user experience could use some polishing.</p>\n\n<ul>\n<li>The first column is inexplicably wider than the others.</li>\n<li>Your terminology is inconsistent: \"PlayerA\"/\"PlayerB\" when prompting <em>vs.</em> \"Player 1\"/\"Player 2\" when announcing the winner. (In your code, you also call them players 0 and 1.) I suggest \"Player X\" and \"Player O\".</li>\n<li><p>This statement appears to be left over from development:</p>\n\n<pre><code>printf(\"Marking player A as the winner \\n\");\n</code></pre></li>\n<li>\"Row\" and \"column\" would be clearer than \"x-position\" and \"y-position\".</li>\n<li>Zero-based numbering is unusual. To eliminate ambiguity, label the rows and columns when printing the board.</li>\n</ul>\n\n<hr>\n\n<p>You fail to check the return value from <code>scanf()</code> for <kbd>EOF</kbd>. If <kbd>EOF</kbd> is encountered, it goes into an infinite loop.</p>\n\n<hr>\n\n<p>Your main loop contains copy-and-pasted code for each player. You should be able to restructure your code to avoid repeating yourself.</p>\n\n<p>Your functions all take their parameters in a different order. Try to be consistent.</p>\n\n<p><code>updateBoard()</code> could be shorter.</p>\n\n<pre><code>void updateBoard(int brd_size, char board[][brd_size], BRDPOS pos, int player) {\n assert(player == 0 || player == 1);\n board[pos.xpos][pos.ypos] = \"XO\"[player];\n}\n</code></pre>\n\n<p><code>isWinningPosition()</code> could also be shorter. Avoid using so many variables. Declare your dummy variables in a tighter scope (which you can do since you're using C99). Return early as soon as you find a win. I believe your <code>//Check if the horizontal has the same characters</code> comment is wrong as well — that loop is actually checking for a vertical win.</p>\n\n<pre><code>int isWinningPosition(BRDPOS position,int brd_size,char brd[][brd_size],int player){\n int xPos = position.xpos;\n int yPos = position.ypos;\n\n // Check for horizontal win\n int win = 1;\n for (int y = 0; win && (y < brd_size); y++) {\n if (brd[xPos][yPos] != brd[xPos][y]) {\n win = 0;\n }\n }\n if (win) return 1;\n\n // Check for vertical win\n win = 1;\n for (int x = 0; win && (x < brd_size); x++) {\n if (brd[xPos][yPos] != brd[x][yPos]) {\n win = 0;\n }\n }\n if (win) return 1;\n\n // Check if the major diagonal has the same characters\n win = (xPos == yPos);\n for (int x = 0; win && (x < brd_size); x++) {\n if (brd[xPos][yPos] != brd[x][x]){\n win = 0;\n }\n }\n if (win) return 1;\n\n // Check if the minor diagonal has the same characters\n win = (xPos == (brd_size - 1 - yPos));\n for (int x = 0; win && (x < brd_size); x++) {\n if (brd[xPos][yPos] != brd[x][(brd_size-1) - x]){\n win = 0;\n }\n }\n return win;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:48:08.320",
"Id": "41310",
"ParentId": "41304",
"Score": "7"
}
},
{
"body": "<p>I guess you could change all this code:</p>\n\n<pre><code> while((winner == -1) && (counter < 16)){\n //Print the tic-tac-toe board\n printBoard(4,board);\n //Ask position to place the X for player 1\n //getPosition keeps asking for the position until a legal position has been entered\n printf(\"Enter positions for PlayerA:\\n\");\n BRDPOS positionA = getPosition(4,board);\n //Update board with positionA\n printf(\"Updating the board:\\n\");\n updateBoard(4,board,positionA,0);\n //Check if the updated position is a winning position\n if(isWinningPosition(positionA,4,board,0)){\n //Mark player A as the winner\n printf(\"Marking player A as the winner \\n\");\n winner = 0;\n break;\n }\n //update the move counter\n counter++;\n //print updated board\n printBoard(4,board);\n //Ask position to place the 'O' for player 2\n printf(\"Enter position for PlayerB:\\n\");\n BRDPOS positionB = getPosition(4,board);\n //Update board with positionB\n updateBoard(4,board,positionB,1);\n //Check if the updated position is a winning position \n if(isWinningPosition(positionB,4,board,1)){\n winner = 1;\n break;\n }\n //update the move counter\n counter++;\n }\n</code></pre>\n\n<p>to only this:</p>\n\n<pre><code> while((winner == -1) && (counter < 16)){\n //Print the tic-tac-toe board\n printBoard(4,board);\n //Ask position to place the X for player 1\n //getPosition keeps asking for the position until a legal position has been entered\n printf(\"Enter positions for PlayerA:\\n\");\n BRDPOS position = getPosition(4,board);\n //Update board with positionA\n printf(\"Updating the board:\\n\");\n updateBoard(4,board,position,counter%2);// change\n //Check if the updated position is a winning position\n if(isWinningPosition(position,4,board,counter%2)){// change\n winner = counter%2;// change\n break;\n }\n\n counter++;\n }\n</code></pre>\n\n<p>the changes occur due to using: <code>counter%2</code></p>\n\n<p>In the initial code, you had <em>two</em> very similar pieces of code, with only difference that once you would pass 0 and other times 1 to certain functions depending on who was playing. You were deducing who was playing sort of manually, which is ok, this is a consecutive game - at first one player plays, at the next step another player. But this consecutive nature you can exploit also using the % operator. You already had <code>counter</code> variable. Do it modulo 2, and once you get 1 and other time 0. Now you can use <code>counter%2</code> instead of manually passing 1 and 0s.</p>\n\n<pre><code>0%2=0\n1%2=1\n2%2=0\n3%2=1\n4%2=0\n....\netc.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:34:49.060",
"Id": "71005",
"Score": "0",
"body": "Could you explain *why* you would change it? **Show** the OP your changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:48:32.460",
"Id": "71006",
"Score": "0",
"body": "@syb0rg: I mentioned where, I just don't know how to format in code so that it is more visible... as to why,I guess less code/redundancy"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T00:01:45.393",
"Id": "71030",
"Score": "0",
"body": "Ahh, much better. Upvote given."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T19:00:53.487",
"Id": "41354",
"ParentId": "41304",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41309",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T01:25:48.907",
"Id": "41304",
"Score": "12",
"Tags": [
"c",
"game",
"tic-tac-toe"
],
"Title": "4×4 Tic-Tac-Toe in C"
}
|
41304
|
<p>I am building a Chrome extension that injects a small overlay in to all websites using a content script. At this point all the injected elements do is sit in the bottom left corner. It has two buttons the top one produces another element and the button one doesn't do anything. The extra element has a button that closes itself, and a text box.</p>
<p>This is my first major JavaScript/Chrome extension project, so my main concerns are:</p>
<ul>
<li><p>Don't violate chrome extension rules that will caused deprecated code or the like</p></li>
<li><p>Given that I am inserting new code into a website I want to make sure that this is as efficient as possible as to minimize strain on Chrome.</p></li>
</ul>
<p><strong>Basic Injection</strong></p>
<blockquote>
<p><img src="https://i.stack.imgur.com/OSDs6.png" alt="Basic Injection"></p>
</blockquote>
<p><strong>Injection after '+' pressed</strong></p>
<blockquote>
<p><img src="https://i.stack.imgur.com/W5XY0.png" alt="Injection after '+' pressed"></p>
</blockquote>
<p><strong>Manifest.json</strong></p>
<pre><code>{
"name": "injection",
"description": "samples at code injection",
"version": "1",
"manifest_version": 2,
"content_scripts": [
{
"matches": [ "<all_urls>"],
"css":["style.css"],
"js":["jquery-2.1.0.min.js", "index.js"]
}
],
"permissions": [ "<all_urls>", "storage" ]
}
</code></pre>
<p><strong>index.js</strong></p>
<pre><code> $(function(){
//$(".add_button").click(add_timeline_element);
function add_timeline_element(){
var text_input = $('<input />', {
type: "text",
class: "t_text_area"
});
var button = $('<button />', {
text: '-',
class: "t_intect_button",
click: function() {$(this).parent().remove();}
});
var timeline_element = $('<td />', {
class: "timeline_element"
});
timeline_element.append(button);
timeline_element.append(text_input);
$(".t_inject_row").append(timeline_element);
}
function minimize_t_inject_container(){
$(".add_button").toggle();
}
function create_twitter_bar(){
var table_container = $("<table />", {
class: "t_inject_container"
});
var row = $("<tr />", {
class: "t_inject_row"
});
var menu = $("<td />", {
class: "menu"
});
var add_element_button = $("<button />", {
text: '+',
class: "add_button t_intect_button",
click: function() {add_timeline_element();}
});
var minimize_button = $("<button />", {
text: 'm',
click: function() {minimize_t_inject_container();},
class: "minimize_button t_intect_button"
});
menu.append(add_element_button);
menu.append(minimize_button);
row.append(menu);
table_container.append(row);
$('body').append(table_container);
}
create_twitter_bar();
var scroll_point = 0;
var done_scrolling;
var counting = "false";
var time_counter = 0.00;
var consecutive_scrolls = 0.00;
var scroll_ending = function () {
console.log("done scrolling");
clearInterval(counting);
counting = "false";
time_counter = 0.00;
}
$(document).scroll(function() {
var new_scroll_point = $(document).scrollTop();
var scroll_delta = scroll_point - new_scroll_point;
if(scroll_delta < 0){
scroll_delta = scroll_delta * (-1);
}
scroll_point = new_scroll_point;
if(counting=="false"){
counting = setInterval(function(){
time_counter += 0.1;
}, 100);
} else{
var scroll_over_time = scroll_delta/time_counter;
console.log("scrolling over time:"+ scroll_over_time);
clearTimeout(done_scrolling);
done_scrolling = setTimeout(scroll_ending, 150);
if(scroll_over_time > 400 && scroll_over_time < 3000){
$(".add_button").hide();
}
}
});
});
</code></pre>
<p><strong>style.css</strong></p>
<pre><code> /*----------------*/
/*----Main Page---*/
/*----------------*/
.t_inject_container
{
position:fixed;
bottom:0px;
left:0px;
z-index: 999;
background-color:grey;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
}
.menu {
background-color:lightblue;
border-radius:5px;
}
.t_intect_button {
background-color:blue;
display:block;
height: 50px;
width: 50px;
margin: 5px;
font-size: 20px;
color: white;
border: 0px;
border-radius:7px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
border-radius:5px;
}
/*-----------------*/
/*Timeline Element*/
/*----------------*/
.timeline_element {
background-color:red;
border-radius:5px;
}
.t_text_area {
height: 50px;
width: 100px;
}
</code></pre>
<p>Here is a working <a href="http://jsfiddle.net/easilyBaffled/7gC4X/" rel="nofollow noreferrer">JSFiddle</a>.</p>
<p>The 'm' button on the main menu has been shrunk down, and now works. It minimizes and resizes the menu. I don't think this can be tested in the jsfiddle, but if you scroll quickly it will also minimize the menu.</p>
<p>The following is what the DOM looks like (copied from the JSFiddle using Chrome's Web Inspector):</p>
<pre><code><html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by easilyBaffled</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
/*----------------*/
/*----Main Page---*/
/*----------------*/
// ... PLUS OTHER CSS AS SHOWN IN SOURCE CODE BELOW ...
</style>
<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$(function(){
//$(".add_button").click(add_timeline_element);
// ... PLUS OTHER JAVASCRIPT AS SHOWN IN SOURCE CODE BELOW ...
});
});
});//]]>
</script>
</head>
<body>
<table class="t_inject_container"><tbody><tr class="t_inject_row"><td class="menu"><button class="add_button t_intect_button">+</button><button class="minimize_button t_intect_button">m</button></td></tr></tbody></table></body></html>
</code></pre>
|
[] |
[
{
"body": "<p>Some notes on your CSS:</p>\n\n<ol>\n<li><p>You can apply the <code>box-sizing</code> declaration to all the elements in your container:</p>\n\n<pre><code>.t_inject_container,\n.t_inject_container * {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n</code></pre></li>\n<li><p>Ommit the units if you have zero values like <code>0px</code>: <code>bottom: 0;</code>, <code>left: 0;</code>, …</p></li>\n<li>In your rule declaration for <code>.t_inject_button</code> you use the <code>border-radius</code> property two times. I guess you were overlooking it and this is not on purpose?</li>\n<li><p>You repeat your <code>border-radius</code> declaration a few times. Let's make this a bit <em>DRY</em>'er and make an abstraction:</p>\n\n<pre><code>.t_rounded {\n border-radius: 5px;\n}\n</code></pre>\n\n<p>Now apply this class to every element you want to have rounded borders on.</p></li>\n</ol>\n\n<p>Feel free to ask, if you have questions. That's it for now.</p>\n\n<h2>Update (based on the added HTML)</h2>\n\n<ol>\n<li><p>There is no doctype in your code. If there really isn't one, you should really add this before the <code>html</code> tag:</p>\n\n<pre><code><!DOCTYPE html>\n</code></pre></li>\n<li><p>If you use the HTML5 doctype (see above), you can switch to a newer, short charset declaration:</p>\n\n<pre><code><meta charset=\"utf-8\">\n</code></pre></li>\n<li><p>You're using a table to wrap your buttons. Tables are for tabular data. Since you this for layout purposes, use <code>div</code>'s like so:</p>\n\n<pre><code><div class=\"t_inject_container\">\n <ul class=\"menu\">\n <li>\n <button class=\"add_button t_intect_button\">+</button>\n </li>\n <li>\n <button class=\"minimize_button t_intect_button\">m</button>\n </li>\n </ul>\n</div>\n</code></pre>\n\n<p>I also used an unordered list to mark up your navigation. Use the following CSS to normalize the typical list styles:</p>\n\n<pre><code>.menu {\n list-style: none;\n margin: 0;\n padding: 0;\n}\n.menu > li {\n display: inline-block;\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T15:18:12.927",
"Id": "70959",
"Score": "0",
"body": "@EasilyBaffled And I copied the DOM from the fiddle into the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:33:35.770",
"Id": "70977",
"Score": "0",
"body": "@EasilyBaffled Thank you for the demo and the added HTML. I've updated my answer based on this. Ask me, if you have questions. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T03:30:19.960",
"Id": "71045",
"Score": "0",
"body": "The div stuff makes sense, I was using a table because I initially had the menu and add as spans and they weren't lining up properly. As for the html, everything is being injected into existing webpages so I no real control of something like doctype."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T05:46:43.297",
"Id": "71062",
"Score": "1",
"body": "@EasilyBaffled I'm not an expert here. Is your stuff injected via an iframe? How does this work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T11:11:08.347",
"Id": "71079",
"Score": "0",
"body": "nope no iframe necessary. Content scripts, are a specific bit of the Chrome Extension, that allows me to directly affect the DOM of any webpage. In this case 'body' in '$('body').append(table_container);' is the body of what ever is the current tab, and I can add stuff right to it. It's worth noting that I can only access the DOM and not the pages javascript"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:01:07.253",
"Id": "71898",
"Score": "0",
"body": "Regarding the rounded boarder change, more things will have it then won't, so would there be anything wrong with including it in the .t_inject_container *{} and then canceling it out when necessary. For example right now the text box is the only thing that won't have it so I can go into it's css and set border-radius:0;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:10:55.320",
"Id": "71899",
"Score": "0",
"body": "Turns out I didn't need '.menu > li { display: inline-block;}' in this case. I want the buttons in the menu to be on top of each other. But I probably will need that for the extra boxes. The boxes that appear when you click '+' should be inline with the menu, inside the container. So should I make the menu and those boxes li in another list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:19:28.050",
"Id": "71901",
"Score": "0",
"body": "@EasilyBaffled I'd still suggest using a seperate class for the `border-radius`. It doesn't hurt and it's easy to handle. Yes, each navigation should be a seperate list. Same story as with a sub menu. Btw if one of the provided answers (the best one in your opinion) helped you, you should mark it as accepted."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T10:38:16.493",
"Id": "41319",
"ParentId": "41305",
"Score": "10"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>The default for JavaScript is lowerCamelCase, so <code>add_timeline_event</code> -> <code>addTimelineEvent</code> etc. etc.</li>\n<li>You only call <code>minimize_t_inject_container</code> once, so I would inline this one-liner:<br>\n<code>click: function() { $(\".add_button\").toggle();},</code> <br>\nor not in-line it, and point straight to the function:<br>\n<code>click:minimize_t_inject_container,</code></li>\n<li>Same goes for <code>click: function() {add_timeline_element();}</code> you could just<br>\n<code>click: add_timeline_element</code></li>\n<li><p>I would put your <code>var</code> block higher in the code, and use only 1 <code>var</code> :<br></p>\n\n<pre><code>var scroll_point = 0,\n done_scrolling,\n counting = \"false\",\n time_counter = 0.00,\n consecutive_scrolls = 0.00;\n</code></pre></li>\n<li><p>I am not sure why you do not use <code>false</code> instead of <code>\"false\"</code> for <code>counting</code></p></li>\n<li><code>console.log</code> does not belong in production ready code</li>\n<li>You never use <code>consecutive_scrolls</code></li>\n<li><p>You could use <code>scroll_delta = Math.abs(scroll_delta);</code> instead of <br> </p>\n\n<pre><code>if(scroll_delta < 0){\n scroll_delta = scroll_delta * (-1);\n}\n</code></pre>\n\n<p>it is faster and cleaner : <a href=\"http://jsperf.com/math-abs-vs-bitwise/6\" rel=\"nofollow\">http://jsperf.com/math-abs-vs-bitwise/6</a></p></li>\n</ul>\n\n<p>As for your concerns:</p>\n\n<p><em>Don't violate chrome extension rules that will caused deprecated code or the like</em> <br>I think this looks fine.</p>\n\n<p><em>Given that I am inserting new code into a website I want to make sure that this is as efficient as possible as to minimize strain on chrome.</em> <br>\nThere would be less strain if you wrote this without jQuery. Also, now you have to test your extension with sites that already use jQuery ( or use <code>$</code> for other purposes).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T03:33:12.690",
"Id": "71046",
"Score": "0",
"body": "Does the number of vars change efficiency or is it just for readability? As for abs, I was having trouble using it in the extension for some reason, I have yet to explore it further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:30:09.930",
"Id": "71136",
"Score": "1",
"body": "That would be for readability, as for `Math` not being available.. that's odd."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:01:54.810",
"Id": "41341",
"ParentId": "41305",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41319",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T01:45:36.517",
"Id": "41305",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"google-chrome"
],
"Title": "Injection with Chrome extension"
}
|
41305
|
<p>With the help of some people here and there, I wrote the module below which works very well <strong><em>if the file <code>targets.csv</code> is not too big.</em></strong></p>
<p>As soon as this file exceeds 100 MB, a <code>MemoryError</code> is returned.</p>
<p>The problem is that I used <code>numpy</code> to make the computations faster (and they became really fast compared to the previous versions of this module), and I think numpy requires to load the entire file into memory.</p>
<p>However, there should be a way to handle the <code>MemoryError</code> that happens there:</p>
<pre><code>targets = np.array([(float(X), float(Y), float(Z))
for X, Y, Z in csv.reader(open('targets.csv'))])
</code></pre>
<p>Any ideas?</p>
<p>Let me know if you need more details (files, etc.)</p>
<pre><code>import csv
import numpy as np
import scipy.spatial
import cv2
import random
"""loading files"""
points = np.array([(int(R), int(G), int(B), float(X), float(Y), float(Z))
for R, G, B, X, Y, Z in csv.reader(open('colorlist.csv'))])
# load X,Y,Z coordinates of 'points' in a np.array
print "colorlist loaded"
targets = np.array([(float(X), float(Y), float(Z))
for X, Y, Z in csv.reader(open('targets.csv'))])
# load the XYZ target values in a np.array
print "targets loaded"
img = cv2.imread("MAP.tif", -1)
height, width = img.shape
total = height * width
# load dimensions of tif image
print "MAP loaded"
ppm = file("walladrien.ppm", 'w')
ppm.write("P3" + "\n" + str(height) + " " + str(width) +"\n" + "255" + "\n")
# write PPM file header
"""doing geometry"""
tri = scipy.spatial.Delaunay(points[:,[3,4,5]], furthest_site=False) # True makes an almost BW picture
# Delaunay triangulation
indices = tri.simplices
# indices of vertices
vertices = points[indices]
# the vertices for each tetrahedron
tet = tri.find_simplex(targets)
U = tri.transform[tet,:3]
V = targets - tri.transform[tet,3]
b = np.einsum('ijk,ik->ij', U, V)
bcoords = np.c_[b, 1 - b.sum(axis=1)]
# find the barycentric coordinates of each point
"""looping through data"""
i = 0
for i in range(total):
if tet[i] == -1:
# this means that the point lies outside the convex hull
R = G = B = 255
ppm.write(str(R) + ' ' + str(G) + ' ' + str(B) + "\n") # writes a pixel
else:
R0 = int(vertices[tet[i]][0][0])
G0 = int(vertices[tet[i]][0][1])
B0 = int(vertices[tet[i]][0][2])
R1 = int(vertices[tet[i]][1][0])
G1 = int(vertices[tet[i]][1][1])
B1 = int(vertices[tet[i]][1][2])
R2 = int(vertices[tet[i]][2][0])
G2 = int(vertices[tet[i]][2][1])
B2 = int(vertices[tet[i]][2][2])
R3 = int(vertices[tet[i]][3][0])
G3 = int(vertices[tet[i]][3][1])
B3 = int(vertices[tet[i]][3][2])
rand = random.uniform(0,1)
BC_0 = bcoords[i][0]
BC_1 = bcoords[i][1]
BC_2 = bcoords[i][2]
BC_3 = bcoords[i][3]
i += 1
if rand <= BC_0:
ppm.write(str(R0) + ' ' + str(G0) + ' ' + str(B0) + "\n") # writes a pixel
elif rand <= BC_0 + BC_1:
ppm.write(str(R1) + ' ' + str(G1) + ' ' + str(B1) + "\n") # writes a pixel
elif rand <= BC_0 + BC_1 + BC_2:
ppm.write(str(R2) + ' ' + str(G2) + ' ' + str(B2) + "\n") # writes a pixel
else:
ppm.write(str(R3) + ' ' + str(G3) + ' ' + str(B3) + "\n") # writes a pixel
ppm.close()
print 'done'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:59:59.847",
"Id": "70934",
"Score": "1",
"body": "What does \"100 Mo\" mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:12:59.137",
"Id": "71010",
"Score": "0",
"body": "100 Mb, sorry, it's a french habit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:39:48.683",
"Id": "71017",
"Score": "1",
"body": "Aha, *mégaoctet*!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:50:52.953",
"Id": "71020",
"Score": "0",
"body": "yes exactly :) haha"
}
] |
[
{
"body": "<p>Here you read your data into a Python list that you pass to <code>array</code>:</p>\n\n<pre><code>targets = np.array([(float(X), float(Y), float(Z))\n for X, Y, Z in csv.reader(open('targets.csv'))])\n</code></pre>\n\n<p>A Python list of floats uses much more memory than a NumPy array, because each float is a separate Python object. You can avoid that overhead by reading directly into an array, eg. using <code>np.loadtxt</code>:</p>\n\n<pre><code>targets = np.loadtxt('targets.csv', delimiter=',')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T11:36:02.860",
"Id": "41323",
"ParentId": "41316",
"Score": "7"
}
},
{
"body": "<h3>1. The MemoryError</h3>\n\n<p>I can't reproduce the <code>MemoryError</code>. Here's the test I ran:</p>\n\n<pre><code>def make_test(n=10**7, output_file='targets.csv'):\n with open(output_file, 'w') as f:\n for _ in range(n):\n f.write('56.08401,55.19490,25.49292\\n')\n\n>>> make_test()\n>>> import os\n>>> os.stat('targets.csv').st_size\n270000000\n</code></pre>\n\n<p>That's 270 megabytes of data, and it loads fine for me:</p>\n\n<pre><code>>>> import csv, numpy as np\n>>> targets = np.array([(float(X), float(Y), float(Z)) for X, Y, Z in csv.reader(open('targets.csv'))])\n>>> targets.shape\n(10000000, 3)\n</code></pre>\n\n<p>So I don't really know what is going wrong for you. Can you provide the exact text of the error message and its traceback? There might be more information there.</p>\n\n<p>Regardless of the cause of the <code>MemoryError</code>, <a href=\"https://codereview.stackexchange.com/a/41323/11728\">Janne is right</a> to suggest that using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html\" rel=\"nofollow noreferrer\"><code>numpy.loadtxt</code></a> to get the data directly from the file (with no intermediate Python list) would be better:</p>\n\n<pre><code>targets = np.loadtxt('targets.csv', delimiter=',')\n</code></pre>\n\n<p>However, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html\" rel=\"nofollow noreferrer\"><code>numpy.loadtxt</code></a> is still quite slow, and if this is a bottleneck for you then you should investigate <a href=\"http://pandas.pydata.org/index.html\" rel=\"nofollow noreferrer\">pandas</a>:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> timeit(lambda:np.loadtxt('targets.csv', delimiter=','), number=1)\n18.912313379812986\n>>> import pandas\n>>> timeit(lambda:pandas.read_csv('targets.csv', delimiter=',').values, number=1)\n0.5977518488653004\n</code></pre>\n\n<h3>2. Other comments on your code</h3>\n\n<ol>\n<li><p>The <a href=\"http://netpbm.sourceforge.net/doc/ppm.html\" rel=\"nofollow noreferrer\">PPM format specification</a> says that width is given before height, but you have:</p>\n\n<pre><code>ppm.write(\"P3\" + \"\\n\" + str(height) + \" \" + str(width) +\"\\n\" + \"255\" + \"\\n\")\n</code></pre>\n\n<p>Is that right? Do you really intend to transpose your image?</p></li>\n<li><p>It's conventional to place a comment <em>before</em> the code that it describes. So instead of:</p>\n\n<pre><code>ppm.write(\"P3\" + \"\\n\" + str(height) + \" \" + str(width) +\"\\n\" + \"255\" + \"\\n\")\n# write PPM file header\n</code></pre>\n\n<p>most Python programmers would write it like this:</p>\n\n<pre><code># Write PPM file header: see <http://netpbm.sourceforge.net/doc/ppm.html>\nppm.write(\"P3\\n{} {}\\n255\\n\".format(width, height))\n</code></pre></li>\n<li><p>You haven't managed to vectorize all your code. Everything up to the computation of <code>bcoords</code> is vectorized and will run fast, but then you have a loop over the data where you pick a random vertex corresponding to each target. This loop runs in slow Python code and so is going to be the bottleneck in your application.</p>\n\n<p>See §3 below for how this part of the code can be vectorized, using\n<a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html\" rel=\"nofollow noreferrer\"><code>numpy.cumsum</code></a> to find the cumulative sums of the barycentric coordinates, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform\" rel=\"nofollow noreferrer\"><code>numpy.random.uniform</code></a> to generate random samples for each target, and <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html\" rel=\"nofollow noreferrer\"><code>numpy.argmax</code></a> to pick the vertex.</p></li>\n<li><p>Similarly, writing the output colours to the PPM would be faster if you used <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html\" rel=\"nofollow noreferrer\"><code>numpy.savetxt</code></a> to write them all at once (instead of one at a time as at present).</p></li>\n<li><p>You compute all four barycentric coordinates for each target using the recipe from <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html\" rel=\"nofollow noreferrer\"><code>scipy.spatial.Delaunay</code></a>:</p>\n\n<pre><code>bcoords = np.c_[b, 1 - b.sum(axis=1)]\n</code></pre>\n\n<p>but in fact you don't need the fourth coordinate since you are only going to use the cumulative sums of these coordinates, and the fourth cumulative sum is always 1.</p></li>\n<li><p>The format of <code>colorlist.csv</code> is quite inconvenient, with a mixture of two types of data (colours and vertices) using a mixture of spaces and commas as delimiters:</p>\n\n<pre><code>255 63 127,35.5344302104,21.380721966,20.3661095969\n</code></pre>\n\n<p>Where does this file come from? If it's under your control, could you generate it in a more convenient format, for example as one file containing colours and another containing vertices? Or if you have to generate it as a single file, then could you consistently use either spaces or commas as delimiters?</p></li>\n<li><p>Where do the targets come from? Your code implies that you have exactly one target for each pixel of the image <code>MAP.tif</code>, so is it the case that the targets are generated by processing this image in some way? If so, shouldn't you just generate the targets directly from <code>MAP.tif</code> instead of via the intermediate <code>targets.csv</code>?</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<p>Here's the dithering algorithm, fully vectorized:</p>\n\n<pre><code>import numpy as np\nimport scipy.spatial\n\nWHITE = np.array([[255, 255, 255]], dtype=np.uint8)\n\n\ndef dither_colors(vertices, colors, targets, default_color=WHITE):\n \"\"\"Randomly dither targets onto vertices and return array of\n corresponding colors.\n\n Input:\n vertices: Points in 3-space. shape=(N,3), dtype=float\n color: RGB colors for each point. shape=(N,3), dtype=uint8\n targets: Points in 3-space. shape=(M,3), dtype=float\n default_color: RGB color for targets not found in convex hull of\n vertices. shape=(1,3), dtype=uint8\n\n Output:\n Array of colors. shape=(M,3), dtype=uint8\n\n Works by triangulating vertices, getting a complex of tetrahedra.\n For each target, randomly pick one of the vertices of the\n tetrahedron it is found in (weighted according to how close the\n target is to that vertex), and assign the color of that vertex to\n the target. Targets that are not found in any tetrahedron get\n assigned default_color.\n\n \"\"\"\n N = len(vertices)\n assert vertices.shape == (N, 3)\n assert colors.shape == (N, 3)\n M = len(targets)\n assert targets.shape == (M, 3)\n assert default_color.shape == (1, 3)\n\n # Compute Delaunay triangulation of vertices.\n triangulation = scipy.spatial.Delaunay(vertices, furthest_site=False)\n\n # Find the tetrahedron containing each target (or -1 if not found)\n tetrahedra = triangulation.find_simplex(targets)\n\n # Affine transformation for tetrahedron containing each target\n U = triangulation.transform[tetrahedra, :3]\n\n # Offset of each target from the origin of its containing tetrahedron\n V = targets - triangulation.transform[tetrahedra, 3]\n\n # First three barycentric coordinates of each target in its tetrahedron.\n # The fourth coordinate would be 1 - b.sum(axis=1), but we don't need it.\n B = np.einsum('ijk,ik->ij', U, V)\n\n # Cumulative sum of barycentric coordinates of each target.\n Bsum = np.c_[B.cumsum(axis=1), np.ones(M)]\n\n # A uniform random number in [0, 1] for each target.\n R = np.random.uniform(0, 1, size=(M, 1))\n\n # Randomly choose one of the tetrahedron vertices for each target,\n # weighted according to its barycentric coordinates\n W = np.argmax(R <= Bsum, axis=1)\n\n # Get the color corresponding to each vertex just chosen.\n C = colors[triangulation.simplices[tetrahedra, W]]\n\n # Mask out the targets where we failed to find a tetrahedron.\n C[tetrahedra == -1] = default_color\n\n assert C.shape == (M, 3)\n return C\n</code></pre>\n\n<p>And here's a function that handles the input and output:</p>\n\n<pre><code>def dither_image(width, height,\n vertices_file='colorlist.csv',\n targets_file='targets.csv',\n output_file='output.ppm'):\n \"\"\"Read colors and vertices from vertices_file. Read targets from\n targets_file. Dither each target to a randomly chosen nearby\n vertex; output the colors for the dithered vertices to output_file\n as a PPM with the given width and height.\n\n \"\"\"\n vertices = np.loadtxt(vertices_file, usecols=(1, 2, 3), delimiter=',')\n colors = np.loadtxt(vertices_file, usecols=(0,), delimiter=',', \n converters={0:lambda s:s.split()}, dtype=np.uint8)\n targets = np.loadtxt(targets_file, delimiter=',')\n\n C = dither_colors(vertices, colors, targets)\n\n # Write output as image in PPM format.\n # See <http://netpbm.sourceforge.net/doc/ppm.html>\n with open(output_file, 'wb') as ppm:\n ppm.write(\"P3\\n{} {}\\n255\\n\".format(width, height).encode('ascii'))\n np.savetxt(ppm, C, fmt='%d')\n</code></pre>\n\n<h3>4. Emacs bug</h3>\n\n<p>In the course of preparing this answer, I discovered a bug in the way Emacs handles PPM images on OS X, which I reported as <a href=\"http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16683\" rel=\"nofollow noreferrer\">bug #16683</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:29:47.800",
"Id": "71013",
"Score": "0",
"body": "Amazing answer, thanks! I learned a lot by reading it. Now I get what is meaned by vectorizing. The file `colorlist.csv` contains 2 types of color coordinates: \"machine code\" `RGB` and real colorimetric coordinates computed from spectrophotometric measurements and the CIE 1931 system: `XYZ`. But you're right, I'll restructure this fine `R, G, B, X, Y, Z` instead of `R G B, X, Y, Z` And no, the targets are not coming from the `.tiff` file. Thanks for showing how amazingly speedy `pandas` is! All my best."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:45:22.747",
"Id": "41326",
"ParentId": "41316",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41326",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T07:25:05.673",
"Id": "41316",
"Score": "7",
"Tags": [
"python",
"numpy"
],
"Title": "Python, numpy, optimize module to handle big file"
}
|
41316
|
<p>Even though I am working with one socket, I have wrapped it with an object which allows <code>.recv()</code> method which accepts timeout, using Python's <code>select.poll()</code>.</p>
<p>The initialization of the wrapping object defines a socket using the address/protocol family, of type stream; then it connects, flags it as non-blocking and registers it to a poll object. So the <code>.__init__()</code> method looks like this:</p>
<pre><code>def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.poll = select.poll()
event_in_mask = select.POLLIN | select.POLLPRI
event_err_mask = select.POLLERR
event_closed_mask = select.POLLHUP | select.POLLNVAL
event_mask = event_in_mask | event_err_mask | event_closed_mask
self.poll.register(self.socket, event_mask)
</code></pre>
<p>I mask the poll object as I am interested in querying only incoming data or errors.</p>
<p>The receive method will look like this:</p>
<pre><code>def recv(self, timeout):
events = self.poll.poll(timeout)
if not events:
return ""
event = events[0][1]
## Invalid request; descriptor not open
if event & select.POLLNVAL:
err = "Invalid request; descriptor not open"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## Hung up
if event & select.POLLHUP:
err = "Hung up"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## Error condition of some sort
if event & select.POLLERR:
err = "Error condition of some sort"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## There is data to read
ready = event & select.POLLPRI or event & select.POLLIN
## Timeout expiry; nothing was received, we pass an empty string
if not ready:
return ""
return self._recv()
</code></pre>
<p>The <code>._recv()</code> method simply calls <code>self.socket.recv(4096)</code> with some error catching.</p>
<p>And finally, the <code>.close()</code> method will look like that:</p>
<pre><code>def close(self):
self.poll.unregister(self.socket)
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
</code></pre>
<p>My questions are:</p>
<ul>
<li>is there anything redundant here?</li>
<li>is polling the right choice? (I've used <code>select.select()</code> before, but it has caused some issues)</li>
<li>do you think the general architecture makes sense?</li>
</ul>
<p><strong>EDIT:</strong> The <code>ConnectionClosedError</code> is some custom <code>Exception</code> that wraps the socket exception just for convenience.</p>
<h1>The Complete Code</h1>
<pre><code>## Framework
import select
import socket
###################################
## ----- Connection Errors ----- ##
###################################
import errno
class ConnectionError(IOError):
def __init__(self, err, host=None, port=None):
self.err = err
self.host = host
self.port = port
err_msg = "{self.err}"
def __str__(self):
return self.err_msg.format(self=self)
class ConnectionClosedError(ConnectionError):
err_msg = "Connection closed (host '{self.host}', port {self.port})"
class ConnectionRefusedError(ConnectionError):
err_msg = "{self.err} (host '{self.host}', port {self.port})"
########################
## ----- Client ----- ##
########################
class SocketClient(object):
""" Low level socket client. """
def __init__(self, host, port, blocking=False):
self.host = host
self.port = port
self.blocking = blocking
## Initialize socket
try:
self.init_socket()
## Couldn't
except socket.error as socket_error:
## Connection was refused
if socket_error.errno == errno.ECONNREFUSED:
raise ConnectionRefusedError(socket_error, host=self.host,
port=self.port)
## There was some other socket problem
raise ConnectionError(socket_error)
def init_socket(self):
""" Instantiate a local socket and connect it with a remote
socket. """
## AF_INET is a constant representing the address/protocol family
## SOCK_STREAM is a constant representing the socket type
## The function returns a Socket object
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Connect to server (a remote socket)
## The format of the address depends on the address family. In the case of
## AF_INET, it is a pair (host, port), where 'host' is a string
## representing either a hostname in internet domain notation like
## 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an
## integer.
try:
self.socket.connect((self.host, self.port))
except TypeError:
if not isinstance(self.port, int):
raise ConnectionError("port must be int (got {})".format(self.port))
## We set the socket to non-blocking mode
if not self.blocking:
self.socket.setblocking(0)
## We construct a polling object and register the socket
self.poll = select.poll()
event_in_mask = select.POLLIN | select.POLLPRI
event_err_mask = select.POLLERR
event_closed_mask = select.POLLHUP | select.POLLNVAL
event_mask = event_in_mask | event_err_mask | event_closed_mask
self.poll.register(self.socket, event_mask)
def close(self):
""" Close the socket. """
## Unregister the socket
self.poll.unregister(self.socket)
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
def _recv(self):
""" A thin wrapper around the socket's recv method. """
## Receive data from socket
## 4096 comes from a recommendation in the python module documentation
## for the socket module
try:
return self.socket.recv(4096)
## Couldn't receive
except socket.error as socket_error:
## Connection was closed
if socket_error.errno == errno.EBADF:
raise ConnectionClosedError(socket_error, host=self.host,
port=self.port)
## There was some other socket problem
raise ConnectionError(socket_error)
def recv(self, timeout=None):
""" Receive data from socket. If *timeout* is given, smartly return an
empty string after *timeout* seconds have passed. """
## If not timeout was given, we think of the socket as if it is ready now
if not timeout:
return self._recv()
## Otherwise, we poll the socket, to check if there is data to read
events = self.poll.poll(timeout)
## If no events were returned, socket is not ready
if not events:
return ""
## Otherwise, we're interested only in one event and we query it
event = events[0][1]
## Invalid request; descriptor not open
if event & select.POLLNVAL:
err = "Invalid request; descriptor not open"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## Hung up
if event & select.POLLHUP:
err = "Hung up"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## Error condition of some sort
if event & select.POLLERR:
err = "Error condition of some sort"
raise ConnectionClosedError(err, host=self.host, port=self.port)
## There is data to read
ready = event & select.POLLPRI or event & select.POLLIN
## Timeout expiry; nothing was received, we pass an empty string
if not ready:
return ""
## Ready? Query socket
return self._recv()
def send(self, string):
""" Send *string* to the socket. Continue to send data from *string* until
either all data has been sent or an error occurs. Return ``None`` on
success, raise on failure. """
## We use 'sendall' as we do not wish to allow partial messages
self.socket.sendall(string)
</code></pre>
|
[] |
[
{
"body": "<p>Looks okay in general. One set of lines that gave me pause was:</p>\n\n<pre><code>## We set the socket to non-blocking mode\nif not self.blocking:\n self.socket.setblocking(0)\n</code></pre>\n\n<p>it looked redundant until I realized this was initial socket configuration. So it might be a little clearer if you did something like:</p>\n\n<pre><code>self.socket.setblocking(1 if self.blocking else 0)\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>self.socket.setblocking(int(self.blocking))\n</code></pre>\n\n<p>I think unconditionally setting it to something drives home the fact that it's a configuration step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T16:42:59.733",
"Id": "113927",
"ParentId": "41317",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T10:10:35.843",
"Id": "41317",
"Score": "4",
"Tags": [
"python",
"socket"
],
"Title": "A polling wrapper for Python's socket library"
}
|
41317
|
<p>I've got this largish (for me) script, and I want to see if anybody could tell me if there are any ways to improve it, both in terms of speed, amount of code and the quality of the code. I still consider myself a beginner, and I think that there are parts of my code that aren't maybe all that good - for example, all the variables I have to initiate before the main <code>for</code>-loop in the script, and the <code>for</code>-loop itself. Are there other ways of getting the same result?</p>
<p>This is what the script does:</p>
<p>First, it reads a large .csv-file (around 100,000 rows) with short strings ("peptides", looks like this: <code>AQSIGR</code>) and creates a reference <code>set()</code> from those. Then it reads a smaller file (around 100 rows) with larger strings ("PrESTs", which look like this: <code>TYQIRTTPSATSLPQKTVVMTRSPVTLTSQTTKTDD</code>, shortened) and analyses these in the following ways:</p>
<ol>
<li>At every <code>K</code> or <code>R</code> not followed by <code>P</code>, cut the PrEST to the right
of the letter (i.e. giving a first peptide <code>TYQIR</code> from above)</li>
<li>Also allow for up to two "missed
cleavages", where the first and/or second <code>R</code> or <code>K</code> is ignored
(i.e. <code>TYQIR.TTPSATSLPQK</code> and <code>TYQIR.TTPSATSLPQK.TVVMTR</code>, etc. from
above) </li>
<li>Check every resulting peptide against the peptide reference
set created in the beginning: only peptides NOT occurring in the set
are of interest (i.e. unique). </li>
<li>Store the various peptides and PrEST data in an excel file.</li>
</ol>
<p>There are various small details in the script as well (like ignoring the first resulting peptide from every PrEST), but the above points is the gist of it:</p>
<pre><code>import pandas as pd
import csv
# ----------------------------------- Input variables -----------------------------------
# Input should be a .csv file with 2 columns (PrEST ID, PrEST Sequence)
data_file = 'Master Thesis 14 PrESTs'
protease_name = 'Trypsin'
#protease_name = 'Lys-C'
# ---------------------------------------------------------------------------------------
data = pd.read_csv(data_file + '.csv', sep=';')
proteasome = 'Non-Unique Reference (' + protease_name + ') (UniProt, canonical).csv'
# Create peptide reference Set
ref_set = set()
with open(proteasome, 'rU') as in_file:
reader_2 = csv.reader(in_file)
for row in reader_2:
(ref_set.add(str(row).replace("'","").replace(",","")
.replace("[","").replace("]","").replace(" ","")))
print(str(len(ref_set)) + ' peptides in reference')
def protease(PrEST_seq, a, type):
if protease_name == 'Trypsin':
if type == 1:
if PrEST_seq[a+1:a+2] != 'P' and (PrEST_seq[a:a+1] == 'R' or PrEST_seq[a:a+1] == 'K'):
return 1
else:
return 0
else:
if PrEST_seq[a+2:a+3] != 'P' and (PrEST_seq[a+1:a+2] == 'R' or PrEST_seq[a+1:a+2] == 'K'):
return 1
else:
return 0
if protease_name == 'Lys-C':
if PrEST_seq[a:a+1] == 'K':
return 1
else:
return 0
# Initiate variables
Peptide_list = [] # List for Peptides (resets for each PrEST)
ID_list = [] # List for PrEST IDs (resets for each PrEST)
Non_Uniques = [] # List for non-unique peptides
Non_Uniques_ID = [] # List for non-unique PrEST IDs
Peptide = '' # Current peptide (no missed cleavages)
Peptide_MC1 = '' # Current peptide with 1 missed cleavage
Peptide_MC2 = '' # Current peptide with 2 missed cleavages
PrEST_data = pd.DataFrame()
# ------------------------------------------------ Main PrEST for-loop ------------------------------------------------
for row in data.iterrows(): # For every PrEST (row)
First = 'Y'
PrEST_seq = row[1][1]
Pep_Count = 0
MC_Pep_Count = 0
Non_Unique_Count = 0
# ----------------------------------------- No missed cleavages for-loop ------------------------------------------
for n in range(len(PrEST_seq)): # For every AA in every PrEST
if protease(PrEST_seq, n, 1) == 1:
if First != 'Y': # Does not count first peptide + MCs (part of ABP)
Peptide += PrEST_seq[n:n+1]
if len(Peptide) >= 6: # Only appends peptide if longer than 6 AA
if Peptide not in ref_set:
ID_list.append(row[1][0])
Peptide_list.append(Peptide)
Pep_Count += 1
else:
Non_Uniques_ID.append(row[1][0])
Non_Uniques.append(Peptide)
Non_Unique_Count += 1
ID_list.append(row[1][0] + ' (Not unique)')
Peptide_list.append(Peptide)
# ----------------------------------- One missed cleavage while-loop ----------------------------------
Peptide_MC1 = Peptide
m = n
while m+1 <= len(PrEST_seq):
m += 1
if protease(PrEST_seq, m, 1) == 1:
Peptide_MC1 += PrEST_seq[m:m+1]
if len(Peptide_MC1) >= 6:
if Peptide_MC1 not in ref_set:
ID_list.append(row[1][0])
Peptide_list.append(Peptide_MC1)
MC_Pep_Count += 1
break
else:
Non_Uniques_ID.append(row[1][0])
Non_Uniques.append(Peptide_MC1)
Non_Unique_Count += 1
ID_list.append(row[1][0] + ' (Not unique)')
Peptide_list.append(Peptide_MC1)
else:
Peptide_MC1 += PrEST_seq[m:m+1]
# ---------------------------------- Two missed cleavages while-loop ----------------------------------
Peptide_MC2 = Peptide_MC1
k = m
while k+1 <= len(PrEST_seq):
k += 1
if protease(PrEST_seq, k, 1) == 1:
Peptide_MC2 += PrEST_seq[k:k+1]
if len(Peptide_MC2) >= 6:
if Peptide_MC2 not in ref_set:
ID_list.append(row[1][0])
Peptide_list.append(Peptide_MC2)
MC_Pep_Count += 1
break
else:
Non_Uniques_ID.append(row[1][0])
Non_Uniques.append(Peptide_MC2)
Non_Unique_Count += 1
ID_list.append(row[1][0] + ' (Not unique)')
Peptide_list.append(Peptide_MC2)
else:
Peptide_MC2 += PrEST_seq[k:k+1]
# -------------------------------------------------------------------------------------------------
# Resets variables
Peptide = ''
Peptide_MC1 = ''
Peptide_MC2 = ''
elif First == 'Y': # Doesn't count first cleavage (contains ABP)
Peptide = ''
First = 'N'
else: # Non-cleavable AAs - Peptide grows
Peptide += PrEST_seq[n:n+1]
# Appends PrEST data
K = row[1][1].count('K')
R = row[1][1].count('R')
PrEST_data = PrEST_data.append(pd.DataFrame(data=[[row[1][0], Pep_Count, MC_Pep_Count, Non_Unique_Count, K, R]],
columns=['PrEST ID', '# Peptides', '# MC Peptides', '# Non-Uniques',
'# K', 'R']))
# Writes PrEST data to file
PrEST_data = PrEST_data[['PrEST ID', '# Peptides', '# MC Peptides', '# Non-Uniques', '# K', 'R']]
ew = pd.ExcelWriter(data_file + ' Results.xlsx', encoding='iso-8859-1')
PrEST_data.to_excel(ew, sheet_name='PrESTs (' + protease_name + ')', index=False)
# Creates peptide list for Perseus and writes to file
peptides = pd.DataFrame(Peptide_list, columns=['Peptides']).join(pd.DataFrame(ID_list, columns=['PrEST ID']))
peptides['temp'] = peptides['Peptides'].str.len()
peptides = peptides.sort(['PrEST ID', 'temp'], ascending=[True, False]).drop('temp', axis=1)
peptides.to_excel(ew, sheet_name='Peptide list for Perseus', index=False)
# List for non-unique peptides
NU_peptides = pd.DataFrame(Non_Uniques, columns=['Peptides']).join(pd.DataFrame(Non_Uniques_ID, columns=['PrEST ID']))
NU_peptides['temp'] = NU_peptides['Peptides'].str.len()
NU_peptides = NU_peptides.sort(['PrEST ID', 'temp'], ascending=[True, False]).drop('temp', axis=1)
NU_peptides.to_excel(ew, sheet_name='Non-unique peptides', index=False)
ew.save()
</code></pre>
<p>Here are some input rows from the peptide reference .csv-file (100,000-ish rows):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Reference peptides
IEPVFHVMGFSVTGRVLNGPEGDGVPEAVVTLNNQIK
LDAKKRR
EILRNPMEAMYPHIFYFHFK
KGPPPPPPKK
MVVEVDSMPAASSVK
ERNRNK
QDWTILHSYVHLNADELEALQMCTGYVAGFVDLEVSNRPDLYDVFVNLAESEITIAPLAK
EQFGQDGPISVHCSAGVGR
ADIGVAMGIAGSDVSK
</code></pre>
</blockquote>
<p>And here is some rows from the input file to be analysed (the Xs are not really there, but since this is confidential gene sequences I changed them here):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>PrEST ID Sequence
HPRR06 QGAWKTISNGFGFKDAVFDGSSCISPTIVQQFGYQRRASDXXXXXXXXXSNTIRVFLPNKQRTVVNVRNXXXXXXXXXKALKVRGLQPECCAVFRLLHEHKGKKARLDWNTXXXXXXXXXLQVDFLDHVPLTTHNFAR
HPRR07 ERTFHVETPEEREEWTTAIQTVADGXXXXXXXXXPSDNSGAEEMEVSLAKPKHRVTMNEFEYLKLLGKGTFGKVILVKEKATGRYYAMKILKKEVIVA
HPRR08 MDPMTVGRIEGDCESLNFSEVSSSSKDVENGGKDKPPQPGAKTSSRNDYIHSGLYSSFTLNSLNSSNVKLFKLIKTENPAEKLAEKKSPQEPTPSVIKFVTTPSKKPPVEPVAATISIGPS
HPRR09 VPVSNQSSLQFSNPSGSLVTPSLVTSSXXXXXXXXXRNSVSPGLPQRPASAGAMLGGDLNSANGACPSPVGNGYVSARASPGLLPVANGNSLNKVIPAKSPPPPTHSXXXXXXXXXDLRVITSQAG
HPRR10 DLQWLVQPALVSSVAPSQTRAPHPFGVPAPSAGAYSRXXXXXXXXXRAQSIGRRGKVEQLSPEEEEKRRIRRERNKMAAAKCRNRRRELTDTLQAETDQLEDEKSALQTEIANLXXXXXXXXXEFILAAHRPACKIPDDL
HPRR52 STIAESEDSQESVDSVTDSQKRREILSRRPSYRKILNDLSSXXXXXXXXXVPTPIYQTSSGQYIAITQGGAIQLANNGTDGVQG
HPRR14 MPKKKPTPIQLNPAPDGSAVNGTSSAXXXXXXXXXELELDEQQRKRLEAFLTQKQ
HPRR35 MEDSHKSTTSETAXXXXXXXXHIAQQVSSLSESEESQDSSDSIGSSQKAHGILARRPSY
HPRR02 EGFLCVFAINNTKXXXXXXXXYREQIKRVKDSEDV
</code></pre>
</blockquote>
<p>The main output (first sheet of excel file, <code>PrEST_data</code> DataFrame) looks like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>PrEST ID # Peptides # MC Peptides # Non-Uniques # K # R
HPRR52 10 31 2 10 9
HPRR10 5 26 5 12 5
HPRR09 7 25 0 13 2
HPRR08 5 12 0 3 6
HPRR06 7 45 4 10 15
HPRR07 1 13 6 3 6
HPRR14 2 10 3 7 2
HPRR02 2 3 0 2 2
HPRR35 1 2 1 3 2
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>I have a limited understanding of the different parts of your code so I'll just comment on some details that can be greatly improved.</p>\n\n<hr>\n\n<p>General:</p>\n\n<p>A few things are not quite pythonic. You can make your code go through some automatic checks with <a href=\"http://pep8online.com/\" rel=\"nofollow\">pep8online</a> (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> is the Style Guide for Python Code) and pylint.</p>\n\n<hr>\n\n<p>About <code>protease</code> :</p>\n\n<pre><code>def protease(PrEST_seq, a, type):\n if protease_name == 'Trypsin':\n if type == 1:\n if PrEST_seq[a+1:a+2] != 'P' and (PrEST_seq[a:a+1] == 'R' or PrEST_seq[a:a+1] == 'K'):\n return 1\n else:\n return 0\n else:\n if PrEST_seq[a+2:a+3] != 'P' and (PrEST_seq[a+1:a+2] == 'R' or PrEST_seq[a+1:a+2] == 'K'):\n return 1\n else:\n return 0\n if protease_name == 'Lys-C':\n if PrEST_seq[a:a+1] == 'K':\n return 1\n else:\n return 0\n</code></pre>\n\n<ul>\n<li><p>from the implementation and the way you use it, it seems like this function always returns <code>0</code> or <code>1</code> and should probably return a boolean. Make yourself a favor and actually use booleans. You can now replace all instances of <code>if protease(foo, bar, foobar) == 1:</code> with <code>if protease(foo, bar, foobar):</code>. Also, in the function itself <code>if condition: return 1 else return 0</code> becomes <code>return condition</code>.</p></li>\n<li><p>You have 2 pretty similar conditions. By adding <code>1</code> to <code>a</code> if <code>type != 1</code>, you could make the 2 conditions actually identical.</p></li>\n<li><p>You do not need to get <code>PrEST_seq[a+1:a+2]</code> twice, just check if its values is in some list.</p></li>\n<li><p>For a string <code>s</code>, <code>s[i:i+1]</code> and <code>s[i]</code> seems to be the same thing when <code>i</code> is smaller than the length of s. Prefer the shorter if you can. You can also consider try-catch.</p></li>\n<li><p>It seems like you do not always return a value which is a bit odd. </p></li>\n</ul>\n\n<p>Taking all these comments into account leads to the following code :</p>\n\n<pre><code>def protease(PrEST_seq, a, type):\n if protease_name == 'Trypsin':\n if type != 1:\n a+=1\n return PrEST_seq[a+1] != 'P' and (PrEST_seq[a] in ['R','K']):\n assert(protease_name == 'Lys-C')\n return PrEST_seq[a] == 'K'\n</code></pre>\n\n<hr>\n\n<p>About <code>First</code>:</p>\n\n<p>You are using <code>First</code> as a character which is either <code>Y</code> or not. Here again a boolean would be more than enough.</p>\n\n<ul>\n<li><code>First = 'Y'</code> becomes <code>first = True</code></li>\n<li><code>if First != 'Y':</code> becomes <code>if not first:</code></li>\n<li><code>elif First == 'Y':</code> is not required and you can do <code>Peptide = ''</code> and <code>first = False</code> no matter what the value of <code>first</code> was in the first place.</li>\n</ul>\n\n<hr>\n\n<p>About loops</p>\n\n<p>Your <code>while</code> loops can easily be transformed into a <code>for</code> loop using <code>range</code>.</p>\n\n<p>For instance,</p>\n\n<pre><code> m = n\n while m+1 <= len(PrEST_seq):\n m += 1\n stuff_about(m)\n</code></pre>\n\n<p>could be written :</p>\n\n<pre><code> for m in range(n+1, len(PrEST_seq)+1):\n stuff_about(m)\n</code></pre>\n\n<p>(but my guess is that what you really want to do is <code>for m in range(n+1, len(PrEST_seq)+1):</code> and this could be an explanation for your 'out-of-range' exceptions)</p>\n\n<hr>\n\n<p>About duplicated code :</p>\n\n<p>You sometimes have duplicated logic, for instance on both branches of a test. If you keep things simple, it will be easier to understand and to maintain.</p>\n\n<p>Also, you should not store the number of element in a list in a variable if you can just as easily check the length of the list.</p>\n\n<p>For instance :</p>\n\n<pre><code> if len(Peptide) >= 6: # Only appends peptide if longer than 6 AA\n if Peptide not in ref_set:\n ID_list.append(row[1][0])\n Peptide_list.append(Peptide)\n Pep_Count += 1\n else:\n Non_Uniques_ID.append(row[1][0])\n Non_Uniques.append(Peptide)\n Non_Unique_Count += 1\n ID_list.append(row[1][0] + ' (Not unique)')\n Peptide_list.append(Peptide)\n</code></pre>\n\n<p>could become :</p>\n\n<pre><code> if len(Peptide) >= 6: # Only appends peptide if longer than 6 AA\n Peptide_list.append(Peptide)\n\n if Peptide not in ref_set:\n ID_list.append(row[1][0])\n Pep_Count += 1\n else:\n Non_Uniques_ID.append(row[1][0])\n Non_Uniques.append(Peptide)\n ID_list.append(row[1][0] + ' (Not unique)')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:23:48.080",
"Id": "70924",
"Score": "0",
"body": "Awesome! I added your code, and while PrEST_seq[a] is the same as PrEST_seq[a:a+1] (if printed next to each other), I get a \"IndexError: string index out of range\" for your version. Which is strange... Why is this so? It'd be very nice to just write PrEST_seq[a]!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T07:25:23.863",
"Id": "71071",
"Score": "0",
"body": "PEP8: The only errors I get is that some of my lines are too long, nothing else. Although \"not pythonic\" is exactly the kind of help I wanted! I will read through the style guide, but was there something specific (other than what you already wrote) that you thought about?\nChanged \"First\" to boolean, thanks!\nThe reason I use while-loops is because using a for-loop with range(len(PrEST_seq)) would make the range fall outside the index. Or am I missing some way to use the for-loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T10:48:42.177",
"Id": "71077",
"Score": "0",
"body": "@ErikF. I've completed my answer. I hope this will help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:02:26.717",
"Id": "71098",
"Score": "0",
"body": "Thank you very much for all your help! I appreciate it ^^"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T11:15:52.920",
"Id": "41322",
"ParentId": "41320",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41322",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T10:46:16.340",
"Id": "41320",
"Score": "4",
"Tags": [
"python",
"strings",
"python-3.x",
"csv",
"bioinformatics"
],
"Title": "Cutting strings into smaller ones based on specific criteria"
}
|
41320
|
<p>I am trying to create a simple validation for forms. I am almost there, but there are few bugs and optimization errors that I am really struggling with. I'm looking for advice on how to make this function simpler and more understandable.</p>
<pre><code>var errorMessage = {
required: "This field can not be empty",
email: "Please enter a valid email address",
number: "Please only enter numbers in this field",
min: "This field should be minimum ",
max: "This field should be maximum ",
date: "Please use the date format outlined above"
};
var $form = $("#contactForm");
var $formInputs = $("#contactForm input");
var $formTextareas = $("#contactForm textarea");
var $formSelects = $("#contactForm select");
var currentRadioSet = "";
$form.submit(function(event) {
event.preventDefault();
if (submitValidate()) {
var $el = $(this);
$submit = $el.find('button[id="submit"]');
$inputs = $el.find('input, textarea, select, label');
$.post($el.attr('action'), $form.serialize(), function(data) {
$('span.error').remove();
if (data) {
$submit.text('Sent. Thank You!');
$submit.add($inputs).addClass('disabled').prop('disabled', true);
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
}
});
$formInputs.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formInputs.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
function submitValidate() {
resetErrorMessages();
$formInputs.each(function() {
var $el = $(this);
checkForClasses($el);
});
$formTextareas.each(function() {
var $el = $(this);
checkForClasses($el);
});
$formSelects.each(function() {
var $el = $(this);
checkForClasses($el);
});
if (!$('.error').length) {
return true;
} else {
return false;
}
}
function checkForClasses(elementIn) {
var $el = $(elementIn);
var isValid = true;
isValid = checkForMin($el);
if (!isValid) {
return;
}
isValid = checkForMax($el);
if (!isValid) {
return;
}
if ($el.hasClass("required")) {
isVaild = requiredVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("email")) {
isVaild = emailVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("number")) {
isVaild = numberVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("date")) {
isVaild = dateVal($el);
if (!isValid) {
return;
}
}
}
function requiredVal(elementIn) {
var $el = $(elementIn);
var valid = true;
if ($el.is(':radio:last') || $el.is(':checkbox:last')) {
currentRadioSet = $el.attr("name");
valid = $("input[name=" + currentRadioSet + "]:checked").val();
}
if ($.trim($el.val()) == "" || !valid) {
manageErrorMessage($el, errorMessage.required);
valid = false;
} else {
resetSingleErrorMessage($el);
valid = true;
}
return valid;
}
function numberVal(elementIn) {
var $el = $(elementIn);
var valid = true;
var numRegEx = /^\d+$/;
var numIn = $.trim($el.val());
if (!$.trim($el.val()) == "") {
if (!numRegEx.test(numIn)) {
manageErrorMessage($el, errorMessage.number);
valid = false;
} else {
resetSingleErrorMessage($el)
valid = true;
}
}
return valid;
}
function emailVal(elementIn) {
var $el = $(elementIn);
var valid = true;
var emailRegEx = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailIn = $.trim($el.val());
if (!$.trim($el.val()) == "") {
if (!emailRegEx.test(emailIn)) {
manageErrorMessage($el, errorMessage.email);
valid = false;
} else {
resetSingleErrorMessage($el)
valid = true;
}
}
return valid;
}
function dateVal(elementIn) {
var $el = $(elementIn);
var valid = true;
var dateRegEx = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var dateIn = $.trim($el.val());
if (!$.trim($el.val()) == "") {
if (!dateRegEx.test(dateIn)) {
manageErrorMessage($el, errorMessage.date);
valid = false;
} else {
resetSingleErrorMessage($el);
valid = true;
}
}
return valid;
}
function checkForMin(elementIn) {
var $el = $(elementIn);
var valid = true;
if ($el.attr("class")) {
if ($el.attr("class").match(/min[0-9]+/)) {
var minClass = $el.attr("class").match(/min[0-9]+/).toString();
minVal = parseInt(minClass.match(/[0-9]+/));
if ($.trim($el.val().length) < minVal) {
manageErrorMinMax($el, errorMessage.min, minVal);
valid = false;
} else {
resetSingleErrorMessage($el);
valid = true;
}
}
}
return valid;
}
function checkForMax(elementIn) {
var $el = $(elementIn);
var valid = true;
if ($el.attr("class")) {
if ($el.attr("class").match(/max[0-9]+/)) {
var maxClass = $el.attr("class").match(/max[0-9]+/).toString();
maxVal = parseInt(maxClass.match(/[0-9]+/));
if ($.trim($el.val().length) > maxVal) {
manageErrorMinMax($el, errorMessage.max, maxVal);
valid = false;
} else {
resetSingleErrorMessage($el);
valid = true;
}
}
}
return valid;
}
function manageErrorMessage(elementIn, errorMessageIn) {
var $el = $(elementIn);
$el.addClass('error');
if (!$el.next().is("span")) {
$el.after('<span class="error"></span>');
}
$el.next().html(errorMessageIn);
}
function manageErrorMinMax(elementIn, errorMessageIn, value) {
var $el = $(elementIn);
$el.addClass('error');
if (!$el.next().is("span")) {
$el.after('<span class="error"></span>');
}
$el.next().html(errorMessageIn + value + " charaters long.");
}
function resetSingleErrorMessage(elementIn) {
var $el = $(elementIn);
$el.removeClass("error");
if ($el.next().is("span")) {
$el.next().remove();
}
}
function resetErrorMessages() {
$("span.error").remove();
$("input .error").removeClass("error");
}
</code></pre>
<ol>
<li><p>The script is really ugly and not optimized at all which is what causing some problems as I can't just understand what is what and which is which, therefore I am now trying to clean it up. I am not an expert in JavaScript but have basic knowledge - the script is the results of a very long nights researching and collecting things and putting them together... </p>
<p><strong>A)</strong> I cleaned up this bit:</p>
<pre><code>var $form = $("#contactForm");
var $formInputs = $("#contactForm input");
var $formTextareas = $("#contactForm textarea");
var $formSelects = $("#contactForm select");
var currentRadioSet = "";
</code></pre>
<p>so now it appears like this:</p>
<pre><code>var $form = $("form");
var $inputs = $("input, textarea, select, label");
</code></pre>
<p><strong>B)</strong> I have accompanied all the key-up and blur together "This is for a feel of a real-time validation": </p>
<pre><code>$inputs.keyup(function () {
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
$formTextareas.keyup(function () {
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
$formTextareas.blur(function () {
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
$inputs.blur(function () {
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
</code></pre>
<p>So now they appear like this:</p>
<pre><code>$inputs.bind('blur keyup focus', function(){
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
</code></pre>
<p><strong>C)</strong> I also cleaned up this section that I believe it validates on submit: </p>
<pre><code>function validate() {
resetErrorMessages();
$inputs.each(function () {
var $element = $(this);
checkForClasses($element);
});
$formTextareas.each(function () {
var $element = $(this);
checkForClasses($element);
});
$formSelects.each(function () {
var $element = $(this);
checkForClasses($element);
});
if (!$('.error').length) {
return true;
} else {
return false;
}
}
</code></pre>
<p>So it appear like this now:</p>
<pre><code>function validate() {
resetErrorMessages();
$inputs.each(function () {
var $element = $(this);
checkForClasses($element);
});
if (!$('.error').length) {
return true;
} else {
return false;
}
}
</code></pre>
<p><strong>D</strong> I have also cleaned this bit up, this section check if the inputs has any classes and then pass it to validate. </p>
<pre><code>function checkForClasses(elementIn) {
var $el = $(elementIn);
var isValid = true;
isValid = checkForMin($el);
if (!isValid) {
return;
}
isValid = checkForMax($el);
if (!isValid) {
return;
}
if ($el.hasClass("required")) {
isVaild = requiredVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("email")) {
isVaild = emailVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("number")) {
isVaild = numberVal($el);
if (!isValid) {
return;
}
}
if ($el.hasClass("date")) {
isVaild = dateVal($el);
if (!isValid) {
return;
}
}
}
</code></pre>
<p>It is now appearing like:</p>
<pre><code>//Check for validation rules in inputs
function checkForClasses(element) {
var $element = $(element);
var valid = true;
//check for required
if ($element.hasClass("required")) {
valid = Required($element);
if (!valid) {
return;
}
}
//check for email
if ($element.hasClass("email")) {
valid = Email($element);
if (!valid) {
return;
}
}
//check for number
if ($element.hasClass("number")) {
valid = Number($element);
if (!valid) {
return;
}
}
//check for minimum
valid = Minimum($element);
if (!valid) {
return;
}
//check for maximum
valid = Maximum($element);
if (!valid) {
return;
}
</code></pre>
<p>}</p></li>
</ol>
<p>Why does Man and Min not work if I did them as all the others? If I used this method, they won't work.</p>
<pre><code>if ($element.hasClass("max")) {
valid = Maximum($element);
if (!valid) {
return;
}
}
</code></pre>
<p>Is there any way to clean this section farther and make it simpler? The form has to be dynamic and I can't seem to be able to figure out away to make it check for classes dynamically without telling it where to go manually.</p>
<p>I just don't know what to do with the rest of the code. Every time I try to optimize it, it breaks. Please can someone help me?</p>
<p>Some of the bugs: I can't validate radio and checkbox buttons, and the validation for the select input only works when submit not in a real time.</p>
<p>Here is the final code after cleaning up:</p>
<pre><code>$(document).ready(function () {
if ($('form').length > 0) {
var errorMessage = {
required: "This field can not be empty",
email: "Please enter a valid email address",
number: "This field can only contain numbers",
min: "This field should be minimum ",
max: "This field should be maximum ",
};
var $form = $("form");
var $inputs = $("input, textarea, select, label");
$form.submit(function (event) {
event.preventDefault();
if (validate()) {
var $element = $(this);
$submit = $element.find('button[id="submit"]');
$inputs = $element.find('input, textarea, select, label');
$.post($element.attr('action'), $form.serialize(),
function (data) {
$('span.error').remove();
if (data) {
$submit.text('Sent. Thank You!');
$submit.add($inputs).addClass('disabled').prop('disabled', true);
} else {
$submit.text('Try Again');
}
});
}
});
//Check for validation rules in inputs
function checkForClasses(element) {
var $element = $(element);
var valid = true;
//check for required
if ($element.hasClass("required")) {
valid = Required($element);
if (!valid) {
return;
}
}
//check for email
if ($element.hasClass("email")) {
valid = Email($element);
if (!valid) {
return;
}
}
//check for number
if ($element.hasClass("number")) {
valid = Number($element);
if (!valid) {
return;
}
}
//check for minimum
valid = Minimum($element);
if (!valid) {
return;
}
//check for maximum
valid = Maximum($element);
if (!valid) {
return;
}
}
//Real-time validation
$inputs.bind('blur keyup focus', function(){
var $element = $(this);
if (!$element.hasClass("required")) {
resetSingleErrorMessage($element);
}
checkForClasses($element);
});
//Validate on submit
function validate() {
resetErrorMessages();
$inputs.each(function () {
var $element = $(this);
checkForClasses($element);
});
if (!$('.error').length) {
return true;
} else {
return false;
}
}
//Required - validation rule
function Required(element) {
var $element = $(element);
var valid = true;
if ($element.is(':radio:last') || $element.is(':checkbox:last')) {
currentRadioSet = $element.attr("name");
valid = $("input[name=" + currentRadioSet + "]:checked").val();
}
if ($.trim($element.val()) == "" || !valid) {
manageErrorMessage($element, errorMessage.required);
valid = false;
} else {
resetSingleErrorMessage($element);
valid = true;
}
return valid;
}
//Email - validation rule
function Email(element) {
var $element = $(element);
var valid = true;
var emailRegEx = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailIn = $.trim($element.val());
if (!$.trim($element.val()) == "") {
if (!emailRegEx.test(emailIn)) {
manageErrorMessage($element, errorMessage.email);
valid = false;
} else {
resetSingleErrorMessage($element)
valid = true;
}
}
return valid;
}
//Number - validation rule
function Number(element) {
var $element = $(element);
var valid = true;
var numRegEx = /^\d+$/;
var numIn = $.trim($element.val());
if (!$.trim($element.val()) == "") {
if (!numRegEx.test(numIn)) {
manageErrorMessage($element, errorMessage.number);
valid = false;
} else {
resetSingleErrorMessage($element)
valid = true;
}
}
return valid;
}
//Minimum - validation rule
function Minimum(element) {
var $element = $(element);
var valid = true;
if ($element.attr("class")) {
if ($element.attr("class").match(/min[0-9]+/)) {
var minClass = $element.attr("class").match(/min[0-9]+/).toString();
minVal = parseInt(minClass.match(/[0-9]+/));
if ($.trim($element.val().length) < minVal) {
manageErrorMinMax($element, errorMessage.min, minVal);
valid = false;
} else {
resetSingleErrorMessage($element);
valid = true;
}
}
}
return valid;
}
//Maximum - validation rule
function Maximum(element) {
var $element = $(element);
var valid = true;
if ($element.attr("class")) {
if ($element.attr("class").match(/max[0-9]+/)) {
var maxClass = $element.attr("class").match(/max[0-9]+/).toString();
maxVal = parseInt(maxClass.match(/[0-9]+/));
if ($.trim($element.val().length) > maxVal) {
manageErrorMinMax($element, errorMessage.max, maxVal);
valid = false;
} else {
resetSingleErrorMessage($element);
valid = true;
}
}
}
return valid;
}
//Show and hide error messages
function manageErrorMessage(element, errorMessageIn) {
var $element = $(element);
$element.addClass('error');
if (!$element.next().is("span")) {
$element.after('<span class="error"></span>');
}
$element.next().html(errorMessageIn);
}
function manageErrorMinMax(element, errorMessageIn, value) {
var $element = $(element);
$element.addClass('error');
if (!$element.next().is("span")) {
$element.after('<span class="error"></span>');
}
$element.next().html(errorMessageIn + value + " charaters long.");
}
function resetSingleErrorMessage(element) {
var $element = $(element);
$element.removeClass("error");
if ($element.next().is("span")) {
$element.next().remove();
}
}
function resetErrorMessages() {
$("span.error").remove();
$("input .error").removeClass("error");
}
}
});
</code></pre>
<p><strong>Here is the HTML of the form:</strong></p>
<pre><code> <form action="contact.php" id="contactForm" method="post" name="contactForm">
<div class="name">
<p>Your Name</p>
<input class="required" name="name">
</div>
<div class="email">
<p>Email Address</p>
<input class="required email" name="email">
</div>
<div class="number">
<p>Number</p>
<input class="required number" name="number">
</div>
<div class="message">
<p>Message</p>
<textarea class="required min5 max10" name="message" rows="5"></textarea>
</div>
<div class="dropdown">
<select class="required">
<option value="">Select</option>
<option value="option">Option</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="sex" type="radio" value="value">radio</label>
<label><input name="sex" type="radio" value="value">radio</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="value">checkbox</label>
<label><input name="checkbox" type="checkbox"value="value">checkbox</label>
</div><button id="submit" type="submit">Send</button>
</form>
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>Function names in JavaScript should only start with a capital if they are constructors, so <code>Number</code> is no good, since it returns a boolean, I would call it <code>isNumber()</code></li>\n<li>I would put a <code>\"use strict\";</code> after <code>$(document).ready(function () {</code></li>\n<li><code>if (!$.trim($element.val()) == \"\") {</code> should be <br>\n<code>if ($.trim($element.val()) != \"\") {</code> ( put the <code>!</code> in the comparison ).</li>\n<li><code>$submit</code>, <code>currentRadioSet</code>, <code>minVal</code> and <code>maxVal</code> were not declared with <code>var</code></li>\n<li>From a design perspective, it does not seem right that your validation rules manage errors and can reset error messages, in my mind, that should be done elsewhere (<code>checkForClasses</code>?), this will reduce a lot copy of paste code</li>\n<li>For <code>Minimum</code> and <code>Maximum</code>, I would advise to get and set the minimum/maximum throught the <code>$().data()</code> mechanism instead of classnames and regexes.</li>\n<li>In <code>checkForClasses</code> you already do <code>var $element = $(element);</code> and then in each validation function you do again <code>var $element = $(element);</code>, that is overkill.</li>\n<li>I would only check for minimum and maximum if the <code>Number</code> class is present</li>\n<li>Use either single or double quotes for strings, dont mix, ideally use single quotes</li>\n<li>In <code>validate()</code> you can simply<br>\n<code>return !$('.error').length;</code></li>\n<li>Also, you are again doing <code>var $element = $(this);</code> in <code>validate()</code> :D</li>\n<li>Please use jshint.com to self review your code, a lot of this feedback comes from there.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:42:58.317",
"Id": "41336",
"ParentId": "41321",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41336",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T10:57:00.267",
"Id": "41321",
"Score": "5",
"Tags": [
"javascript",
"optimization",
"html",
"form",
"validation"
],
"Title": "Validating HTML Form"
}
|
41321
|
<p>I am working on Android applications for last 2 years and about 80% applications I have developed involve web-services consumption followed by some sort of XML or JSON parsing. Initially, when I had to call a web service, I had to create a separate <code>AsyncTask</code> class and then parsing was also the part of that AsyncTask class. The HTTP request sending and other stuff was being handled in my <code>ConnectionManager</code> class. Then I realized there should be some general and single structure which can handle such things like <code>Async</code> call, <code>HttpGet</code> and <code>HttpPost</code> and parsing stuff. So I created this simple structure.</p>
<p>Now my question is, what changes and improvements I can add to make it work better and handle such different use cases?</p>
<p><strong>TaskResult.class</strong></p>
<pre><code>public class TaskResult {
public static int CODE_ERROR = 0;
public static int CODE_SUCCESS = 1;
public int code = CODE_ERROR;
public String message = null;
private Object data = null;
public Object getResultData() {
return data;
}
public void setResultData(Object data) {
this.data = data;
}
}
</code></pre>
<p><strong>BaseParser.class</strong></p>
<pre><code>public interface BaseParser {
public TaskResult parse(InputStream in);
}
</code></pre>
<p><strong>ConnectionManager.class</strong></p>
<pre><code>public class ConnectionManager {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
public static int GET_REQUEST = 0;
public static int POST_REQUEST = 1;
private int mRequestType = POST_REQUEST;
public ConnectionManager() {
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void addParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void addHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
}
public void setRequestType(int type) {
mRequestType = type;
}
public void setUrl(String url) {
this.url = url;
}
public InputStream getHttpInputStream() throws ClientProtocolException, Exception {
if(url == null) {
throw new NullPointerException();
}
System.setProperty("http.keepAlive", "false");
if(mRequestType == POST_REQUEST) {
HttpPost request = new HttpPost(url);
request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
for(int i = 0; i < headers.size(); i++) {
StringEntity entity = new StringEntity(headers.get(i).getValue(), "UTF-8");
request.setEntity(entity);
}
if(!params.isEmpty()){
HttpEntity httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
request.setEntity(httpEntity);
}
DefaultHttpClient mClient = new DefaultHttpClient();
HttpResponse httpResponse;
httpResponse = mClient.execute(request);
HttpEntity mEntity = httpResponse.getEntity();
if (mEntity != null) {
return mEntity.getContent();
}
}
else if(mRequestType == GET_REQUEST) {
String queryString = "";
for(int i = 0; i < params.size(); i++) {
if(i == 0) {
queryString = queryString + params.get(i).getName( ) + "=" + params.get(i).getValue();
}
else {
queryString = queryString + "&" + params.get(i).getName( ) + "=" + params.get(i).getValue();
}
}
DefaultHttpClient mClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url + queryString);
HttpResponse httpResponse;
httpResponse = mClient.execute(httpGet);
HttpEntity mEntity = httpResponse.getEntity();
if (mEntity != null) {
return mEntity.getContent();
}
}
return null;
}
}
</code></pre>
<p><strong>BaseAsyncTask.class</strong></p>
<pre><code>public class BaseAsyncTask extends AsyncTask<Void, Integer, TaskResult>{
ConnectionManager mConnectionManager = null;
OnTaskCompleteListener mListener;
BaseParser mParser;
public BaseAsyncTask.class() {
mConnectionManager = new ConnectionManager();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected TaskResult doInBackground(Void... params) {
String message = "";
try {
InputStream in = mConnectionManager.getTestInputStream();
return mParser.parse(in);
} catch (ClientProtocolException e) {
e.printStackTrace();
message = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
message = e.getMessage();
} catch(Exception e) {
e.printStackTrace();
message = e.getMessage();
}
TaskResult rs = new TaskResult();
rs.message = "Internal error. Please try later." + message;
return rs;
}
@Override
protected void onPostExecute(TaskResult result) {
super.onPostExecute(result);
mListener.onComplete(result);
}
public void setRequestType(int type) {
mConnectionManager.setRequestType(type);
}
public void setUrl(String url) {
mConnectionManager.setUrl(url);
}
public void addParam(String name, String value) {
mConnectionManager.addParam(name, value);
}
public void addHeader(String name, String value) {
mConnectionManager.addHeader(name, value);
}
public void setCallbackListener(OnTaskCompleteListener listener) {
this.mListener = listener;
}
public void setParser(BaseParser parser) {
this.mParser = parser;
}
public interface OnTaskCompleteListener {
public void onComplete(TaskResult rs);
}
}
</code></pre>
<p>and this is how I call a web-service:</p>
<pre><code> BaseAsyncTask mAsyncTask = new BaseAsyncTask();
mAsyncTask.setUrl(WEB_URL);
mAsyncTask.addParam("id", "some_id");
mAsyncTask.setRequestType(ConnectionManager.GET_REQUEST);
mAsyncTask.setCallbackListener(callbackListener);
mAsyncTask.setParser(new MyListingParser());
mAsyncTask.execute();
public class MyListingParser implements BaseParser {
@Override
public TaskResult parse(InputStream in) {
TaskResult result = new TaskResult();
// convert inputstream to string and then parse
ArrayList<MyClass> data = parseString(in);
result.setResultData(data);
result.code = TaskResult.CODE_SUCCESS;
return result;
}
}
private OnTaskCompleteListener callbackListener = new OnTaskCompleteListener() {
@Override
public void onComplete(TaskResult rs) {
if(rs.code == TaskResult.CODE_ERROR) {
// handle error
}
else if(rs.code == TaskResult.CODE_SUCCESS) {
// handle success case like getting data from TaskResult and populating some listview or other stuff
}
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Your idea seems quite feasible, I just had a brief look through and these would be my suggestions:</p>\n\n<ol>\n<li><p>TaskResult class </p>\n\n<ul>\n<li>\"code\" and \"message\" members should probably be encapsulated via getter/setter with proper namings.</li>\n</ul></li>\n<li><p>ConnectionManager class </p>\n\n<ul>\n<li>Depending on your scenario maybe you should consider calling \"shutdown\" on your mClient member.</li>\n<li>When creating your queryString you should use String.format() instead of manually concatenating strings.</li>\n<li>The getHttpInputStream() method could suffer a bit of refactoring, you have common code and behaviour in both if/else branches.</li>\n</ul></li>\n</ol>\n\n<p>Other then that, imo the code looks okey.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:22:08.453",
"Id": "73861",
"Score": "0",
"body": "Yeah, your points are very noteworthy and I will add them to my original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:57:33.770",
"Id": "42746",
"ParentId": "41325",
"Score": "3"
}
},
{
"body": "<p>I use <a href=\"https://www.youtube.com/watch?v=yhv8l9F44qo\" rel=\"nofollow\">volley library</a> to do these work.\nVolley is a library developed by Google, it is tried and tested.\nIt has other features network response caching, network image caching, request cancelation etc.. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:54:38.087",
"Id": "46700",
"ParentId": "41325",
"Score": "3"
}
},
{
"body": "<p>It's simple and elegant and useful for many cases but I'd do something else</p>\n\n<ol>\n<li>I would enhance <code>HttpRequest</code> with <code>Multipart</code> (I know, it's not what you wanted but it's very useful for Http Connections, if you want to upload/download something,Multipart is a MUST)</li>\n<li>I would enhance <code>HttpResponse</code> instead <code>TaskResult</code> and there, I would also use Multipart</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T17:35:00.970",
"Id": "116799",
"Score": "0",
"body": "Ok, I didn't know, sorry, I just saw the anterior answer, which solves nothing and provides nothing and I thought, my answer would be completer. And the second answer provides a pair of advices no more useful than my answer but I note your remark. Regards"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T17:21:24.780",
"Id": "63885",
"ParentId": "41325",
"Score": "0"
}
},
{
"body": "<p>Just one thing I'd like to mention here.</p>\n\n<ol>\n<li>In your AsyncTask you are not doing anything in <code>onPreExecute()</code> so I would remove it.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T20:35:21.257",
"Id": "63902",
"ParentId": "41325",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:41:54.737",
"Id": "41325",
"Score": "3",
"Tags": [
"java",
"parsing",
"android",
"asynchronous",
"web-services"
],
"Title": "Android AsyncTask, HTTP Request and Parsing"
}
|
41325
|
<p>I need to create an efficient algorithm that returns unique values from an unsorted input. I don't know the length of the input.</p>
<p>As the function that will call this algorithm can abort the reading at any time, I think that using a well defined <code>Iterable</code> implementation is the right way, so I will not waste extra processing power for the uneeded input.</p>
<p>Today, I am using a <code>Set</code> to keep track of the values I've already read. But I don't know if this is the most efficient algorithm, as my input length can be huge.</p>
<p>The code below is my today's working algorithm:</p>
<pre><code>import java.util.Iterator;
import java.util.HashSet;
import java.util.Set;
import java.util.NoSuchElementException;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class UniqueValues implements Iterable<String> {
private final Iterator<String> iterator;
public UniqueValues(BufferedReader r) {
this.iterator = new UniqueValuesIterator(r);
}
public Iterator<String> iterator() {
return iterator;
}
static class UniqueValuesIterator implements Iterator<String> {
private final BufferedReader r;
private final Set<String> values = new HashSet<>();
// When 'next' is null, need to get the next value
private String next;
public UniqueValuesIterator(BufferedReader r) {
this.r = r;
}
public boolean hasNext() {
// Good point from OldCurmudgeon
if(next != null) return true;
try {
String line;
while((line = r.readLine()) != null) {
if(values.add(line)) { // add() returns 'true' when it is not a duplicate value.
next = line;
return true;
}
}
} catch(IOException e) { }
return false;
}
public String next() {
if(next == null) {
if(! hasNext() ) throw new NoSuchElementException();
}
final String temp = next;
next = null;
return temp;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
// For testing
public static void main(String... args) {
final StringReader r = new StringReader("value1\nvalue6\nvalue1\nvalue3\nvalue3\nvalue6\nvalue1\nvalue6");
for(final String value : new UniqueValues(new BufferedReader(r)) ) {
System.out.println(value);
}
/* Output is (order is not important):
*
* line 1
* line 6
* line 3
*/
}
}
</code></pre>
<p>Does it have any better algorithm to do this?</p>
|
[] |
[
{
"body": "<p>you have a O(n) time algorithm using O(n) space I don't see how much better this can be without using an external data store or a <code>RandomAccessFile</code></p>\n\n<p>calling hasNext will advance the input several times which is not what you want. to fix test if next is already set:</p>\n\n<pre><code>public boolean hasNext() {\n try {\n if(next!=null)return true;\n String line;\n while((line = r.readLine()) != null) {\n if(values.add(line)) { // add() returns 'true' when it is not a duplicate value.\n next = line;\n return true;\n }\n }\n } catch(IOException e) { }\n\n return false;\n}\n</code></pre>\n\n<p>however I believe that <code>Iterator</code> is not the right interface for this, instead consider using a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/FilterReader.html\"><code>FilteredReader</code></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:09:09.510",
"Id": "41331",
"ParentId": "41327",
"Score": "4"
}
},
{
"body": "<p>There are three significant issues I would address here...</p>\n\n<ul>\n<li><p>Ratchet Freak is right about being concerned about the Iterator/FilteredReader... but I disagree with his suggestion. I think the problem is that your code is converting a BufferedReader in to an Iterator, and making the results unique at the same time. This is a class that is performing 2 functions... and you shoould have two classes instead. One that converts the BufferedReader to an interator, and the other that enforces uniqueness.</p></li>\n<li><p>If your input data really is huge, then a Set may not be the right data structure because of it's memory footprint. I have found that custom implementations of memory-efficient structures can save a lot of space. I hesitate to recommend that you change from the Set though, it is the 'logical' choice, but, if, for example, your average String value is about 16 characters, then more than half of your memory will be in the Set overhead. I have, in the past, had reason to do similar things to you, and have written a memory-efficient class that can be <a href=\"https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/StringBin.java\">seen in JDOM here</a> (you will need to make changes to that code if you want to use it because it will need to have a mechanism for a true/false <code>seen-it</code> test).</p></li>\n<li><p>I have a pattern I use for Iterators that is really effective, and makes the Iterator logic much simpler/readable. I'll give you an example....</p></li>\n</ul>\n\n<p>First, part 1, a Reader-to-Iterator implementation:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n@SuppressWarnings(\"javadoc\")\npublic class ReaderLineIterator implements Iterator<String> {\n\n private final BufferedReader reader;\n private String nextval;\n\n public ReaderLineIterator(Reader reader) {\n this.reader = (reader instanceof BufferedReader) ? (BufferedReader)reader :\n new BufferedReader(reader);\n\n advance();\n\n }\n\n private void advance() {\n try {\n nextval = reader.readLine();\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to read from reader.\", ioe);\n }\n }\n\n @Override\n public boolean hasNext() {\n return nextval != null;\n }\n\n @Override\n public String next() {\n if (nextval == null) {\n throw new NoSuchElementException();\n }\n try {\n return nextval;\n } finally {\n advance();\n }\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n}\n</code></pre>\n\n<p>Note how, in this class, I use a trick for the <code>nextval</code>, where it is advanced in the finally block of the <code>next()</code> call. This is a pattern I like because it makes the <code>hasNext()</code> method very light-weight, and it is always a step-ahead of the data.</p>\n\n<p>So, that is a single-purpose class, it converts a <code>Reader</code> to a line-at-a-time <code>Iterator</code>.</p>\n\n<p>Now, you need a unique <code>Iterator</code>... which can look something like:</p>\n\n<pre><code>import java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\n\n@SuppressWarnings(\"javadoc\")\npublic class UniqueIterator implements Iterator<String> {\n\n private final Iterator<String> source;\n private String nextval = null;\n Set<String> seenit = new HashSet<String>();\n\n public UniqueIterator(Iterator<String> source) {\n this.source = source;\n advance();\n }\n\n private void advance() {\n while (source.hasNext()) {\n String nxt = source.next();\n if (seenit.add(nxt)) {\n // found a unique value....\n nextval = nxt;\n return;\n }\n }\n // no more unique values.\n nextval = null;\n\n }\n\n\n\n @Override\n public boolean hasNext() {\n return nextval != null;\n }\n\n @Override\n public String next() {\n if (nextval == null) {\n throw new NoSuchElementException();\n }\n try {\n return nextval;\n } finally {\n advance();\n }\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:20:03.320",
"Id": "70943",
"Score": "0",
"body": "a `String tmp = nextval;advance();return tmp;` us IMO much more readable than the needless `try ... finally`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:31:48.600",
"Id": "70947",
"Score": "0",
"body": "@ratchetfreak perhaps... it's a habit I am in, which makes it readable to me. If I recall, there was a case where I store any advance() exceptions to the next() call, and also, it's slightly faster without the temporary store... What I have above is the general pattern, on the whole, I think I will leave it unchanged. It shows a different mechanism and may be educational"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:38:42.237",
"Id": "70950",
"Score": "0",
"body": "JIT will take care of \"slightly faster\" soon enough"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:41:24.430",
"Id": "70951",
"Score": "0",
"body": "@ratchetfreak I am aware of what JIT can do, but, the times I have looked really hard at these problems, I have found the assembly that the JIT produces to be slightly inefficient (extra load/stores), and that was only part of my reasoning."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:13:41.417",
"Id": "41334",
"ParentId": "41327",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:46:01.427",
"Id": "41327",
"Score": "6",
"Tags": [
"java",
"algorithm"
],
"Title": "Algorithm to return unique values from unsorted input"
}
|
41327
|
<p>I'm using simple script to handle tab menu like this:</p>
<p>HTML:</p>
<pre><code><nav id="personal">
<ul class="clearfix">
<li id="personal-info">Info</li>
<li id="personal-orders">Orders</li>
<li id="personal-models">Models</li>
<li id="personal-balance">Balance</li>
</ul>
</nav>
<div id="personal-content"></div>
</code></pre>
<p>and CoffeeScript:</p>
<pre><code>jQuery ($) ->
class Nav
constructor: (@elements) ->
self = @
wHash = document.location.hash.replace("#", "") or "info"
# activate element by location hash
@.activate document.getElementById "personal-#{wHash}"
# bind element activation on click
elements.click ->
self.activate @
activate: (elem) ->
@elements.removeClass "active"
$(elem).addClass "active"
# set a proper hash
wHash = elem.id.split("-")[1]
document.location.hash = "##{wHash}"
# load proper content into an inner section
# it works very fast and is the reason i use this type of navigation in the first place
$("#personal-content").load "/user/#{wHash}"
new Nav $("#personal").find("li")
</code></pre>
<p>This code works, but i'm pretty sure that it's very far away from best practices, and can be greatly improved, as these are my first tries in CoffeeScript. So the question is, can this code be beautified in some way?</p>
|
[] |
[
{
"body": "<p>You're building a navigation, however there are no links. It's highly recommended to use <code>anchor</code> tags for linking purposes.</p>\n\n<p>Your naming is a bit loose. What is <em>personal</em> in your context? Please specify that. Even something like <code>personal-navigation</code> is quite loose, but still better.</p>\n\n<p>I've changed your markup a bit to reflect my small suggestions. Note that I changed the ID's from your list items to classes. ID's are only for elements which will occur only once a page in any situation. You can't say that for sure for single navigation items.</p>\n\n<pre><code> <nav id=\"personal-navigation\">\n <ul class=\"clearfix\">\n <li class=\"personal-info\"><a href=\"#\">Info</a></li>\n <li class=\"personal-orders\"><a href=\"#\">Orders</a></li>\n <li class=\"personal-models\"><a href=\"#\">Models</a></li>\n <li class=\"personal-balance\"><a href=\"#\">Balance</a></li>\n </ul>\n </nav>\n\n <div id=\"personal-content\"></div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:36:18.807",
"Id": "70985",
"Score": "0",
"body": "`personal` is the name of the page this navigation bar is located at, it is a personal cabinet, where you can see your info, orders, models and stuff. I'm quite sure, that my `li` id's are unique, and as this page isn't meant for indexing of any sort I'm fine with that, keeping in mind that using ids is way more convenient when you want to get one single DOM element, and faster too. My question goes for the scripting part, not markup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:38:27.790",
"Id": "70986",
"Score": "2",
"body": "You've put the [tag:html] on your question so I was assuming this is part of your question. I'm no scripting guy, so I can't tell whether getting ID's or classes is faster. If this is the way you do it, it's perfectly fine. Keep in mind answers here are no orders but suggestions. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:41:21.443",
"Id": "70987",
"Score": "2",
"body": "My comment doesn't mean I don't appreciate Your effort to help :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:10:38.050",
"Id": "41347",
"ParentId": "41329",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:04:13.083",
"Id": "41329",
"Score": "8",
"Tags": [
"jquery",
"html",
"coffeescript"
],
"Title": "Simple CoffeeScript navigation menu"
}
|
41329
|
<p>I am trying to populate a vector of integers with one billion random number. The only constraint is that there can be no duplicates in the array.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
vector<int> container;
vector<int>::iterator i1;
for (int i=0;i<1000000000;i++) //a billion numbers
{
int number = rand() ;
i1 = find (container.begin(),container.end() , number );
if ( i1 != container.end() )
{
container.push_back(number);
}
}
}
</code></pre>
<p>How can my solution be improved on? It can be anything, like time taken or space complexity. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:26:23.547",
"Id": "70945",
"Score": "1",
"body": "1) `rand` *sucks*. On some machines there might not even be enough distinct values for `rand` to return. `RAND_MAX` may be as small as 2^15. 2) A hash set based approach would be much faster. Alternatively you could also use a sorting or tree based approach, but those tend to be slower than hashing."
}
] |
[
{
"body": "<p>Your solution as it stands currently is going to be incredibly slow - it's complexity is <code>O(n^2)</code>, so you're looking at roughly 10^18 \"operations\" for a billion numbers. This is because you need to search through the vector as it grows to see if you have a duplicate, which will go through the vector (on average) <code>(1 + 2 + ... + 999,999,999) / 2</code> times over the course of the algorithm. </p>\n\n<p>Edit: In fact, it's actually slightly worse than this, since as you generate more numbers, the probability that you generate something you've already \"seen\" increases.</p>\n\n<p>I'd suggest the following: since an <code>int</code> on most platforms is still 4 bytes, this still has a maximum value of a bit over 2 billion. Hence create a vector with the first billion values in order, and use <code>std::shuffle</code>. This will give you a billion \"random\" values, with the constraint that nothing will be selected from the upper range [1e9, INT_MAX].</p>\n\n<pre><code>int main()\n{\n constexpr int num_values = 1000000000;\n std::vector<int> rand_values(num_values);\n std::mt19937 eng{std::random_device{}()};\n\n for(int i = 0; i < num_values; ++i) {\n rand_values[i] = i;\n }\n\n std::shuffle(rand_values.begin(), rand_values.end(), eng);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:24:48.833",
"Id": "72202",
"Score": "0",
"body": "In the event that OP wishes to use truly random numbers, this approach will not work. The constraint of the domain of values doesn't seem reasonable in the general case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:50:18.977",
"Id": "41337",
"ParentId": "41332",
"Score": "12"
}
},
{
"body": "<p>I would just load from a file of predetermined random numbers:</p>\n\n<pre><code>std::ifstream randFile(\"NameOfFileWithRandoms\");\nstd::vector<int> randvalues(std::istream_iterator<int>(randFile),\n std::istream_iterator<int>());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T14:15:20.253",
"Id": "142202",
"Score": "0",
"body": "And what if there ever is a need for different random numbers? After all the code in the OP seeds with the current time so your solution doesn't has the same behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T19:20:43.330",
"Id": "142220",
"Score": "1",
"body": "@user45891: And that is a different question (if you ask that question I will be sure to answer it). But that was not the question. The question was just to fill a vector with unique values **As quickly as possible**."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T00:07:21.700",
"Id": "41368",
"ParentId": "41332",
"Score": "8"
}
},
{
"body": "<p>A possible solution would be to store the values in a std::unordered_set (std::unordered_set will only store unique values), and once your set reaches the desired size, to copy the set into a vector.</p>\n\n<p>This is probably not the most efficient solution but it would push the logic of determining if values are unique into the standard library and simplify your own code.</p>\n\n<pre><code>srand(time(NULL));\nauto uniqueSetOfValues = unordered_set<int>();\nwhile(uniqueSetOfValues.size() < 1000000000)\n{\n // this will only insert unique values into the set\n uniqueSetOfValues.insert(rand());\n}\n\n// start the vector with the correct size\nauto uniqueVectorOfValues = vector<int>(uniqueSetOfValues.size());\n// copy the set into the vector\ncopy(\n begin(uniqueSetOfValues),\n end(uniqueSetOfValues),\n begin(uniqueVectorOfValues));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:36:31.897",
"Id": "71182",
"Score": "1",
"body": "You might even be able to use std::move instead of std::copy since you probably don't need to keep the unordered_set around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:27:40.287",
"Id": "72203",
"Score": "1",
"body": "This has amortized O(n) time complexity. I approve. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:34:56.263",
"Id": "41429",
"ParentId": "41332",
"Score": "8"
}
},
{
"body": "<p>As per Yuushi, since the upper limit for int is 2 billion, you might just want to start with 0 and keep adding 1 or 2 a billion times. This way you are guaranteed</p>\n\n<ul>\n<li>unique numbers</li>\n<li>to stay within the int range</li>\n<li>no lookups or swaps</li>\n</ul>\n\n<p>So something like this:</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n\nusing namespace std;\n\n\nint main()\n{\n srand(time(NULL));\n\n vector<int> container;\n\n int number = 0; //Start with the number 0\n\n for (int i=0;i<1000000000;i++) //a billion numbers\n {\n number += rand() & 1 + 1; //Keep right most bit, add 1 to get 1 or 2\n container.push_back(number);\n } \n}\n</code></pre>\n\n<p>I am not a C++ expert, feel free to burninate if I am wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T01:19:07.217",
"Id": "71206",
"Score": "1",
"body": "-1 you have way too much rep to be a regular [tag:javascript] bunny. (nah, kidding)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-16T22:02:25.523",
"Id": "140837",
"Score": "1",
"body": "It looks like the distribution of numbers using this method is heavily weighted towards smaller numbers: there is approximately a 50% chance the first number is a 1 (and a 100% chance the first number is either 1 or 2) and almost no chance of ever getting the number 2 billion. Also the numbers in the container are in order from smallest to largest so you may still need to shuffle the container afterwards to make them feel more random and less ordered."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:57:31.373",
"Id": "41430",
"ParentId": "41332",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:25:12.287",
"Id": "41332",
"Score": "11",
"Tags": [
"c++",
"optimization",
"performance"
],
"Title": "Most efficient way to populate a vector of integers with no duplicates"
}
|
41332
|
<p>I am trying to find whether a given number is a perfect square or not by using just addition and subtraction.</p>
<p>Please review my code.</p>
<pre><code>#include<stdio.h>
int check(int);
main()
{
int N;
printf("\n Enter the N:");
scanf("%d",&N);
if(check(N))
{
printf("\n[%d] Perfect Square:\n",N);
}
else
{
printf("\nNot perfect Square\n");
}
}
int check(int n)
{
int i=1;
while(n>0)
{
n-=i;
printf("[%d]",n);
i+=2;
}
if(n==0)
return 1;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:17:23.430",
"Id": "70942",
"Score": "1",
"body": "Applying proper formatting to your code would be a good first step."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:21:18.743",
"Id": "70944",
"Score": "1",
"body": "Since this is C++, you could use a proper `bool` and the check at the end simplifies to `return n == 0;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:43:46.383",
"Id": "70953",
"Score": "0",
"body": "There is nothing C++ in this code, so I am going to remove that tag."
}
] |
[
{
"body": "<p><strong>Presentation</strong></p>\n\n<p>I have re-indented your code, I do not know how your code is on your side but you should definitly indent it properly.\nAlso, you should remove useless lines.</p>\n\n<p><strong>Naming</strong></p>\n\n<p><code>check</code> is not a good function name. <code>isPerfectSquare</code> would probably be easier for everyone to understand.</p>\n\n<p><strong>Documentation</strong></p>\n\n<p>Is it a good habit to add some documentation telling what your code is supposed to do. In your case, it could be nice to also tell the reader how it works.</p>\n\n<blockquote>\n <p>The expression for the nth square number is n2. This is also equal to the sum of the first n odd numbers.</p>\n</blockquote>\n\n<p><strong>Types</strong></p>\n\n<p>You can use the bool type in C++.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:22:12.087",
"Id": "41335",
"ParentId": "41333",
"Score": "14"
}
},
{
"body": "<p>Your code should only be 26 lines long. Most of the empty lines in your code are unnecessary.</p>\n\n<pre><code>#include <stdbool.h>\n#include <stdio.h>\n\nstatic bool isPerfectSquare(int n) {\n</code></pre>\n\n<p>I changed the return type to <code>bool</code>, since the function either returns <code>true</code> or <code>false</code>.</p>\n\n<pre><code> int i = 1;\n\n while (n > 0) {\n n -= i;\n i += 2;\n }\n return n == 0;\n}\n</code></pre>\n\n<p>I also removed the <code>printf</code> statement, since that has been only for debugging. Instead of leaving these statements in the code, you should write unit tests.</p>\n\n<pre><code>int main(void) {\n</code></pre>\n\n<p>I changed the return type to <code>int</code>, since that is the required return type since the year 1989.</p>\n\n<pre><code> int n;\n\n printf(\"Enter the number: \");\n</code></pre>\n\n<p>There should not be an extra newline and space in front of the word <code>Enter</code>. But there should be a space behind the colon.</p>\n\n<pre><code> if (scanf(\"%d\", &n) == 1) {\n</code></pre>\n\n<p>When the <code>scanf</code> fails, the program should not continue.</p>\n\n<pre><code> if (isPerfectSquare(n)) {\n printf(\"The number %d is a perfect square.\\n\", n);\n } else {\n printf(\"The number %d is not a perfect square.\\n\", n);\n }\n</code></pre>\n\n<p>I changed the text messages, so that they don't contain unnecessary brackets. You wrote a colon at the end of the line, which suggests that some text follows. That was misleading, so I removed it.</p>\n\n<pre><code> }\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:58:53.080",
"Id": "52021",
"ParentId": "41333",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:54:51.817",
"Id": "41333",
"Score": "7",
"Tags": [
"c",
"algorithm",
"reinventing-the-wheel"
],
"Title": "Find whether a given number is a perfect square or not"
}
|
41333
|
<p>I was asked to create a function that checks if an array of <code>double</code>s has all negative numbers or none. If these 2 (all negative, all positive) are false, check the first negative number, using recursion and <strong>only using built-in C++ features</strong>.</p>
<pre><code>int first_negative(const double val [] , unsigned array, unsigned short instance_ = 0) //Dont change instance!
{
//None negative?
bool none_negative;
for(int i = 0; i < array; i++)
{
if(val[i] > 0) none_negative = true;
else
{
none_negative = false;
break;
}
}
if(none_negative) return 0;
//All negative?
bool negative_instance;
for(int i = 0; i < array; i++)
{
if(val[i] < 0) negative_instance = true;
else
{
negative_instance = false;
break;
}
}
//Never change instance!
static short instance = instance_;
if(array < 1) return 0;
if(val[instance] < 0) return instance;
instance++;
return first_negative(val, array, instance);
}
</code></pre>
<p>Can I make it better? Can I remove the <code>instance</code> parameter?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T15:56:49.993",
"Id": "70960",
"Score": "0",
"body": "Can you please rephrase on what this is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T15:58:11.167",
"Id": "70961",
"Score": "0",
"body": "@Bobby Sure. I'll edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:34:18.247",
"Id": "70978",
"Score": "0",
"body": "You probably have a bug since you use `none_negative == true` as assignment, when it is not..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:54:26.273",
"Id": "71575",
"Score": "0",
"body": "Is the recursion imposed somehow? Because for such a task, a simple loop is going to be a lot faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T06:51:03.057",
"Id": "71589",
"Score": "0",
"body": "@AlexisWilke Yep."
}
] |
[
{
"body": "<ul>\n<li><p>I believe the parameter names <code>val</code> and <code>array</code> are switched around. An array shouldn't be a single variable, and a value shouldn't be an array. Otherwise, the names themselves are okay.</p></li>\n<li><p>It's preferred to index through a C-style array with an <code>std::size_t</code>, especially if the array size is larger than an <code>int</code>. This could be helpful if you'll be working with very large numbers, although the recursion aspect here may render that unlikely. Even if you're not, it's best to develop that habit.</p></li>\n<li><p>This looks a bit misleading:</p>\n\n<pre><code>if(val[instance] < 0) return instance;\ninstance++;\n</code></pre>\n\n<p>At first, I thought the <code>instance++</code> was missing indentation and belonged to the <code>if</code> statement. To make this clearer, you could separate the two lines or, even better, have curly braces for the <code>if</code> statement. The latter also helps with better maintainability.</p>\n\n<pre><code>if (val[instance] < 0)\n{\n return instance;\n}\n\ninstance++;\n</code></pre></li>\n<li><p>Again, some of the naming is misleading:</p>\n\n<pre><code>if(array < 1) return 0;\n</code></pre>\n\n<p>From a glance, that just looks incorrect as you cannot check an array like that. Proper naming is <em>very</em> important, even for a small program like this.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:12:56.790",
"Id": "70962",
"Score": "0",
"body": "Yep, I already use containers. This challenge was creating algorithm only built-in C++ features."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:19:41.943",
"Id": "70964",
"Score": "0",
"body": "Array is from 0 to \"array\", scan from the first value, with the \"array\" delimiter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:28:28.297",
"Id": "70973",
"Score": "0",
"body": "@LucasHenrique: That's fine. I can remove the second bulletpoint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:31:28.650",
"Id": "70975",
"Score": "0",
"body": "So, my code, can be better? (With the requirements)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:45:51.757",
"Id": "70988",
"Score": "0",
"body": "@LucasHenrique: I hope this was helpful enough for you. :-) I understand that I didn't address the recursion nor the `instance` variable, but I also didn't run this code myself. The main thing here, in terms of performance, is that you should avoid looping when you already have recursion. That was addressed very well in another answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T19:07:01.507",
"Id": "70996",
"Score": "0",
"body": "Jamal - I can check if is the first instance (0), then if it ia, I do the loops :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T15:59:39.957",
"Id": "41340",
"ParentId": "41339",
"Score": "14"
}
},
{
"body": "<p>This sounds artificial to me. Why the mundane/recursive requirements?</p>\n\n<p>To check if all values are positive, or negative, you have to scan all of the doubles.</p>\n\n<p>While you are doing that, you may as well identify which member is the first negative.</p>\n\n<p>Doing it all in combination would result in an O(n) operation that is small, and as fast as it could possibly be (unless you have things like sorted data).</p>\n\n<p>So, create a <code>DoubleDetails</code> class that takes an array of double as a parameter, scan the entire array, and save away the first negative, and two bools, whether it is all positive, or all negative.</p>\n\n<p>Then have methods that you can call on the class that return:</p>\n\n<ul>\n<li><code>allpositive()</code> - true if they are all positive</li>\n<li><code>allnegative()</code> - true if all negative.</li>\n<li><code>firstnegative()</code> - the first negative value (<code>if !allpositive && !allnegative</code>).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:07:18.573",
"Id": "41342",
"ParentId": "41339",
"Score": "7"
}
},
{
"body": "<p>You might be missing the point of recursion. Basically recursion replaces a loop. So, in your case, it doesn't make much sense to have the loop(s) inside the function. See if something like this works:</p>\n\n<pre><code>int FirstNeg(const double dblearray[], size_t size, int firstnegindex = -1, unsigned int index = 0, bool allpos = true, bool allneg = true)\n{\n if((int)size == index || (!allpos && !allneg))\n {\n if(allpos || allneg)\n firstnegindex = -1;\n return firstnegindex;\n }\n if(firstnegindex == -1 && dblearray[index] < 0)\n firstnegindex = index;\n if(allpos && dblearray[index] < 0)\n allpos = false;\n if(allneg && dblearray[index] >= 0)\n allneg = false;\n return FirstNeg(dblearray,size,firstnegindex,++index,allpos,allneg);\n}\n</code></pre>\n\n<p>This will return a -1 if the array is all negative or all positive and will return as soon as both positive and negative are shown to be present. I used an array but this should work for any indexed container.</p>\n\n<p>Your call to the function only needs to include the array and the size assuming you are starting at index 0.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:20:40.837",
"Id": "41348",
"ParentId": "41339",
"Score": "10"
}
},
{
"body": "<p>I thought \"negative\" means \"less than zero\" and \"positive\" means \"greater than zero\", with zero being neither positive nor negative. So if all array elements are zero, they are not all positive, not all negative, and there is no first negative element. If the array has no elements at all, then they are all positive and at the same time all negative. So the specification for the function is a bit on the weak side. </p>\n\n<p>Usually you use \"non-negative\" for \"positive or zero\". If you meant \"Positive or zero\" when writing \"positive\" that should be checked. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T19:02:03.893",
"Id": "41355",
"ParentId": "41339",
"Score": "11"
}
},
{
"body": "<p>I started with tinstaafl's answer, but modified it a bit to short circuit as soon as we know the answer:</p>\n\n<pre><code>int FirstNeg(const double dblearray[], size_t size, int firstnegindex = -1, unsigned int index = 0, bool haspos = false, bool hasneg = false)\n{\n if((int)size == index)\n return -1;\n if(!hasneg && dblearray[index] < 0) {\n firstnegindex = index;\n hasneg = true;\n }\n if(!haspos && dblearray[index] >= 0)\n haspos = true;\n if (haspos && hasneg)\n return firstnegindex; \n return FirstNeg(dblearray,size,firstnegindex,++index,haspos,hasneg);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:31:19.763",
"Id": "41358",
"ParentId": "41339",
"Score": "6"
}
},
{
"body": "<p>First, let's write a recursive function that returns the index of the first negative number. </p>\n\n<pre><code>int first_negative(const double numbers[], int size, int current) \n{\n if (current >= size)\n {\n return -1;\n }\n\n if (numbers[current] < 0.0)\n {\n return current;\n }\n\n return first_negative(numbers, size, ++current);\n}\n</code></pre>\n\n<p>This is nice and simple. Easy to read and understand. It doesn't fit the criteria, so it may not be obvious how this helps. But using this, let's write the more complicated function. </p>\n\n<pre><code>int first_negative_if_has_positives(const double numbers[], int size) \n{\n if (size <= 0)\n {\n return -1;\n }\n\n if (numbers[0] < 0.0)\n {\n return (first_nonnegative(numbers, size, 1) >= 0) ? 0 : -1;\n }\n\n return first_negative(numbers, size, 1);\n}\n</code></pre>\n\n<p>The basic logic here is simple. If the first number in the array is negative, check if there are any positive numbers in the array. If there are, return 0 (the index of the first element in the array, which we already know is negative). If not, return -1 because all the numbers are negative. Otherwise if the first number is not negative, we know that there are some positives, so we can just look for the first negative number. </p>\n\n<p>Now we need <code>first_nonnegative</code>, which is essentially the same function as <code>first_negative</code> with a different test. </p>\n\n<pre><code>int first_nonnegative(const double numbers[], int size, int current) \n{\n if (current >= size)\n {\n return -1;\n }\n\n if (numbers[current] >= 0.0)\n {\n return current;\n }\n\n return first_nonnegative(numbers, size, ++current);\n}\n</code></pre>\n\n<p>Now we have a complete solution. While this is more code than the other solutions, it will actually do fewer operations. The other solutions don't make full use of the elegance of recursion. They try to carry state from call to call that is unnecessary. They have to check that state in each call. Instead of carrying that state around, this solution uses the state of the first number to determine what it needs to learn. Then it uses one of two functions depending on that initial state. </p>\n\n<p>Let's look back at the criteria:</p>\n\n<ul>\n<li><code>return -1</code> if the numbers are all negative or all positive. This does that. </li>\n<li>Find the index of the first negative number otherwise. This does that.</li>\n<li>Using recursion. While the initial function is not recursive itself, it does use two recursive functions to generate the answer. It uses no loops. </li>\n<li>Only built-in C++ features. I'm not entirely sure what this means, but this solution only uses function calls, <code>if</code> statements, and <code>return</code>. It seems to fit. </li>\n</ul>\n\n<p>Complexity is the enemy of good software. It decreases performance and increases bugs. If you find yourself adding complexity, it is often helpful to step back and ask if you're going the wrong direction. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-28T15:30:15.550",
"Id": "126954",
"ParentId": "41339",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "41340",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T15:50:21.947",
"Id": "41339",
"Score": "14",
"Tags": [
"c++",
"algorithm",
"recursion"
],
"Title": "Identifying first negative number in array of doubles"
}
|
41339
|
<blockquote>
<p>There is no error checking in <code>day_of_year</code> or <code>month_day</code>. remedy this defect.</p>
</blockquote>
<p>Here is the solution:</p>
<pre><code>int day_of_year(unsigned int year, unsigned int month, int day) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if(((month >= 1) && (month <= 12)) && ((day >= 1) && (day <= daytab[leap][month]))) {
for(i = 1; i < month; i++) {
day += daytab[leap][i];
}
return day;
}
return -1;
}
void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 366))) {
for(i = 1; yearday > daytab[leap][i]; i++) {
yearday -= daytab[leap][i];
}
*pday = yearday;
*pmonth = i;
}
else {
printf("error: the yearday is invalid");
}
}
</code></pre>
<p>In the <code>day_of_year</code>'s case I have to check if the <code>yearday</code> is a valide one. <code>1 <= yearday <= (365 || 366)</code>. I changed the parameters type to unsigned, because a day can't be negative nor a year.</p>
<p>In the <code>month_day</code>'s case I check if the <code>month</code> is a valid one, it should be <code>1 <= month <= 12</code>. After this, I check if the <code>day</code> belongs to a valid interval. </p>
<p>This exercise can be found in K&R2 at page 126.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Incorrect <code>yearday</code> limit</p>\n\n<pre><code>// if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 366))) {\nif((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 365))) {\n// 365 \n</code></pre></li>\n<li><p><code>month_day()</code> and <code>day_of_year()</code> should use consistent types for <code>month</code>. Suggest <code>int</code> for both.</p>\n\n<pre><code>// int day_of_year(unsigned int year, unsigned int month, int day) {\n// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {\nint day_of_year(unsigned int year, int month, int day) {\n</code></pre></li>\n<li><p><code>month_day()</code> and <code>day_of_year()</code> should use consistent types for <code>yearday</code>. Suggest <code>int</code> for both.</p>\n\n<pre><code>// int day_of_year(unsigned int year, unsigned int month, int day) {\n// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {\nint day_of_year(unsigned int year, int month, int day) {\nvoid month_day(unsigned int year, int yearday, int *pmonth, int *pday) {\n</code></pre></li>\n<li><p>Leap year calculation <code>leap = ((year...</code> is good back to 1583. For years 4 to 1582 it is <code>leap = (year % 4 == 0);</code> 1582 has other complications. Before 4 has complications.</p></li>\n<li><p>Suggest <code>month_day()</code> return <code>int</code> to indicate success or failure.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:22:36.197",
"Id": "71003",
"Score": "0",
"body": "if `yearday` will be an int the user may pass negative values. Should I modify my function such that it will handle a negative`yearday`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:04:38.203",
"Id": "71008",
"Score": "1",
"body": "@Ionut Grt. Suggest that a negative `yearday` is treated like 0 or 367+. Looks like code `yearday >= 1` catches that already."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:10:14.347",
"Id": "41356",
"ParentId": "41343",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:11:08.653",
"Id": "41343",
"Score": "6",
"Tags": [
"c",
"beginner",
"datetime",
"error-handling"
],
"Title": "Functions that converts day of year to month and day and reverse with error checking"
}
|
41343
|
<p>I don't understand what is taking the program so long:</p>
<pre><code>#!/bin/python
primes=[]
i=0
j=0
k=0
for i in range(2,2000000): #fill in the list
primes.append(i)
i=0
while i<len(primes):
j=primes[i]
print(j)
k=0
while j*(j+k)<primes[len(primes)-1]: ##referred as 'line A'
try:
primes.remove(j*(j+k))
except ValueError:
k=k+1
continue
k=k+1
i=i+1
sump=0
i=0
for i in range(len(primes)):
sump=sump+primes[i]
print(sump)
</code></pre>
<p>I understand why the overall code is very inefficient, but line A takes 2 hours for <code>j=2</code>, and I don't understand why that is. Surely the <code>list.remove(x)</code> method is very inefficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:16:55.577",
"Id": "70963",
"Score": "0",
"body": "There is a lot you can do to improve performances in this script. The first for loop can be replaced with `primes = list(range(2,2000000))`, `primes[len(primes)-1]` is `primes[-1]` and the last for loop is `sump = sum(primes)`. I don't think that's your problem, but it's a start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:19:43.710",
"Id": "70965",
"Score": "0",
"body": "Is this Python 2? Have you done any profiling before asking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:20:14.807",
"Id": "70966",
"Score": "0",
"body": "Try moving the value of len(primes) into a variable and use that in the while loop. And try modifying the expression to \"j*(j+k)\" to \"j*j + j * k\" where \"j*j\" is pre calculated and put into some variable which would be used in computing the value of the expression"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:22:57.307",
"Id": "70967",
"Score": "0",
"body": "Tight loops are not exactly Python strongest point. Removing the inner loop with an equivalent idiomatic construct would improve things a lot. Eg. `primes = [x for x in primes if x % j or x == j]`. Even creating a completely new list each loop, this is orders of magnitude faster"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:23:02.037",
"Id": "70968",
"Score": "0",
"body": "@Wooble This is python 3 and I don't know what profiling is"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:23:41.857",
"Id": "70969",
"Score": "0",
"body": "sump = n**2 * math.log(n) / 2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:28:32.533",
"Id": "70974",
"Score": "1",
"body": "Anyway, yes, `list.remove` is an O(n) operation; first it needs to search through the list to find the item, then move all of the items after it in the list one spot to the left. Using a set would be much more efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:34:54.380",
"Id": "70979",
"Score": "0",
"body": "list.remove() is expensive, and you don't need it. If you keep your `primes` list intact, you know exactly where to find `j*(j+k)` -- it is at index `j*(j+k) - 2`. You can just set that element to zero, and then ignore zero elements in your `sump` loop."
}
] |
[
{
"body": "<p>I don't believe it is actually the specific <code>Lne A</code> that is the problem, but everything that is happening inside that loop, and most importantly, the line: <code>primes.remove(...)</code>. From <a href=\"https://stackoverflow.com/questions/1521784/cost-of-list-functions-in-python\">this StackOverflow answer</a> you can see that remove(...) is an <em>O(n)</em> operation, thus it's performance is relative to the amount of data in the array. In this case, there's a lot.... and you are doing a lot of <code>removes()</code> since you are essentially removing all even values except <code>2</code>.</p>\n\n<p>What you should be doing is using a more efficient algorithm. You should read up on the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>, and introduce that algorithm here.</p>\n\n<p>it will be much faster because it does not do any array-size changes. There are a number of posts here on CodeReview that have this problem solved quite nicely:</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/6477/sieve-of-eratosthenes-making-it-quicker\">Sieve of Eratosthenes: making it quicker</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/21659/criticize-my-first-python-module-please\">Project Euler: primes in Python</a></li>\n</ul>\n\n<p>(<a href=\"https://codereview.stackexchange.com/search?q=%5Bpython%5D%20Eratosthenes\">Primes in Python...</a>)</p>\n\n<p>(<a href=\"https://codereview.stackexchange.com/search?q=is:question%20Sieve%20Eratosthenes\">Sieve in other languages</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:43:08.997",
"Id": "70982",
"Score": "0",
"body": "Thanks, this is helpful (: This was actually a (failed) implementation of Sieves of Eratosthenes. I see that the list.remove method isn't the right thing to use, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:34:12.593",
"Id": "41345",
"ParentId": "41344",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41345",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:11:23.807",
"Id": "41344",
"Score": "4",
"Tags": [
"python",
"performance",
"primes"
],
"Title": "Sum of primes program is taking too long"
}
|
41344
|
<p>I'm just starting to learn PHP. I have three random questions about PHP and one question about Code Review. None of them are technical questions ("will this work?"); they're best practices questions ("is this the best way to do this?"). Can you offer advice?</p>
<ol>
<li><p>I put commonly used data in separate files and use include to insert them into other pages. This avoids typing the exact same code into dozens of files. Is that considered a best practice? Is there a better way to organize common page elements? An example:
A file named footer.php:</p>
<pre><code><?php echo "<p>Copyright Michael</p><p><a href="index.html">Go home</a></p>" ?>
</code></pre>
<p>And a snippet that's in all my other files:</p>
<pre><code><div id="footer"> <?php include "footer.php ?> </div>
</code></pre></li>
<li><p>What's the best way to store a MySQL connect string? I saved it in a separate "util.php" file. It reads something like:</p>
<pre><code><?php $con=mysqli_connect("localhost","admin","password","devDatabase");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
</code></pre>
<p>All files that connect to the db have:</p>
<pre><code><?php include "util.php" ?>
</code></pre>
<p>Is than an efficient and/or secure way to store the connection string?</p></li>
<li><p>What PHP frameworks do you recommend? I'm trying to get a solid understanding of PHP/Javascript/MySQL for basic web design. After that, should I select a particular PHP framework? Or should I skip PHP and move to a newer language like Ruby on Rails?</p></li>
</ol>
<p>Finally, can I get feedback by posting my URL here? If I list www.mynewsite.com and post the code for the main PHP files, could I get general feedback on the site?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:53:41.470",
"Id": "70989",
"Score": "3",
"body": "Your third question is not really on-topic for this site. Such questions tends to attract opinion answers and spam. The only SE place I know of where that question would be on-topic is [Software Recommendations](http://area51.stackexchange.com/proposals/60887/software-recommendations) which is currently in private beta."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:05:05.323",
"Id": "70990",
"Score": "1",
"body": "Regarding site feedback, we can only review code posted here (as an answer, at least)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T23:51:20.003",
"Id": "71029",
"Score": "0",
"body": "Thanks for the feedback and the editing. Can you give me specific feedback on item 2? I'm concerned that keeping the password to my database in a php file is bad security practice, but I can't think of a better place to put it. Given that I'm using a shared hosting service and can't directly access the PHP config files, is there a better place to store those credentials?"
}
] |
[
{
"body": "<p><strong>1.)</strong> What you do here is to extract code used in several locations into a shared file. Instead of describing what do to you refer to a building block to use here (the <code>footer</code> building block). This is a technique commonly used in other engineering areas as well (e.g. construction). This approach greatly boosts re-usability. In my opinion it helps to see software as a set of building blocks to combine (of course those are composed of other smaller building blocks as well). Many software architecture diagrams and techniques use this view.</p>\n\n<p>Other principles this approach relates to are:</p>\n\n<ul>\n<li><code>Modularity</code>: Decompose your system into modules. Each module represents one functional aspect of your application. Related is the <code>separation of concerns</code>: each building block has one dedicated responsibility., i.e. the rendering of the footer. </li>\n<li><code>Information hiding</code>: Hides the detail how the footer is actually rendered and how the information is retrieved.</li>\n<li><code>Don't repeat yourself</code>: Probably the most generic one applicable for all of real-life as well: Don't repeat the footer, refer to it. </li>\n</ul>\n\n<p>These principles usually are applied at another level of architecture. Yet it really helps to practice them in a smaller scale. These principles (and others not mentioned) are the foundation of software development. They are very generic though and in my opinion you really can't learn them but do experience them by applying them gradually while refining your projects. </p>\n\n<p><strong>2.)</strong> For smaller projects it is probably a good idea to keep all configuration in one location. How to actually store passwords and other sensitive information is really up to your use-case: either store it in a file, in environment variables and others. Especially for web-sites it is very common to store all configuration in one file (including passwords). Of course this file should not be accessible by visitors ;).</p>\n\n<p><strong>3.)</strong> I won't give a recommendation on any particular framework or language. With experience it mostly doesn't matter. The common principles and patterns are the same for most languages and frameworks. Yet I highly recommend to have a look at other projects and try to understand them. Learn by observing how others solve problems. Start with some smaller projects (can be as simple as a single function or class) and gradually approach more complex frameworks. Among the complex frameworks written in PHP are the big MVC-Frameworks (e.g.. Symphony, Zend Framework... ) or Doctrine. The important thing really is to understand and work with those frameworks, yet abstract their approach and not just learn how this is done in this particular framework. Of course this requires a lot of research and experimentation :). </p>\n\n<p>A final remark: the stackexchange sites works best for one new question per (unrelated) question (e.g. one for each, 1 & 2).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:10:16.393",
"Id": "41484",
"ParentId": "41349",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:44:38.767",
"Id": "41349",
"Score": "7",
"Tags": [
"php",
"beginner",
"mysql"
],
"Title": "Best Practices concerning Includes and SQL Connect Strings"
}
|
41349
|
<p>I'm working on a small GTK+ program and I'm now implementing undo and redo capabilities. This is the code that I'm using to handle the different states.</p>
<p>It's just a linked list storing the allocated <code>char *</code> returned by the text buffer. It monitors the size of the structure and the <code>char *</code>s so it will always be less than the maximum size set.</p>
<p>What should I change?</p>
<p><strong>Header</strong>:</p>
<pre><code>#ifndef TEXT_STATE_H
#define TEXT_STATE_H
#include <stdlib.h>
#include <stdbool.h>
#define TS_SUCCESS 0
#define TS_ERROR 1
#define TS_GREATER_THAN_BUFFER 2
#define TS_FAILED_TO_ALLOCATE_NODE 4
/* Here's how it works:
1 - a buffer is set
2 - every new state is pushed to the next position, if there are other "next"
states, they are removed, so if the user clicks undo then writes, he can't redo the
previous "next" states
3 - if the new state is bigger than the total allocated space, an error is
returned
4 - if there's not enough space for the new state, the oldest is removed
repeatedly until there's space.
5 - if it fails to allocate the node structure, nothing is done and an error
is returned
Size means total size, structure + text. So there's no chance of using a lot
more memory when the text states are really small.
*/
/* Store the state */
typedef struct Text_Node Text_Node;
typedef struct {
char *text;
size_t size; //including '\0'
} State;
/* The states are stored in a linked-list */
typedef struct {
Text_Node *first;
Text_Node *current;
Text_Node *last;
size_t in_use;
size_t buffer_size;
} Text_State;
//Set up the structure, buffer size
static inline void ts_init(Text_State *ts, size_t buffer_size)
{
ts->first = NULL;
ts->current = NULL;
ts->last = NULL;
ts->in_use = 0;
ts->buffer_size = buffer_size;
}
//Free all
void ts_free(Text_State *ts);
//Free all, keep buffer size, set structure so it can be used again (e.g. when
//a new document is created)
void ts_clear(Text_State *ts);
//Push new state, delete all old "next" states
int ts_push_state(Text_State *ts, char *text);
//Set state to the next if there's one and return it, otherwise return NULL
const State *ts_redo(Text_State *ts);
//Set state to the previous if there's one and return it, otherwise return NULL
const State *ts_undo(Text_State *ts);
//Return if there are next states
bool ts_can_redo(Text_State *ts);
//Return if there are previous states
bool ts_can_undo(Text_State *ts);
//Set state to the newest, return it
const State *ts_redo_all(Text_State *ts);
//Set state to the oldest, return it
const State *ts_undo_all(Text_State *ts);
//Set buffer size. If it's smaller, the first and last state will be removed
//repeatedly until the buffer size is smaller or equal to the new size
void ts_set_size(Text_State *ts, size_t new_size);
#endif
</code></pre>
<p><strong>Source</strong>:</p>
<pre><code>#include "text_state.h"
#include <string.h>
struct Text_Node {
State state;
Text_Node *next;
Text_Node *previous;
};
/////////
// Internal functions
///////
static inline size_t available_space(Text_State *ts)
{
return ts->buffer_size - ts->in_use;
}
static inline size_t space_required(Text_Node *node)
{
return sizeof(Text_Node) + node->state.size;
}
//Return an allocated copy of node
static inline Text_Node *make_node_like(Text_Node *node)
{
Text_Node *temp = malloc(sizeof(Text_Node));
if(temp != NULL)
*temp = *node;
return temp;
}
static inline bool enough_space(Text_State *ts, Text_Node *node)
{
return available_space(ts) >= space_required(node);
}
static inline bool buffer_is_too_small(Text_State *ts, Text_Node *node)
{
return space_required(node) > ts->buffer_size;
}
//There must be a first node for it to work
static void remove_first_node(Text_State *ts)
{
Text_Node *node = ts->first;
if(node == ts->current)
ts->current = node->next;
if(node->next != NULL)
node->next->previous = NULL;
//Last node
else
ts->last = NULL;
ts->first = node->next;
ts->in_use -= space_required(node);
free(node->state.text);
free(node);
}
static void remove_last_node(Text_State *ts)
{
Text_Node *node = ts->last;
if(node == ts->current)
ts->current = node->previous;
if(node->previous != NULL)
node->previous->next = NULL;
//First node
else
ts->first = NULL;
ts->last = node->previous;
ts->in_use -= space_required(node);
free(node->state.text);
free(node);
}
//Remove the current node only if there's no other option
static void remove_one(Text_State *ts, size_t *counter)
{
++*counter;
//The undo list is probably longer
if(*counter % 3 != 0){
if(ts->first != ts->current)
remove_first_node(ts);
else
remove_last_node(ts);
}
else {
if(ts->last != ts->current)
remove_last_node(ts);
else
remove_first_node(ts);
}
}
static void remove_all_nodes_after(Text_State *ts, Text_Node *node)
{
Text_Node *next = node->next;
node->next = NULL;
while((node = next) != NULL){
next = node->next;
ts->in_use -= space_required(node);
free(node->state.text);
free(node);
}
}
static void push_new_node(Text_State *ts, Text_Node *node)
{
//Handle first node
if(ts->current == NULL){
node->previous = node->next = NULL;
ts->first = ts->current = ts->last = node;
ts->in_use += space_required(node);
return;
}
node->previous = ts->current;
node->next = NULL;
ts->current->next = node;
ts->current = ts->last = node;
ts->in_use += space_required(node);
}
/////////
// Public functions
///////
void ts_free(Text_State *ts)
{
Text_Node *next;
Text_Node *current;
for(current = ts->first; current != NULL; current = next){
next = current->next;
free(current->state.text);
free(current);
}
}
//Keep the buffer size
void ts_clear(Text_State *ts)
{
ts_free(ts);
ts->first = NULL;
ts->current = NULL;
ts->last = NULL;
ts->in_use = 0;
}
int ts_push_state(Text_State *ts, char *text)
{
Text_Node temp;
temp.state.text = text;
temp.state.size = strlen(text) + 1;
//Handle separately
if(!enough_space(ts, &temp)){
if(buffer_is_too_small(ts, &temp))
return TS_ERROR | TS_GREATER_THAN_BUFFER;
//After this point, it can't fail
Text_Node *new_node = make_node_like(&temp);
if(new_node == NULL)
return TS_ERROR | TS_FAILED_TO_ALLOCATE_NODE;
//First remove all nodes that will be removed anyway
remove_all_nodes_after(ts, ts->current);
//Remove the oldest nodes if it's necessary
while(!enough_space(ts, &temp))
remove_first_node(ts);
push_new_node(ts, new_node);
return TS_SUCCESS;
}
Text_Node *new_node = make_node_like(&temp);
if(new_node == NULL)
return TS_ERROR | TS_FAILED_TO_ALLOCATE_NODE;
push_new_node(ts, new_node);
return TS_SUCCESS;
}
const State *ts_redo(Text_State *ts)
{
if(ts->current != NULL && ts->current->next != NULL){
ts->current = ts->current->next;
return &ts->current->state;
}
return NULL;
}
const State *ts_undo(Text_State *ts)
{
if(ts->current != NULL && ts->current->previous != NULL){
ts->current = ts->current->previous;
return &ts->current->state;
}
return NULL;
}
bool ts_can_redo(Text_State *ts)
{
return ts->current != NULL && ts->current->next != NULL;
}
bool ts_can_undo(Text_State *ts)
{
return ts->current != NULL && ts->current->previous != NULL;
}
const State *ts_redo_all(Text_State *ts)
{
if(ts->current == NULL)
return NULL;
ts->current = ts->last;
return &ts->current->state;
}
const State *ts_undo_all(Text_State *ts)
{
if(ts->current == NULL)
return NULL;
ts->current = ts->first;
return &ts->current->state;
}
void ts_set_size(Text_State *ts, size_t new_size)
{
if(new_size >= ts->buffer_size){
ts->buffer_size = new_size;
return;
}
//Prefer removing the first since it will probably be further from the current
size_t counter = 0;
do {
remove_one(ts, &counter);
} while(ts->buffer_size > new_size);
ts->buffer_size = new_size;
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a few notes:</p>\n\n<ul>\n<li><p>You have some <code>#define</code> statements at the beginning of your header.</p>\n\n<blockquote>\n<pre><code> #define TS_SUCCESS 0\n #define TS_ERROR 1\n #define TS_GREATER_THAN_BUFFER 2\n #define TS_FAILED_TO_ALLOCATE_NODE 4\n</code></pre>\n</blockquote>\n\n<p>You could use an <code>enum</code> instead.</p>\n\n<pre><code>typedef enum \n{\n SUCCESS = 0;\n ERROR = 1;\n GREATER_THAN_BUFFER = 2;\n FAILED_TO_ALLOCATE_NODE = 4;\n} TS;\n</code></pre>\n\n<p>If <code>FAILED_TO_ALLOCATE_NODE</code> could be set to equal 3, this could even be reduced to a one-liner.</p>\n\n<pre><code>typedef enum {SUCCESS, ERROR, GREATER_THAN_BUFFER, FAILED_TO_ALLOCATE_NODE} TS;\n</code></pre></li>\n<li><p>I'm usually not a fan of including <code><stdbool.h></code>. The only reason you use it is for return values.</p>\n\n<blockquote>\n<pre><code> static inline bool buffer_is_too_small(Text_State *ts, Text_Node *node)\n {\n return space_required(node) > ts->buffer_size;\n }\n</code></pre>\n</blockquote>\n\n<p>I prefer to just return <code>int</code> values themselves. This way, you can return a value to indicate an error (probably a negative number), a value to indicate success (probably 0), and/or a value to guide the user if there is an error (for example, <code>buffer_is_too_small</code> could return how much larger the buffer needs to be).</p></li>\n<li><p>Your <code>NULL</code> checks can be simplified.</p>\n\n<blockquote>\n<pre><code>if(node->previous != NULL)\n node->previous->next = NULL;\n</code></pre>\n</blockquote>\n\n<p>The <code>!= NULL</code> can be excluded while testing <code>node->previous</code>.</p>\n\n<pre><code>if(node) node->previous->next = NULL;\n</code></pre>\n\n<p>It is also quite simple to check if a value is <code>NULL</code> in a simpler form.</p>\n\n<pre><code>if(!ts->current) // Same as: if(ts->current == NULL)\n{\n ...\n}\n</code></pre></li>\n<li><p>I'm not the biggest fan of your very large comments.</p>\n\n<blockquote>\n<pre><code>/////////\n// Public functions\n///////\n</code></pre>\n</blockquote>\n\n<p>But that is to your discretion.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T23:05:40.863",
"Id": "41366",
"ParentId": "41350",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T17:58:23.197",
"Id": "41350",
"Score": "11",
"Tags": [
"c",
"linked-list",
"stack",
"gtk"
],
"Title": "Undo and redo functionality for a GTK+ program"
}
|
41350
|
<p>I am solving one problem with shortest path algorithm, but it is too slow.</p>
<p>The problem is that I have N points and these can be connected only if the distance between them is smaller or equal than the D. I have a <code>start</code> index and finish(<code>ciel</code> in code) index and have to return the shortest path in double format.</p>
<p>Firstly I thought that the <code>sqrt</code> is too slow, but when I changed it, it was still too slow. I am backtracking the distance and using <code>sqrt</code> just there for better speed, but it is too slow. I have used a priority queue. For more information, the input consists of the X and Y of the points , D maximal distance to make edge, start index and finish index. There can be max 1000 points.</p>
<p>// The main problem is that, it crashes of memory, I do not think I use so much of it but, it crashes from bad_alloc</p>
<p><a href="http://pastebin.com/pQS29Vw9" rel="nofollow">Here is my code</a>.</p>
<p>Are there any ways of making it faster, please?</p>
<pre><code>#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <utility>
using namespace std;
const int MAX = 1001;
const int INF = 1e9;
std::vector< std::pair<int, int> > edges[MAX]; // hrany a vzdialenosti medzi bodmi a hranami
int N; // pocet vrcholov
int start, ciel; // start a ciel index
double dijkstra() {
int vis[N]; // pocet navstiveni daneho bodu
int prevNodes[N][2];
for(int i=0;i < N;i++)
prevNodes[i][1] = INF;
std::priority_queue< std::pair<int, int> > heap; // halda
for(int i = 0; i < N; i++) vis[i] = 0;
heap.push(pair<int, int>(0, start));
while(!heap.empty())
{
pair<int, int> min = heap.top(); // vybratie dalsieho
heap.pop(); // vyhodenie pozreteho
min.first *= -1.0; // kvoli spravnemu fungovaniu priority
int v = min.second; // len pre oko
vis[v]++;
if (v == ciel && vis[v] == 1)
{
double d = 0.0;
int prevIndex = ciel, nextIndex = prevNodes[ciel][0];
while(1)
{
for(int j=0;j < edges[nextIndex].size();j++)
if(edges[nextIndex][j].first == prevIndex)
{
d += sqrt(double( edges[nextIndex][j].second ));
break;
}
prevIndex = nextIndex; // posunutie
if(nextIndex == start) // ak sme uz na zaciatku
break;
else
nextIndex = prevNodes[nextIndex][0];// posun dalej
}
return d; // najkratsia cesta
}
for (int i = 0; i < (int) edges[v].size(); i++)
{
if (vis[edges[v][i].first] < 1)
{
if(prevNodes[edges[v][i].first][1] > min.first + edges[v][i].second)
{
prevNodes[edges[v][i].first][0] = min.second;
prevNodes[edges[v][i].first][1] = min.first + edges[v][i].second;
}
heap.push(pair<int, int>(-(min.first + edges[v][i].second), edges[v][i].first));
}
}
}
return -1;
}
int main()
{
int X;
scanf("%d",&X);
double answers[X];
for(int i=0;i < X;i++)
{
int D, sIndex, eIndex; // N je globalne
scanf("%d %d", &N, &D); // N
int DD = D * D;
for(int j=0;j < N;j++)
edges[j].clear();
int V[N][2]; // N
int x, y;
for(int k=0;k < N;k++) // N
{
scanf("%d %d", &x, &y);
V[k][0] = x;
V[k][1] = y;
}
for(int a=0;a < N;a++)
for(int b=0;b < N;b++)
{
int v = (((V[a][0] - V[b][0]) * (V[a][0] - V[b][0]) +
(V[a][1] - V[b][1]) * (V[a][1] - V[b][1])));
if(v > DD)
continue;
else
{
edges[a].push_back(pair<int, int>(b, v));
edges[b].push_back(pair<int, int>(a, v));
}
}
scanf("%d %d", &start, &ciel);
start--;
ciel--;
double dijLen = dijkstra();
if(dijLen < 0)
answers[i] = -1;
else
answers[i] = dijLen;
}
for(int i=0;i < X;i++)
if(answers[i] < 0)
printf("Plan B\n");
else
printf("%.2f\n", answers[i]);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>C++-specific:</strong></p>\n\n<ul>\n<li><p>You're mixing C and C++ libraries:</p>\n\n<ul>\n<li><p>You already have <code><iostream></code>, so you don't need <code><stdio.h></code>.</p>\n\n<p>However, if you can <em>only</em> use <code>printf</code> and <code>scanf</code> for whatever reason, then remove <code><iostream></code>. Otherwise, just use <code>std::cout</code> and <code>std::cin</code>, and remove <code><stdio.h></code>.</p></li>\n<li><p>The C++ library version of <code><stdlib.h></code> is <code><cstdlib></code>.</p></li>\n<li><p>The C++ library version of <code><math.h></code> is <code><cmath></code>.</p></li>\n</ul></li>\n<li><p>Global variables is bad practice:</p>\n\n<pre><code>std::vector< std::pair<int, int> > edges[MAX];\nint N;\nint start, ciel;\n</code></pre>\n\n<p>Prefer to pass these variables to functions as needed, or keep them in the one needed function. Having them global can introduce bugs, which will just make maintenance more difficult.</p></li>\n<li><p>Although you're not doing <em>everything</em> in <code>main()</code> (which is good), you still seem to be doing quite a bit in it. If <code>dijkstra()</code> is supposed to handle most of the work, then you may need more functions to call from <code>main()</code>. It should <em>not</em> be doing the hard work; that's for the other functions.</p>\n\n<p>From a maintainability standpoint, also, this isn't the best approach. You should mostly be taking the initial input, give it to the function(s) to do the work, then receive and display the results.</p></li>\n<li><p>This loop:</p>\n\n<pre><code>for(int i=0;i < X;i++)\n if(answers[i] < 0)\n printf(\"Plan B\\n\");\n else\n printf(\"%.2f\\n\", answers[i]);\n</code></pre>\n\n<p>should have curly braces:</p>\n\n<pre><code>for(int i=0;i < X;i++)\n{\n if(answers[i] < 0)\n printf(\"Plan B\\n\");\n else\n printf(\"%.2f\\n\", answers[i]);\n}\n</code></pre></li>\n</ul>\n\n<p><strong>Performance:</strong></p>\n\n<ul>\n<li><p>Part of your performance issue may have to do with the nested <code>for</code>-loops in <code>main()</code>. At the least, you'll have O(n<sup>2</sup>), which will already be quite large, depending on the number. You then have a loop outside of that, which will increase this complexity.</p>\n\n<p>Overall, you have many loops throughout the program, which, alongside the performance issue, <em>could</em> be an indication that your algorithm implementation in't ideal. You also don't use <code>new</code> or <code>malloc</code> anywhere, so one of the container operations may be throwing <code>bad_alloc</code>. You may need to use breakpoints to determine this, perhaps where you call <code>push()</code> and <code>push_back()</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:45:58.300",
"Id": "70993",
"Score": "0",
"body": "I know about all these things, but when I am tweaking and playing with it I use some of them sometimes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:50:37.503",
"Id": "70994",
"Score": "1",
"body": "@user36546: If so, that should be stated in the explanation for the reviewers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T19:12:10.980",
"Id": "70998",
"Score": "2",
"body": "I do not think it has something to do with the real problem or its part. It is unimportant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T19:14:17.197",
"Id": "70999",
"Score": "3",
"body": "@user36546: True, but on Code Review, feedback on anything is fair game. Specific questions are still important, but they don't have to be the only things addressed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:17:08.463",
"Id": "71002",
"Score": "0",
"body": "Nested for loops in main are for for checking the distance between points and adding edge if there can exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:54:45.933",
"Id": "71116",
"Score": "0",
"body": "It's not fair game when the nitpicky stuff has nothing to do with the performance crux of his question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:59:09.147",
"Id": "71143",
"Score": "3",
"body": "@0A0D - See the [help/on-topic] for what is fair-game... it clearly says: `6. Do I want feedback about any or all facets of the code?`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:08:46.303",
"Id": "71149",
"Score": "0",
"body": "Ok, I give. It's still doesn't make sense.. what a waste of time /opinion"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:38:55.853",
"Id": "41353",
"ParentId": "41351",
"Score": "11"
}
},
{
"body": "<p>Couple things that I see that would make this a lot more efficient:</p>\n\n<p>First, you don't need to determine all of the valid edges before you start the Dijkstra algorithm. Assuming that the only constraint on whether two points have a valid edge is that \"the distance between them is smaller or equal than the D\", there is no reason to determine the complete connection tree before entering the path search. The loop in main is essentially just computing the distance from every node to every other node, with up to 1000 nodes. This gives the maximum number of distance calculations as 1000 <em>factorial</em>. Since the weight for any given edge is only the distance between them, it would be much better to just assume that all nodes are connected and reject edges <em>inside</em> the Dijkstra algorithm if the edge distance is greater than D.</p>\n\n<p>Second, you don't need to test all of the resulting edges within the Dijkstra algorithm. You can cut down on your set of edges to weigh by filtering them each time you take a step through the tree, and only calculate distances (and thus edge weighting) for nodes that are possible edges. You only have to calculate distances between any two nodes where both x[a] - x[b] and y[a] - y[b] are less than D. Taking this a step further, you only have to calculate square roots on the set of nodes where delta x plus delta y are equal <em>and</em> are the lowest value. This takes the vast majority of the math that is currently being performed with relatively expensive multiply and root calls and replaces it with cheap additions and subtractions. </p>\n\n<p>Third, depending on the distribution of the input set and the method you chose for rejecting edges in the Dijkstra algorithm, it might be faster to sort the input set before you start. That way you can just ignore any indices that fall outside of your distance constraint from the current node. Even if you are only sorting by one of the coordinates, it gives a really easy way to identify edges that have a distance greater than D because you don't have to traverse the entire set of nodes each time you are applying edge weights.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:29:51.380",
"Id": "71167",
"Score": "0",
"body": "I implemented the first and the third, but the heap sometimes ran out of memory with 1000 points, crashes, I checked it and it has about 67 000 000 items at the crash."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:43:15.260",
"Id": "71172",
"Score": "0",
"body": "Here is modified code, can you check it for logic errors due to wrong answer text please? http://pastebin.com/0WiuVCNM"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T18:51:36.997",
"Id": "71322",
"Score": "0",
"body": "I tried the A* way because it was crashing due to heap overflow. Here it is pastebin.com/sNf1w55c , I am waiting response from judge because it cannot get compiled on their compiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:17:08.163",
"Id": "71323",
"Score": "0",
"body": "I fixed it, but now I am getting wrong answer again, can somebody check the code logic please?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T01:21:21.757",
"Id": "41371",
"ParentId": "41351",
"Score": "12"
}
},
{
"body": "<p>Instead of checking:</p>\n\n<blockquote>\n <p><code>distance</code> < <code>D</code> // distance has <code>sqrt</code> calculations</p>\n</blockquote>\n\n<p>try checking</p>\n\n<blockquote>\n <p>(<code>distance</code> squared) < (<code>D</code> squared)</p>\n</blockquote>\n\n<p>No <code>sqrt</code> is required, equivalent to your test case (i.e. no imaginary distances, right?).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T06:39:28.360",
"Id": "41390",
"ParentId": "41351",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:07:37.420",
"Id": "41351",
"Score": "7",
"Tags": [
"c++",
"algorithm",
"performance",
"pathfinding"
],
"Title": "Shortest path algorithm is too slow"
}
|
41351
|
<p>This is a (relatively) cleaned-up version of a Python script I've been working on for the past day or two based on <a href="http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html" rel="nofollow">Tim Golden's first solution</a> to the above problem. I know about watchdog but I'm trying to keep dependencies down to a minimum.</p>
<p>I'm concerned about how Pythonic my code is, as this is the first "real" script I've worked on. I'm also unsure of whether I have any redundancies (like all the <code>if not ignored else None</code>s) or inefficiencies in my code.</p>
<p>Any comments on how I can properly refactor the script are appreciated.</p>
<p><strong>ianus.py</strong></p>
<pre><code>import os
def ianus(path, interval=60, recursive=True, ignore_dirs=False, ignore_files=False):
import time
def path_join(root, dest):
return os.path.join(root, dest)
def path_replace(path):
return path.replace('\\', '/') + ['', '/'][os.path.isdir(path)]
def pathify(root, dest):
return path_replace(path_join(root, dest))
def mod_time(root, dest):
return os.stat(pathify(root, dest)).st_mtime
def build(path, recursive=True, ignore_dirs=False, ignore_files=False):
def flatten(list):
return [item for sublist in list for item in sublist]
if recursive:
walk = list(os.walk(path)) if recursive else None
rdirs = flatten(
[[pathify(root, dir) for dir in dirs] for (root, dirs) in \
[(root, dirs) for (root, dirs, files) in walk]]) \
if not ignore_dirs else None
rfiles = flatten(
[[pathify(root, f) for f in files] for (root, files) in \
[(root, files) for (root, dirs, files) in walk]]) \
if not ignore_files else None
else:
l = [pathify(path, u) for u in os.listdir(path)]
rdirs = [d for d in l if os.path.isdir(d)] \
if not ignore_dirs else None
rfiles = [f for f in l if os.path.isfile(f)] \
if not ignore_files else None
return rdirs, rfiles
path = path_replace(path)
print 'Watching ' + path + '...'
print '---'
dirs_before, files_before = build(path, recursive, ignore_files, ignore_dirs)
dir_times = [(d, mod_time(path, d)) for d in dirs_before] \
if not ignore_dirs else None
file_times = [(f, mod_time(path, f)) for f in files_before] \
if not ignore_files else None
while True:
time.sleep(interval)
dirs_after, files_after = build(path, recursive, ignore_dirs, ignore_files)
new_dir_times = [(d, mod_time(path, d)) for d in dirs_after] \
if not ignore_dirs else None
new_file_times = [(f, mod_time(path, f)) for f in files_after] \
if not ignore_files else None
msg = [None, None]
if not ignore_dirs:
dirs_added = [d for d in dirs_after if not d in dirs_before]
dirs_removed = [d for d in dirs_before if not d in dirs_after]
dirs_updated = [d[0] for d in new_dir_times if not \
((d in dir_times) or (d[0] in files_added))]
msg[0] = (dirs_added, dirs_removed, dirs_updated)
if not ignore_files:
files_added = [f for f in files_after if not f in files_before]
files_removed = [f for f in files_before if not f in files_after]
files_updated = [f[0] for f in new_file_times if not \
((f in file_times) or (f[0] in files_added))]
msg[1] = (files_added, files_removed, files_updated)
print msg
print '---'
dirs_before = dirs_after
files_before = files_after
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p', type=str,
help='Set the path to be watched.')
parser.add_argument('-intr', type=int,
help='Set the poll interval of the watching thread.')
parser.add_argument('-rec',
help='Checks all subdirectories for changes.')
parser.add_argument('--ignd',
help='Ignores directories. Leaves msg[0] as None.',
action='store_true')
parser.add_argument('--ignf',
help='Ignores files. Leaves msg[1] as None.',
action='store_true')
args = parser.parse_args()
path = os.getcwd()
interval = 60
recursive, ignore_dirs, ignore_files = False, False, False
if args.p:
if os.path.isdir(args.p):
path = args.p
else:
print 'Not a valid directory.'
sys.exit(1)
if args.intr:
if args.intr < 10:
print 'Too short an interval.'
sys.exit(1)
else:
interval = args.intr
if args.rec:
recursive = True
if args.ignd:
ignore_dirs = True
if args.ignf:
ignore_files = True
if(ignore_dirs and ignore_files):
print 'Both directories and files are ignored. Nothing is watched.'
sys.exit(1)
ianus(path, interval, recursive, ignore_dirs, ignore_files)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-10T18:14:15.563",
"Id": "269829",
"Score": "0",
"body": "Readers may be interested in an alternative solutions to this problem, such as this one, and the others on the same page: http://superuser.com/a/970780/57697"
}
] |
[
{
"body": "<p>I think it's generally good! There are a few little things that stand out to me as being repetitive and not quite Pythonic. </p>\n\n<p>For instance the block at the end could be rewritten to avoid all the extra assignments. Unless you think they add readability. In which case I would suggest that the argument names themselves should be changed. </p>\n\n<pre><code>if(args.ignd and args.ignf):\n print 'Both directories and files are ignored. Nothing is watched.'\n sys.exit(1)\n\nianus(args.p, args.intr, args.rec, args.ignd, args.ignf)\n</code></pre>\n\n<p>By default, if an optional argument isn't given to argparse it is given the value of None. Which in Python is falsy. So in the block below you don't need the third line at all.</p>\n\n<pre><code>path = os.getcwd()\ninterval = 60\nrecursive, ignore_dirs, ignore_files = False, False, False\n</code></pre>\n\n<p>The other two lines could be made default arguments.</p>\n\n<pre><code>parser.add_argument('-p', type=str, default=os.getcwd(),\n help='Set the path to be watched.')\nparser.add_argument('-intr', type=int, default=60,\n help='Set the poll interval of the watching thread.')\n</code></pre>\n\n<p>It's generally accepted in Python that imports go at the top of the module/script unless you have a really good reason for delaying the import. I can't see one in this case. </p>\n\n<p>You have a helper function called <code>path_join</code>. Which is fine. But it could just as easily have been written like so</p>\n\n<pre><code>path_join = os.path.join\n</code></pre>\n\n<p>No need to create a new function that calls an existing one with exactly the same signature. If you want to call it something else for readability just assign it to a variable. </p>\n\n<p>One thing that most Python people attempt to do is write in a highly readable style. Generally avoiding shorter variable names and instead attempting to use full nouns. For instance I might write this block</p>\n\n<pre><code>l = [pathify(path, u) for u in os.listdir(path)]\n</code></pre>\n\n<p>As </p>\n\n<pre><code>contents = [pathify(path, child) for child in os.listdir(path)]\n</code></pre>\n\n<p>For the same reason most people agree that double negatives are harder to read/grok. So I might change my variable names and set the defaults to True rather than False, like below:</p>\n\n<pre><code>rfiles = [f for f in l if os.path.isfile(f)] \\\n if watch_files else None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:14:39.477",
"Id": "71245",
"Score": "0",
"body": "Thanks! Concerning imports, I thought that you import what you need in a function so that when you need to import *that* function in another script, that library gets imported as well. Is that not the case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:35:45.570",
"Id": "71257",
"Score": "0",
"body": "That is not the case. In Python there is no way to import a function from a module without loading the module itself. For the interpreter to even be aware of a function definition in a module it has to load it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T08:06:46.147",
"Id": "41394",
"ParentId": "41357",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>There are no docstrings. What do your functions do, what arguments do they take, and what do they return?</p></li>\n<li><p>It's not clear to me what I could use your program for. The output is produced like this:</p>\n\n<pre><code>print msg\nprint '---'\n</code></pre>\n\n<p>where <code>msg</code> is a complicated Python data structure (a list of tuples of lists of strings). There's no easy way for me to use this output in a shell script: it would take too much parsing.</p>\n\n<p>So what are the use cases for your program?</p></li>\n<li><p>Your code does not run under Python 3.</p></li>\n<li><p>You've defined a bunch of functions inside the function <code>ianus</code>. Presumably this is for reasons of \"privacy\" — the functions are only called in this context, so you have defined them there. However, in Python we generally don't define local functions like this unless we have a better reason than \"privacy\" (such as use of variables from the local scope). It would be simpler to define these functions at top level.</p></li>\n<li><p><code>path_join</code> is just a wrapper around <a href=\"http://docs.python.org/3/library/os.path.html#os.path.join\"><code>os.path.join</code></a> and so seems hardly worth defining. But if you really insisted on having such an alias, you could create it like this:</p>\n\n<pre><code>path_join = os.path.join\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>from os.path import join as path_join\n</code></pre></li>\n<li><p>You call <code>pathify</code> all over the place but I doubt this is necessary. The paths mostly come from <a href=\"http://docs.python.org/3/library/os.html#os.walk\"><code>os.walk</code></a> and so should be fine without this kind of manipulation.</p></li>\n<li><p>A function that does the same thing as your <code>flatten</code> is already in the standard library: <a href=\"http://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable\"><code>itertools.chain.from_iterable</code></a>.</p></li>\n<li><p>You always test <code>not ignore_files</code> and <code>not ignore_dirs</code>. This suggests that these Booleans are the wrong way round and you should have named them <code>watch_files</code> and <code>watch_dirs</code> instead.</p></li>\n<li><p>You set <code>rfiles</code> to <code>None</code> if <code>ignore_files</code> is set. This means you have to keep testing <code>if not ignore_files</code>. But if you had set <code>rfiles</code> to the empty list in that case, then you could skip the test in several places (because iterating over the empty list would yield no files).</p></li>\n<li><p>You don't need to use backslashes to continue lines inside brackets. So the backslash here is unnecessary:</p>\n\n<pre><code>dirs_updated = [d[0] for d in new_dir_times if not \\\n ((d in dir_times) or (d[0] in files_added))]\n</code></pre></li>\n<li><p>The parentheses here are unnecessary:</p>\n\n<pre><code>if(ignore_dirs and ignore_files):\n</code></pre>\n\n<p>(Python is not C.)</p></li>\n<li><p>After collecting files and directories into separate lists <code>dirs_after</code> and <code>files_after</code>, you treat them almost identically. The only difference is that changes to directories go into <code>msg[0]</code> and changes to files go into <code>msg[1]</code>. Is this distinction really necessary? If not, why not just keep one list containing all watched paths, and simplify the code accordingly.</p></li>\n<li><p>This code seems over-complicated, with double list comprehensions:</p>\n\n<pre><code>if recursive:\n walk = list(os.walk(path)) if recursive else None\n\n rdirs = flatten(\n [[pathify(root, dir) for dir in dirs] for (root, dirs) in \\\n [(root, dirs) for (root, dirs, files) in walk]]) \\\n if not ignore_dirs else None\n\n rfiles = flatten(\n [[pathify(root, f) for f in files] for (root, files) in \\\n [(root, files) for (root, dirs, files) in walk]]) \\\n if not ignore_files else None\nelse:\n l = [pathify(path, u) for u in os.listdir(path)]\n\n rdirs = [d for d in l if os.path.isdir(d)] \\\n if not ignore_dirs else None\n\n rfiles = [f for f in l if os.path.isfile(f)] \\\n if not ignore_files else None\n</code></pre>\n\n<p>I would write it like this:</p>\n\n<pre><code>watched_paths = []\nif recursive:\n for root, dirs, files in os.walk(path):\n if watch_dirs:\n watched_paths.extend(os.path.join(root, d) for d in dirs)\n if watch_files:\n watched_paths.extend(os.path.join(root, f) for f in files)\nelse:\n for entry in os.listdir(path):\n entry = os.path.join(path, entry)\n if (watch_dirs and os.path.isdir(entry)\n or watch_files and os.path.isfile(entry)):\n watched_paths.append(entry)\n</code></pre></li>\n<li><p>You've spelled the arguments <code>-intr</code> and <code>-rec</code> with a single hyphen. Generally you should reserve single hyphens for options with just one letter. So I would change these to <code>-i</code> and <code>-r</code> respectively (with long versions <code>--interval</code> and <code>--recursive</code>).</p></li>\n<li><p>In your argument parsing code, you should use the <a href=\"http://docs.python.org/3/library/argparse.html#default\"><code>default</code></a> keyword to <a href=\"http://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument\"><code>ArgumentParser.add_argument</code></a> to simplify the argument processing. For example, instead of:</p>\n\n<pre><code>parser.add_argument('-rec',\n help='Checks all subdirectories for changes.')\nparser.add_argument('--ignd',\n help='Ignores directories. Leaves msg[0] as None.',\n action='store_true')\nparser.add_argument('--ignf',\n help='Ignores files. Leaves msg[1] as None.',\n action='store_true')\n\n# ...\n\nrecursive, ignore_dirs, ignore_files = False, False, False \n\n# ...\n\nif args.rec:\n recursive = True\nif args.ignd:\n ignore_dirs = True \nif args.ignf:\n ignore_files = True\n</code></pre>\n\n<p>`\nyou could write:</p>\n\n<pre><code>parser.add_argument('-rec', default=False,\n help='Checks all subdirectories for changes.',\n action='store_true')\nparser.add_argument('--ignd', default=False,\n help='Ignores directories. Leaves msg[0] as None.',\n action='store_true')\nparser.add_argument('--ignf', default=False,\n help='Ignores files. Leaves msg[1] as None.',\n action='store_true')\n</code></pre>\n\n<p>though as explained above I would recommend reversing the sense of the option variables and write something like this instead:</p>\n\n<pre><code>parser.add_argument('-r', '--recursive', default=False,\n help='Checks all subdirectories for changes.',\n action='store_true')\nparser.add_argument('--ignore-dirs', dest='watch_dirs', default=True,\n help='Ignore directories?',\n action='store_false')\nparser.add_argument('--ignore-files', dest='watch_files', default=True,\n help='Ignore files?',\n action='store_false')\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:13:17.287",
"Id": "71244",
"Score": "0",
"body": "Thank you! That was very comprehensive and helpful. If you wouldn't mind, I still have a few questions to address to you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T13:14:48.207",
"Id": "41402",
"ParentId": "41357",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41402",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:29:29.553",
"Id": "41357",
"Score": "4",
"Tags": [
"python",
"file-system"
],
"Title": "Python script that polls for changes in filesystems"
}
|
41357
|
<p>The purpose of this code is to return an address for one of the seven judicial circuits for the cases that is passed into the function. </p>
<p>I am taking a Node ID, which is a 3-digit number the circuit number is the first digit and the county number is the last two digits.</p>
<pre><code>Set oNode = XmlDoc.SelectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Court/NodeID")
Dim Addresses() = (
"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip"
,"Title /n Street Address /n City, State Zip")
Select Case oNode/100
Case 1
ReturnData = Addresses(0)
Case 2
ReturnData = Addresses(1)
Case 3
ReturnData = Addresses(2)
Case 4
ReturnData = Addresses(3)
Case 5
ReturnData = Addresses(4)
Case 6
ReturnData = Addresses(5)
Case 7
ReturnData = Adresses(6)
End Select
</code></pre>
<p>Am I using the best coding practices and VBScript that I can be using?</p>
|
[] |
[
{
"body": "<p>Your faith in your input data is absolute... you do not do any validation. This is not a 'best practice'.</p>\n\n<p>You should at least be doing an input range check on the <code>oNode</code>.</p>\n\n<p>Once you have the range-check done, you can avoid the whole switch statement, and skip to some simple math for the index lookup:</p>\n\n<pre><code>' only process valid input.\nIf oNode >= 100 and oNode < 800 Then\n ' take advantage of the Addresses order to just do an index lookup.\n ' instead of a whole select/case statement\n ReturnData = Addresses(oNode/100 - 1)\nEnd If\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T05:03:03.863",
"Id": "71052",
"Score": "0",
"body": "that is a good idea. the input can only be certain numbers, it is a controlled field in a Database that populates an XML file that is read by my Token, so there is plenty of Data Validation already done. but I see your point"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T04:25:02.567",
"Id": "41376",
"ParentId": "41364",
"Score": "5"
}
},
{
"body": "<p>Just a couple suggestions. Since VBScript isn't a strongly typed language, I would do a recommend doing more to make sure that you are making it clear what underlying types you are working on. I prefer an explicit Array call syntax for one, but that's a matter of taste more than anything:</p>\n\n<pre><code>Dim sVariable() = Array(\"foo\",\"bar\")\n</code></pre>\n\n<p>Also make sure you declare Option Explicit (although I can't tell if it is declared or not here - this appears to be a snippet from a longer piece of code). I would also use (<em>shudder</em>) some sort of variable notation to let you keep track variable types. You apparently used one character Hungarian notation for your object - why not extend this to other types? Just because VBScript treats everything as a Variant doesn't mean you shouldn't keep track of how you are using them.</p>\n\n<p>Next is to make sure that when you are performing casts, you are doing them explicitly. The line that jumps out is:</p>\n\n<pre><code>Select Case oNode/100\n</code></pre>\n\n<p>This is implicitly doing 2 things that are non-obvious - it takes an XmlNode object, calls its default method (.Value), and then casts it to an undefined numeric type to perform division on it. While it's fairly obvious what you are doing in this case, this is a habit that can cause all types of problems in longer scripts and can be hard to figure out when debugging or re-visiting the code in a couple months.</p>\n\n<p>Speaking of debugging, I would also add error handling or trapping of some sort. Obviously trapping errors would be better than the sample below because you can give more meaningful error messages - i.e., invalid NodeID.</p>\n\n<p>Finally, you can simplify this quite a bit by just indexing into the array directly:</p>\n\n<pre><code>On Error Goto Ooops:\n\nSet oNode = XmlDoc.SelectSingleNode(\"/Record/CelloXml/Integration/Case/Hearing/Court/NodeID\")\nDim sAddresses() = Array(\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\",\n \"Title /n Street Address /n City, State Zip\")\n\nDim iIndex = CInt(oNode.Value) / 100\nsReturnData = sAddresses(iIndex - 1)\n\nOoops:\n'Fall-through is OK as long as you check for an error condition here.\nIf Err.Number <> 0 Then\n sReturnData = vbNullString\n 'Do some other useful things.\nEnd If\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:42:08.407",
"Id": "71103",
"Score": "0",
"body": "unfortunately I cannot stop the flow with a goto when there is an error because it would crash the application that I am using, but I see your point. I would have to return the error through the `ReturnData` variable (which is assigned by the application that this script is run in) I upvote because you are right and the application I am forced to work in is wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:47:49.897",
"Id": "71104",
"Score": "0",
"body": "the script that you see is what I run on a Word document (and XML) to return certain information. so I don't really have access to the rest of the code. this is pretty much what I get to work with. I will probably be posting more of these as I have posted several in the past, just so we don't bump into the same issues and think that I am not listening, lol"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T04:28:24.047",
"Id": "41377",
"ParentId": "41364",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T22:51:42.510",
"Id": "41364",
"Score": "6",
"Tags": [
"vbscript"
],
"Title": "Extracting information and returning specific data"
}
|
41364
|
<p>I'm writing a program to process log files. Currently, I have a script that will extract the desired information from each log and put it into a list - I have about nine different lists all containing different information.</p>
<p>Currently, I'm loading the file, extracting the desired information, and storing it in a list, finally I write the lists to a CSV.</p>
<p>The program roughly follows this outline.</p>
<pre><code>#load data
#create lists
list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
#extract information to populate lists.
#write CSV's
with open('output1.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list1:
writer.writerow(line)
with open('output2.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list2:
writer.writerow(line)
with open('output3.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list3:
writer.writerow(line)
with open('output4.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list4:
writer.writerow(line)
with open('output5.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list5:
writer.writerow(line)
with open('output6.csv', 'wb') as csvfile:
writer = csv.writer(out)
for line in list6:
writer.writerow(line)
</code></pre>
<p>I'm wondering if there is a better/faster way to do this. Considering these lists can get pretty large. I feel like it might be quicker/faster to load the data and immediately write is to a file as it gets processed. Thoughts?</p>
|
[] |
[
{
"body": "<p>Are you more worried about memory, speed or maintainability? if the lists are long enough that you worry about them filling up your available memory, write them out one at a time. If not, process them in bulk.</p>\n\n<p>in either case, a list-of-lists is better than maintaining 6 copies of identical code. You could use a dictionary to store the different lists with their output filenames and avoid the duplication:</p>\n\n<pre><code> lots_o_data = {\n 'list1': [.....],\n 'list2': [.....],\n 'list3': [.....]\n }\n\n for eachfilename, eachlist in lots_o_data.items():\n with open(eachfilename, 'wb') as csvfile:\n writer = csv.writer(csvfile)\n for line in eachlist: \n writer.writerow(line)\n</code></pre>\n\n<p>If the data is interleaved - stuff from different ouput lists comes up intermingled - you have to collect it all before writing. If it's sequential you can do it read A - write A - read B - write B style. Ordinarily the total time won't change much - reading and writing the data will be way slower than whatever you do in the processing. </p>\n\n<p>One thing you don't want to do is open the same source file multiple times if you don't have to - that will add extra time. Only do that if you're worried about memory. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:19:56.320",
"Id": "71195",
"Score": "0",
"body": "Yeah, I was just thinking from a speed point of view. I'll have enough memory to process in bulk, but was wondering if reading/processing/writing one log at a time offered any substantial speed benefit. I'll add the lists to a dictionary just to clean up the code. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T07:30:46.940",
"Id": "41393",
"ParentId": "41365",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-10T22:56:19.153",
"Id": "41365",
"Score": "6",
"Tags": [
"python",
"performance",
"csv"
],
"Title": "Fastest way to write multiple CSV's"
}
|
41365
|
<p>I am very new to Java so please ignore if there are obvious mistakes. If my question seems redundant then please guide me towards the correct link. However, I have surfed enough in order to find the answer. Any changes in code will be greatly appreciated.</p>
<p>I am reading an input file and storing the elements of it in a 2D array. What I want to do is split that array in 2 separate arrays. 1st array would contain all the characters which is <code>firstDimension</code> in my code. Now, I want another array which stores all the integers in an array. I just have to print those arrays. This array should be created as soon as the special character <code>></code> is observed.</p>
<p>This can be done in 2 ways:</p>
<ol>
<li>Read the strings in the file and store all of the elements in a 2D array and then divide the array into 1 double and one 2D char array</li>
<li>Read only chars from the file and store it in char array and then read only double values from the file and store it in different array.</li>
</ol>
<p>My input file has text:</p>
<blockquote>
<pre><code>a A b u>0.0001
b b X g>0.0005
Y z N H>0.0003
</code></pre>
</blockquote>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Delimiter {
public static void main(String[] args)
{
try {
Scanner scanner = new Scanner(new File("hello.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
list.add(scanner.next());
}
scanner.close();
// finally convert the arraylist to a char[][]
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i = 0; i < firstDimension.length; i++)
{
for (int j = 0; j < firstDimension[i].length; j++)
{
//System.out.println(firstDimension[i][j]);
System.out.print(" "+firstDimension[i][j]);
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T00:17:14.197",
"Id": "71031",
"Score": "0",
"body": "Your code does not actually process the `double` values...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T00:52:04.650",
"Id": "71032",
"Score": "0",
"body": "Can you guide me as to how should i parse only the characters and make one array."
}
] |
[
{
"body": "<p>Assuming that the characters on the left of the \">\" are unique (or the doubles to the right are unique), the easiest way I can think of to do this is to use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html\">HashMap</a> object. Just split the string on the \">\", and use one of them as the key and one as the value. When you're done, just retrieve the 2 collections with the keySet() and values() methods and then convert them with toArray().</p>\n\n<p>I'd also take a look at the string <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29\">split()</a> method - makes parsing really easy with a fixed format like this.</p>\n\n<p>Edit:</p>\n\n<pre><code> HashMap<String, Double> lists = new HashMap<String, Double>();\n while (scanner.hasNext()) \n {\n String[] temp = scanner.next().split(\">\");\n lists.put(temp[0], Double.parseDouble(temp[1]));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:35:14.860",
"Id": "71035",
"Score": "0",
"body": "Thankyou so much for your input.Since i am storing all the characters in the strig in ArrayList, split method does not work here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:35:44.723",
"Id": "71036",
"Score": "0",
"body": "However I will try doing it using hashmap. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:43:10.417",
"Id": "71038",
"Score": "1",
"body": "@user3293848 Welcome to Code Review / Stack Exchange! Please note, the best way to say \"Thanks!\" on SE, is by **voting** (and *accepting*) on the helpful answers :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:43:30.600",
"Id": "71039",
"Score": "0",
"body": "The .split() function is a good way to process both sides of the \">\". If you take each line that you are putting into the ArrayList and call .split(\">\") on it, element 0 will be the characters and element 1 will be your double."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:51:13.610",
"Id": "71040",
"Score": "1",
"body": "Thankyou for your help.But when I tried splitting the string which(in my code) is stored in 'list'. It says, split method is not defined for ArrayLists. Can you please show me a pseudo code if possible, it would be a great help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T03:13:45.690",
"Id": "71043",
"Score": "0",
"body": "The ArrayList isn't ever being used, so you can replace it with a HashMap and read your scanner into a temp variable. See the example edit above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:00:40.293",
"Id": "71145",
"Score": "0",
"body": "I have tried this implementation with hash map. But when I am trying to print the values in the map(double), it gives very strage values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:05:44.797",
"Id": "71148",
"Score": "0",
"body": "Modiefied code looks like this: try {Scanner scan = new Scanner(new File(\"hello.txt\"));\n scan.useDelimiter(System.getProperty(\"line.separator\"));\nMap<String, Double> lists = new HashMap<String, Double>(); while (scan.hasNext()) {String[] temp = scan.next().split(\">\");\nlists.put(temp[0], Double.parseDouble(temp[1]));}\nfor(Map.Entry<String, Double> entry:lists.entrySet()){\nString key = entry.getKey(); Double value = entry.getValue(); System.out.println(key); System.out.println(value);\nscan.close();"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:07:50.767",
"Id": "41372",
"ParentId": "41367",
"Score": "6"
}
},
{
"body": "<p>A useful first step for you to take is to separate out 1 item of functionality in to a class. Your method should be broken up in to several classes, but you will get the idea with just one.</p>\n\n<p>This one class, call it <code>DataParser</code> for want of a better name, will be used like this:</p>\n\n<pre><code>DataParser parser = new DataParser();\n// set up a loop over the input data\nfor (String line : inputlines) {\n parser.parseLine(line)\n}\nchar[][] chars = parser.getChars();\ndouble[] doubles = parser.getDoubles();\n</code></pre>\n\n<p>The advantage of this is that you can separate out your file-reading logic from your parsing logic.</p>\n\n<p>Now, about how we read the file. I recommend something simple that's new in Java 7: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29\" rel=\"nofollow\">Files.readAllLines(Path, Charset)</a>.</p>\n\n<pre><code>Path inputpath = Paths.get(\"hello.txt\");\nList<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);\n</code></pre>\n\n<p>OK, we have our input lines that way, and we can string together the two sections:</p>\n\n<pre><code>Path inputpath = Paths.get(\"hello.txt\");\nList<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);\n\nDataParser parser = new DataParser();\n// set up a loop over the input data\nfor (String line : inputlines) {\n parser.parseLine(line);\n}\nchar[][] chars = parser.getChars();\ndouble[] doubles = parser.getDoubles();\n</code></pre>\n\n<p>Now, about that <code>DataParser</code> class.... it should look something like:</p>\n\n<pre><code>public class DataParser {\n private final List<char[]> charlist = new ArrayList<>();\n private final List<Double> doublelist = new ArrayList<>();\n\n public void parseLine(String line) {\n int charpos = line.indexOf('>');\n if (charpos >= 0) {\n charlist.add(line.substring(0, charpos).toCharArray());\n doublelist.add(Double.parseDouble(line.substring(charpos + 1)));\n } else {\n // the line does not have a >\n // throw an exception?\n }\n }\n\n public char[][] getChars() {\n return charlist.toArray(new char[charlist.size()][]);\n }\n\n public double[] getDoubles() {\n double[] ret = new double[doublelist.size()];\n int cnt = 0;\n for (Double d : doublelist) {\n ret[cnt++] = d;\n }\n return ret;\n }\n\n}\n</code></pre>\n\n<p>This class will 'accumulate' the parsed data, and return it when asked. It needs to do some tricks with both accumulators to get the data out in the right format, but you should be able to figure it out.</p>\n\n<p><strong>Edit</strong> Here, I did it for you:</p>\n\n<pre><code>import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n\npublic class DataParser {\n private final List<char[]> charlist = new ArrayList<>();\n private final List<Double> doublelist = new ArrayList<>();\n\n public void parseLine(String line) {\n int charpos = line.indexOf('>');\n if (charpos >= 0) {\n charlist.add(line.substring(0, charpos).toCharArray());\n doublelist.add(Double.parseDouble(line.substring(charpos + 1)));\n } else {\n // the line does not have a >\n // throw an exception?\n }\n }\n\n public char[][] getChars() {\n return charlist.toArray(new char[charlist.size()][]);\n }\n\n public double[] getDoubles() {\n double[] ret = new double[doublelist.size()];\n int cnt = 0;\n for (Double d : doublelist) {\n ret[cnt++] = d;\n }\n return ret;\n }\n\n public static void main(String[] args) throws IOException {\n Path inputpath = Paths.get(\"hello.txt\");\n List<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);\n\n DataParser parser = new DataParser();\n // set up a loop over the input data\n for (String line : inputlines) {\n parser.parseLine(line);\n }\n char[][] chars = parser.getChars();\n double[] doubles = parser.getDoubles();\n\n System.out.println(Arrays.deepToString(chars));\n System.out.println(Arrays.toString(doubles));\n }\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n<pre><code> [[a, , A, , b, , u], [b, , b, , X, , g], [Y, , z, , N, , H]]\n [1.0E-4, 5.0E-4, 3.0E-4]\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:59:19.020",
"Id": "71144",
"Score": "0",
"body": "Thankyou for such a detailed idea about the implementation. But can you tell me if 'StandardCharSets cannot be resolved to a variable' is the issue, what actually is going wrong. Beacuse of this error 'inputlines' has null values and it is not getting used to create char or double list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:44:02.067",
"Id": "71173",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12980/discussion-between-user3293848-and-rolfl)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T03:29:12.410",
"Id": "41375",
"ParentId": "41367",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41375",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T23:55:48.173",
"Id": "41367",
"Score": "6",
"Tags": [
"java",
"beginner",
"array",
"parsing"
],
"Title": "Read an input text file and store the tokens in 2 different arrays"
}
|
41367
|
<p>I have this code in a model for an invoicing app. This virtual attribute <code>current_invoice</code> gets the only non-rescinded invoice associated with a contract. The code works but it seems really verbose. Can this be done in a prettier way?</p>
<pre><code> def current_invoice
result = []
invoices.each do |i|
if i.current_status != "rescinded"
result.push(i)
else
false
end
end
if result.length > 1
raise "Only one non-rescinded invoice association per contract"
else
result[0]
end
end
</code></pre>
<p>You might be wondering why not just do this...</p>
<pre><code>invoices.where.not(current_status: "rescinded").first
</code></pre>
<p>...but current_status is a virtual attribute on invoice.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T11:45:56.857",
"Id": "71089",
"Score": "2",
"body": "I know you said current_status is virtual, but is it initialised based on a value in the database, perhaps in another model and may be you could use that to create a query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-17T12:38:51.057",
"Id": "294602",
"Score": "0",
"body": "Related to the previous comment, if you could filter on the database level, it would be *much* faster than fetching all invoices and then filtering them in Ruby."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>result = []</code>: Try not to use generic names like <code>result</code>. Also, use plural names for collections.</p></li>\n<li><p>init empty array + each + conditional push = select/reject. More on <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming</a>.</p></li>\n<li><p><code>else false</code>. In an <code>each</code> block the value is ignored, so this does nothing.</p></li>\n<li><p><code>result[0]</code>. People usually write <code>result.first</code>, but <code>[0]</code> is also ok.</p></li>\n<li><p><code>if result.length > 1</code>. There is a serious conceptual problem here, validations should be enforced somewhere else (this is Rails, so using a validation callback). </p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def current_invoice\n non_rescinded_invoices = invoices.select { |i| i.current_status != \"rescinded\" }\n if non_rescinded_invoices.size > 1 # but this should be probably an AR validation\n raise(\"Only one non-rescinded invoice association per contract\")\n else\n non_rescinded_invoices.first\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T02:43:42.757",
"Id": "71211",
"Score": "0",
"body": "Thanks for this great answer. I actually am checking that no invoices be created if one non-rescinded invoice exists as an ActiveRecord validation, but I thought it might be a good idea to double check it here and raise an exception. What do you think about that? Is it unnecessary duplication?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:31:51.750",
"Id": "71236",
"Score": "2",
"body": "Yes, I think it's unnecessary, you need to trust your own code :) Personally I don't want a \"read-only\" method like this to raise an error regarding validations. Another matter would be if you wanted to do some asserts on the arguments of a method, some sanity checks here and there are ok."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:12:37.347",
"Id": "41421",
"ParentId": "41374",
"Score": "4"
}
},
{
"body": "<p>Here's what I would change:</p>\n\n<ol>\n<li><p>The else false isn't being used for anything</p></li>\n<li><p>Move \"rescinded\" logic to invoice instead of querying invoice and then comparing with a string.</p></li>\n<li><p>use Array#reject to eliminate rescinded invoices</p></li>\n</ol>\n\n<p>Add method to the Invoice class</p>\n\n<pre><code>class Invoice\n def rescinded?\n current_status == \"rescinded\"\n end\nend\n</code></pre>\n\n<p>and then in your method</p>\n\n<pre><code>def current_invoice\n rescinded_invoices = invoices.reject &:rescinded?\n\n raise \"Only one non-rescinded invoice association per contract\" if rescinded_invoices.length == 1\n\n rescinded_invoices.first\nend\n</code></pre>\n\n<p>EDIT for clarity:</p>\n\n<pre><code>def current_invoice\n non_rescinded_invoices = invoices.reject &:rescinded?\n\n raise \"Only one non-rescinded invoice association per contract\" if non_rescinded_invoices.length > 1\n\n non_rescinded_invoices.first\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T02:08:07.563",
"Id": "72890",
"Score": "0",
"body": "Plus one for the helpful alternative! But I'm trying to get invoices that were *not* rescinded so probably best to change the variable name. Also, would this be alright in the `current_invoice` method: `invoices.reject(&:rescinded?).first`? Without using a variable name at all if I were to ditch the exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:09:47.697",
"Id": "73114",
"Score": "1",
"body": "yep.. without your exepction it could just be `invoices.detect(&:not_rescinded?)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:31:33.630",
"Id": "42098",
"ParentId": "41374",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42098",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T02:30:36.903",
"Id": "41374",
"Score": "7",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Shorter, better way to write a \"query\" involving virtual attributes"
}
|
41374
|
<p>I just want to know if my schema file is correct:</p>
<p>XML File:</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<xs:books xmlns="http://www.w3.com/1999/XML/prjXMLValidation"
xmlns:xs="http://www.w3.org/2001/XMLSchema/prjXMLValidation"
xs:noNamespaceSchemaLocation="collection.xsd">
<xs:book title="A Lesson Before Dying" author="Ernest J. Gaines" version="1">
<xs:stars>
5
</xs:stars>
<xs:description>
This is a story about a young man that was wrongly
accused of killing a white man in the south at a time
when blacks were not given the same rights as whites.
This is the story of how Jefferson becomes a man.
</xs:description>
<xs:thoughts>
Great book!
</xs:thoughts>
</xs:book>
</xs:books>
</code></pre>
<p>Here is my XSD File:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3.org/2001/XMLSchema/prjXMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:element name="book">
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element name="stars">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element ref="1" />
<xs:element ref="2" />
<xs:element ref="3" />
<xs:element ref="4" />
<xs:element ref="5" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="description" type="xs:string" />
<xs:element name="thoughts" type="xs:string" />
</xs:sequence>
<xs:attribute name="title" type="xs:string" use="required" />
<xs:attribute name="author" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:complexType>
</xs:element>
</xs:schema>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T05:01:14.207",
"Id": "71051",
"Score": "0",
"body": "Well, you may want to include the XSD file `collection.xsd` ... ;-)"
}
] |
[
{
"body": "<p>Overall your structures look OK. Your actual XML document could be indented more neatly, but it's OK.</p>\n\n<p>I would recommend that you change your <code>stars</code> element to have an attribute. Using the PCDATA space is not a great place to put a numeric value.... Actually, I would recommend adding a <code>stars</code> attribute to the <code>thoughts</code> element (seems like a logical place to put it)....</p>\n\n<pre><code><xs:thoughts stars=\"5\" >\n Great book!\n</xs:thoughts>\n</code></pre>\n\n<p>This brings up the validation of the stars value too.... you have broken references in your XSD:</p>\n\n<pre><code> <xs:complexType>\n <xs:choice minOccurs=\"0\" maxOccurs=\"1\">\n <xs:element ref=\"1\" />\n <xs:element ref=\"2\" />\n <xs:element ref=\"3\" />\n <xs:element ref=\"4\" />\n <xs:element ref=\"5\" />\n </xs:choice>\n </xs:complexType>\n</code></pre>\n\n<p>The references <code>1</code> .... <code>5</code> are not declared. This is a problem. But, you should be using references (just not those ones....). You should be separating out your XSD types and then merging them up in complex-types with <code>ref</code> references. You should also be declaring the types outside of their usage... which makes things easier to manage.</p>\n\n<p>Consider the following (which changes the stars validation, and location).</p>\n\n<pre><code><xs:simpleType name=\"startype\">\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"[1-5]\"/>\n </xs:restriction>\n</xs:simpleType>\n\n.....\n<xs:element name=\"thoughts\">\n <xs:complexType>\n <xs:simpleContent>\n <xs:extension base=\"xs:string\">\n <xs:attribute name=\"stars\" type=\"startype\" />\n </xs:extension>\n </xs:simpleContent>\n </xs:complexType>\n</xs:element> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T11:46:31.993",
"Id": "71091",
"Score": "0",
"body": "Sorry about the formatting of my XML file. It was not like that originally, but when I put my code into the site it refused to format correctly. At least my XSD turned out the way I made it. And thank you for your advice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T05:33:18.647",
"Id": "41381",
"ParentId": "41379",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41381",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T04:56:02.280",
"Id": "41379",
"Score": "3",
"Tags": [
"xml",
"xsd"
],
"Title": "XML Schema File that validates my XML File"
}
|
41379
|
<p>My work is pretty simple. I have to migrate a bulk of data into the specified tables, so that the data does show up at the front-end. The data is provided through the Excel sheet and I have to convert it into a CSV file with <code>$</code> as a field delimiter.</p>
<p>And later I have to write a method in an Active Record Model to perform the migration.</p>
<pre><code>def self.discipline_and_speciality_migration_21Jan14
filename = "#{RAILS_ROOT}/config/discipline_and_speciality_migration_220114.csv"
file=File.new(filename,"r")
while (line = file.gets)
columns = line.split("$")
location = Location.find_by_name(columns[2].to_s.chomp.strip)
if location.blank?
location = Location.create!(:name => columns[2].to_s.chomp.strip,:short_name => columns[2].to_s.slice(0,11) , :status => "Active")
end
discipline = Discipline.find_by_name_and_location_id(columns[0].to_s.chomp.strip,location.id)
if discipline.blank?
discipline = Discipline.create!(:name=>columns[0].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[1].to_s.chomp.strip)
else
discipline.update_attributes(:location_id => location.id)
end
speciality = Speciality.find_by_name_and_location_id(columns[3].to_s.chomp.strip)
if speciality.blank?
speciality = Speciality.create!(:name => columns[3].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[4].to_s.chomp.strip,:discipline_id => discipline.id)
else
speciality.update_attributes(:location_id => location.id,:discipline_id => discipline.id)
end
end
end
</code></pre>
<p>I have no Issues with the code. I am just wondering is there any better approach to do this. Is CSV the only way? Notable modifications in the code are also welcomed.</p>
|
[] |
[
{
"body": "<p>Using an array to hold your variables is hard to maintain and to read. You can assign the fields to real variable names:</p>\n\n<pre><code>while (line = file.gets)\n discipline_name, _, location_name, speciality_name, code = \n line.split(\"$\").map(&:to_s).map(&:chomp).(&:strip)\n\n\n location = Location.find_by_name(location_name)\n if location.blank?\n location = Location.create!(:name => location_name,:short_name => columns[2].to_s.slice(0,11) , :status => \"Active\")\n end\n\n discipline = Discipline.find_by_name_and_location_id(discipline_name,location.id)\n if discipline.blank?\n discipline = Discipline.create!(:name=>discipline_name,:status=>'Active',:location_id => location.id,:code=> columns[1].to_s.chomp.strip)\n else\n discipline.update_attributes(:location_id => location.id)\n end\n\n speciality = Speciality.find_by_name_and_location_id(speciality_name)\n if speciality.blank?\n speciality = Speciality.create!(:name => speciality_name,:status=>'Active',:location_id => location.id,:code=> code,:discipline_id => discipline.id)\n else\n speciality.update_attributes(:location_id => location.id,:discipline_id => discipline.id)\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:12:42.170",
"Id": "41415",
"ParentId": "41382",
"Score": "3"
}
},
{
"body": "<p>You can use <code>first_or_initialize</code> and <code>first_or_create!</code> to skip the <code>if...else</code> statementes. </p>\n\n<pre><code>location = Location.where(name: 'New York').first_or_create! do |loc| \n loc.short_name = 'NY'\n loc.status = 'Active'\nend\n\ndiscipline = Discipline.where(name: 'Name', location_id: location.id).first_or_initialize\ndiscipline.assign_attributes code: 'code', status: 'Active'\ndiscipline.save!\n\nspeciality = Speciality.where(name: 'Name', location_id: location.id).first_or_initialize\nspeciality.assign_attributes code: 'code', discipline_id, discipline.id\nspeciality.save!\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:59:03.317",
"Id": "41431",
"ParentId": "41382",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T05:37:38.300",
"Id": "41382",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"excel",
"csv"
],
"Title": "Updating tables with bulk of data through CSV"
}
|
41382
|
<p>Help me refactor this class that helps to represent an object state as String:</p>
<pre><code>public class ConvertorToString {
private static final String SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE = "=";
private static final String SEPARATOR_BETWEEN_FIELDS = ", ";
private static final String OPEN_FIELDS = "( ";
private static final String CLOSE_FIELDS = " )";
private final String className;
private String[] fieldNames;
private Object[] fieldValues;
public static ConvertorToString buildFor(Object someObject) {
return new ConvertorToString(someObject.getClass().getName());
}
private ConvertorToString(String className) {
this.className = className;
}
public ConvertorToString withFieldNames(String... fieldNames) {
this.fieldNames = fieldNames;
return this;
}
public ConvertorToString withFieldValues(Object... fields) {
this.fieldValues = fields;
return this;
}
private class Field {
private final int index;
public Field(int index) {
this.index = index;
}
public String toString() {
checkIndex(index);
return fieldNames[index] + SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE + fieldValues[index];
}
private void checkIndex(int index) {
if (index < 0 || index >= countOfFields()) {
throw new IllegalArgumentException("Index should be inside a range: " +
"[0," + countOfFields() + "]; " + "but index was: " + index);
}
}
}
public String toString() {
checkState();
return className
+ OPEN_FIELDS +
StringsCombiner.combine(getFields(), SEPARATOR_BETWEEN_FIELDS)
+ CLOSE_FIELDS;
}
private void checkState() {
if (fieldNames == null || fieldValues == null || fieldNames.length != fieldValues.length) {
throw new IllegalStateException("count of fieldNames should be equal to count of fieldValues");
}
}
private List<Field> getFields() {
List<Field> fields = new ArrayList<Field>(countOfFields());
int countOfFields = countOfFields();
for (int i = 0; i < countOfFields; ++i) {
fields.add(new Field(i));
}
return fields;
}
private int countOfFields() {
return fieldNames.length;
}
}
</code></pre>
<p><strong>Using:</strong></p>
<pre><code>class SomeClass {
int id;
String title;
@Override
public String toString() {
return ConvertorToString.buildFor(this)
.withFieldNames("id", "title")
.withFieldValues(id, title)
.toString();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T08:29:51.237",
"Id": "71073",
"Score": "1",
"body": "Is there a particular reason why your're using your own `toString()` instead of, for example, Guava's String Helper: http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#toString?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T11:09:50.067",
"Id": "71078",
"Score": "0",
"body": "@ElServidor I didn't know about the Guava's String Helper. Thanks for the link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T13:33:12.610",
"Id": "195371",
"Score": "0",
"body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)."
}
] |
[
{
"body": "<p>I like the idea of this utility class, but there are a few points I would like to mention.</p>\n\n<p>Let's start with naming. I would rename the <code>ConvertorToString</code> class, probably, to one of the following <code>ToStringUtil</code>, <code>ToStringHelper</code>, <code>ObjectToString</code> or <code>ObjectToStringConvertor</code>. The rule of thumb is to put the <code>-or</code>/<code>-er</code> nouns in the end of the class name. Personally, I like the first two. Then come the constant fields which could be shorter. For instance, they could be named as <code>FIELD_NAME_AND_VALUE_SEPARATOR</code> instead of <code>SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE</code> and <code>FIELDS_SEPARATOR</code> instead of <code>SEPARATOR_BETWEEN_FIELDS</code>. That is, the 'BETWEEN' part is redundant because it's already obvious that a separator separates the one from the other. Two other fields would be better named as <code>FIELDS_START</code> and <code>FIELDS_END</code>, which is more intuitive.</p>\n\n<p>Another thing is that you have two separate methods for adding the field names and values and then you check that there is a corresponding value for each field name in the <code>ConvertorToString.checkState()</code> method. You also check for indexes and arrays' length in the <code>ConvertorToString.Field.checkIndex()</code> method. All these checks are error-prone, but they could be eliminated by enforcing the one-to-one correspondence rule of the field names and values in a single method for adding those fields and their values:</p>\n\n<pre><code>ToStringUtil.addField(String name, Object value);\nToStringUtil.addFields(Map<String, Object> fields);\n</code></pre>\n\n<p>This way you control the state of your object and have no need in the <code>ConvertorToString.checkState()</code> and <code>ConvertorToString.Field.checkIndex()</code> methods anymore. Moreover, internally I would store the field names and values in one data structure, rather than in two separate arrays. The single structure could be a <code>Map<String, Object></code> or a <code>List<Field></code>, the latter one is preferable if you have a <code>Field</code> class. This brings us to the <code>ConvertorToString.Field</code> class.</p>\n\n<p>I think, it would be more practical to encapsulate the field names and values within the <code>ConvertorToString.Field</code> class, which will yield a better OOP-style design. Also, this change will allow you to transform the <code>ConvertorToString.Field</code> class from an inner class to a static nested class, because you don't need the reference to the outer class anymore. After you encapsulate the field name and its value in the <code>ConvertorToString.Field</code> class, the <code>FIELD_NAME_AND_VALUE_SEPARATOR</code> field would naturally belong to the <code>ConvertorToString.Field</code> class. And because the class name is <code>Field</code>, the <code>FIELD_NAME_AND_VALUE_SEPARATOR</code> field could further be renamed to <code>NAME_AND_VALUE_SEPARATOR</code>.</p>\n\n<p>One other opinion on the <code>ConvertorToString</code> constants would be that you don't actually need them because you don't use them anywhere else besides the <code>toString()</code> methods. So, you could just use the string literals instead:</p>\n\n<pre><code>public class ToStringConvertor {\n private final String className;\n private final List<Field> fields;\n ...\n @Override\n public String toString() {\n return String.format(\n \"%s(%s)\", \n className, \n StringsCombiner.combine(fields, \", \")\n );\n }\n\n private static class Field {\n private final String name;\n private final Object value;\n ...\n @Override\n public String toString() {\n return String.format(\"%s=%s\", name, value);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T10:16:48.223",
"Id": "41397",
"ParentId": "41387",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41397",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T06:10:25.557",
"Id": "41387",
"Score": "1",
"Tags": [
"java",
"strings",
"converting"
],
"Title": "Refactor ConvertorToString class"
}
|
41387
|
<p>I have implemented a linked list. I feel I overdid it with pointers, used old standards and C++11, and I ended with too many lines of code. I will make my quotations into two parts: one for the <code>Node</code> and iterator struct and the other for rest of the class.</p>
<p>For node and iterator, how can I optimize for C++11? Can you review it?</p>
<pre><code>#include <vector>
#include <cassert>
template <typename T_>
class LinkedList
{
private:
struct Node
{
T_ data;
Node* prev;
Node* next;
/*Node(T_ D, Node* p = nullptr, Node* n = nullptr) : data(d), prev(p), next(n) {}*/
Node( const T_ & d = Object{ }, Node * p = nullptr, Node * n = nullptr )
: data(d), prev(p), next(n) { }
Node( T_ && d, Node * p = nullptr, Node * n = nullptr )
: data( std::move(d)), prev(p), next(n) { }
Node( Node && n ) { // Rvalue move ctor
data = std::move(n.data);
prev = std::move(n.prev);
next = std::move(n.next);
}
Node& operator = ( Node && n ) { // Rvalue = operator
data = std::move(n.data);
prev = std::move(n.prev);
next = std::move(n.next);
return *this;
}
void swap(Node& rhs) throw ()
{
std::swap(prev, rhs.prev); std::swap(next, rhs.next);
}
};
public:
struct LinkedListIterator : public std::iterator<std::forward_iterator_tag, T_, int>
{
Node* _pNode;
LinkedListIterator(Node* p = nullptr) : _pNode(p) {}
Node* getNode() { return _pNode; }
T_ operator * () { return _pNode->data; }
LinkedListIterator & operator ++ () { _pNode = _pNode->next; return *this; } // pre
LinkedListIterator operator ++ (int) { LinkedListIterator retval = *this; ++*this; return retval; } // post
bool operator < ( LinkedListIterator const& rhs ) const { return _pNode < rhs._pNode; }
bool operator != ( LinkedListIterator const& rhs ) const { return _pNode != rhs._pNode; }
bool operator == ( LinkedListIterator const& rhs ) const { return _pNode == rhs._pNode; }
};
</code></pre>
|
[] |
[
{
"body": "<p>There are several small things I can see in class <code>Node</code>:</p>\n\n<ul>\n<li>You have a move constructor, but no copy constructor.</li>\n<li>You have a move assignment operator, but no copy assignment operator.</li>\n<li>Since you use C++11, you should replace the exception specification <code>throw ()</code> (now deprecated) by <code>noexcept</code>.</li>\n<li>Your move assignment operator is not protected against self-assignment. You should add the condition <code>if (&n != this) { ... }</code>.</li>\n<li>Also, if possible, your move constructor and <code>operator=</code> should be <code>noexcept</code> too.</li>\n<li><p>Generally speaking, with move assignment operator, you don't want to move pointers, you only want to swap them since - I believe - your nodes own the pointed values (more information <a href=\"https://stackoverflow.com/questions/3106110/what-is-move-semantics\">here</a>).</p>\n\n<pre><code>Node& operator=(Node&& n) noexcept {\n if (&n != this) {\n std::swap(data, n.data);\n std::swap(prev, n.prev);\n std::swap(next, n.next);\n }\n return *this;\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T13:08:42.440",
"Id": "41401",
"ParentId": "41388",
"Score": "5"
}
},
{
"body": "<p>For the move stuff you want to use swap when you get down to the level of pointers.</p>\n\n<p>This is because when you move an object the src of the move should be left in a valid but indeterminate state. But you should leave it in a state so that when it is destroyed it will not affect other code.</p>\n\n<p>So this looks OK.</p>\n\n<pre><code> Node( Node && n )\n // Note there is an implicit constructor of `data` here.\n // So you construct `data` then move the content into it later.\n {\n data = std::move(n.data);\n prev = std::move(n.prev);\n next = std::move(n.next);\n }\n</code></pre>\n\n<p>But now think of the situation where somebody (a clumsey maintainer a few years from now) adds a destructor to Node that does stuff. The source object <code>n</code> still has its original value of pointer and may affect the list of nodes. What you really want to do is move the content from <code>n</code> but also put <code>n</code> into a state that it can never be harmful to the surrounding code. setting the current objects members to NULL and swapping them achieves this:</p>\n\n<pre><code> Node( Node && n )\n : data(std::move(n.data)) // move data to dst.\n , prev(NULL) // Set up pointers for swap\n , next(NULL)\n { // Rvalue move ctor\n std::swap(prev, n.prev); // swaping values should be no-throw.\n std::swap(next, n.next);\n }\n // Now 'n' is completely disconnected.\n // It can not harm the chain no matter what you do.\n</code></pre>\n\n<p>The next one is more subtle.<br>\nYou should only use the move of a templated class <code>T</code> if you can guarantee that <code>T</code> has a nothrow move semantics. </p>\n\n<pre><code> Node& operator = ( Node && n ) { // Rvalue = operator\n data = std::move(n.data);\n</code></pre>\n\n<p>What happens if half way through this move you throw an exception? Then you leave the source object <code>n</code> in some intermediate state.</p>\n\n<p>If you look at <code>std::vector</code> if the data type used does not have a nothrow move semantics then it will use copy semantics to guarantee that's its operations have the strong exception guarantee. You should strive to have the same semantics in your class.</p>\n\n<p>There is some template magic to do this test but I don;t have my notes with me.</p>\n\n<p>Are you sure you only want a forward iterator?</p>\n\n<pre><code>struct LinkedListIterator : public std::iterator<std::forward_iterator_tag, T_, int>\n ^^^^^^^^^^^^^^^^^^^^\n</code></pre>\n\n<p>You have a doubly linked list. You can easily support Bi-directional iterator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:56:56.977",
"Id": "71200",
"Score": "2",
"body": "You're likely thinking of `std::is_nothrow_move_constructible` in `<type_traits>`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:16:39.393",
"Id": "41437",
"ParentId": "41388",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T06:12:15.427",
"Id": "41388",
"Score": "5",
"Tags": [
"c++",
"optimization",
"c++11",
"linked-list",
"pointers"
],
"Title": "Optimising a LinkedList data structure - Part 1"
}
|
41388
|
<p>This is part 2. My problems are with too any pointers and with long body code in the following functions: </p>
<blockquote>
<pre><code>void push_back(T_ data);
void push_front(T_ data);
T_ pop_back();
T_ pop_front();
void insert(iterator_t& i, T_ data);
void erase(iterator_t& i);
T_ front();
T_ back();
void print();
void clear();
</code></pre>
</blockquote>
<hr>
<pre><code>private:
Node* _head;
Node* _tail;
int _size;
public:
typedef LinkedList<T_> list_t;
typedef Node node_t;
typedef list_t* listPtr;
typedef node_t* node_ptr_t;
typedef LinkedListIterator iterator_t;
LinkedList() : _head( nullptr ), _tail( nullptr ), _size( 0 ) {}
LinkedList( LinkedList && list ) { // Rvalue move ctor
_head = std::move(list._head);
_tail = std::move(list._tail);
_size = std::move(list._size);
}
~LinkedList() {
// dtor deletes all of the node ptrs in the list
// very important to avoid memory leaks
while(_head)
{
node_ptr_t tmpNode(_head);
_head = _head->next;
delete tmpNode;
}
}
LinkedList& operator = ( LinkedList && list ) { // Rvalue = operator
_head = std::move(list._head);
_tail = std::move(list._tail);
_size = std::move(list._size);
return *this;
}
bool empty() const { return ( !_head || !_tail ); }
operator bool() const { return !empty(); }
node_ptr_t head() { return _head; }
node_ptr_t tail() { return _tail; }
int size() { return _size; }
iterator_t begin() { return iterator_t(_head); }
iterator_t end() { iterator_t i(_head); while(i != nullptr) ++i; return i; }
void push_back(T_ data){
_tail = new node_t(data, _tail, nullptr);
if( _tail->prev )
_tail->prev->next = _tail;
if( empty() )
_head = _tail;
++_size;
}
void push_front(T_ data)
{
_head = new node_t(data, nullptr, _head);
if( _head->next )
_head->next->prev = _head;
if( empty() )
_tail = _head;
++_size;
}
T_ pop_back(){
assert( !empty() );
node_ptr_t tmpNode(_tail);
T_ result = _tail->data;
if(_tail->prev)
_tail = _tail->prev;
else
_tail = _head;
_tail ? _tail->next=nullptr : _head=nullptr;
--_size;
delete tmpNode;
return result;
}
T_ pop_front(){
assert( !empty() );
node_ptr_t tmpNode(_head);
T_ result = _head->data;
if(_head->next)
_head = _head->next;
else
_head = _tail;
_head ? _head->prev=nullptr : _tail=nullptr;
--_size;
delete tmpNode;
return result;
}
void insert(iterator_t& i, T_ data){
node_ptr_t tmpNode = new node_t(data, i.getNode()->prev, i.getNode());
if(i.getNode()->prev)
i.getNode()->prev->next = tmpNode;
i.getNode()->prev = tmpNode;
if(i.getNode() == _head)
_head = i.getNode()->prev;
i = iterator_t(tmpNode);
++_size;
}
void erase(iterator_t& i) {
node_ptr_t tmpNode = i.getNode();
if(i.getNode() == _head) {
_head = i.getNode()->next;
}
if(i.getNode() == _tail) {
_tail = i.getNode()->prev;
}
if( i.getNode()->next )
i = iterator_t( i.getNode()->next );
else if( i.getNode()->prev)
i = iterator_t( i.getNode()->prev );
if(tmpNode->prev)
tmpNode->prev->next = tmpNode->next;
else
tmpNode->prev = nullptr;
if(tmpNode->next)
tmpNode->next->prev = tmpNode->prev;
else
tmpNode->prev = nullptr;
delete tmpNode;
--_size;
//node_ptr_t newTail = (tail == i.getNode()->prev ) ? i.getNode()->prev : tail;
//tail = newtail;
//--_size;
//delete i.Node
}
T_ front(){
return _head->data;
}
T_ back(){
return _tail->data;
}
void print();
void clear(){
while(_head)
{
node_ptr_t tmpNode(_head);
_head = _head->next;
delete tmpNode;
}
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:12:31.403",
"Id": "71193",
"Score": "0",
"body": "You should probably include your `Node` implementation, or at least mention that it exists. At first glance, I thought you were implementing the list *and* the node in one class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:24:07.000",
"Id": "71196",
"Score": "1",
"body": "Your code becomes much simpler if you add a sentinal to the list. This will remove all the checks for NULL in the list as there is always at least one element (the sentinal). See http://codereview.stackexchange.com/a/9399/507"
}
] |
[
{
"body": "<p><strong>Size</strong></p>\n\n<p>Normally I'd say right away that <code>size</code> should return an <code>std::size_t</code> instead of an <code>int</code>, but some recent collaborations amongst top C++ experts (including Bjarne Stroustrup himself) have revealed that this can be problematic due to signed/unsigned mismatch. In your implementation at least, you could probably keep it as is, but I at least wanted to bring that up here.</p>\n\n<p><strong>Pointers</strong></p>\n\n<p>In general, keep in mind that you should use smart pointers for C++. They are preferred as they can take ownership of what they point to, which especially ensures that their data will be cleaned up properly.</p>\n\n<p>However, for containers (like you have here), you <em>would</em> use raw pointers. Just make sure to manage them correctly because the list should still be responsible for cleaning up after itself.</p>\n\n<p><strong><code>clear()</code> and <code>~LinkedList()</code></strong></p>\n\n<p>You may not need <code>clear()</code> since you already have to do the same thing in the destructor. If you prefer to be able to clear the nodes at will but keep the same object, then you can keep it. If you choose to keep it, then you can just call <code>clear()</code> in the destructor to avoid duplicate code.</p>\n\n<p><strong>Self-assignment</strong></p>\n\n<p>Normally you (may) do self-assignment with the copy constructor and <code>operator=</code>, <em>but</em> with a move contstructor, you likely will not. A more detailed answer on this can be found <a href=\"https://stackoverflow.com/a/9322542/1950231\">here</a>.</p>\n\n<p>Nonetheless, this is what <code>operator=</code> would look like if you were to use it anyway. This would also be similar for the copy constructor.</p>\n\n<pre><code>LinkedList& operator = ( LinkedList && list ) {\n if (this != &list) {\n _head = std::move(list._head);\n _tail = std::move(list._tail);\n _size = std::move(list._size);\n }\n\n return *this;\n}\n</code></pre>\n\n<p><strong>Misc.</strong></p>\n\n<ul>\n<li><p>Your <code>pop_front()</code> and <code>pop_back()</code> should just be <code>void</code>. This is especially useful as they may potentially fail (especially with templated types), and so you won't be forced to return something. However, popping from an empty container can still cause undefined behavior.</p>\n\n<p>Along with that, you can also have define <code>front()</code> and <code>back()</code> to return references to elements. With a <code>pop_back()</code> that is <code>void</code>, this will allow you to copy to a local variable before the pop.</p>\n\n<p>Note that these are all done in the STL, which you should try to imitate.</p></li>\n<li><p>With <code>begin()</code> and <code>end()</code>, you may also define <code>cbegin()</code> and <code>cend()</code>, which return <code>const</code> iterators. This would be useful for uses such as displaying the list contents.</p></li>\n<li><p><code>head()</code>, <code>tail()</code>, and <code>size()</code> should be <code>const</code> as they're accessors:</p>\n\n<pre><code>node_ptr_t head() const { return _head; }\nnode_ptr_t tail() const { return _tail; }\nint size() const { return _size; }\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:26:42.490",
"Id": "41438",
"ParentId": "41389",
"Score": "7"
}
},
{
"body": "<p>Here your code is going to crash(or have undefined behavior):</p>\n\n<pre><code>LinkedList getValue() {/*Something*/ return result;}\n\nint main()\n{\n LinkedList x = getValue();\n LinkedList y(std::move(x));\n}\n</code></pre>\n\n<p>That's because the move constructor moves all the pointers from <code>x</code> into <code>y</code>. But you have not set <code>x</code> into a different state. It still has its old values. Now <code>y</code> goes out of scope destroying the internal data. Then <code>x</code> goes out of scope with its pointers pointing at the delocated objects. But its destructor does not know they were deallocated and will do a second delete on all the members.</p>\n\n<p>This is a very expensive way to get end:</p>\n\n<pre><code>iterator_t end() { iterator_t i(_head); while(i != nullptr) ++i; return i; }\n</code></pre>\n\n<p>What happens if I write:</p>\n\n<pre><code>for(auto loop = list.begin(); loop != list.end(); ++loop)\n{}\n</code></pre>\n\n<p>Every time we test loop against end we have to loop through the whole list to construct the end iterator. That basically converts this from <code>O(n)</code> into an <code>O(n^2)</code> operation.</p>\n\n<p>If you must do it this way keep a copy for re-use. You only need to re-create it when you add/remove elements to the container the rest of the time just return your cached copy (a lot of containers use this simple optimization tactic).</p>\n\n<p>But really this class is so simple I would expect to see:</p>\n\n<pre><code>iterator_t end() { return iterator_t(tail)++;} \n</code></pre>\n\n<p>Your code could be much simpler if you use a sentinel node(s). It removes all the code that checks for NULL (as an empty list has the sentinel in it so no NULLs). Because you don't need to check for NULL it makes the code much more trivial to write).</p>\n\n<pre><code>// Look how short erase is when you don't need to worry about NULL.\nvoid erase(iterator_t& i) {\n node_ptr_t tmpNode = i.getNode();\n\n tmpNode->next->prev = tmpNode->prev;\n tmpNode->prev->next = tmpNode->next;\n\n delete tmpNode;\n --_size;\n}\n</code></pre>\n\n<p>Stop using a leading underscore:</p>\n\n<pre><code>_size\n</code></pre>\n\n<p>The rules about a leading underscore are non trivial so just don't use them. In a lot of cases they are reserved for the implementation. So the standard library can use it legitimately all the time (you can't always use it).</p>\n\n<p>Don't always return a copy.</p>\n\n<pre><code>T_ front(){\n return _head->data;\n}\nT_ back(){\n return _tail->data;\n}\n</code></pre>\n\n<p>Return a reference to the internal object. That way they can be modified in place.</p>\n\n<pre><code>T_& front(){\n return _head->data;\n}\nT_& back(){\n return _tail->data;\n}\nT_ const& front() const {\n return _head->data;\n}\nT_ const& back() const {\n return _tail->data;\n}\n</code></pre>\n\n<p>This code is exactly the same as the destructor:</p>\n\n<pre><code>void clear(){\n while(_head)\n {\n node_ptr_t tmpNode(_head);\n _head = _head->next;\n delete tmpNode;\n }\n}\n</code></pre>\n\n<p>Write DRY code. Make the constructor call clear(). But also make the destructor catch all exceptions (unlike clear). This way if a user wants to check for errors they call clear. If they don't care then the destructor will clean up and catch any exceptions (as you should never allow an exception to escape a destructor).</p>\n\n<pre><code> ~LinkedList()\n {\n try {\n clear();\n }\n catch(...) {}\n }\n</code></pre>\n\n<p>Don't expose the internal implmentation of your class:</p>\n\n<pre><code>node_ptr_t head() { return _head; }\nnode_ptr_t tail() { return _tail; }\n</code></pre>\n\n<p>We have the abstract concept of iterator to allow users to search or move through containers. Don't provide them with implementation details in the public interface as this locks you to using the implementation forever.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:35:37.907",
"Id": "41585",
"ParentId": "41389",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T06:28:01.287",
"Id": "41389",
"Score": "5",
"Tags": [
"c++",
"c++11",
"linked-list",
"pointers"
],
"Title": "Optimising LinkedList class - Part 2"
}
|
41389
|
<p>I have implemented the following PHP magic method behavior to save my time of creating accessor and mutators for properties of any class that extends this base class.</p>
<p>I am looking for suggesiongs on improving it for my application that assumes the following:</p>
<p><strong>Properties of the form:</strong></p>
<ul>
<li><code>$_first_name</code></li>
<li><code>$_user_id</code></li>
</ul>
<p><strong>Methods of the form:</strong></p>
<ul>
<li><code>getUserId()</code></li>
<li><code>setFirstName("Mohammad")</code></li>
</ul>
<p><strong>I have some points that I think need more research:</strong></p>
<ul>
<li><p>Is it a secure way? What are the insecurities here?</p></li>
<li><p>Is my way of handling errors by using <code>throw new Exception('my message');</code> a good practice? What are the alternatives?</p></li>
<li><p>Is there a best practice or a design pattern that addresses such a solution for reusability?</p></li>
<li><p>Am I exaggerating the steps? Are there any steps can be combine into one step with the same results?</p></li>
</ul>
<p><strong>The __call function of my Base class:</strong></p>
<pre><code>class Base
{
private $_first_name; // just an example
public function __call($name, $args)
{
// The begining of a method must be in all lower case characters.
// E.g. set, get
$result = preg_match('/^[a-z]*/', $name, $matches);
if($result !== 1)
{
throw new Exception('Action not recognized.');
}
// Hold the found action.
$action = $matches[0];
// Find the rest of the method name.
$result = preg_match_all('/[A-Z][a-z]*/', $name, $matches);
// $matches will hold a multi-dimensional array
// we need the first 1D array only.
$matches = $matches[0];
if($result < 1 || $result === FALSE)
{
throw new Exception('Malformed method name.');
}
// Construct the property name.
$property = '_' . strtolower(implode('_', $matches));
if(! property_exists($this, $property))
{
throw new Exception("Property: '{$property}' not found.");
}
switch($action)
{
// Mutator
case 'set':
{
if(count($args) === 1)
{
$this->$property = $args[0];
return;
}
else
{
throw new Exception('You must provide 1 argument only.');
}
}
// Accessor
case 'get':
{
return $this->$property;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Exceptions are fine, but consider using less general <code>Exception</code> classes, like <code>BaseException</code> or whatever. This will allow for more flexible error reporting.</p>\n\n<p>First thing that strikes me as odd about your code is that you're using underscore to name your properties, but CamelCase to name your methods. This is quite inconsistent and leads to unnecessary complexity here. Using naming convention that actually helps you is a good idea.</p>\n\n<p>With that in mind, a little change in naming convention could turn into something like this:</p>\n\n<pre><code>function __call($method, $args)\n{\n $action = substr($method, 0, 3);\n $prop = strtolower(substr($method, 3));\n $getter = \"get\".ucfirst($prop);\n $setter = \"set\".ucfirst($prop);\n\n switch ($action) {\n case \"get\" :\n if (isset($this->_fields[$prop])) {\n return $this->_fields[$prop];\n } else throw new EntityException(\"Unknown property {$prop}\");\n break;\n case \"set\" :\n if (isset($this->_fields[$prop])) {\n $this->_fields[$prop] = $args[0];\n return null;\n } else\n throw new EntityException(\"Unknown property {$prop}\");\n break;\n default : throw new EntityException(\"Unknown action {$action[0]}\");\n }\n}\n</code></pre>\n\n<p>Notice i use a an array <code>$this->_fields</code> to store all my fields. This goes for my second point - Safety and Reusability.</p>\n\n<p>Consider this piece of code:</p>\n\n<pre><code>class User\n{\n private $_name; \n\n function getName(){\n return $this->_name;\n }\n}\n</code></pre>\n\n<p>We use our <code>getName</code> method everywhere, but later we need to add another field - second name. We can safely insert this second field inside our <code>getName</code> and the code would change without taking any further actions. This is kinda the whole point behind getters and setters - incapsulating logic away.</p>\n\n<p>Now with your code you'll have complications with overriding your setters, and that doesn't make it safe in any way.</p>\n\n<p>Now, reusability. In your base class, you write all your fields explicitly, which doesn't seem very reusable to me. Look this code (warning, large wall of text incoming).</p>\n\n<pre><code>abstract class Entity\n{\n private $_fields;\n protected $schema = array();\n\n function __construct(array $data = array())\n {\n /** Check that our concrete implementation has its Schema */\n if (!$this->schema) {\n throw new EntityException(\"Class \".get_called_class().\" Schema not defined\");\n }\n /**\n * mapping fields value to our schema\n *\n * @TODO Move to separate method to do this not only on Construct;\n */\n\n $this->_fields = array_reduce(\n $this->schema,\n function ($fields, $element) use ($data) {\n $fields[$element] = $data[$element];\n return $fields;\n }\n );\n }\n\n function __call($method, $args)\n {\n /** Same call implementation here as above */\n }\n\n /**\n * Inner getter for getter/setter overrides\n */\n\n protected function getField($name)\n {\n if (!isset($this->_fields[$name])) {\n throw new EntityException (\"Property {$name} not found\");\n }\n return $this->_fields[$name];\n }\n\n /**\n * Inner setter for getter/setter overrides\n */\n\n protected function setField($name, $value)\n {\n if (!isset($this->_fields[$name])) {\n throw new EntityException (\"Property {$name} not found\");\n } \n $this->_fields[$name] = $value;\n }\n}\n\n/**\n * Class User\n *\n * Concrete implementation of Entity class\n *\n */\nclass User extends Entity\n{\n /**\n * List of our entity fields\n * @var array\n */\n protected $schema = array(\"id\", \"name\", \"email\", \"phone\");\n\n /**\n * method getName concrete implementation;\n *\n * @return string\n */\n\n function getName()\n {\n return \"My name is \".$this->getField(\"name\");\n }\n}\n\n\ntry {\n $userData = array(\"id\" => 1, \"name\" => \"Andrew\", \"phone\" => \"000000000\", \"email\" => \"test@test.com\");\n\n $user = new User($userData);\n\n echo $user->getName().\"<br />\";\n echo $user->getEmail().\"<br />\";\n $user->setPhone(\"111111111\");\n echo $user->getPhone();\n\n} catch (Exception $e) {\n echo $e->getMessage();\n}\n</code></pre>\n\n<p>Now, if you want to create a <code>News</code> entity, you can simply write:</p>\n\n<pre><code>class News extends Entity\n{\n protected $schema = array(\"id\", \"title\", \"text\", \"time\");\n}\n</code></pre>\n\n<p>And use it at your leisure. Later you can add active record methods to <code>Entity</code>, like <code>save</code>, <code>delete</code>, <code>update</code> and so on, and still use them on any entity you might want.</p>\n\n<p>As to why i used array <code>$_fields</code> instead of simply listing fields - array is much more convenient when you have to map values to your fields and build queries from them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T23:12:56.670",
"Id": "71194",
"Score": "1",
"body": "For reference, the `ucfirst` to create the getter and setter names aren't necessary. Besides the fact that function/method names in PHP are case-insensitive...you already *have* the method name, as `$method`. In fact, if the method already exists and is public, `__call` will never be called at all, so you don't really have to check for its existence; you already know it doesn't exist, unless `private` and `protected` are being used incorrectly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T13:05:10.743",
"Id": "71273",
"Score": "0",
"body": "First i use `strtolower` to get desired property name. Then i have to use `ucfirst`. And case-insensitivity is one of those things that hurt me alot about PHP, so i prefer not to use it. Good point about method_exists check though, thanks, i'll made necessary edits."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T10:09:32.893",
"Id": "41396",
"ParentId": "41392",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T07:14:00.683",
"Id": "41392",
"Score": "4",
"Tags": [
"php",
"design-patterns"
],
"Title": "PHP magic function for accessors and mutators"
}
|
41392
|
<p>I'am trying to build a PHP/MySQL/jQuery comment system. Off late I started to realize that manual spamming is a serious issue that need to be addressed carefully. So I thought of building a PHP function (initially, later can be implemented in OOPS concept) that will sniff the content and give points (spam points) based on some criteria. Getting a spam point less than will make the content inactive and send for moderation, whereas posts with spam points greater than 2 won't make the content eligible to be inserted in DB. This is a very basic piece of codes, so I want you to give me your valuable suggestion as how to make this code much better and if I am doing something wrong here.</p>
<pre><code><?php
#spam points < 2 { will be send for moderation}
#spam points > 2 { wont be posted , ie wont be inserted in DB}
function sniffSpams($content)
{
$spam_points = 0;
$url_pattern = '#(www\.|https?://)?[a-z0-9]+\.[a-z0-9]{2,4}\S*#i';
preg_match_all($url_pattern, $content, $matches, PREG_PATTERN_ORDER);
if(! empty($matches))
{
//url is/are present
$get_number_of_urls = count($matches[0]); //get the number of urls/emails present in content
if($get_number_of_urls > 2)
$spam_points += $get_number_of_urls; //1 point per link
else
{
$spam_words_uri = array('free', 'vote', 'play');
//if less thamn 2 , check for length of url
foreach ($matches[0] as $url)
{
if(strlen($url) > 150) //long url mostly are spam
$spam_points += 1;
foreach($spam_words_uri as $spam)
{
if(stripos($url, $spam) !== false )
$spam_points += 1;
}
}
}
}
$spam_words = array('Levitra', 'viagra', 'casino', '*');
foreach($spam_words as $spam)
{
if(stripos($content, $spam) !== false )
$spam_points += 1;
}
return $spam_points;
}
echo sniffSpams('the * dsjdjsd ');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:28:38.340",
"Id": "71509",
"Score": "1",
"body": "You could pull the spam words from a database or text file. That way you don't have to keep change the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T06:50:59.800",
"Id": "71588",
"Score": "0",
"body": "@James yep , that is the next thing , will be pulling strings (banned etc) form text file or so . Next will be wrapping this thing into a class . But what do you thing about the function ? Feasible or need some more changes ?"
}
] |
[
{
"body": "<p>Minor (and subjective) remarks:</p>\n\n<ul>\n<li>Function name: The function does not sniff spam but calculate a score for the given content. Therefore I'd rename the function to something like <code>getSpamScore</code></li>\n<li>The variable <code>$matches</code> is not declared. Declaring it before using in in <code>preg_match_all</code> allows IDEs to perform code analysis and other developers don't have a hard time looking for its declaration. </li>\n<li>Two empty lines just take up space. Your code should be clear enough from structure not to need any extra indentions (which you don't have) or double blank lines. As the <code>preg_match_all</code> is directly related to the <code>if</code> and only to it, I'd not have any lines at all between the match and the if-statement. (This applies to all other lines too)</li>\n<li><code>//url is/are present</code> comment: more of a personal thing maybe: I don't like obvious comments. Personally I prefer the <code>if it needs a comment it needs to be refactored</code> way of writing comments (non in about almost every case). Comments need maintenance time (updating comments for changed code). But time should only be spent here if it provides value. Additionally comments tend to loose their relation to the code they originally were attached to (mostly by refactoring). This greatly confuses other developers. </li>\n<li><code>$get_number_of_urls</code> naming: this variable contains a verb. Verbs indicate actions (e.g. a method). In PHP I'd expect this variable to be a closur, not an integer. Yet you don't actually get the number or urls, you already have them. A proper name might be <code>number_of_urls</code> instead. </li>\n<li>Stick to one convention of styling code: in your case this especially applies for where to have whitespaces. In your <code>if</code> and <code>foreach</code> lines you mix up <code>foreach(</code> <code>foreach (</code> and your <code>if</code> conditions sometimes have whitespaces in between and sometimes not. I suppose this is some kind of work-in-progress code. Yet later styling costs time. Code you write always should meet <code>production ready</code> requirements (regarding style). It takes some time at the beginning to stick with someones conventions, but you'll get used to it and do it automatically after some time.</li>\n<li>In my opinion this function has too many responsibilities (at least two). I'd suggest splitting this function into two sub-functions. This function itself only calls and sums of the results of the independent tests. When going OO this of course wants a design pattern ;)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:49:22.270",
"Id": "71997",
"Score": "0",
"body": "Thanks a ton for the remarks . Will be working on those you pointed out !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:22:49.030",
"Id": "41676",
"ParentId": "41399",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T12:59:51.270",
"Id": "41399",
"Score": "3",
"Tags": [
"php"
],
"Title": "Spam detection in PHP for comment system"
}
|
41399
|
<p>This will be a function that returns a random number from Dice Notation (<a href="http://en.wikipedia.org/wiki/Dice_notation" rel="nofollow">more on Wikipedia</a>). I will later use this function to determine whether some skill check is passed or not.</p>
<ol>
<li>Is there any need for optimization?</li>
<li>If so, how?</li>
<li>Any other thoughts about this code?</li>
</ol>
<hr>
<pre><code>#include <string>
using namespace std;
int toInt(string text) {
return atoi(text.c_str());
}
int main(int argc, char* argv[]) {
srand(time(NULL));
string diceString = "1d6+4";
unsigned int dice1number = 0;
string info = "dice ["+diceString+"] = %i\n";
printf("==[START]================\n");
printf(info.c_str(),dice1number);
// parse dice
unsigned int i=0;
unsigned int part = 1;
string dicePart1 = "";
string dicePart2 = "";
string dicePart3 = "";
for(i=0;i<diceString.length();i++) {
if (diceString[i]=='d') {
part = 2;
continue;
}
if (diceString[i]=='+') {
part = 3;
continue;
}
if (diceString[i]=='-') {
dicePart3 += "-";
part = 3;
continue;
}
if (part==1 && diceString[i]>='0' && diceString[i]<='9') {
dicePart1 += diceString[i];
}
if (part==2 && diceString[i]>='0' && diceString[i]<='9') {
dicePart2 += diceString[i];
}
if (part==3 && diceString[i]>='0' && diceString[i]<='9') {
dicePart3 += diceString[i];
}
}
printf("dicePart1 = [%s]\n",dicePart1.c_str());
printf("dicePart2 = [%s]\n",dicePart2.c_str());
printf("dicePart3 = [%s]\n",dicePart3.c_str());
int roll = 0;
int add = toInt(dicePart3);
roll = toInt(dicePart1) * (rand() % toInt(dicePart2)) + add;
printf("roll = [%i]\n",roll);
printf("==[END]==================\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:49:58.487",
"Id": "71105",
"Score": "2",
"body": "Hi, and welome to CodeReview's 'First Question' review. It would be helpful if you added a bit more of a description about what your code is supposed to do. Adding a description gives the reviewer something to reference back to, and to identify discrepancies. Otherwise, decent question!"
}
] |
[
{
"body": "<h1>Bug</h1>\n\n<p>Your code has an integer-division/multiplication problem/bug.</p>\n\n<p>Consider the dice-roll specification <code>10d10+0</code>.</p>\n\n<p>Your code will parse this down to:</p>\n\n<pre><code>string dicePart1 = \"10\";\nstring dicePart2 = \"10\";\nstring dicePart3 = \"0\";\n</code></pre>\n\n<p>and this will be used as:</p>\n\n<pre><code>int add = toInt(dicePart3);\nroll = toInt(dicePart1) * (rand() % toInt(dicePart2)) + add\n</code></pre>\n\n<p>At face value, this may be OK, but, in reality, the calculation boils down to:</p>\n\n<pre><code>roll = 10 * (rand() % 10) + 0;\n</code></pre>\n\n<p>This will only ever be able to produce 10 results, <code>0, 10, 20, 30, ...., 90</code>, which really is not what you want.</p>\n\n<p>You really should do this as a loop, or as a floating point operation.... the loop seems to be easier:</p>\n\n<pre><code>roll = toInt(dicePart3);\nfor (i = toInt(dicePart1); i > 0; i--) {\n roll += (rand() % toInt(dicePart2));\n}\n</code></pre>\n\n<h1>Second Bug</h1>\n\n<p>In addition to the bug I pointed out above, I have actually identified a second bug. Dice are always 1-based.... you cannot roll a '0'. So, the method would actually have to be:</p>\n\n<pre><code>roll = toInt(dicePart3);\nfor (i = toInt(dicePart1); i > 0; i--) {\n roll += 1 + (rand() % toInt(dicePart2));\n}\n</code></pre>\n\n<h1>Discussion on distribution...</h1>\n\n<p>You may be tempted to be more efficient and use the function:</p>\n\n<pre><code>int p1 = toInt(dicePart1);\nint p2 = toInt(dicePart2);\nint p3 = toInt(dicePart3);\n\nroll = p1 + (rand() % (p1 * p2)) + p3;\n</code></pre>\n\n<p>The above will create a result that is distributed in the correct range.... but the actual distribution curve is flat.... the odds of a <code>10d10+0</code> being 10 is the same as it being 50.... but, in reality, there are many ways to throw a 50, but only 1 way to throw a 10. As a result, the roll-value of <code>10d10+0</code> is not evenly distributed in the range <code>10 ... 100</code>. You <strong>need</strong> to use a method where each dice is rolled individually.</p>\n\n<pre><code>int p1 = toInt(dicePart1);\nint p2 = toInt(dicePart2);\nint p3 = toInt(dicePart3);\n\n....\n\nroll = p3;\nfor (i = p1; i > 0; i--) {\n roll += 1 + (rand() % p2);\n}\n</code></pre>\n\n<p>The above will, for <code>10d10+0</code> produce values in the correct range <code>10 ... 100</code> and the value frequencies will be distributed normally, as expected.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:55:55.710",
"Id": "41408",
"ParentId": "41403",
"Score": "11"
}
},
{
"body": "<p>I would recommend a more object-oriented approach. </p>\n\n<p>I would encapsulate the functionality of the dice into a class.<br>\nHere's an example of what the class could look like:</p>\n\n<pre><code>class Dice\n{\npublic:\n Dice () ;\n Dice (const std::string &diceNotation) ;\n int Roll () const ;\n\nprivate:\n int n1 ;\n int n2 ;\n int n3 ;\n\n friend std::istream& operator>> (std::istream& is, Dice &dice) ;\n friend std::ostream& operator<< (std::ostream& os, const Dice &dice) ;\n};\n</code></pre>\n\n<p>I would use <code>operator>></code> and <code>operator<<</code> for inputting and outputting data respectively. Please note, this is just to give you an idea. I did minimal testing with this.</p>\n\n<pre><code>std::istream& operator>> (std::istream& is, Dice &dice)\n{\n is >> dice.n1 ;\n is.ignore () ;\n is >> dice.n2 ;\n is >> dice.n3 ;\n\n return is ;\n}\n\nstd::ostream& operator<< (std::ostream& os, const Dice &dice)\n{\n std::string sign = (dice.n3 > 0) ? \"+\" : \"\" ;\n os << dice.n1 << \"d\" << dice.n2 << sign << dice.n3 ;\n return os ;\n}\n</code></pre>\n\n<p>Then you could use <code>operator>></code> in your constructor.</p>\n\n<pre><code>Dice::Dice () : n1 (0), n2 (0), n3 (0)\n{\n}\n\nDice::Dice (const std::string &diceNotation) : n1 (0), n2 (0), n3 (0)\n{\n std::stringstream ss (diceNotation) ;\n ss >> *this ;\n}\n</code></pre>\n\n<p>Here's a <code>main()</code> function just to show how this could be used.</p>\n\n<pre><code>int main () \n{\n Dice d1 (\"1d6+4\") ;\n Dice d2 (\"3d8-5\") ;\n Dice d3 (\"345d12+55\");\n\n std::cout \n << d1 << \"\\n\" \n << d2 << \"\\n\"\n << d3 << \"\\n\" ;\n\n return 0;\n}\n</code></pre>\n\n<p>One thing I will note, is that streams can be pretty slow on some systems.<br>\nAn alternate way to parse the strings would be to use <code>std::string::find()</code> to find the index of the 'd' and <code>std::string::find_first_of()</code> to find the index of the '-' or '+'.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T16:13:07.267",
"Id": "41413",
"ParentId": "41403",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41408",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T13:57:52.997",
"Id": "41403",
"Score": "11",
"Tags": [
"c++",
"strings",
"game",
"random",
"dice"
],
"Title": "Simple dice roll using std::string as dice notation"
}
|
41403
|
<p>I have a Python script I have written to copy files to a mounted Windows SMB share on a Mac.</p>
<pre><code>import os
import distutils.core
# Create a local site for the mount to reside
directory = "/Users/username/share"
if not os.path.exists(directory): os.makedirs(directory)
# Mount the Windows smb share
os.system("mount_smbfs //service.account:password@server.domain.com/share ~/share")
# set source and destination
fromDirectory1 = "/Volumes/Macintosh HD/folder1/folder2/folder3"
fromDirectory2 = "/Volumes/Macintosh HD/folder4/folder5/folder6"
fromDirectory3 = "/Volumes/Macintosh HD2/folder1/folder2"
fromDirectory4 = "/Volumes/Macintosh HD2/folder1/folder3/folder4"
toDirectory1 = "/Users/username/share/folder3"
toDirectory2 = "/Users/username/share/folder6"
toDirectory3 = "/Users/username/share/folder2"
toDirectory4 = "/Users/username/share/folder4"
#Do the copying
distutils.dir_util.copy_tree(fromDirectory1, toDirectory1)
distutils.dir_util.copy_tree(fromDirectory2, toDirectory2)
distutils.dir_util.copy_tree(fromDirectory3, toDirectory3)
distutils.dir_util.copy_tree(fromDirectory4, toDirectory4)
#Unmount the share
os.system("umount ~/share")
</code></pre>
<p>I understand the script is verbose but I wrote it this way to # out lines to problem solve. Can you suggest a cleaner way to write it?</p>
<p>Any insights gratefully received.</p>
<p>Version 2:</p>
<pre><code>import os
import distutils.core
# Create a local site for the mount to reside
directory = "/Users/username/share"
if not os.path.exists(directory): os.makedirs(directory)
# Mount the Windows smb share
os.system("mount_smbfs //service.account:password@server.domain.com/share ~/share")
# set source and destination
copy_jobs = []
copy_jobs.append({"from": "/Volumes/Macintosh HD/folder1/folder2/folder3", "to": "/Users/username/share/folder3"})
copy_jobs.append({"from": "/Volumes/Macintosh HD/folder4/folder5/folder6", "to": "/Users/username/share/folder6"})
copy_jobs.append({"from": "/Volumes/Macintosh HD2/folder1/folder2", "to": "/Users/username/share/folder2"})
copy_jobs.append({"from": "/Volumes/Macintosh HD2/folder1/folder3/folder4", "to": "/Users/username/share/folder4"})
#Do the copying
for job in copy_jobs:
distutils.dir_util.copy_tree(job["from"], job["to"])
# Unmount the Windows smb share
os.system("umount ~/share")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:40:00.133",
"Id": "71102",
"Score": "1",
"body": "You do not use `toDirectory1`. Is it normal ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:14:38.517",
"Id": "71109",
"Score": "0",
"body": "@Josay typo! Good eyes. Have corrected it. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:28:12.330",
"Id": "71111",
"Score": "1",
"body": "It would be better to use [`shutil.copytree`](http://docs.python.org/3/library/shutil.html#shutil.copytree) from the standard library instead of the version from `distutils`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T16:10:51.713",
"Id": "71121",
"Score": "0",
"body": "@GarethRees Thanks for your reply. Never had much luck with shutil - if I import shutil and replace distutils.dir_util.copy_tree with shutil.copytree I get a page of [Errno 22] invalid argument errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:18:20.917",
"Id": "71130",
"Score": "1",
"body": "That probably indicates a bug in `shutil.copytree` which you should report."
}
] |
[
{
"body": "<p>The code looks OK. A few specific improvements can be made.</p>\n\n<h2>Readability</h2>\n\n<pre><code>import os\nimport distutils.core\n</code></pre>\n\n<p>Learn about PEP8, you should have two empty lines between imports and the rest of the code. More generally, you should give more structure to your code to make it more readable. Empty lines are one way to achieve that. For example, one empty line before each comment could be nice.</p>\n\n<pre><code># Create a local site for the mount to reside\ndirectory = \"/Users/username/share\"\nif not os.path.exists(directory): os.makedirs(directory)\n</code></pre>\n\n<p>PEP8 comment: prefer indenting <code>if</code>s to make clear they are <code>if</code>s.</p>\n\n<h2>\"Security\"</h2>\n\n<pre><code># Mount the Windows smb share\nos.system(\"mount_smbfs //service.account:password@server.domain.com/share ~/share\")\n</code></pre>\n\n<p>Don't store account and password in your source file. You could move them to a configuration file (that would not be tracked if you used git or svn) or retrieve them from the environment (but then they would show up in your shell logs).</p>\n\n<h2>Don't Repeat Yourself</h2>\n\n<pre><code># set source and destination\nfromDirectory1 = \"/Volumes/Macintosh HD/folder1/folder2/folder3\"\nfromDirectory2 = \"/Volumes/Macintosh HD/folder4/folder5/folder6\"\nfromDirectory3 = \"/Volumes/Macintosh HD2/folder1/folder2\"\nfromDirectory4 = \"/Volumes/Macintosh HD2/folder1/folder3/folder4\"\ntoDirectory1 = \"/Users/username/share/folder3\"\ntoDirectory2 = \"/Users/username/share/folder6\"\ntoDirectory3 = \"/Users/username/share/folder2\"\ntoDirectory4 = \"/Users/username/share/folder4\"\n</code></pre>\n\n<p>Variables name <code>var1</code>, <code>var2</code> and so on indicate that you should use a list of pairs or a dictionary!</p>\n\n<pre><code>directories = [\n (\"/Volumes/Macintosh HD/folder1/folder2/folder3\", \"/Users/username/share/folder3\"),\n (\"/Volumes/Macintosh HD/folder4/folder5/folder6\", \"/Users/username/share/folder6\"),\n]\n\n#Do the copying\nfor from, to in directories:\n distutils.dir_util.copy_tree(from, to)\n\n#Unmount the share\nos.system(\"umount ~/share\")\n</code></pre>\n\n<p>A note about the 80-char limit: in this case, the <code>directories</code> list is more readable if you don't enforce the rule.</p>\n\n<h2>Recovering from failures</h2>\n\n<p>What happens when mounting works but not copying? You should still try to unmount your folder.</p>\n\n<pre><code>try:\n # mount\n # copy\nfinally:\n # umount\n</code></pre>\n\n<p>You can also decide to catch exceptions <em>if you know what to do about them</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:26:04.913",
"Id": "71246",
"Score": "2",
"body": "Excellent answer. As an additional comment, depending on how your requirements change in the future, you might want `directories` to become a list of pairs <from, to> if the same folder is to be copied in different places. The change should be pretty straight forward to perform and the idea is still to use the right data structure instead of duplicating logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:29:22.477",
"Id": "71247",
"Score": "0",
"body": "Nice spot. I didn't really know which one to choose, I'll switch to a list of pairs. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:57:47.117",
"Id": "71251",
"Score": "0",
"body": "@QuentinPradet Thanks for your insights. I have used a dictionary and revised my code (see version 2 above). Am aware of the security issues but it is on a secure Mac server. Never-the-less I will investigate a config file. I need to put the recovering from failure and perhaps a logging step into the code. Thanks again"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:05:35.700",
"Id": "41463",
"ParentId": "41405",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41463",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:31:03.027",
"Id": "41405",
"Score": "5",
"Tags": [
"python",
"beginner",
"file-system",
"osx"
],
"Title": "Python script using distutils to copy files on a Mac"
}
|
41405
|
<p>I have inherited a function which calculates a first payment due after a certain age.<br>
Using the function I typically pass in database values to custom calculate certain dates:</p>
<pre><code> Dim result = FPDA("#1/12/1952#", "9/29/1948", 1, 55)
MsgBox(result) 'in this example, I am returning first payment due after age 55
</code></pre>
<p>As far as the parameters, EffDate is the date the account became active, DOB is date of birth, mode is a payment mode value and age is the attained age to check. The function looks like this:</p>
<pre><code>Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date
'FUNCTION TO CALCULATE THE FIRST PAYMENT DUE AFTER SPECIFIED AGE.
Select Case Mode
Case "1"
Do Until EffDate > DateAdd("yyyy", Age, [DOB])
EffDate = DateAdd("yyyy", 1, EffDate)
Loop
Case "2"
Do Until EffDate > DateAdd("yyyy", Age, [DOB])
EffDate = DateAdd("m", 6, EffDate)
Loop
Case "4"
Do Until EffDate > DateAdd("yyyy", Age, [DOB])
EffDate = DateAdd("q", 1, EffDate)
Loop
Case "12"
Do Until EffDate > DateAdd("yyyy", Age, [DOB])
EffDate = DateAdd("m", 1, EffDate)
Loop
End Select
Return EffDate
End Function
</code></pre>
<p>Is there a better or more efficient way than to achieve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:47:18.970",
"Id": "71113",
"Score": "0",
"body": "Well, if you need to explain the meaning of the variable, I guess you could consider renaming the variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:54:08.237",
"Id": "71115",
"Score": "0",
"body": "I would, but that is the standard for the business terminology"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:45:49.673",
"Id": "71175",
"Score": "2",
"body": "The first thing I'd address is the cryptic `Mode` parameter. It's dying to be an `Enum` with real descriptive names instead of magic `Integer` values. And `EffDate` would look much cooler as `FxDate`, but that's just me :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:48:12.513",
"Id": "71176",
"Score": "1",
"body": "A better name for `Mode` could be `TimeSpanType`, with values like `Yearly`, `Quarterly`, `Monthly` and `SemiAnnual`."
}
] |
[
{
"body": "<p>You're doing a lot more looping than necessary. It would probably be more efficient to jump the return date to the same year than adjust the month accordingly. As was mentioned an enum, properly named makes the code much more readable and manitainable. Something like this:</p>\n\n<pre><code>Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal PaymentMode As PaymentInterval, ByVal Age As Integer) As Date\n 'FUNCTION TO CALCULATE THE FIRST PAYMENT DUE AFTER SPECIFIED AGE.\n 'Find the year the payments is to be made\n Dim TargetDate = DOB.AddYears(Age)\n 'Find the payment start day for the year in question\n FPDA = EffDate.AddYears(TargetDate.Year - EffDate.Year)\n 'These conditionals adjust the return value according to \n 'whether the date is before or after the birthdate and whether \n 'the interval is bigger than the payment interval\n If FPDA < TargetDate Then\n Do Until FPDA >= TargetDate\n FPDA = FPDA.AddMonths(PaymentMode)\n Loop\n ElseIf FPDA > TargetDate Then\n While FPDA.Month - TargetDate.Month >= PaymentMode\n FPDA = FPDA.AddMonths(PaymentMode * -1)\n End While\n End If\n If FPDA.Month <> 2 AndAlso FPDA.Day <> EffDate.Day Then\n FPDA = New Date(FPDA.Year, FPDA.Month, EffDate.Day)\n End If\nEnd Function\n\nEnum PaymentInterval\n Yearly = 12\n Semi_Annually = 6\n Quaterly = 3\n Monthly = 1\nEnd Enum\n</code></pre>\n\n<p>This will only loop in specific cases and then only for a few iterations.</p>\n\n<p>This assumes that the payment day is the same as the EffDate day</p>\n\n<p>I tried to test this with as many different scenarios as I could. If I missed something let me know.</p>\n\n<p>If you would like simplicity over performance your original code could be optimized like this:</p>\n\n<pre><code>Public Function FPDA2(ByVal EffDate As Date, ByVal DOB As Date, ByVal PaymentMode As PaymentInterval, ByVal Age As Integer) As Date\n FPDA2 = EffDate\n Do Until FPDA2 >= DOB.AddYears(Age)\n FPDA2 = FPDA2.AddMonths(PaymentMode)\n Loop\n If FPDA2.Month <> 2 AndAlso FPDA2.Day <> EffDate.Day Then\n FPDA2 = New Date(FPDA2.Year, FPDA2.Month, EffDate.Day)\n End If\nEnd Function\n</code></pre>\n\n<p>Both achieve the exact same result, but one is more complicated and more efficient and the other is very simple but inefficient</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T19:32:29.677",
"Id": "41425",
"ParentId": "41410",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>This is going to be a brain dump -type review. Feel free to jump straight to <strong>TL;DR</strong> if my thinking out loud gets annoying :)</p>\n</blockquote>\n\n<p>Let's start with the function's signature:</p>\n\n<pre><code>Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date\n</code></pre>\n\n<p>You're taking all parameters <code>ByVal</code>, which is good - it means the function cannot alter these values if it tried, it's receiving a copy of what the caller gave it.</p>\n\n<p>I can live with <code>EffDate</code>, <code>DOB</code> and <code>Age</code> identifiers. But as I've mentioned in the comments, <code>Mode</code> is a no-no, especially if it's a <em>magic</em> <code>Integer</code> variable.</p>\n\n<p>Looking at the body of the function I think what <code>Mode</code> is really about is something more like this:</p>\n\n<pre><code>Public Enum TimeSpanType\n Year\n HalfYear\n Quarter\n Month\nEnd Enum\n</code></pre>\n\n<p>So we can have a body like this:</p>\n\n<pre><code>Select Case Mode\n Case TimeSpanType.Year\n Do Until EffDate > DateAdd(\"yyyy\", Age, [DOB])\n EffDate = DateAdd(\"yyyy\", 1, EffDate)\n Loop\n\n Case TimeSpanType.HalfYear\n Do Until EffDate > DateAdd(\"yyyy\", Age, [DOB])\n EffDate = DateAdd(\"m\", 6, EffDate)\n Loop\n\n Case TimeSpanType.Quarter\n Do Until EffDate > DateAdd(\"yyyy\", Age, [DOB])\n EffDate = DateAdd(\"q\", 1, EffDate)\n Loop\n\n Case TimeSpanType.Month\n Do Until EffDate > DateAdd(\"yyyy\", Age, [DOB])\n EffDate = DateAdd(\"m\", 1, EffDate)\n Loop\n\nEnd Select\n\nReturn EffDate\n</code></pre>\n\n<p>It's more readable and less error-prone, but it's doing the exact same thing. It <em>gives another meaning to the received parameter</em> <code>EffDate</code>, which might work <em>now</em>, but it's error-prone, and this is where <code>ByVal</code> is saving you.</p>\n\n<p>I would make a copy of <code>EffDate</code>:</p>\n\n<pre><code>Dim result As Date\nresult = EffDate\n</code></pre>\n\n<p>And change the last line to:</p>\n\n<pre><code>Return result\n</code></pre>\n\n<p>Now every branch looks like a <kbd>Copy</kbd>+<kbd>Paste</kbd> party. How about this:</p>\n\n<pre><code>Dim interval As String\n\nSelect Case Mode\n Case TimeSpanType.Year\n interval = \"yyyy\"\n\n Case TimeSpanType.HalfYear\n interval = \"m\"\n\n Case TimeSpanType.Quarter\n interval = \"q\"\n\n Case TimeSpanType.Month\n interval = \"m\"\n\nEnd Select\n</code></pre>\n\n<p>And then you can just do:</p>\n\n<pre><code>Do Until result > DateAdd(interval, Age, [DOB])\n result = DateAdd(interval, 1, result)\nLoop\n</code></pre>\n\n<p>But this is rather ugly. <code>DateAdd</code> lives in the <a href=\"http://msdn.microsoft.com/en-us/library/c157t28f%28v=vs.90%29.aspx\"><code>Microsoft.VisualBasic</code> namespace</a>, which only exists to make VB6 developers happy with transition to the <em>Wonderful World of .NET</em>... but by using that namespace, you're missing out on everything the <em>Wonderful World of .NET</em> has to offer!</p>\n\n<p><code>Date</code> is just a language alias for <code>System.DateTime</code>, <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%29.aspx\">which exposes the .NET way of life</a> - exposing methods like <code>AddMonths</code>, which is really all you need here:</p>\n\n<pre><code>Dim monthsToAdd As Integer\n\nSelect Case Mode\n Case TimeSpanType.Year\n monthsToAdd = 12\n\n Case TimeSpanType.HalfYear\n monthsToAdd = 6\n\n Case TimeSpanType.Quarter\n monthsToAdd = 3\n\n Case TimeSpanType.Month\n monthsToAdd = 1\n\nEnd Select \n</code></pre>\n\n<p>Or better yet - get rid of the <code>Select...Case</code> altogether, because <code>Enum</code>s are <code>Integer</code>s under the hood:</p>\n\n<pre><code>Public Enum TimeSpanType\n Year = 12\n HalfYear = 6\n Quarter = 3\n Month = 1\nEnd Enum\n</code></pre>\n\n<h2>TL;DR</h2>\n\n<p>And then you can just do this:</p>\n\n<pre><code>Dim interval As Integer\ninterval = CType(Mode, Integer)\n\nDo Until result > DOB.AddMonths(interval*Age)\n result = result.AddMonths(1)\nLoop\n</code></pre>\n\n<p>And now that you've got code that's easy to read, follow and maintain, you can start thinking about how the loop could be simplified.</p>\n\n<p><strong>Strive to get rid of <code>Imports Microsoft.VisualBasic</code> anywhere you see it. VB.NET is .NET, not VB6.</strong> Your code will only get better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T21:19:54.333",
"Id": "71183",
"Score": "0",
"body": "Thank you, your write up was very good. I was able to stick with it the whole way. The function was UDF in access which explains the dateadd() and vb6 likeness . Why is it better to use a variable such as 'result'? Thank you for taking the time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T21:27:24.327",
"Id": "71185",
"Score": "0",
"body": "Because when you're reassigning `EffDate`, you're *changing its meaning* - it's no longer the parameter value you received from the caller, it's *something else*, and that makes it confusing code, because as you scroll down the code the meaning of the identifier changes and you have to mentally keep up with it (I've seen worse than this though). As for the naming itself, it could be personal preference, but I find an identifier named `result` is very explicit about its meaning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:10:47.230",
"Id": "71302",
"Score": "0",
"body": "I really like the complete process from Mode to the final Enum. This help having an incremental process to the final solution, it's more easily to reproduce."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T20:33:54.043",
"Id": "41428",
"ParentId": "41410",
"Score": "7"
}
},
{
"body": "<p>Since the previous posts covered most of the structural issues (VB6 data structures v .NET, enumerating the payment modes, etc.), I'll address the remaining elephant in the room here. Looping through dates like this is similar to counting on your fingers to find out how many fingers you have on your hands. Nobody would even consider (or maybe \"should\" is the better word) doing this with a numeric type:</p>\n\n<pre><code>Dim Fingers As Integer = 1;\n\nDo Until Fingers > 9\n Fingers = Fingers + 1\nLoop\n\nReturn Fingers\n</code></pre>\n\n<p>Much better to just calculate the result, especially if this is being looped over in the calling code. You tend to see code like the sample you posted when people are afraid to work with dates. The calculation involved isn't that hard. You first figure out the payee's birthday for the given age and find the following [insert financial vehicle here] anniversary based on the effective date. This lets you calculate the number of months until the next anniversary. Taking the modulus of the number of months until the anniversary and the number of months between payments gives you the month that the next payment is due. The only reason to work with anything other than the month is to cover cases where the birthday falls on a modal cycle:</p>\n\n<pre><code>Public Function FPDA(ByVal EffDate As DateTime, ByVal DOB As DateTime, ByVal Mode As Integer, ByVal Age As Integer) As DateTime\n\n Dim ModeFrequency As Integer = 12 / Mode\n Dim BirthDay As DateTime = DOB.AddYears(Age)\n Dim TargetMonth As EffDate.Month\n\n If BirthDay.Month > TargetMonth Then\n TargetMonth = TargetMonth + 12\n End If\n\n Dim Offset As Integer = ((TargetMonth - DOB.Month) Mod ModeFrequency) + (BirthDay.Month - EffDate.Month)\n DateTime NextPayment = new DateTime(BirthDay.Year, EffDate.Month, EffDate.Day).AddMonths(Offset)\n\n 'Test for DOB landing in payment month, but before or on the birthday.\n If NextPayment <= BirthDay\n NextPayment = NextPayment.AddMonths(ModeFrequency)\n End If\n\n FPDA = NextPayment\n\nEnd Function\n</code></pre>\n\n<p>Forgive any syntax errors - my VB is rusty. If you can't change the calling convention and have to work with VB6 types, there are similar date handling functions for the VB6 Date type to extract the year, month, and day. The logic would be the same though. The code above can be stream-lined a bit, TargetMonth and ModeFrequency are declared mainly for the sake of clarity.</p>\n\n<p>One final note (and this is more something to be aware of as opposed to something I would change) is that the code is relying on how the language handles dates to enforce a business rule. In this case it is when the payment is due if the effective date has more days of the month than the due date. The original code (and the sample above) both assume that the due date reverts to the last day of the month (behavior of .AddMonths() and DateAdd()). Some companies assume the first of the next month. Some companies like the one I currently work for won't assign an issue date after the 28th.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-13T04:04:27.287",
"Id": "114635",
"Score": "0",
"body": "I have accepted your answer for explaining the calculation and demonstrating the core issue with the calculation. Your concise explanation and calculation demonstration works perfectly. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:28:37.707",
"Id": "41505",
"ParentId": "41410",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41505",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:45:32.620",
"Id": "41410",
"Score": "8",
"Tags": [
"vb.net"
],
"Title": "Calculate a payment due after X age"
}
|
41410
|
<p>I am trying to speed up the process of inserting all of the rows in my text file into an Access DB. I originally switched to this route because of the size of those text files (that I am generating on another step of my process). I have more ROM than RAM. The overall process is working now, but I am falling into the rabbit hole of "optimizing" and can use someone else's opinion.</p>
<p><strong>Limitations and specifications:</strong></p>
<ul>
<li>I can't load all of the text file into one variable. I can't get more RAM.</li>
<li>My logic needs to accept any text size (Column x Row). </li>
<li>All the data will be inserted to an existing empty Access table. </li>
</ul>
<p>I will try to minimize the code posted here. Feel free to ask questions if anything important seems to be missing. Here is the logic in question:</p>
<p>Method that contains the code:</p>
<pre><code>Public Sub InsertTextFileRowsIntoAccessDB2(sAccessTableName As String, sDBFilePath As String, CashePath As String)
'...all the code here
End Sub
</code></pre>
<p><strong>Logic A: Best I could do</strong></p>
<pre><code> 'Insert each Row from the text file into the access DB
Do While (Not reader.EndOfStream)
Try
Dim fullRow() = reader.ReadLine.Split(CChar(vbTab))
'Create the parameters
Dim Prams As String = "@p1"
For i = 2 To fullRow.Count
Prams = Prams & " ,@p" & i
Next
Dim insertQuery As String = "INSERT INTO " & sAccessTableName & " VALUES (" & Prams & ");"
Dim cmd2 = New OleDbCommand(insertQuery, conn)
For index As Integer = 1 To fullRow.Length
Dim tempP As String = "@p" & index 'Array starts from zero
cmd2.Parameters.AddWithValue(tempP, fullRow(index - 1))
Next
cmd2.ExecuteNonQuery()
Catch ex As Exception
Dim rex = ex 'TODO: Write the row and the exception somewhere
End Try
Loop
</code></pre>
<p><strong>Logic 2</strong></p>
<pre><code> 'Insert each Row from the text file into the access DB
Do While (Not reader.EndOfStream)
Try
Dim fullRow() = reader.ReadLine.Split(CChar(vbTab))
'Build the query string to have all the columns
Dim query As String = "INSERT INTO " & sAccessTableName & " VALUES (" & "'" & fullRow(0) & "'"
For index As Integer = 1 To fullRow.Length - 1
If fullRow(index).Equals("") Then 'Check if the column is empty
query = query & ", NULL "
Else
'Check if the string has a quote in it (which causes issues to SQL)
query = query & ", '" & fullRow(index).Replace("'", "''") & "'"
End If
Next
query = query & ");"
Dim cmd As OleDbCommand = New OleDbCommand(query, conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
Dim rex = ex 'TODO: Write the row and the exception somewhere
End Try
Loop
</code></pre>
<p>How can I improve my inserts?</p>
<p><strong>Questions asked in comments:</strong></p>
<blockquote>
<p>What version of Access is it? Can you post your connection string?</p>
</blockquote>
<pre><code>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sDBFilePath
</code></pre>
<p>Let me know if this could cause any issues with other machines or how to avoid incompatibility.</p>
<blockquote>
<p>Also, what does the table you are inserting into look like?</p>
</blockquote>
<p>It depends on the data (table) I am getting. I am trying to get the column count to be dynamic so the method would work with any table. However, I am making the assumption that the column number in the table will be the same as the column number in the text file that I am reading from.</p>
|
[] |
[
{
"body": "<p>OK, thought I might get a quick win if you were using a version of Access old enough to be using the Jet engine (in that case DAO is inherently much faster).</p>\n\n<p>First thing: Don't go down the road of your \"Logic 2\". The fact that you realized you have to escape any quotes in the input file should be a great reminder as to why using parameters is good practice - it sanitizes input and avoids SQL injection.</p>\n\n<p>Second, and this is the main one. You are looping over code that should always execute with the same results. Pull these out of you loop so you only do them once:</p>\n\n<pre><code> 'Create the parameters\n Dim Prams As String = \"@p1\"\n For i = 2 To fullRow.Count\n Prams = Prams & \" ,@p\" & i\n Next\n\n Dim insertQuery As String = \"INSERT INTO \" & sAccessTableName & \" VALUES (\" & Prams & \");\"\n Dim cmd2 = New OleDbCommand(insertQuery, conn)\n</code></pre>\n\n<p>The dynamic parameter generation isn't ideal, but isn't really avoidable if you need a general purpose function. I'm guessing that a large amount of the inefficiency is repeatedly creating new OleDbCommand objects (as well as the SQL string) when they can be re-used. In fact, parameterized OleDbCommand objects are optimized for looping over with multiple inserts. Add your parameter list without values before you go into the main loop, and then assign to them by index.</p>\n\n<p>This should speed you up quite a bit. If that doesn't get you into the ballpark of where you need to be performance-wise, the Access object model will let you automate a bulk insert from a tab delimited file. You may want to benchmark how long it takes Access to import the file and explore this possibility too, especially if you control the datafile generation.</p>\n\n<p>One last note: Don't forget to \"'TODO: Write the row and the exception somewhere\" and keep swallowing the exceptions.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Good starting place for Access automation is <a href=\"http://msdn.microsoft.com/en-us/library/office/ff192643.aspx\" rel=\"nofollow\">here</a> - there are some community links at the bottom of the page that are pretty good. I'd only use this as a last resort as it pulls in lots of dependencies and requires starting an Access process. I'm fairly sure managing the OleDbCommand outside the loop is going to give the best performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T05:22:36.657",
"Id": "71385",
"Score": "0",
"body": "For answer completeness, can you elaborate on the Jet engine or automating the bulk insert? Links to methods you would take would be sufficient. Thank you so much for your time and input!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T05:27:30.590",
"Id": "71386",
"Score": "1",
"body": "Jet was the older Access database engine that they replaced with ACE, and it was built around DAO. DAO classes are still available in .NET, but they are deprecated in preference to the ADO way of doing things. It was much faster to use with Jet, because it was using native methods. ACE is much, much better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T05:36:04.003",
"Id": "71387",
"Score": "1",
"body": "...and an edit above for a good starting place for Office automation. It's more or less like starting Access and controlling remotely through your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T23:25:55.503",
"Id": "72666",
"Score": "0",
"body": "Hopefully last question. I followed your suggestion, but I am running into an issue where the parameters are not updating when I pass in new values (line cmd2.Parameters.AddWithValue()). Any way around this? I looked around and I can't seem to find a way to clear the parameter list easily."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T00:04:30.710",
"Id": "72675",
"Score": "1",
"body": "Without seeing the new code, I would say that instead of using .AddWithValue() inside the loop, you should use something like cmd2.Parameters[tempP].Value = fullRow(index - 1); When you put the Parameters into the OleDbCommand before the loop, add them without values, such as: cmd2.Parameters.Add(tempP, [datatype]);"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:03:48.993",
"Id": "41507",
"ParentId": "41411",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T15:58:07.263",
"Id": "41411",
"Score": "5",
"Tags": [
"strings",
".net",
"vb.net"
],
"Title": "Inserting text file rows into an Access DB"
}
|
41411
|
<p>I've got a view which has a corresponding template. The template looks something like like:</p>
<pre><code><div id="streamItems" class="left-list droppable-list"></div>
<div class="context-buttons">
<div class="left-group">
<div id="shuffleButtonView" class="view-placeholder"></div>
<div id="repeatButtonView" class="view-placeholder"></div>
<div id="radioButtonView" class="view-placeholder"></div>
</div>
<div class="right-group">
<button id="saveStream" class="button-icon button-small save <%= userLoaded ? '' : 'disabled' %>" title="<%= userLoaded ? saveStreamMessage : cantSaveNotSignedInMessage %>">
<i class="fa fa-save"></i>
</button>
<button id="clearStream" class="button-icon button-small clear" title="<%= chrome.i18n.getMessage('clearStream') %>" >
<i class="fa fa-trash-o"></i>
</button>
</div>
</div>
</code></pre>
<p>I've passed into the template some variables such as <code>userLoaded</code>. This allows me to render the initial state of the <code>saveStream</code> button.</p>
<p>Now, the state of <code>userLoaded</code> has changed and I would like to update the button. I don't want to render my entire template again because <code>streamItems</code> is an expensive list to render.</p>
<p>So, I wrote the following:</p>
<pre><code>initialize: function() {
this.listenTo(User, 'change:loaded', this.toggleSaveStream);
},
toggleSaveStream: function () {
var userLoaded = User.get('loaded');
var templateHelpers = this.templateHelpers();
this.ui.saveStreamButton.toggleClass('disabled', userLoaded);
this.ui.saveStreamButton.attr('title', userLoaded ? templateHelpers.saveStreamMessage : templateHelpers.cantSaveNotSignedInMessage);
}
</code></pre>
<p>Which serves to keep my button up to date.</p>
<p>I'm unhappy with this solution because the logic for the disabled state of the button is duplicated into two spots. Is this a valid concern? How to handle?</p>
<p>Button is rendered disabled in template and I don't want to re-render whole template to change button state. How to stay DRY?</p>
|
[] |
[
{
"body": "<p>From looking at it, the name of your function <code>toggleSaveStream</code> is lying, calling it twice will not make it toggle, it will look at the the status of the user and set the status accordingly. So I would simply call it <code>updateSaveStreamButton</code>.</p>\n\n<p>Since it does that, you could call it at first, de-activating the button, and then once the user is loaded call it again. </p>\n\n<p>Then you would simply have</p>\n\n<pre><code><button id=\"saveStream\" class=\"button-icon button-small save disabled>\" title=\"\">\n</code></pre>\n\n<p>And then</p>\n\n<pre><code>initialize: function() {\n this.updateSaveStreamButton();\n this.listenTo(User, 'change:loaded', this.updateSaveStreamButton);\n},\n\nupdateSaveStreamButton: function () {\n var userLoaded = User.get('loaded');\n var templateHelpers = this.templateHelpers();\n\n this.ui.saveStreamButton.toggleClass('disabled', userLoaded);\n this.ui.saveSelectedButton.attr('title', userLoaded ? templateHelpers.saveStreamMessage : templateHelpers.cantSaveNotSignedInMessage);\n}\n</code></pre>\n\n<p>This sounds too easy, so feel free to point what I am missing ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:39:49.273",
"Id": "71138",
"Score": "0",
"body": "I am mostly concerned about the fact that I misrepresent the state of the button during the period of time between rendering the view and calling updateSaveStreamButton. If a naive developer were to look at my template -- they would have no idea that saveStream's state changes or that it has a title. It feels weird to be moving that logic out of my template, but I guess I have to if I don't want to duplicate it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:47:24.350",
"Id": "71163",
"Score": "0",
"body": "Well, the state should be correctly represented unless it is possible for the user to be loaded already. You could put a comment in your HTML /* State is set in updateSaveStreamButton */"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:48:27.170",
"Id": "71164",
"Score": "0",
"body": "The user can be loaded already -- thus the concern. I agree that it seems like the best solution is just to comment and keep it DRY in the JavaScript and not rely on a template."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:37:29.997",
"Id": "41420",
"ParentId": "41417",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:27:49.703",
"Id": "41417",
"Score": "4",
"Tags": [
"javascript",
"template"
],
"Title": "toggleSaveStream button template"
}
|
41417
|
<p>My intention is to separate components on a file basis. For example, I want a specific controller to have it's own file (Same goes with services, filters and directives). Of course, files will be group together based on the module they will fall into.</p>
<p>Here's an overview of what I currently have:</p>
<p>Directory</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>User/
User/UserModule.js
User/UserDirective.js
User/UserService.js
User/UserFilter.js
User/UserController.js
</code></pre>
</blockquote>
<p>UserModules.js</p>
<pre class="lang-js prettyprint-override"><code>UserModule = angular.module('UserModule', []);
UserModule.controller('userCtrl', ['$scope', 'UserService', UserCtrl])
.factory('userService', function() {
return new UserService();
})
.filter('userFilter', UserFilter)
.directive('userDirective', UserDirective);
</code></pre>
<p>UserController.js</p>
<pre class="lang-js prettyprint-override"><code>UserCtrl = function($scope, UserService) {
// ...
};
</code></pre>
<p>UserDirective.js</p>
<pre class="lang-js prettyprint-override"><code>UserDirective = function() {
return {
// ...
}
};
</code></pre>
<p>UserService.js</p>
<pre class="lang-js prettyprint-override"><code>UserService = function() {
// ...
};
</code></pre>
<p>UserFilter.js</p>
<pre class="lang-js prettyprint-override"><code>UserFilter = function() {
return function() {
// ...
}
};
</code></pre>
<p>Then I'll just push the user module to the app module.</p>
<pre class="lang-js prettyprint-override"><code>app.requires.push('UserModule');
</code></pre>
<p>My concern lies on the registration of the concepts (Such as controllers, services...) to the module. I was wondering if this is the best way to go and if it's correct. Also possible issues on the <code>parameters</code> and the external .js file. </p>
<p>Consider this part: </p>
<pre class="lang-js prettyprint-override"><code>.controller('userCtrl', ['$scope', 'UserService', UserCtrl])
</code></pre>
<p>The <code>UserCtrl</code> above refers to a function defined in a separate file. Will I be able to pass the <code>$scope</code> and <code>UserService</code> dependency as parameters to the <code>UserCtrl</code>?</p>
<pre class="lang-js prettyprint-override"><code>UserCtrl = function($scope, UserService) { // Pass parameters (UserController.js)
</code></pre>
<p>What's the correct way of doing this in terms of Services, Filters and Directives?</p>
<p>Finally, how can I improve the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-11T12:50:55.577",
"Id": "139838",
"Score": "0",
"body": "I would organise the files exactly as you have done: functional. Otherwise the components that works together are split around and are likely not so easy available for reuse. More arguments can be found in the www: http://henriquat.re/modularizing-angularjs/modularizing-angular-applications/modularizing-angular-applications.html"
}
] |
[
{
"body": "<p>It would be much easier to give feedback if we saw your actual code, for those 5 js files.</p>\n\n<p>Regardless, I tend to organize differently:</p>\n\n<pre><code>controllers/\n user.js\nviews/\n user.js\nmodels/\n user.js\n</code></pre>\n\n<p>So anything that does not fit <code>controller/user.js</code> or <code>views/user.js</code> goes into <code>models/user.js</code>.</p>\n\n<p><em>I want a specific controller to have it's own file (Same goes with services, filters and directives).</em> There is no good enough reason to do this, keep controllers and views together, and do not split up everything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:56:10.723",
"Id": "41565",
"ParentId": "41418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:31:07.827",
"Id": "41418",
"Score": "4",
"Tags": [
"javascript",
"angular.js",
"meteor"
],
"Title": "Angular Modular File Structure"
}
|
41418
|
<p>Not a follow-up, but related to <a href="https://codereview.stackexchange.com/q/41207/35408">Member list reveals member information on click (#1)</a>. I now want my CSS reviewed.</p>
<p><strong>What I'm doing?</strong></p>
<p>The content in a list of members is revealed by jQuery (see review #1). Instead of having the content pop out, I'm using a transition to make this smooth. Because one can't transition to <code>height: auto;</code>, it's triggered by using <code>max-height: 2000px;</code>.</p>
<p>I have feeling this can be improved.</p>
<p><strong>HTML:</strong></p>
<pre><code><ul class="block-list member-list">
<li id="member-name-1">
<a href="#member-name-1" class="block-list__link">
<div class="block-list__thumbnail">
<img src="member-name-1-thumbnail.jpg" alt="Thumbnail">
</div>
<span class="block-list__title">Member Name 1</span>
</a>
<div class="block-list__content">
<p>Content area. No layout things inside. Paragraphs, lists, images.</p>
</div>
</li>
<li id="member-name-2">
<a href="#member-name-2" class="block-list__link">
<div class="block-list__thumbnail">
<img src="member-name-2-thumbnail.jpg" alt="Thumbnail">
</div>
<span class="block-list__title">Member Name 2</span>
</a>
<div class="block-list__content">
<p>Content area. No layout things inside. Paragraphs, lists, images.</p>
</div>
</li>
<li id="member-name-3">
<a href="#member-name-3" class="block-list__link">
<div class="block-list__thumbnail">
<img src="member-name-3-thumbnail.jpg" alt="Thumbnail">
</div>
<span class="block-list__title">Member Name 3</span>
</a>
<div class="block-list__content">
<p>Content area. No layout things inside. Paragraphs, lists, images.</p>
</div>
</li>
</ul>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.block-list__link {
text-decoration: none;
.block-list__title:after {
/* Adding a space followed by `&raquo;` after titles inside links */
content: "\0020" "\00BB";
}
}
.block-list__thumbnail {
width: 100px;
height: 100px;
background-color: #f60;
float: left;
}
.block-list__title {
line-height: 100px;
margin-bottom: 0;
margin-left: 30px;
}
.block-list__content {
overflow: hidden;
/* Omitting vendor-prefixes for demonstration */
transition: max-height 0.8s linear;
height: 0;
max-height: 0;
&.visible {
margin-top: 30px;
height: 100%;
max-height: 2000px;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>this popped out at me, I haven't looked at the entire code completely yet, so take this with a grain of salt please</p>\n\n<p>not sure why you do this</p>\n\n<pre><code><a href=\"#member-name-2\" class=\"block-list__link\">\n <div class=\"block-list__thumbnail\">\n <img src=\"member-name-2-thumbnail.jpg\" alt=\"Thumbnail\">\n </div>\n <span class=\"block-list__title\">Member Name 2</span>\n</a>\n</code></pre>\n\n<p>I would probably write it like this instead</p>\n\n<pre><code><a href=\"member-name-2\" class=\"block-list__link\">\n <img src=\"member-name-2-thumbnail.jpg\" alt=\"Thumbnail\" class=\"block-list__thumbnail\" />\n <span class=\"block-list__title\">Member Name 2</span>\n</a>\n</code></pre>\n\n<p>I am pretty sure that you don't need that extra <code>div</code>\nI think the image tag is going to act similar to the div tag, and I assume that you want to style the image and not the div anyway, it looks more like a container for the image which I think is redundant. ( <em>I have been wrong before and am not afraid to admit it when someone gives me some solid evidence</em> )</p>\n\n<p>that is the only thing that I can see right now, but I haven't spent much time looking at it either.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:29:19.127",
"Id": "41567",
"ParentId": "41423",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41567",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:38:14.483",
"Id": "41423",
"Score": "6",
"Tags": [
"html",
"css",
"sass"
],
"Title": "Member list reveals member information on click (#2)"
}
|
41423
|
<p>Partial ordering may be useful in some scientific contexts. This is quick prototype in Python, which I believe works correctly.</p>
<p>Do you notice any flaws? Can you provide a counter-example of wrong results? Additional test cases will be also rewarded with +1.</p>
<pre><code>#!/usr/bin/env python3
import unittest as ut
def leq (L1, L2):
assert len(L1) == len(L2)
l = g = 0
for v1, v2 in zip(L1, L2):
if v1 < v2:
l += 1
elif v1 > v2:
g += 1
return l >= 0 and g == 0
class Test (ut.TestCase):
def test1 (self):
V1 = [1, 2, 3]
V2 = [1, 2, 2]
self.assertFalse(leq(V1, V2))
self.assertTrue(leq(V2, V1))
def test2 (self):
V1 = [1, 2, 3]
V2 = [2, 2, 3]
self.assertTrue(leq(V1, V2))
self.assertFalse(leq(V2, V1))
def test3 (self):
V1 = [1, 2, 3]
self.assertTrue(leq(V1, V1))
def test4 (self):
V1 = [1, 2, 3]
V2 = [3, 2, 1]
self.assertFalse(leq(V1, V2))
self.assertFalse(leq(V2, V1))
</code></pre>
<p><strong>Edit:</strong> redefining the <code>leq</code> function (thanks to Cary for the comment)</p>
<pre><code>leq = lambda L1, L2: sum(v1 > v2 for v1, v2 in zip(L1, L2)) == 0
</code></pre>
<p>Proved to be working with the same unit test.</p>
<p>Same result, but using short-circuit logic and avoiding to scan both lists:</p>
<pre><code>leq = lambda L1, L2: not any (v1 > v2 for v1, v2 in zip(L1, L2))
</code></pre>
<p>As suggested in comment, equivalent version, more natural:</p>
<pre><code>leq = lambda L1, L2: all(v1 > v2 for v1, v2 in zip(L1, L2))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T04:44:58.760",
"Id": "71216",
"Score": "2",
"body": "Decav, since `l >= 0` is always `true`, the `return` statement appears to be the same as `return g == 0`, suggesting that `false` is returned if and only if `v1 > v2` for at least one pair `v1, v2`. In Ruby, this could be expressed `return !L1.zip.L2.any? {|v1,v2| v1 > v2}`. (I'm not familiar with Python, so maybe I'm missing something.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:01:48.330",
"Id": "71227",
"Score": "0",
"body": "Correct. Let me update the question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:38:48.417",
"Id": "71228",
"Score": "1",
"body": "I wouldn't go for the solution with sum at it would iterate all the way instead of stopping as soon as possible. I am not a big fan of \"not any\" because it doesn't sound natural and I'd prefer :\nleq = lambda L1, L2: all(v1 <= v2 for v1, v2 in zip(L1,L2))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:02:36.103",
"Id": "71232",
"Score": "0",
"body": "@Josay, I added the `not any` indeed because of the short-circuit logic. The `all` is equivalent but actually more natural. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:06:22.817",
"Id": "71347",
"Score": "0",
"body": "I agree with @Josey re `!any?` vs `all?`. When I suggested the former I was just not thinking straight. The two are obviously equivalent, as both terminate when they encounter `v1 > v2`."
}
] |
[
{
"body": "<p>Not much to say about it, good job!</p>\n\n<ul>\n<li>Documentation: explain the mathematical explanation of your partial ordering unless it's really that obvious for your intended readers</li>\n<li>Names:\n<ul>\n<li>In Python, names starting with uppercase letters are for class names: of course you're free to use your own convention, but this one makes it easy to share code between Python developers</li>\n<li>Explicit is better than implicit: <code>less</code> is better than <code>l</code> which could also mean left or leave or whatever.</li>\n</ul></li>\n<li>Style: In Python (see PEP8), we usually don't but spaces before function definitions.</li>\n<li>Test cases: always add a test case for degenerate cases, eg. the empty list and lists of different lengths: those are the ones which usually fail.</li>\n</ul>\n\n<p>(And +1 to the comments who should become an answer.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:18:19.560",
"Id": "41464",
"ParentId": "41433",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41464",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T21:54:58.647",
"Id": "41433",
"Score": "7",
"Tags": [
"python"
],
"Title": "Review implementation for Partial Ordering of Vectors"
}
|
41433
|
<p>I am interested in the performance tradeoffs of linked lists, standard lists and unrolled linked lists. This will depend on various factors including what operation is being performed (e.g. delete, insert, and from where), and the size of the nodes. I've written some performance tests (not listed here).</p>
<p>I am interested in whether the node class could be implemented as an array rather than a list, so I'll be trying this in the future. This class works quite well as a stack, but I am also interested in its use as a queue; in order to try this I might alter the Node class to store pointers for the start and end of the list/array.</p>
<p>Does anyone have any feedback on my unrolled linked list class? I did it just for fun.</p>
<pre><code>/// <summary>
/// An unrolled linked list implements the standard list operations.
/// Its implementation is inbetween that of a standard List and a LinkedList.
/// </summary>
public class UnrolledLinkedList<T> : IList<T>
{
private Node first, last;
private int count;
/// <summary>
/// Create a new (empty) unrolled linked list
/// </summary>
public UnrolledLinkedList()
{
count = 0;
}
/// <summary>
/// Create an unrolled linked list which is populated with data from an enumerable
/// </summary>
public UnrolledLinkedList(IEnumerable<T> enumerable)
: this()
{
if (enumerable.Any())
{
first = new Node();
Node node = first;
foreach(T t in enumerable)
{
node = AddAfterIfFull(node, t);
count++;
}
last = node;
}
}
public int IndexOf(T item)
{
int offset = 0;
foreach (Node node in Nodes)
{
int nodeResult = node.IndexOf(item);
if (nodeResult >= 0)
{
return offset + nodeResult;
}
offset += node.Count;
}
return -1;
}
public void Insert(int index, T item)
{
if (first == null) //if the list is empty, then thats only ok if index=0
{
if (index == 0)
{
Initialise(item);
}
else
{
throw new IndexOutOfRangeException("The list is empty, so you can only insert at index 0");
}
}
else
{
if (index == count) //adding right at the end of the list
{
AddAfterIfFull(last, item);
}
else
{
FindResult findResult = Find(index);
if (findResult.node.IsFull)
{
T t = findResult.node.RemoveLast();
AddAfter(findResult.node, t);
}
findResult.node.Insert(index - findResult.offset, item);
}
}
count++;
}
public T this[int index]
{
get
{
FindResult findResult = Find(index);
return findResult.node[index - findResult.offset];
}
set
{
FindResult findResult = Find(index);
findResult.node[index - findResult.offset] = value;
return;
}
}
public void Add(T item)
{
if (first == null)
{
Initialise(item);
}
else
{
AddAfterIfFull(last, item);
}
count++;
}
public void Clear()
{
first = null;
count = 0;
}
public bool Contains(T item)
{
return Nodes.Any(x => x.Contains(item));
}
public void CopyTo(T[] array, int arrayIndex)
{
int i = arrayIndex;
foreach (T t in this)
{
array[i] = t;
i++;
}
}
public int Count
{
get
{
return count;
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
foreach (Node node in Nodes)
{
int i = node.IndexOf(item);
if (i >= 0)
{
if (node.Count == 1)
{
DeleteNode(node);
}
else
{
node.RemoveAt(i);
}
count--;
return true;
}
}
return false;
}
public void RemoveAt(int index)
{
FindResult findResult = Find(index);
findResult.node.RemoveAt(index - findResult.offset);
if (!findResult.node.Any())
{
DeleteNode(findResult.node);
}
count--;
return;
}
public IEnumerator<T> GetEnumerator()
{
foreach (Node node in Nodes)
{
foreach (T t in node)
{
yield return t;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Initialise this list so it contains only one item.
/// DOES NOT increase the count
/// </summary>
private void Initialise(T firstItem)
{
first = new Node();
first.Add(firstItem);
last = first;
}
/// <summary>
/// Gets an enumerator over all the nodes
/// </summary>
private IEnumerable<Node> Nodes
{
get
{
Node node = first;
while (node != null)
{
yield return node;
node = node.next;
}
}
}
/// <summary>
/// If the node supplied is full then a new one is created afterwards;
/// the item is added
/// </summary>
/// <returns>If the node is full then the new node; otherwise just the node supplied</returns>
private Node AddAfterIfFull(Node node, T item)
{
if (node.IsFull)
{
return AddAfter(node, item);
}
else
{
node.Add(item);
return node;
}
}
/// <summary>
/// Adds a new node after the node supplied, and populates it with the item supplied.
/// DOES NOT increase the count
/// </summary>
private Node AddAfter(Node node, T item)
{
Node newNode = new Node();
newNode.Add(item);
newNode.next = node.next;
newNode.previous = node;
if (node.next == null)
{
last = newNode;
}
else
{
node.next.previous = newNode;
}
node.next = newNode;
return newNode;
}
/// <summary>
/// Removes a node from the list
/// </summary>
private void DeleteNode(Node node)
{
if (node.next == null)
{
last = node.previous;
}
if (node.previous != null)
{
node.previous.next = node.next;
}
if (node.next != null)
{
node.next.previous = node.previous;
}
}
/// <summary>
/// Finds the item with this index,
/// and the index of the first item within that node
/// </summary>
private FindResult Find(int index)
{
int offset = 0;
foreach (Node node in Nodes)
{
int nextOffset = offset + node.Count;
if (index >= offset && index < nextOffset) //found node
{
return new FindResult(node, offset);
}
offset = nextOffset;
}
throw new IndexOutOfRangeException("No item at that index!");
}
/// <summary>
/// Stores the two values returned by Find
/// </summary>
private class FindResult
{
public readonly Node node;
public readonly int offset;
public FindResult(Node node, int offset)
{
this.node = node;
this.offset = offset;
}
}
////////////////////// NODE CLASS //////////////////////
private class Node : List<T>
{
internal const int MaxSize = 100;
public Node next, previous;
public bool IsFull
{
get
{
return Count >= MaxSize;
}
}
public T RemoveLast()
{
int i = Count - 1;
T t = this[i];
RemoveAt(i);
return t;
}
}
}
</code></pre>
<p><strong>Performance</strong></p>
<p>Here are some performance statistics. It's not scientific but it gives you a rough idea. Times are in milliseconds.</p>
<ul>
<li><em>Adding 100000 integers</em> (list): 1 </li>
<li><p>Adding (unrolled linked list): 12</p></li>
<li><p><em>Finding the index of an integer at the end of 1000 integers</em> (list):
10886 </p></li>
<li><p>Finding (unrolled linked list): 18055</p></li>
<li><p><em>Inserting 100000 integers into the middle</em> (list): 22694</p></li>
<li><p>Insertion(unrolled linked list): 2238</p></li>
<li><p><em>Deletion of 1000 items from the start</em> (list): 2331</p></li>
<li>Deletion (unrolled linked list): 1</li>
</ul>
<p>It looks like an unrolled linked list could be a good choice for a long list where there is a lot of insertion or deletion at places other than the end. It will have a lower memory footprint than a linked list (I've not tested that out though).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T04:24:17.763",
"Id": "71215",
"Score": "1",
"body": "Welcome to CR! Please add a bit more context / details about your implementation. Is there any part you think deserves particular attention?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:55:45.973",
"Id": "71225",
"Score": "0",
"body": "@lol.upvote I am interested generally in the performance tradeoffs of unrolled linked list vs standard list and linked list. I have written some timed methods to investigate this. It will depend on several factors such as the size of the nodes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:51:38.357",
"Id": "71249",
"Score": "1",
"body": "@PaulRichards that explanation would be a good addition to the question, if you would add it. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-30T22:11:56.363",
"Id": "345163",
"Score": "0",
"body": "What about creating a `List<T>` that will hold the first (or the last) item of each Node used by `UnrolledLinkedList<T>` ? That way when you want to find the index of an element you just need to perform a binary search in that list (which is always sorted) to know in which Node that element is. If you have a lot of nodes, it will pay. when you think about it, it is somehow similar to a `B+Tree`but with only one level below root."
}
] |
[
{
"body": "<p>A few things off the bat:</p>\n\n<ol>\n<li>You should consider prefixing private field names with underscores, so it is possible to distinguish them from local variables.\n<strong>Edit:</strong> There is no \"official\" naming conventions regarding private members. Not that i know of anyway. Underscore however is a somewhat accepted industrial standart nowadays. Mainly, because a) it is used by Microsoft, b) it is used by ReSharper (by default), c) better intelli-sense support, d) when it comes to choosing between <code>this.name = name;</code> and <code>_name = name;</code> most people choose the latter. <a href=\"http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices\" rel=\"nofollow\">I think this is pretty accurate</a></li>\n<li><pre><code>IEnumerator<T> enumerator = enumerable.GetEnumerator();\nwhile (enumerator.MoveNext())\n</code></pre>\n\n<p>emm, why dont you use <code>foreach</code>?</p></li>\n<li><p><code>tuple.Item1[index - tuple.Item2] = value;</code> - really hard to read.</p></li>\n<li><pre><code>public void Clear()\n{\n first = null;\n count = 0;\n}\n</code></pre>\n\n<p>waht happens to <code>last</code> reference?</p></li>\n<li><p><code>internal</code> members in <code>private</code> class do not make much sense (consider making those <code>public</code>).</p></li>\n<li><p>Your <code>Node</code> class should probably extend <code>List<T></code> and not encapsulate it. This way you can drop all those proxy methods and therefore reduce the amount of code. <strong>Edit2:</strong> i think using arrays in <code>Node</code> class is an overkill. You'll end up re-writing <code>List</code> implementation. Resizing is the only noticable performance drawback of <code>List</code> but that is not going to happen in your case (since you specify the size in constructor). The rest is unlikely to become any kind of bottleneck, so you probably want to keep it simple.</p></li>\n<li><p><code>internal const int MaxSize = 100;</code> this should probably be a parameter rather than a constant (at least as a user i would like to be able to set up the size of a node)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:59:26.647",
"Id": "71226",
"Score": "0",
"body": "Thanks for the great feedback. Personally I don't like underscores, is there a standard somewhere that supports their use? The parameter thing is important for my performance testing.\n\nThe reason why I didn't make Node extend List<T> is because I wanted to test using an array to hold the values instead of a list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:13:51.730",
"Id": "71233",
"Score": "0",
"body": "@PaulRichards, check my edit regarding underscores"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:12:31.537",
"Id": "71243",
"Score": "1",
"body": "`internal members in private class do not make much sense` If they (e.g. the Node constructor) were a private member instead of internal, then the containing class (e.g. UnrolledLinkedList) wouldn't be able to invoke it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:00:12.250",
"Id": "71252",
"Score": "0",
"body": "@NikitaBrizhak `most people choose the latter [citation needed]` - that is *not*, IMO, why it is chosen; it is chosen only for CLS compliance. Also, in the constructor you could set the property directly and not the backing field, avoiding the \"oh-so-problematic\" extra 5 characters `this.`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:53:02.513",
"Id": "71260",
"Score": "1",
"body": "The link you referred to says, \"Microsoft recommends against the m_ (and the straight _) even though they did both in their code\" and \"If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables.\" So using an underscore prefix seems to be controversial advice, at best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T12:40:46.073",
"Id": "71267",
"Score": "0",
"body": "@ChrisW, i do not suggest replacing `internal` with `private` obviously. I do, however suggest replacing it with `public`, as there is no difference in access level between `public` and `internal` modifiers on `private` class, and using both is somewhat confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T12:54:50.080",
"Id": "71271",
"Score": "0",
"body": "@ANeves, CLS compliance does not matter. Remember, we are talking about *private* fields here. Your class is CLS-compliant as long as its public members are CLS-compliant. Meanwhile Microsoft documentation says nothing regarding naming of private members. The actual reason for underscore is (d) - ability to distinct variable from field just by looking at its name. (a,b,c) just made this concept popular. And no, not every field backs a property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T13:54:31.733",
"Id": "71274",
"Score": "0",
"body": "`CLS compliance does not matter` true"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:36:50.603",
"Id": "71294",
"Score": "0",
"body": "Microsoft has no one standard for the underscore prefix. Some use it, some don't. Resharper has it on by default, which is why many people use it. As for me, I turn on extra color support in Resharper, so an underscore would be overkill."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:19:03.827",
"Id": "41452",
"ParentId": "41436",
"Score": "5"
}
},
{
"body": "<p>Few things (mostly small things that could slightly improve performance):</p>\n\n<ol>\n<li><code>public UnrolledLinkedList(IEnumerable<T> enumerable)</code> - do not call <code>enumerable.Any()</code> - instead start enumerating it and check on the first iteration if there is any data. This is for the performance nitpicker.</li>\n<li>The same constructor - you should dispose the enumerator if it is disposable (that is what <code>foreach</code> would do automatically).</li>\n<li>Do not use <code>Tuple<,></code> - instead create your own <code>struct</code> that has two fields (not properties). Named fields will make the code a bit more readable and accessing fields will be faster than properties (it is only used in private members which is why it can be safely done).</li>\n<li><code>Insert()</code> checks <code>first==null</code> while <code>Add()</code> checks <code>last == null</code>. Should be consistent.</li>\n<li>Since <code>.IsReadOnly</code> always return <code>false</code> you might hide it by implementing it <a href=\"http://msdn.microsoft.com/en-us/library/ms173157.aspx\" rel=\"nofollow\">explicitly</a>.</li>\n<li><code>RemoveAt()</code> - use the same approach with <code>node.Count==1</code> as in <code>Remove()</code>. Should be slightly faster.</li>\n<li><code>ToString()</code> - do not print the whole contents of the list since it rarely will give the expected result. Since this is most likely done to enhance debugging experience, use <a href=\"http://msdn.microsoft.com/en-us/library/ms228992%28v=vs.110%29.aspx\" rel=\"nofollow\">debugging attributes</a></li>\n<li><code>Find()</code> - you are doing <code>offset + node.Count</code> twice - instead use <code>offset = nextOffset;</code>.</li>\n<li><code>Node(List<T>)</code> constructor will result in the internal list being created and then promptly removed.</li>\n<li>Since <code>Node</code> class is private, do not use properties for <code>Next</code> and <code>Previous</code> - instead use fields.</li>\n</ol>\n\n<p>There also could be a benefit of (maybe a parameter that controls it) not destroying the last <code>Node</code> that you remove - instead hold it in another variable. When you need to create a new node first check if you have one stored there. You might save a lot of operations on memory allocation if the list is used in certain way. You might even store all previously created nodes in a pool. This would be consistent with the behavior of other .NET collection classes that do not decrease their allocated capacity automatically instead always remaining at their peak capacity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:50:34.860",
"Id": "71688",
"Score": "0",
"body": "Thanks, I created the FindResult class in place of the Tuple, and implemented some more of your suggested changes also."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:42:28.727",
"Id": "41556",
"ParentId": "41436",
"Score": "4"
}
},
{
"body": "<p>This part is used twice, don't duplicate the code but instead create a common method and call it from both places.</p>\n\n<pre><code> if (last.IsFull)\n {\n AddItemAfterInNewNode(last, item);\n }\n else\n {\n last.Add(item);\n } \n</code></pre>\n\n<p>You could also use LINQ here.</p>\n\n<pre><code>public bool Contains(T item)\n{\n return Nodes.Any(x => x.Contains(item));\n}\n</code></pre>\n\n<p>And I also would recommend you to inherit from List, it would save you a lot of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:49:19.600",
"Id": "71645",
"Score": "0",
"body": "-1 I cannot endorse subclassing `List<T>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:31:15.523",
"Id": "71678",
"Score": "0",
"body": "what's wrong about extending from List<>?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:45:11.070",
"Id": "71684",
"Score": "0",
"body": "See [Why not inherit from `List<T>`?](http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) - although this particular case isn't really a case for *composition*, even implementing `IList<T>` [wouldn't be the recommended way](http://stackoverflow.com/questions/1176416/implementing-ilist-interface), since `ICollection<T>` has all the needed members and is more *generic*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:49:00.953",
"Id": "71687",
"Score": "2",
"body": "Thanks, I used the common method and LINQ. Also inheriting from List<T> saved a LOT of code, I think it makes it much simpler."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:22:48.427",
"Id": "41665",
"ParentId": "41436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41452",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T22:35:27.523",
"Id": "41436",
"Score": "11",
"Tags": [
"c#",
"performance",
"linked-list",
"collections"
],
"Title": "Unrolled linked list"
}
|
41436
|
<p>My class takes functions as a parameter. There are 6 of them, along with numerous other parameters. Almost all of the fields have default values.</p>
<p>It also has a class method that creates an instance of the class with 2 of the fields initialized randomly. It has a subclass that cheats a bit by making 2 of the functions passed in as a parameter unnecessary.</p>
<p>All of this has a lot of redundant information. I have found bugs in my code caused by mistakes in the constructor calls because they were so long. I indeed found another while writing this question.</p>
<p>How can I improve this?</p>
<h3>ParentClass</h3>
<pre><code>class NeuralNet:
def __init__(self,
weights,
biases,
learning_rate=0.01,
momentum=0.9, #Set to zero to nut use mementum
post_process=lambda i: i, #Post Process is applied to final output only (Not used when training), but is used when checkign error rate
topErrorFunc=squaredMean, d_topErrorFunc=dSquaredMean,
actFunc=sigmoid, d_actFunc=dSigmoid,
topActFunc = sigmoid, d_topActFunc = dSigmoid):
self.weights = weights
self.biases = biases
assert len(self.biases)==len(self.weights), "Must have as many bias vectors as weight matrixes"
self._prevDeltaWs = [np.zeros_like(w) for w in self.weights]
self._prevDeltaBs = [np.zeros_like(b) for b in self.biases]
self.learning_rate = learning_rate
self.momentum = momentum
self.post_process = post_process
self.topErrorFunc = topErrorFunc
self.d_topErrorFunc = d_topErrorFunc
self.actFunc = actFunc
self.d_actFunc=d_actFunc
self.topActFunc = topActFunc
self.d_topActFunc = d_topActFunc
@classmethod
def random_init(cls,
layer_sizes,
learning_rate=0.01,
momentum=0.9, #Set to zero to nut use mementum
post_process=lambda i: i, #Post Process is applied to final output only (Not used when training), but is used when checkign error rate
topErrorFunc=squaredMean, d_topErrorFunc=dSquaredMean,
actFunc=sigmoid, d_actFunc=dSigmoid,
topActFunc=sigmoid, d_topActFunc=dSigmoid):
weights = [np.random.normal(0,0.01,(szNext,szThis)) for (szThis,szNext) in pairwise(layer_sizes)]
biases = [np.random.normal(0,0.01,sz) for sz in layer_sizes[1:]]
return cls(weights, biases, learning_rate, momentum, post_process, topErrorFunc, d_topErrorFunc, actFunc, d_actFunc, topActFunc,d_topActFunc)
#... Class methods
</code></pre>
<h3>Subclass</h3>
<pre><code>class FixedTopErrorSignalNeuralNet(NeuralNet):
def __init__(self,
weights,
biases,
learning_rate=0.01,
momentum=0.9, #Set to zero to nut use mementum
post_process=lambda i: i, #Post Process is applied to final output only (Not used when training), but is used when checkign error rate
actFunc=sigmoid, d_actFunc=dSigmoid,
topActFunc = softmax, d_topActFunc = dSoftmax):
NeuralNet.__init__(self,
weights=weights,
biases=biases,
momentum=momentum,
post_process=post_process,
topErrorFunc=None, d_topErrorFunc=None,
actFunc=actFunc, d_actFunc=d_actFunc,
topActFunc=topActFunc, d_topActFunc=d_topActFunc)
@classmethod
def random_init(cls,
layer_sizes,
learning_rate=0.01,
momentum=0.9, #Set to zero to nut use mementum
post_process=lambda i: i, #Post Process is applied to final output only (Not used when training), but is used when checkign error rate
actFunc=sigmoid, d_actFunc=dSigmoid,
topActFunc=softmax, d_topActFunc=dSoftmax):
weights = [np.random.normal(0,0.01,(szNext,szThis)) for (szThis,szNext) in pairwise(layer_sizes)]
biases = [np.random.normal(0,0.01,sz) for sz in layer_sizes[1:]]
return cls(weights, biases, learning_rate, momentum, post_process, actFunc, d_actFunc, topActFunc,d_topActFunc)
#... Overrides etc
</code></pre>
<h3>What the parameters do</h3>
<p>It has been suggested that this class is doing too many things, because of its large number of parameters. Here are what they do, which may provide insight.</p>
<p>The functional parameters are mostly there to avoid hard-coding them in. They are all very simple mathematical (pure) 1-2 liners.</p>
<ul>
<li><code>actFunc</code> is a mathematical activation function</li>
<li><code>d_actFunc</code> is its derivative</li>
<li><code>top_actFunc</code> is a alternative activation function used at the top of the neural net (very common technique)</li>
<li><code>d_top_actFunc</code> is its derivative</li>
<li><code>ErrorFunc</code> is used to calculate the error for during training</li>
<li><code>d_errorFunc</code> is its derivative</li>
<li><code>post_process</code> is simple mathematical transform used to get the final output, when used on nontraining data</li>
</ul>
<p>They are all parameters of the model.</p>
<p>One alternative could be that rather than passing them in as a parameter, I make them abstract methods, and then for each variation I could override them. This doesn't feel right to me, though something like <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html">Java's anonymous classes</a> might work.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T01:33:18.667",
"Id": "71207",
"Score": "1",
"body": "[I know nothing of python](http://codereview.stackexchange.com/users/23788/lol-upvote?tab=tags&sort=votes), but in other languages having a class with lots of constructor parameters is often a sign our object is breaking SRP and basically *does too many things*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T01:45:37.793",
"Id": "71208",
"Score": "1",
"body": "I don't think it is breakign the SRP, as it has one responsibility, being a neural-net. It is just highly parametrised."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T02:16:13.520",
"Id": "71209",
"Score": "0",
"body": "Well +1 anyway, looks like a good CR question... the code works right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T02:32:53.343",
"Id": "71210",
"Score": "1",
"body": "It does. and indeed (/however) even with the terrible constructor bugs i had, it still worked because neural nets are super fault tolerant, so i was usign the wrong derivative and it was just fine..."
}
] |
[
{
"body": "<p>A few suggestions:</p>\n\n<ol>\n<li>You can simplify <code>random_init</code> as: <code>def random_init(self, **kwargs):</code>; this allows you to pass any provided arguments straight through to <code>return cls(weights, biases, **kwargs)</code> without explicitly specifying them. This prevents the current duplication of default values, which could lead to problems if you change one and forget to change the other.</li>\n<li><code>random_init</code> in <code>FixedTopErrorSignalNeuralNet</code> appears identical to that in <code>NeuralNet</code>, so just use the inherited version; don't define it again.</li>\n<li>More broadly, <code>FixedTopErrorSignalNeuralNet</code> appears to only provide two different arguments to the <code>NeuralNet.__init__</code> (note: should access this via <code>super(FixedTopErrorSignalNeuralNet, self).__init__</code>); unless it has different methods, too, you could just use another <code>@classmethod</code> to create this variant. Again, you could use <code>**kwargs</code> to reduce duplication.</li>\n<li>Could you pass only the standard functions (e.g. <code>actFunc</code>) then differentiate them locally? That would save passing pairs of functions.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T00:03:44.287",
"Id": "71364",
"Score": "0",
"body": "Re Point 3: FixedTopErrorSignalNeuralNet, has other methods, (as to does NeuralNet) not show."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T00:05:02.183",
"Id": "71365",
"Score": "0",
"body": "Re 4. No It is not worth integrating a CAS system just to skip out on a few arguments. CAS systems would stuggle with the differentiation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T00:09:31.737",
"Id": "71366",
"Score": "0",
"body": "Re Super: I though super was not to be used in python 2,\n http://stackoverflow.com/a/5066411/179081"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T12:30:54.880",
"Id": "41473",
"ParentId": "41440",
"Score": "4"
}
},
{
"body": "<p>There's three ways I could see this going.</p>\n<h3>stronger hierarchy</h3>\n<p>Create what amounts to an abstract base class for NeuralNet with stubs for the math functions and then make subclasses to override the methods.</p>\n<pre><code>class NeuralNetBase(object):\n def __init__(self, biases, learning_rate=0.01, momentum=0.9):\n self.weights = weights\n self.biases = biases\n\n assert len(self.biases)==len(self.weights), "Must have as many bias vectors as weight matrixes"\n\n self._prevDeltaWs = [np.zeros_like(w) for w in self.weights]\n self._prevDeltaBs = [np.zeros_like(b) for b in self.biases]\n self.learning_rate = learning_rate\n self.momentum = momentum\n\n def act_func(self):\n raise NotImplemented\n def d_act_func(self):\n raise NotImplemented\n def top_act_func(self):\n raise NotImplemented\n def d_top_act_func(self):\n raise NotImplemented\n\n\nclass SigmoidNeuralNet(NeuralNetBase):\n \n def act_func(self):\n # magic here\n def d_act_func(self):\n # more magic\n def top_act_func(self):\n # even more... \n def d_top_act_func(self):\n # like hogwarts!\n</code></pre>\n<p>This would work well if there is a high correlation between the optional functions: if they tend to cluster together they'd make a natural class hierarchy (and you'd have an easy way to see which nodes were using which function sets just by looking at their concrete classes). OTOH this won't work well if the functions are not correlated.</p>\n<h3>Kwargs to the rescue</h3>\n<p>You can simplify the constructor logic by using kwargs and by including the defaults in the <strong>init</strong> method (for sanity's sake I'd move the pure data into required parameters, but that's just aesthetics);</p>\n<pre><code>class NeuralNet(object):\n def __init__(self, biases, learning_rate, momentum, **kwargs):\n self.weights = weights\n self.biases = biases\n\n assert len(self.biases)==len(self.weights), "Must have as many bias vectors as weight matrixes"\n\n self._prevDeltaWs = [np.zeros_like(w) for w in self.weights]\n self._prevDeltaBs = [np.zeros_like(b) for b in self.biases]\n self.learning_rate = learning_rate\n self.momentum = momentum\n\n # assuming the default implementations 'private' class methods \n # defined below\n self.act = kwargs.get('act_func', self._default_act_func)\n self.top_act = kwargs.get('top_act_func', self._default_top_act_func)\n self.d_act = kwargs.get('d_act_func', self._default_d_act_func)\n self.d_top_act_func = kwargs.get('top_d_act_func', self._default_d_top_act_func)\n self.postprocess = kwags.get('post', self._default_postprocess)\n</code></pre>\n<h2>function components</h2>\n<p>If a lot of reasoning goes into the choice or relationship of the functions, you could just put them all into an object and work with those objects instead of loose funcs:</p>\n<pre><code> class NeuralNet(object):\n def __init__(self, biases, learning_rate, momentum, funcs = DefaultFuncs):\n self.weights = weights\n self.biases = biases\n #... etc\n self.Functions = funcs(self)\n\n class DefaultFFuncs(object):\n def __init__(self, target, act_func, top_func, d_act_func, d_top_func);\n self.Target = target\n self._act_func = act_func\n self._act_func = act_func\n self._d_top_func = d_top_func\n self._d_top_func = d_top_func\n\n def act_func(self):\n return self._act_func(self.Target)\n\n def d_act_func(self):\n return self._d_act_func(self.Target)\n\n def top_act_func(self):\n return self._top_act_func(self.Target)\n\n def d_top_act_func(self):\n return self._d_top_act_func(self.Target)\n</code></pre>\n<p>This would let you compose and reuse a collection of funcs into a DefaultFuncs and then reuse it -- default funcs is really just an elaborate Tuple tricked out so you can call into the functions from the owning NeuralNet instance</p>\n<p>All of these are functionally identical approaches (it sounds like you've already got the thing working and just want to clean it up). The main reasons for choosing among them amount to where you want to put the work #1 is good if the functions correlate and you want to easily tell when a given net instance is using a set; #2 is just syntax sugar on what you've already got; #3 is really just #2 except that you compose a function set as class (perhaps with error checking or more sophisticated reasoning) instead of a a dictionary</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T20:37:29.920",
"Id": "466625",
"Score": "0",
"body": "This is a great answer, useful to consider in many contexts. Bundling args into a helper class, using base/subs, etc. I like."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:45:50.087",
"Id": "41499",
"ParentId": "41440",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T01:23:27.560",
"Id": "41440",
"Score": "10",
"Tags": [
"python",
"constructor",
"python-2.x"
],
"Title": "Long constructors, inheritance, class method constructors"
}
|
41440
|
<p>I have solved fibonacci series and then used the topdown and bottom up approaches to solve it. Also I have included the stairway climbing question as follows "You are climbing a stair case. Each time you can either make 1 step or 2 steps. The staircase has numStairs steps. Returns In how many distinct ways can you climb the staircase."
Looking for code review, optimizations, best practices etc. </p>
<pre><code>public final class Fibo {
private Fibo() {}
/**
* Returns the nth number in the fibonacci sequence.
*
* @param n nth position in the fibo series, which starts from 0th position.
* @return the nth number in the fibonacci series.
*/
/*
* TimeComplexity: O(n)
* Space Complexity: http://www.geeksforgeeks.org/g-fact-86/
*/
public static int fibo(int n) {
if (n <= 1) return n;
return fibo(n - 1) + fibo(n - 2);
}
/**
* Returns the nth number in the fibonacci sequence.
*
* @param n nth position in the fibo series, which starts from 0th position.
* @return the nth number in the fibonacci series.
*/
/*
* Time complexity: O(n)
* Aux Space: O(n)
*/
public static int fiboTopDown(int n) {
if (n < 0) throw new IllegalArgumentException("The value of n: " + n + " should be positive.");
final Map<Integer, Integer> fiboCache = new HashMap<Integer, Integer>();
return fiboCompute(n, fiboCache);
}
private static int fiboCompute(int n, Map<Integer, Integer> fiboCache) {
if (n <= 1) return n;
if (fiboCache.containsKey(n)) {
return fiboCache.get(n);
}
int sum = fiboCompute (n - 1, fiboCache) + fiboCompute (n - 2, fiboCache);
fiboCache.put(n, sum);
return sum;
}
/**
* Returns the nth number in the fibonacci sequence.
*
* @param n nth position in the fibo series, which starts from 0th position.
* @return the nth number in the fibonacci series.
*/
/*
* Time complexity: O(n)
* Aux Space: O(1)
*/
public static int fiboBottomUp(int n) {
if (n < 0) throw new IllegalArgumentException("The value of n: " + n + " should be positive.");
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i < n; i++) {
a = b;
b = c;
c = a + b;
}
return c;
}
/**
* You are climbing a stair case. Each time you can either make 1 step or 2 steps
* The staircase has numStairs steps. Returns In how many distinct ways can you climb the staircase.
*
* @param numStairs
* @return
*/
public static int stairCount(int numStairs) {
if (numStairs <= 0) throw new IllegalArgumentException("The number of stairs: " + numStairs + "
should be positive.");
return fiboBottomUp(numStairs + 1);
}
public static void main(String[] args) {
System.out.println(fibo(0) + ":" + fibo(1) + ":" + fibo(2) + ":" + fibo(3) + ":" + fibo(4) + ":" + fibo(5));
System.out.println(fiboTopDown(0) + ":" + fiboTopDown(1) + ":" + fiboTopDown(2) + ":"
+ fiboTopDown(3) + ":" + fiboTopDown(4) + ":" + fiboTopDown(5));
System.out.println(fiboBottomUp(0) + ":" + fiboBottomUp(1) + ":"
+ fiboBottomUp(2) + ":" + fiboBottomUp(3) + ":"
+ fiboBottomUp(4) + ":" + fiboBottomUp(5));
System.out.println(stairCount(1) + ":"
+ stairCount(2) + ":" + stairCount(3) + ":"
+ stairCount(4) + ":" + stairCount(5));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>The parameter name in <code>stairCount</code> represents the number of steps, maybe it ought to be called <code>numSteps</code> instead of <code>numStairs</code>. Also, personally, I would prefer <code>stepCount</code>.</p></li>\n<li><p>There really should be a new line after <code>(numStairs <= 0)</code> to make the code look better</p></li>\n<li><p>That could give</p>\n\n<pre><code>public static int stairCount(int stepCount) {\n if (stepCount <= 0) \n throw new IllegalArgumentException(\"stepCount should be positive\");\n return fiboBottomUp(stepCount + 1);\n}\n</code></pre></li>\n<li><p>Since you only work with <code>int</code> which is 32 bits, and so can only hold 46 numbers ( 46th is 1836311903 ), you might as well cache all 46 numbers and have your code run super fast.</p></li>\n<li><p>This</p>\n\n<pre><code>System.out.println(fiboBottomUp(0) + \":\" + fiboBottomUp(1) + \":\"\n + fiboBottomUp(2) + \":\" + fiboBottomUp(3) + \":\"\n + fiboBottomUp(4) + \":\" + fiboBottomUp(5));\n</code></pre>\n\n<p>is begging for a <code>for</code> loop to make it more DRY.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T03:19:30.510",
"Id": "41443",
"ParentId": "41441",
"Score": "3"
}
},
{
"body": "<p>This comment is inaccurate:</p>\n\n<pre><code>/*\n * TimeComplexity: O(n)\n * Space Complexity: http://www.geeksforgeeks.org/g-fact-86/\n */\npublic static int fibo(int n) { … }\n</code></pre>\n\n<p>A naïve recursive <code>fibo()</code> has O(2<sup><em>n</em></sup>) time complexity. Think of it this way: to calculate <code>fibo(n)</code>, you break it up into two problems, each of size <em>n</em> - 1.</p>\n\n<p>In <code>fiboBottomUp()</code>, don't declare/define <code>int a = 0</code>, since it is only ever used as a temporary variable inside the for-loop.</p>\n\n<pre><code>public static int fiboBottomUp(int n) {\n if (n < 0) {\n // Message is inaccurate: n = 0 is allowable\n throw new IllegalArgumentException(\"The value of n: \" + n + \" should be non-negative.\");\n }\n\n int b = 1;\n int c = 0;\n for (int i = 0; i < n; i++) {\n int a = b;\n b = c;\n c = a + b;\n }\n return c;\n}\n</code></pre>\n\n<p>Using a <code>HashMap<Integer, Integer></code> for <code>fiboCache</code> is more complicated than necessary. An <code>ArrayList<Integer></code> or even an <code>int[n + 1]</code> will do, since all the keys are consecutive integers.</p>\n\n<p>Consider widening your return types to <code>long</code> to stave off overflow for a while longer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-13T17:40:07.367",
"Id": "101492",
"Score": "0",
"body": "\" Think of it this way: to calculate fibo(n), you break it up into two problems, each of size n - 1.\", don't you mean one of size n - 1 and other of size n - 2, though ultimately every fibo(n) produces two problems of size O(n)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:37:13.257",
"Id": "41446",
"ParentId": "41441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41446",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T02:04:10.020",
"Id": "41441",
"Score": "3",
"Tags": [
"java",
"fibonacci-sequence"
],
"Title": "Fibonacci series, topdown and bottom up approaches, stairway climbing"
}
|
41441
|
<p>I recently had a Java interview where I was asked to write a client-server application. I don't code primarily in Java, but with my preliminary Java knowledge, I thought I built a reasonable working solution. After evaluating my solution, I was told that I wasn't going to be interviewed further. I'm fine with their decision, but I'd like to know what parts of my solution weren't right. Any feedback on my code below will be greatly appreciated.</p>
<p>These were the requirements:</p>
<p><strong>Client: Program called ClientEmulator</strong></p>
<ul>
<li><p>Command line option to specify TCP/IP Address, port, and file to read XML data file. </p></li>
<li><p>Should open XML data file and send to server. XML will be of this format</p>
<blockquote>
<pre><code><Message>
<Command>Print</Command>
<Command>Display</Command>
<Command>Query</Command>
</Message>
</code></pre>
</blockquote></li>
<li><p>Display the response sent by server to the console.</p></li>
</ul>
<p><strong>Server: Program called ServerSocketMonitor</strong></p>
<ul>
<li><p>Command line option to specify TCP/IP Address and port </p></li>
<li><p>Socket Listener: Open socket and listen for incoming data </p></li>
<li><p>Send client a receipt notice when a command is received </p></li>
<li><p>Application must remain operational until CTL+C is detected </p></li>
<li><p>Server will create a command queue and process each client command in a separate thread </p></li>
<li><p>Server's execution/processing of these commands was supposed to be dumb: just print the command name and the execution time</p></li>
</ul>
<p>This was my solution:</p>
<p><strong>Client</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
*
* @author DigitalEye
*/
public class ClientEmulator {
// Singleton Implementation: In the context of this app,
private static ClientEmulator _singletonInstance = null;
// Default constructor is private to make sure it can't be accessed outside
// the class
private ClientEmulator() {
}
/**
* Returns single instance of ClientEmulator
* @return Instance of ClientEmulator
*/
public static ClientEmulator getSingleClientEmulator() {
if (_singletonInstance == null) {
_singletonInstance = new ClientEmulator();
}
return _singletonInstance;
}
/**
* Waits on response from server
* @param socket Server socket
*/
public void readServerResponse(Socket socket) {
try {
BufferedReader serverReader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String serverResponse = null;
while ((serverResponse = serverReader.readLine()) != null) {
System.out.println("Server Response: " + serverResponse);
}
} catch (IOException ex) {
System.out.println("Error: Unable to read server response\n\t" + ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Make sure command line arguments are valid
if (args.length < 3) {
System.out.println("Error: Please specify host name, port number and data file.\nExiting...");
return;
}
try {
// Open a socket to the server
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
// Wait for the server to accept connection before reading the xml file
BufferedReader reader = new BufferedReader( new FileReader (args[2]));
String line;
StringBuilder stringBuilder = new StringBuilder();
while((line = reader.readLine() ) != null) {
stringBuilder.append(line);
}
// Send xml data to server
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println(stringBuilder.toString());
// Wait for server response
getSingleClientEmulator().readServerResponse(socket);
} catch (IOException | NumberFormatException ex) {
System.out.println("Error: " + ex);
}
}
}
</code></pre>
<p><strong>Server</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author DigitalEye
*/
public class SocketServerMonitor {
/**
* Server Socket
*/
private ServerSocket _serverSocket = null;
/**
* Client Socket
*/
private Socket _clientSocket = null;
/**
* List of client commands
*/
private ArrayList<Runnable> _workQueue = null;
/**
* Date Time formatter
*/
private final SimpleDateFormat _dateTimeFormatter =
new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
/**
* Singleton Implementation: In the context of this app, only one instance of
* SocketServerMonitor makes sense
*/
private static SocketServerMonitor _singletonInstance = null;
/**
* Hidden constructor prevents instantiation of this type
*/
private SocketServerMonitor() {
}
/**
* Creates, if the singleton instance hasn't been created before and returns
* the single instance of SocketServerMonitor
*
* @return Singleton Instance of SocketServerMonitor
*/
public static SocketServerMonitor getSingleSocketServerMonitor() {
if (_singletonInstance == null) {
_singletonInstance = new SocketServerMonitor();
}
return _singletonInstance;
}
/**
* Starts monitoring the server socket. Blocks until a client connects on
* this socket
* @param serverEndPoint Address to which the server socket is bound
*/
public void start(SocketAddress serverEndPoint) {
if (_serverSocket != null) {
stop();
} else {
try {
_serverSocket = new ServerSocket();
_serverSocket.bind(serverEndPoint);
System.out.println("Listening for connections at " + serverEndPoint.toString());
_clientSocket = _serverSocket.accept();
} catch (IOException ex) {
System.out.println("Error: Unable to Start Server Socket!\n\t" + ex);
}
}
}
/**
* Stop monitoring. Closes server and client sockets
*/
public void stop() {
if (_serverSocket != null) {
try {
System.out.println("Stopping Server Socket Monitor");
_serverSocket.close();
_clientSocket.close();
_serverSocket = null;
} catch (IOException ex) {
System.out.println("Error: Unable to stop server socket monitor! " + ex);
}
}
}
/**
* Adds a client command to work queue
* @param commandNode Node corresponding to XML element Command
*/
private void addToWorkQueue(final Node commandNode) {
if (_workQueue == null)
_workQueue = new ArrayList<>();
_workQueue.add(new Runnable() {
@Override
public void run() {
System.out.println(((Element) commandNode).getTextContent() + " " + _dateTimeFormatter.format(new Date()));
}
});
}
/**
* Executes queued client commands. The execution is started in a new thread
* so the callee thread isn't blocked until commands are executed. Each command
* is executed in a separate thread and the commands are guaranteed to be executed
* in the order in which they were received by the server
*/
private void processCommandQueue() {
if (_workQueue != null) {
new Thread(new Runnable() {
@Override
public void run() {
try {
for (Runnable work : _workQueue) {
Thread workerThread = new Thread(work);
workerThread.start();
workerThread.join();
}
} catch (InterruptedException ex){
System.out.println("Error: Unable to process commands!\n\t" + ex);
} finally {
_workQueue.clear();
}
}
}).start();
}
}
/**
* Read a string from the client that contains a XML document hierarchy
* @return Document Parsed XML document
*/
private Document acceptXMLFromClient() {
Document xmlDoc = null;
try {
BufferedReader clientReader = new BufferedReader(
new InputStreamReader(_clientSocket.getInputStream()));
// block until client sends us a message
String clientMessage = clientReader.readLine();
// read xml message
InputSource is = new InputSource(new StringReader(clientMessage));
xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
} catch (IOException | ParserConfigurationException | SAXException ex) {
// FIXME: put exceptions in log files?
System.out.println("Error: Unable to read XML from client!\n\t" + ex);
}
return xmlDoc;
}
/**
* Waits on client messages. Attempts to read client messages as a XML document
* and sends a receipt notice to the client when a message is received. Attempts
* to read the Command tag from the client and queues up the client command
* for execution
*/
private void listenToClient() {
assert _clientSocket != null : "Invalid Client Socket!";
// open a writer to client socket
PrintWriter pw = null;
try {
pw = new PrintWriter(_clientSocket.getOutputStream(), true);
} catch (IOException ex) {
System.out.println("Error: Unable to write to client socket!\n\t" + ex);
}
while (true) {
// Read xml from client
Document xmlDoc = acceptXMLFromClient();
if (xmlDoc != null) {
// Send receipt notice to client
if (pw != null) {
pw.println("Message Received " + _dateTimeFormatter.format(new Date()));
}
NodeList messageNodes = xmlDoc.getElementsByTagName("Command");
for (int i = 0; i < messageNodes.getLength(); i++) {
addToWorkQueue(messageNodes.item(i));
}
} else {
System.out.println("Unknown Message Received at " + _dateTimeFormatter.format(new Date()));
}
processCommandQueue();
}
}
/**
* @param args the command line arguments
*/
public static void main(final String[] args) {
// Make sure command line arguments are valid
if (args.length < 2) {
System.out.println("Error: Please specify host name and port number.\nExiting...");
return;
}
try {
getSingleSocketServerMonitor().start(
new InetSocketAddress(args[0],Integer.parseInt(args[1])));
getSingleSocketServerMonitor().listenToClient();
} catch (NumberFormatException ex) {
System.out.println(ex);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h3>Protocol</h3>\n\n<p>I find your client-server protocol odd. <strong>Usually, XML is mostly indifferent to whitespace.</strong> That is, a document spread over multiple lines, such as</p>\n\n<pre><code><hello>\n <message language=\"en\">How are you</message>\n</hello>\n</code></pre>\n\n<p>… is usually interpreted the same way as</p>\n\n<pre><code><hello><message language=\"en\">How are you</message></hello>\n</code></pre>\n\n<p>That behaviour isn't required by any XML specification, but it is conventional to ignore such whitespace.</p>\n\n<p>However, the protocol you've designed is <strong>line-oriented</strong>, with each line containing an XML message. The client strips carriage returns / newlines when reading its files. Correspondingly, the server expects the client to send its XML all as one line — it feeds the result of only one <code>readLine()</code> call to the XML parser.</p>\n\n<p>For robustness, the server should be lenient in what it accepts, and that means it should try to read until it sees a complete XML document, possibly spread over multiple lines. Then the client could be simplified — it can just feed the entire input file to the server without stripping carriage returns / newlines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:14:26.913",
"Id": "41454",
"ParentId": "41445",
"Score": "6"
}
},
{
"body": "<p><em>I should preface this review by noting that it is easy for me to criticize your code, with the luxury of being able to look up whatever resources I want and without the pressure or time constraints of being in an interview.</em></p>\n\n<h3>Client</h3>\n\n<p>Why is the class called <code>ClientEmulator</code> — what is it emulating? In fact, <strong>what is its purpose</strong>? It looks like the only thing in the class is <code>readServerResponse()</code>. Oddly, <code>main()</code> is responsible for sending the request. I would expect that your object would be responsible for sending the request <em>and</em> handling the response. In short, <strong>that's not object-oriented programming</strong>; it's a function that has been awkwardly incorporated into a class.</p>\n\n<p>Should <code>ClientEmulator</code> really be a <strong>singleton</strong>? I know that as you wrote it, your <code>main()</code> happens to use just one <code>ClientEmulator</code>. However, most client-server systems allow multiple clients, and multiple clients in the same process wouldn't be inconceivable.</p>\n\n<p>Even if <code>ClientEmulator</code> were a singleton, <strong>why instantiate it lazily?</strong> The constructor is so trivial. You might as well say</p>\n\n<pre><code>private static ClientEmulator instance = new ClientEmulator();\n</code></pre>\n\n<p>and be done with it. Also, it's customary to name the singleton-fetching function <strong><code>getInstance()</code>.</strong></p>\n\n<p>Assuming that you accept my <a href=\"https://codereview.stackexchange.com/a/41454/9357\">suggested protocol improvements</a>, you could <strong>simplify the file I/O.</strong><br>\nJust use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,%20java.io.OutputStream)\" rel=\"nofollow noreferrer\"><code>java.nio.file.Files.copy(Path, OutputStream)</code></a>.</p>\n\n<p>Normal output should go to <code>System.out</code>; <strong>error messages should go to <code>System.err</code></strong> to avoid mingling with the output.</p>\n\n<p>After sending the request, it's polite to <strong>cleanup.</strong> You should at minimum <code>flush()</code> the output stream. In the case of this one-shot client, it's never going to send anything again, so you could just <code>shutdownOutput()</code>. After everything is done, it's good practice to <code>close()</code> the socket, or better yet, use try-with-resources and autoclosing.</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.file.Files;\nimport java.nio.file.FileSystems;\nimport java.nio.file.Path;\nimport java.net.Socket;\n\npublic class Client implements Closeable {\n private Socket socket;\n\n public Client(String host, int port) throws IOException {\n this(new Socket(host, port));\n }\n\n public Client(Socket s) {\n this.socket = s;\n }\n\n @Override\n public void close() throws IOException {\n this.socket.close();\n }\n\n public void send(String filePath) throws IOException {\n Path path = FileSystems.getDefault().getPath(filePath);\n Files.copy(path, this.socket.getOutputStream());\n this.socket.shutdownOutput();\n }\n\n public void recv() {\n try {\n BufferedReader serverReader = new BufferedReader(\n new InputStreamReader(socket.getInputStream()));\n\n String serverResponse;\n while ((serverResponse = serverReader.readLine()) != null) {\n System.out.println(\"Server Response: \" + serverResponse);\n }\n } catch (IOException ex) {\n System.err.println(\"Error: Unable to read server response\\n\\t\" + ex);\n } \n }\n\n public static void main(String[] args) {\n // Make sure command line arguments are valid\n String hostname, filePath;\n int port;\n try {\n hostname = args[0];\n port = Integer.parseInt(args[1]);\n filePath = args[2];\n } catch (ArrayIndexOutOfBoundsException | NumberFormatException ex) {\n System.err.println(\"Error: Please specify host name, port number and data file.\\nExiting...\");\n return;\n }\n\n try (Client c = new Client(hostname, port)) {\n c.send(filePath);\n c.recv();\n } catch (IOException ex) {\n System.err.println(\"Error: \" + ex);\n }\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:05:52.173",
"Id": "71337",
"Score": "0",
"body": "Thanks for the great answer! They wanted it named ClientEmulator, it wasn't my call. I also see why it's poor OOP code to have main() send the request and the ClientEmulator read the response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:28:01.577",
"Id": "41455",
"ParentId": "41445",
"Score": "6"
}
},
{
"body": "<p>Two of the specific requirements on the server side are:</p>\n\n<ul>\n<li>server must run until Ctrl-c is pressed.</li>\n<li>it must process commends in a queue in a separate thread.</li>\n</ul>\n\n<p>These two requirements indicate that they want a 'standard' server system, and probably a standard Executor service.</p>\n\n<p>I would expect to see code that looks something like:</p>\n\n<pre><code>ServerSocket serversocket = new ServerSocket();\nserversocket.bind(....);\nExecutorService threadpool = new Executors.newCachedThreadPool();\nwhile (true) {\n final Socket client = serversocket.accept();\n // will need to create this class that handles the client.\n // the class should implement Runnable.\n Runnable clienthandler = new MyClientHandler(client);\n threadpool.submit(clienthandler);\n}\n</code></pre>\n\n<p>The above code will listen for <strong>multiple</strong> clients, not just one.\nIt will handle each client in a separate thread.</p>\n\n<p><strong>Update:</strong> The question: <em>\"My solution was to create a separate command processor thread, which would then span a new thread for each command. Any comments on my approach to ensure that commands are processed in the order that they are received?\"</em></p>\n\n<p>There are two parts to processing the commands... the first part is that they should be acknowledged to the client, and it is appropriate that the ack is in the correct order. There is no requirement that the commands are actually processed in that same order.</p>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li>*I only just saw that the XML input file was in the question, but 'hidden'... I edited the Q and made it show up properly)</li>\n<li>I never reviewed this part of your problem the first time around.... it is 'bigger' than just the server-socket thread.</li>\n<li>the more I look in to it, the more problems I am seeing..... this is frustrating...</li>\n<li>your server, as it stands, <strong>does not</strong> notify the client when it receives each command, it just notifies when it receives the first data... and does not print each command....</li>\n</ul>\n\n<p>The network server I described above is pretty typical. Here are some results from google which describe it:</p>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/socket-140484.html\" rel=\"nofollow noreferrer\">The Oracle tutorial</a></li>\n<li><a href=\"http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html\" rel=\"nofollow noreferrer\">another Oracle tutorial</a></li>\n<li><a href=\"http://www.developer.com/java/ent/article.php/1356891/A-PatternFramework-for-ClientServer-Programming-in-Java.htm\" rel=\"nofollow noreferrer\">A Pattern/Framework for Client/Server Programming in Java</a></li>\n<li><a href=\"http://www.kieser.net/linux/java_server.html\" rel=\"nofollow noreferrer\">A multi-threaded socket-based server</a> <-- horrible code style!!!</li>\n</ul>\n\n<p>The point is that they all follow the same pattern, and it's a good one.</p>\n\n<p>Now, your problem is that a client may send more than one request. This is a problem because.... you need a protocol to support it.</p>\n\n<ul>\n<li>the protocol I imagined in a simple case was that the client 'dumps' the request, and the server processes it, and responds.</li>\n<li>if the client can send multiple requests... how do we know when one request ends, and the next one starts?</li>\n<li>XML input cannot just be read from the socket... because any additional client requests will cause the XML to become invalid....</li>\n<li>your current code just reads a file from disk, and dumps it to the socket.... and does not 'parse' the input in to individual requests. <strong>Actually</strong>, your code strips all the newlines from the input XML before sending it, so the XML is only one one line.... you should <strong>comment</strong> that, because it is not obvious.</li>\n</ul>\n\n<p><strike>One of the big 'gotcha's' with network processing is that data does not arrive when you expect it. For example, in your client, it may just hang forever.... because you never close the OutputStream in the client..... in fact.... <strong>Your server WILL NOT complete the parsing of the client's data....</strike> --- I just realized that you force all the XML on to one line, and that my previous comment is wrong... you need to **document</strong> these things.</p>\n\n<p>I had previously assumed that the protocol was a simple:</p>\n\n<ul>\n<li>client opens socket</li>\n<li>dumps request on socket's OutputStream</li>\n<li>flushes stream</li>\n<li>closes stream</li>\n<li>listens on socket's InputStream for server response.</li>\n<li>processes responses until InputStream is closed</li>\n<li>done.</li>\n</ul>\n\n<p>But, as 200_success points out, it is nothing of the sort.... you should be forcing the data through the socket, and you are not! You are not flushing the output stream, and you are not closing it.</p>\n\n<p>As a result the timing of when your client request is actually sent is unpredictable.</p>\n\n<p>So, your client-side management is poor.... for a simple single-method client, you have managed to put a lot of broken things in there. I would recommend the following main-method client:</p>\n\n<ul>\n<li>nevermind, <a href=\"https://codereview.stackexchange.com/a/41455/31503\">use 200_successes recommendation</a>. It is good.</li>\n</ul>\n\n<p>Given all the above, I would recommend that the socket-server management/configuration is not changed from my previous recommendation, but each client-socket-handling thread in the server should look something like:</p>\n\n<pre><code>class MyClientHandler implements Runnable {\n // have one thread pool running with as many threads as there are CPU's\n // this thread pool will process the actual server commands.\n private static final ExecutorService COMMANDSERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());\n\n private final Socket clientSocket;\n\n MyClientHandler(Socket client) {\n clientSocket = client;\n }\n\n public void run() {\n // parse the XML from the client...\n try (Writer writer = new OutputStreamWriter(clientSocket.getOutputStream())) {\n Document document = parseXMLDocument(clientSocket.getInputStream());\n NodeList messageNodes = xmlDoc.getElementsByTagName(\"Command\");\n for (int i = 0; i < messageNodes.getLength(); i++) {\n final String command = ((Element)messageNodes.item(i)).getTextContent();\n writer.write(String.format(\"Processing command %d - %s\\n\", i + 1, command));\n writer.flush(); // send the data to the client....\n COMMANDSERVICE.submit(new Runnable() {\n public void run () {\n // implemented somewhere else.\n // will print date, and command.\n processServerCommand(command);\n }\n });\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:20:15.087",
"Id": "71338",
"Score": "0",
"body": "Good answer! I like how you have serversocket.accept() inside a while(true) which lets you listen to multiple clients. They wanted each client command to be handled in a separate thread. I assumed that a message from client can have multiple commands, like this: \"<message><command>c1</command><command>c2</command></message>\". My solution was to create a separate command processor thread, which would then span a new thread for each command. Any comments on my approach to ensure that commands are processed in the order that they are received?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T08:31:23.913",
"Id": "97676",
"Score": "0",
"body": "I like that each client gets its own thread."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:29:19.507",
"Id": "41471",
"ParentId": "41445",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:27:46.343",
"Id": "41445",
"Score": "6",
"Tags": [
"java",
"multithreading",
"xml",
"interview-questions",
"networking"
],
"Title": "Client Sends XML, Server Parses XML, Queues Up and Executes Commands"
}
|
41445
|
<p>It took me a while to figure out how to write this code, but I'm glad to say that I did eventually figure it out.</p>
<p>Can someone tell me what they think about it? Is it well written? What could have been done better?</p>
<p>Note that I am going through exercises in a book; I know there's a <code>math.h</code> that problem solves this, but I don't want to use that since I am not currently in that chapter.</p>
<pre><code>#include <stdio.h>
int main(void)
{
printf("\n Table of Factorials\n\n");
printf(" n ------------- Factorial\n");
int n, factorial, counter;
factorial = 1;
n = 1;
counter = 1;
for ( ; counter <= 10; ++counter)
{
for ( ; n <= counter; ++n)
{
factorial = factorial * n;
}
printf("%2i --------------%7i\n", counter, factorial);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:51:51.883",
"Id": "71238",
"Score": "3",
"body": "I'd move the factorial computation into its own function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T12:30:39.753",
"Id": "71266",
"Score": "0",
"body": "I hope you understands what happens if you try to get the factorial of 14 or maybe even 40? And why the simple fix isn't the right fix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:10:51.300",
"Id": "71277",
"Score": "0",
"body": "I'm glad to see a non-recursive implementation of factorial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T04:24:49.093",
"Id": "81660",
"Score": "0",
"body": "Answers below have remarked on the indentation problems, but that seems to have been an artifact of copying-and-pasting the code into the text editor on this site. Markdown syntax requires four leading _spaces_ to form a code block; the Markdown written in the question contained leading tabs instead."
}
] |
[
{
"body": "<p>Looks pretty good! Just a few minor things:</p>\n\n<ul>\n<li><p>Your variables should be on separate lines, which is useful for maintainability and possible commenting. They can also be initialized instead of declared and then assigned.</p>\n\n<pre><code>int n = 1;\nint factorial = 1;\nint counter = 1;\n</code></pre></li>\n<li><p>Instead of this:</p>\n\n<pre><code>factorial = factorial * n;\n</code></pre>\n\n<p>you can just have this:</p>\n\n<pre><code>factorial *= n;\n</code></pre>\n\n<p>This works for any of the mathematical operators.</p></li>\n<li><p>Instead of hard-coding the <code>10</code>, you can have the user provide the number of values to display.</p>\n\n<pre><code>puts(\"Enter the number of values to display: \");\nint numValues;\nscanf(\"%d\", &numValues);\n\nfor (int counter = 1; counter <= numValues; counter++)\n{\n // ...\n} \n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:52:45.817",
"Id": "41449",
"ParentId": "41447",
"Score": "13"
}
},
{
"body": "<p>Firstly, your indentation is a bit off. You should be indenting within a function body, so instead of:</p>\n\n<pre><code>int main(void)\n{\nprintf(...);\n// Other code\n}\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>int main(void)\n{\n printf(...);\n // Other code\n}\n</code></pre>\n\n<p>Similarly with:</p>\n\n<pre><code>for ( ; n <= counter; ++n)\n{ \nfactorial = factorial * n;\n}\n</code></pre>\n\n<p>This is something to really watch out for; it makes for a jarring experience when reading the code.</p>\n\n<p>The constant <code>10</code> here: </p>\n\n<pre><code>for ( ; counter <= 10; ++counter)\n</code></pre>\n\n<p>should be given a name:</p>\n\n<pre><code>#define MAX_COUNTER 10\n\nfor( ; counter <= MAX_COUNTER; ++counter)\n</code></pre>\n\n<p>The line:</p>\n\n<pre><code>factorial = factorial * n;\n</code></pre>\n\n<p>can be simplified into:</p>\n\n<pre><code>factorial *= n;\n</code></pre>\n\n<p>Having two loops here is more complex than it needs to be. It can be simplified to just using 1 loop. You could also pull the initialization of counter into this loop:</p>\n\n<pre><code>int counter;\n\nfor (counter = 1 ; counter <= MAX_COUNTER; ++counter)\n{\n factorial *= counter;\n printf(\"%2i --------------%7i\\n\", counter, factorial);\n}\n</code></pre>\n\n<p>If you're using C99, which allows variable declarations anywhere within a function (not just at the top), this can be simplified even more:</p>\n\n<pre><code>int factorial = 1;\nfor(int counter = 1; counter <= MAX_COUNTER; ++counter) {\n factorial *= counter;\n printf(\"%2i --------------%7i\\n\", counter, factorial);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:27:20.720",
"Id": "71223",
"Score": "0",
"body": "Awesome how much simpler this is. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:42:21.650",
"Id": "71237",
"Score": "3",
"body": "Good, I was also wondering what the variable n was for. Maybe a personal idea but I think it's clearer to declare each variable on a single line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:44:52.103",
"Id": "71258",
"Score": "1",
"body": "@dyesdyes I agree, unless the variables belong to each other. For example: float x,y,z; or int screenWidth,screenHeight; That sort of thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:08:39.840",
"Id": "71276",
"Score": "0",
"body": "Is it me or does the last simplification make no difference to the complexity or number of lines of code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:12:29.693",
"Id": "71280",
"Score": "0",
"body": "@Charleh It limits variable scope to the smallest possible scope. In such a small function it makes almost no difference, but is a good habit to get into (assuming you're using a C99 compatible compiler, and aren't stuck with MSVC)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:12:38.263",
"Id": "71281",
"Score": "1",
"body": "Better yet would be `const int MAX_COUNTER=10;`. Doesn't change anything here, but generally it's better to make constants via `const` instead of `#define`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:17:02.397",
"Id": "71282",
"Score": "0",
"body": "@Ruslan I agree, however, while the book has likely introduced `#DEFINE` by this point; I'm less sure about `const`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:41:53.297",
"Id": "71285",
"Score": "0",
"body": "You don't even need a body in the `for` loop. Try: `for(int c = 1 ; c <= MAX_COUNTER ; printf(\"%2i --- %7i\\n\", c, (factorial *= c++)));`. This is perhaps somewhat nasty, the result is implementation-dependent (which gets evaluated first, pushing `c` onto the stack to call printf, or the `c++` in the assignment to `factorial`? :-), and you may get arrested for \"abuse of a `for` loop\" but hey - you saved having to code up a block to follow the `for` statement, and it runs on **my** machine - what could go wrong? :-). And BTW - indentation is a religious issue - not for SO. :-) Share and enjoy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:15:33.433",
"Id": "71292",
"Score": "0",
"body": "@BobJarvis: To be precise, this is not implementation-defined; it is undefined behaviour, and so any result is valid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:48:52.523",
"Id": "71295",
"Score": "0",
"body": "@Yuushi Ah I see what you mean, just compressing variable scope - I'm used to Resharper doing this for me I think I'm getting lazy :)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:58:30.050",
"Id": "41450",
"ParentId": "41447",
"Score": "18"
}
},
{
"body": "<p>Start by fixing your indentation. Lines of code inside each pair of braces should be indented by another level. I won't start any discussions about exactly how many spaces, but it's imperative that you do it consistently.</p>\n\n<p>Your for-loop is missing the initializer field. That is legal in C, but you should consider it a red flag. In the case of your outer for-loop, you should just initialize <code>counter</code> there. Then you have a proper for-loop! In C99 (which is what nearly everyone uses these days), you can even move the <code>int</code> declaration into the for-loop initializer.</p>\n\n<p>Next, tighten up your variable declarations. You can declare and define on the same line for better readability.</p>\n\n<pre><code>int main(void)\n{\n printf(\"\\n Table of Factorials\\n\\n\");\n printf(\" n ------------- Factorial\\n\");\n\n int factorial = 1;\n int n = 1;\n\n for (int counter = 1; counter <= 10; ++counter)\n {\n for ( ; n <= counter; ++n)\n {\n factorial = factorial * n;\n }\n\n printf(\"%2i --------------%7i\\n\", counter, factorial);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>I'm still not happy with that, though. Notice…</p>\n\n<ul>\n<li>Your table is supposed to display <em>n</em> and <em>n</em>!, but your <code>printf()</code> mentions <code>counter</code>.</li>\n<li>Your inner for-loop is still missing an initializer.</li>\n</ul>\n\n<p>It turns out that your <code>n</code> and <code>counter</code> variables are redundant. This simpler program produces the same output:</p>\n\n<pre><code>int main(void)\n{\n printf(\"\\n Table of Factorials\\n\\n\");\n printf(\" n ------------- Factorial\\n\");\n\n int factorial = 1;\n for (int n = 1; n <= 10; ++n)\n {\n factorial *= n;\n printf(\"%2i --------------%7i\\n\", n, factorial);\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:48:11.193",
"Id": "71287",
"Score": "0",
"body": "Indentation scheme \"discussions\" often devolve into religious/flame wars. Most dev tools include a code formatter - set it up to your preference, use it (dare I say?) religiously, and co-exist. :-) Share and enjoy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:09:28.410",
"Id": "41451",
"ParentId": "41447",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "41450",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:40:12.707",
"Id": "41447",
"Score": "13",
"Tags": [
"c"
],
"Title": "Factorial code in C"
}
|
41447
|
<blockquote>
<p>Given a staircase with N steps, you can go up with 1 or 2 steps each
time. Output all possible ways you go from bottom to top.</p>
</blockquote>
<p>I'm looking for code review, best practices, optimizations etc. Complexity: O(2<sup>n</sup>)</p>
<pre><code> public final class StairRoutes {
private StairRoutes() {}
/**
* Given a staircase with N steps, you can go up with 1 or 2 steps each time.
* Output all possible way you go from bottom to top.
*
* @param stepCount The number of steps in the stairway
* @return A list containing all possible routes.
*/
public static List<List<Integer>> stairClimbingRoutes(int stepCount) {
if (stepCount <= 0) throw new IllegalArgumentException("The step count: " + stepCount + " should be positive.");
/* a container containing all the possible routes */
final List<List<Integer>> stairRoutes = new ArrayList<List<Integer>>();
calcAllRoutes(stepCount, new LinkedList<Integer>(), stairRoutes);
return stairRoutes;
}
private static void calcAllRoutes(int stepCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
if (stepCount <= 1) {
populateRoute (stepCount, tempList, stairRoutes);
return;
}
processSteps(stepCount, 1, tempList, stairRoutes);
processSteps(stepCount, 2, tempList, stairRoutes);
}
private static void populateRoute (int numStairs, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
if (numStairs == 0) {
stairRoutes.add(new ArrayList<Integer>(tempList));
return;
}
if (numStairs == 1) {
tempList.add(1);
stairRoutes.add(new ArrayList<Integer>(tempList));
tempList.removeLast();
return;
}
}
private static void processSteps(int numStairs, int hopCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
tempList.add(hopCount);
calcAllRoutes(numStairs - hopCount, tempList, stairRoutes);
tempList.removeLast();
}
public static void main(String[] args) {
List<List<Integer>> stairRoutes = stairClimbingRoutes(5);
for (List<Integer> route : stairRoutes) {
for (Integer stair : route) {
System.out.print(stair + ":");
}
System.out.println();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Very nice code, well done. The first thing that came to mind was that it contains the <code>main()</code> function inside the same class as work is done. This is not bad in itself, but consider to keep it in it's own class. That way the program is better structured.</p>\n\n<hr>\n\n<p>It's not necessary, but consider to also document the private functions. This is especially useful if they do a complex operation or there's some complex interaction with each other.</p>\n\n<p>Don't forget to document the exceptions and limitations on the parameters as well.</p>\n\n<hr>\n\n<p>You're inconsistent with the naming of your variables, in one function it is called <code>stepCount</code> in the next <code>numStairs</code>. Was that an active decision to name it differently?</p>\n\n<hr>\n\n<pre><code>calcAllRoutes(stepCount, new LinkedList<Integer>(), stairRoutes);\n...\nprivate static void calcAllRoutes(int stepCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {\n</code></pre>\n\n<p>Why are you handing it a new list? That list seems only to be used inside <code>calcAllRoutes</code> and as far as I can see does not \"leak\" outside except for being added to <code>stairRoutes</code>. Shouldn't this be declared inside <code>calcAllRoutes</code> instead?</p>\n\n<p>Also consider if this function should return a <code>List</code> instead of getting one passed.</p>\n\n<hr>\n\n<pre><code> List<List<Integer>> stairRoutes ...\n</code></pre>\n\n<p>You could create an object which abstracts some of this away. I would at least wrap the inner <code>List</code> into something like <code>Route</code> which removes most of the functionality of <code>List</code> and instead gives it a nice and clean interface.</p>\n\n<p>Additionally this would allow you to override the <code>toString()</code> method and simplify the code in <code>main()</code>:</p>\n\n<pre><code>for (Route route : stairRoutes) {\n System.out.println(route.toString());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:37:31.327",
"Id": "41456",
"ParentId": "41448",
"Score": "4"
}
},
{
"body": "<p>In general, recursion is a complicated technique. It is often hard to understand the state of the system at any point in time because you have to add a dimension to your thinking.</p>\n\n<p>I consider it to be bad practice to have a recursive process where the recursion is unnecessarily split across multiple methods. In your case, you have a 2-method split in your recursion.</p>\n\n<pre><code>calcAllRoutes calls processSteps\n processSteps calls calcAllRoutes\n calcAllRoutes calls processSteps\n processSteps calls calcAllRoutes\n ...\n</code></pre>\n\n<p>Sometimes this is not avoidable... but, in this case, it is unnecessary. By splitting the logic in to two methods, it becomes harder to 'grok' the recursion.</p>\n\n<p>Additionally, your previous questions where you have had similar sorts of work, you have always 'defaulted' to using <code>java.util.*</code> collections instead of using simpler mechanisms like arrays of primitives. Arrays are much faster, and smaller, and tend to lead to better structured code. This is because the array is essentially a stack, and popping the stack is as easy as changing it's size.... you do not have to do as much manipulation of the stack head.</p>\n\n<p>Finally, this problem is one which should have a more general solution. You have hard-coded this solution to only work with 1-step and 2-step 'strides'. The problem is actually <strong><em>simpler</em></strong> if you make the stride options a general thing....</p>\n\n<p>Consider this alternative code... it:</p>\n\n<ol>\n<li>has a single recursive method.</li>\n<li>the recursive method has the standard layout:\n<ul>\n<li>check recursion-ending-conditions</li>\n<li>initiate further recursion</li>\n</ul></li>\n<li>it can use any number of positive-valued strides to get to the destination</li>\n<li>it is just a single recursive method.</li>\n<li>it uses an array of primitive ints to accumulate the current combination</li>\n</ol>\n\n<p>So, this code is, in my opinion, preferable:</p>\n\n<pre><code>public class Stairway {\n\n /**\n * Calculate all possible ways to ascend `steps` stairs, using the different-sized strides provided.\n * @param strides the different number of steps that can be taken.\n * @param steps the number of steps to ascend.\n * @return a list of all step combinations.\n */\n public static final List<int[]> stairClimbingRoutes(int[] strides, int steps) {\n\n // create the combination stack.\n // Longest possible combination is 1 step each time.\n int[] combination = new int[steps];\n int comblength = 0;\n\n List<int[]> results = new ArrayList<>();\n\n recurseRoute(steps, strides, combination, comblength, results);\n return results;\n }\n\n private static void recurseRoute(final int remaining, final int[] strides,\n final int[] combination, final int comblength, final List<int[]> results) {\n if (remaining < 0) {\n // this combination takes us too far.\n return;\n }\n if (remaining == 0) {\n // this combination is just right.\n results.add(Arrays.copyOf(combination, comblength));\n return;\n }\n // need to go further.\n for (int s : strides) {\n combination[comblength] = s;\n recurseRoute(remaining - s, strides, combination, comblength + 1, results);\n }\n\n }\n\n public static void main(String[] args) {\n\n for (int[] combination : stairClimbingRoutes(new int[] {1, 2}, 10)) {\n int check = 0;\n for (int s : combination) {\n check += s;\n }\n System.out.println(\"Actual \" + check + \" using \" + Arrays.toString(combination));\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:04:51.187",
"Id": "71336",
"Score": "0",
"body": "very very nice answer"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T13:26:39.093",
"Id": "41475",
"ParentId": "41448",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41475",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T05:46:38.807",
"Id": "41448",
"Score": "5",
"Tags": [
"java",
"combinatorics",
"fibonacci-sequence"
],
"Title": "Print routes on the stairway when only 1 or 2 steps are possible"
}
|
41448
|
<p>I have this WCF service providing search functionality - to be used by our client in his web application. There can be any number of search parameters and possible nesting of <code>AND</code>/<code>OR</code> operations.</p>
<p>Could you please have a look and share some ideas on if I can make it more client-friendly?</p>
<pre><code> <con:Search>
<con:clientID>xxx</con:clientID>
<con:propertyQueries>
<wil:PropertyQuery Id="0">
<wil:PropertyID>DocumentType</wil:PropertyID>
<wil:Value>Statement</wil:Value>
<wil:Operator>EQUALS</wil:Operator>
</wil:PropertyQuery>
<wil:PropertyQuery Id="1" AND="0">
<wil:PropertyID>BANK</wil:PropertyID>
<wil:Value>HSBC</wil:Value>
<wil:Operator>EQUALS</wil:Operator>
</wil:PropertyQuery>
<wil:PropertyQuery Id="2" OR="1">
<wil:PropertyID>BANK</wil:PropertyID>
<wil:Value>BARCLAYS</wil:Value>
<wil:Operator>EQUALS</wil:Operator>
</wil:PropertyQuery>
<wil:PropertyQuery Id="3" AND="0">
<wil:PropertyID>Date</wil:PropertyID>
<wil:Value Start="1">11/01/2014</wil:Value>
<wil:Value End="1">11/02/2014</wil:Value>
<wil:Operator>BETWEEN</wil:Operator>
</wil:PropertyQuery>
</con:propertyQueries>
</con:Search>
</code></pre>
<p>The values in <code>AND</code> and <code>OR</code> attribute indicates the <code>Id</code> of <code>PropertyQuery</code> to which the condition to be added. For example: </p>
<pre><code><wil:PropertyQuery Id="2" OR="1">
</code></pre>
<p>performs an <code>OR</code> operation between Property Queries with ID of 1, 2.</p>
<p>Any better ideas out there to improve the interface?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:14:45.767",
"Id": "71234",
"Score": "0",
"body": "Can you add information like is this a search page, and the user customises the AND/OR scenarios for all permutations? Is this application used for the internet or intranet? Do you provide a calling proxy so that users do not call this service directly, meaning you have some control over the data coming in?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T08:32:05.053",
"Id": "116694",
"Score": "0",
"body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_"
}
] |
[
{
"body": "<p>Without knowing its intended audience (Intranet / Internet), I'm assuming Intranet.</p>\n\n<p>In my opinion, you are giving a lot of flexibility to this service in one method call, which isn't immediately clear how a user would structure a call to this. The caller has to have knowledge of a \"propertyId\" which doesn't make too much sense on a glance. I hope your API documentation describes this well, and how the user would retrieve what these IDs are.</p>\n\n<p>So here is my assumption of the coded interface:</p>\n\n\n\n<pre><code>public interface ISearchService\n{\n List<object> Search(string clientId, IEnumerable<PropertyQuery> propertyQueries);\n}\n\n// Element\npublic class PropertyQuery\n{\n // Attribute\n public string PropertyID { get; set; }\n\n // Array\n public IEnumerable<Value> Values { get; set; }\n\n // Attribute\n public byte AND { get; set; }\n\n // Attribute\n public byte OR { get; set; }\n\n // Element\n public string Operator { get; set; }\n}\n\n// Element\npublic class Value\n{\n // Attribute\n public int Id { get; set; }\n\n // Attribute\n public byte Start { get; set; }\n\n // Attribute\n public byte End { get; set; }\n\n // Text\n public string Text { get; set; }\n}\n</code></pre>\n\n<p>To make this a little simpler, I would add a single class that takes all parameters and a class returning the results, following the Request/Response pattern. This means that the interface can change over time, and should not affect backwards compatibility.</p>\n\n<pre><code>public interface ISearchService\n{\n // Gets the search criteria for the screen\n SearchCriteriaResponse GetSearchCriterias(SearchCriteriaRequest request);\n\n // Searches by the search criteria\n SearchResponse SearchBy(SearchRequest searchCriteria);\n}\n\n// Base elements for a response\npublic abstract class ResponseBase\n{\n public bool Success { get; set; }\n public string Message { get ; set; }\n}\n\npublic class SearchCriteriaResponse : ResponseBase\n{\n public string[] DocumentTypes { get; set; }\n public string[] BankName { get; set; }\n}\n\npublic class SearchResponse : ResponseBase\n{\n public IEnumerable<SearchResult> Results { get; set; }\n}\n\npublic class SearchRequest\n{\n public string ClientId { get; set; }\n public string[] BankNamesToMatchExactly { get; set; }\n public string[] BankNamesToPartiallyExactly { get; set; }\n public string[] DocumentTypesToMatchExactly { get; set; }\n public string[] DocumentTypesToPartiallyExactly { get; set; }\n public DateTime? StartDate { get; set; }\n public DateTime? EndDate { get;set; }\n public bool CheckBetweenDates { get; set; }\n}\n</code></pre>\n\n<p>This interface is a more clean on its approach. Its slightly larger, but it makes the ORing and ANDing much more obvious. It also makes the code cleaner at the service side as each of these properties have well-named properties and should be easy to implement:</p>\n\n<pre><code>public List<SearchResponse> SearchBy(SearchRequest searchCriteria)\n{\n IQueryable dbQuery = DbContext.BankNames;\n\n foreach(var bankName in searchCriteria.BankNamesToMatchExactly)\n {\n dbQuery = dbQuery.Where(bn => bn.BankName == bankName);\n }\n\n foreach(var bankName in searchCriteria.BankNamesToMatchPartially)\n {\n dbQuery = dbQuery.Where(bn => bn.BankName.Contains(bankName);\n }\n\n // etc..\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T08:31:46.893",
"Id": "116693",
"Score": "0",
"body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:30:24.407",
"Id": "41458",
"ParentId": "41453",
"Score": "1"
}
},
{
"body": "<p>The way you're composing expressions seems very unintuitive to me. I think that you should take advantage of the fact that you're trying to express (part of) the SQL syntax tree in the XML tree. So, <code>AND</code> should be a separate node and it should have its child expressions as child nodes. Something like (if I misunderstood how your AND/ORs work, that only proves my point):</p>\n\n<pre><code><wil:combinedQuery operator=\"AND\">\n <wil:combinedQuery operator=\"AND\">\n <wil:PropertyQuery Id=\"0\">\n <wil:PropertyID>DocumentType</wil:PropertyID> \n <wil:Value>Statement</wil:Value>\n <wil:Operator>EQUALS</wil:Operator> \n </wil:PropertyQuery>\n <wil:PropertyQuery Id=\"3\">\n <wil:PropertyID>Date</wil:PropertyID> \n <wil:Value Start=\"1\">11/01/2014</wil:Value>\n <wil:Value End=\"1\">11/02/2014</wil:Value>\n <wil:Operator>BETWEEN</wil:Operator> \n </wil:PropertyQuery> \n </wil:combinedQuery>\n <wil:combinedQuery operator=\"OR\">\n <wil:PropertyQuery Id=\"1\" AND=\"0\">\n <wil:PropertyID>BANK</wil:PropertyID> \n <wil:Value>HSBC</wil:Value> \n <wil:Operator>EQUALS</wil:Operator> \n </wil:PropertyQuery> \n <wil:PropertyQuery Id=\"2\" OR=\"1\">\n <wil:PropertyID>BANK</wil:PropertyID> \n <wil:Value>BARCLAYS</wil:Value>\n <wil:Operator>EQUALS</wil:Operator> \n </wil:PropertyQuery> \n </wil:combinedQuery>\n</wil:combinedQuery>\n</code></pre>\n\n<hr>\n\n<p>Dates should be in the unambiguous <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow\">ISO 8601</a> format, not in the ambiguous and confusing (<code>mm/dd/yyyy</code>, or is it <code>dd/mm/yyyy</code>?) format.</p>\n\n<hr>\n\n<p>I don't like much the way you're representing <code>BETWEEN</code>. I think that <code>Start</code> and <code>End</code> should be in elements (or attributes) with those names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:55:41.623",
"Id": "71239",
"Score": "0",
"body": "Thanks a lot for your reply. I think apart from being unintuitive my solution was not foolproof because I was not always sure what the end-user actually wants-ending up myself being manipulating in wrong way - so your reply does help. Could you please give an example for how you will prefer to have values for Start and End date defined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:59:12.503",
"Id": "71240",
"Score": "0",
"body": "Apart from Between, I have other operators as: Equals, NotEquals, StartsWith, EndsWith etc...\nAll other operators apart from Between need one value. So, one option could be to have same node<Value> declared twice then my app will figure out lower and upper range after comparing the two values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:53:32.473",
"Id": "71250",
"Score": "0",
"body": "do you have any comments on how Start and End date should be defined? I do not want to add separate elements ValueFrom and ValueTo just for Between operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:22:28.457",
"Id": "71256",
"Score": "0",
"body": "@user1552869 I'm not sure what would be a good solution for that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:35:00.140",
"Id": "41459",
"ParentId": "41453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41459",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T08:11:58.827",
"Id": "41453",
"Score": "1",
"Tags": [
"c#",
".net",
"sql",
"wcf"
],
"Title": "Exposing WCF Service with dynamic search operation"
}
|
41453
|
<p>I am programming a rotator using Delphi, with two different angles: azimuth and elevation. Up to now I am testing, so I tried to move the rotator 1 by 1 degree in azimuth and elevation. The rotator starts in (0,0) and finishes in (30,30).</p>
<p>Another important thing is that I need to pause or have the program sleep before the rotator reads the next azimuth and elevation angle because of the operating of the device. If I don't do this, the application crashes. So I implemented this, having the program sleep for 0.64 seconds before increasing the angles.</p>
<p>Do you think that this program is properly implemented? In the future I will program a "Path Wizard" to set the path and the step, so I need to know if there is an easier way to do it. I don't know if using Sleep is the proper way to implement it.</p>
<pre><code>procedure TForm1.btn_testClick(Sender: TObject);
var p: TMD_ALL_ROTOR_ANGLES_PARAMS;
error_flag, step: Integer;
begin
p.calibration := 0;
p.angles[0] := -1;
p.angles[1] := -1;
p.startMotorIx := 0;
p.dev.group := 1;
p.dev.number := 1;
error_flag := 0;
step:= 1;
While (p.angles[0] < 30) And (p.angles[1] < 30) do
begin
p.angles[0] := p.angles[0] + step;
p.angles[1] := p.angles[1] + step;
case md_set_all_rotor_angles(@app_id, @p) of
MD_NO_ERROR: Sleep(640);
else
error_flag := error_flag + 1;
end;
end;
if error_flag > 0 then
ShowMessage('error');
end;
</code></pre>
<hr>
<p><a href="https://docs.google.com/file/d/0BxUf98iq0kLDQ1gwYmRXMVZWeWM/edit" rel="nofollow">This</a> is the documentation provided by the manufacturer. I modified the test program slightly to add the function that I described above. In the doc folder there is a file which describes the library, but I didn't find it really helpful.</p>
<hr>
<p>As you have seen, the documentation that I have is not really helpful, and the manufacturer doesn't answer my emails. Now I'd like to know when the initial angles are reached in order to start moving the rotator. I mean, if I am in position (5,5) and I want to move from (10,10) to (20,20), I move the rotator to (10,10) and I need to know when the rotator is in that position to start moving to (20,20). </p>
<p>I could calculate the time by subtracting the angles and using the time needed per angle. So I could use the Sleep command to have program slept during that time, and then start the trajectory. </p>
<p>I have another <a href="https://docs.google.com/file/d/0BxUf98iq0kLDQ1gwYmRXMVZWeWM/edit" rel="nofollow">file</a> in case it could be helpful, but it is not for me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:18:11.020",
"Id": "71255",
"Score": "2",
"body": "Depending on the implementation and operating system, `sleep` functions only provide a rough estimation. It can be that they sleep too long or too short, are you aware of that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:54:09.377",
"Id": "71290",
"Score": "0",
"body": "Can you put a link to the API, there should be a callback mechanism instead of sleeping an arbitrary amount of time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:34:54.767",
"Id": "71312",
"Score": "0",
"body": "I didn't find the file in which parameters like TMD_ALL_ROTOR_ANGLES_PARAMS are defined. The API manual doesn't describe the md_set_all_rotor_angles function. You haven't specified what kind of \"application crash\" you get. You might need to ask this question on a support forum or user group for the device."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:07:28.490",
"Id": "74855",
"Score": "0",
"body": "Please remember that you can always edit your post to add, remove, or change any information. Information additions do *not* belong as answers, so please refrain from doing so."
}
] |
[
{
"body": "<p>A minor comment re. the code style: I don't like <code>angle = -1; while (angle < 30) begin angle = angle + 1; use angle</code>. If angle were an unsigned integer then <code>angle = -1</code> wouldn't work properly. I'd prefer to see a <a href=\"http://www.tutorialspoint.com/pascal/pascal_for_do_loop.htm\">for loop</a> because that ensues that the variable is never set to anything except a correct value.</p>\n\n<p>Re.the algorithm, Sleep(640) is suspicious. You said, \"If I don't do this, the application crashes\" ... what does \"crashes\" mean?</p>\n\n<p>I would guess that:</p>\n\n<ul>\n<li>The number (640) might need to be bigger if you were moving through a bigger angle</li>\n<li>Your device API should give you a way to read the current location of the angle, or to tell you when the current move is finished. If there were an API like that then you could write code like <code>while not is_move_completed() Sleep(10)</code></li>\n<li>Or your device API might (should) even be able to notify you via a callback or 'event' when the move is finished.</li>\n<li>Or there might be a \"synchronous\" version of the API which doesn't complete (doesn't return from the md_set_all_rotor_angles procedure) until after it has finished moving and can safely move again.</li>\n</ul>\n\n<p>You might get a better answer if you post a link to the API for the device.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:02:42.267",
"Id": "41469",
"ParentId": "41457",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:21:09.317",
"Id": "41457",
"Score": "7",
"Tags": [
"delphi"
],
"Title": "Sleeping in Delphi"
}
|
41457
|
<p>I've written this minishell but I'm not sure I'm making a correct control of the errors. Could you give me some advice?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define LINE_LEN 50
#define MAX_PARTS 50
int main ()
{
char* token;
char str[LINE_LEN];
char* arr[MAX_PARTS];
int i,j;
bool go_on = true;
while (go_on == true){
printf("Write a line:('quit' to end) \n $:");
fgets(str, LINE_LEN, stdin);
if (str==NULL) {
goto errorfgets;
} else {
size_t l=strlen(str);
if(l && str[l-1]=='\n')
str[l-1]=0;
i=0;
/* split string into words*/
token = strtok(str, " \t\r\n");
while( token != NULL )
{
arr[i] = token;
i++;
token = strtok(NULL," \t\r\n");
}
fflush(stdin);
/* check if the first word is quit*/
if (strcmp(arr[0],"quit")==0)
{
printf("Goodbye\n");
go_on = false;
} else {
for (j=0; j < i; j++){
printf("pajaritos por aqui'%s'\n", arr[j]);
}
}
}
}
return 0;
errorfgets:
printf("fgets didn't work correctly");
return -1;
}
</code></pre>
|
[] |
[
{
"body": "<p>I think I haven't really understood the point of your program but I'll try to give you a few hints :</p>\n\n<ul>\n<li>The indentation is not really good. I am not sure if this is because of SE but I'd rather point it out just in case.</li>\n<li>You'll hear everything and its opposite about <code>goto</code>. It surely has drawbacks but it can be quite useful to handle errors and free the ressources that are not required anymore. However, in your case, there's no need for <code>goto</code> so it's probably better to <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">Keep It Simple</a> and just use <code>return</code>.</li>\n<li>I am not a big fan of a <code>go_on</code> variable if <code>break</code> can do the trick. Also, it makes <code>stdbool</code> pointless.</li>\n<li>Things will be easier to understand if you declare local variables in the smallest possible scope. Depending on the version of C you are using, you can even declare <code>j</code> in your <code>for</code> statement : <code>for (int j=0; j < i; j++)</code>.</li>\n<li>Because of <code>return</code>/<code>break</code>, you can now remove levels of indentation (again, this is purely personal preference).</li>\n<li>You shouldn't repeat <code>\"quit\"</code> in multiple places. It will make it hard to change if it has to change in the future.</li>\n<li>There is a risk that <code>arr[i] = token;</code> goes to far if you ever change a constant without changing the other. Let's make sure it does not go too far.</li>\n</ul>\n\n<p>At the end, here what the code would be like :</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define LINE_LEN 50\n#define MAX_PARTS 50\n\nstatic const char quit[] = \"quit\";\n\nint main ()\n{\n char str[LINE_LEN];\n char* arr[MAX_PARTS];\n\n for (;;) {\n printf(\"Write a line:('%s' to end) \\n $:\", quit);\n fgets(str, LINE_LEN, stdin);\n\n if (str==NULL) {\n printf(\"fgets didn't work correctly\");\n return -1;\n }\n size_t l = strlen(str);\n if (l && str[l-1]=='\\n')\n str[l-1]=0;\n\n /* split string into words*/\n int i;\n char* token = strtok(str, \" \\t\\r\\n\");\n for (i=0; i<MAX_PARTS && token != NULL; i++)\n {\n arr[i] = token;\n token = strtok(NULL,\" \\t\\r\\n\");\n }\n\n fflush(stdin);\n\n /* check if the first word is quit*/\n if (strcmp(arr[0], quit)==0)\n {\n printf(\"Goodbye\\n\");\n break;\n }\n for (int j=0; j < i; j++){\n printf(\"pajaritos por aqui '%s'\\n\", arr[j]);\n }\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:57:28.270",
"Id": "41468",
"ParentId": "41460",
"Score": "4"
}
},
{
"body": "<p>I would suggest following:</p>\n\n<ol>\n<li>A separate error handler function. Don't exit from shell until user wants to. (most of shells do this)</li>\n<li><code>fgets()</code> is dangerous function (from compiler warnings). you could look into some system level functions to replicate <code>getch()</code> which gets a character and doesn't prints on screen and doesn't require a <code>return</code> for getting the character. It just get the character when you press the key. This way you can have a long input.(you have to print the characters manually if you use <code>getch()</code>)</li>\n<li>Break down the loop into functions.</li>\n<li>If you go for <code>getch()</code> you could even have shortcuts also.(not necessary as its a mini shell).</li>\n<li><code>getch()</code> can be helpful in getting the passwords as well.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:33:16.220",
"Id": "42730",
"ParentId": "41460",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41468",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:36:22.487",
"Id": "41460",
"Score": "4",
"Tags": [
"c",
"error-handling"
],
"Title": "Making a minishell in C. How to improve error control with feoh and ferror?"
}
|
41460
|
<p>The input pointer <code>*data</code> contains the data that needs to be split into different arrays and put in <code>yuvInput</code>. Each pixel is 32 bytes 4 * 8. Note the (j*4) to break it up per pixel segment. The 4th byte is the alpha channel which gets skipped (the reason there is no idx+3).</p>
<p>This method needs optimization. If anyone is willing to help, please do.</p>
<pre><code>void SplitYUVPlanes(int width, int height, unsigned char *data, int size, unsigned char *yuvInput[3])
{
// live input *data is YUV444 Packed
// Conversion from 444 Packed -> 444 Planar
int index = 0;
int srcStride = size;
// need to flip image from bottom-up to top-down
int revheight = height - 1;
unsigned char* pLuma = yuvInput[0];
unsigned char* pChromaU = yuvInput[1];
unsigned char* pChromaV = yuvInput[2];
for (int i = 0; i < height; ++i)
{
// read bottom line first
int line = (revheight - i) * srcStride;
for (int j = 0; j < width; ++j)
{
int idx = line + (j * 4);
pLuma[index] = data[idx + 2]; //Y
pChromaV[index] = data[idx + 1]; //V
pChromaU[index] = data[idx + 0]; //U
index++;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:10:59.433",
"Id": "71242",
"Score": "0",
"body": "Your issue is locality of reference. you are very limited. one thing you can do is read as much data at once, and then write that. for instance, you can read 8 bytes in a 64 bit integer first, and then write once in a 64 bit integer. To read more than 64 bit you will have to be architecture dependent."
}
] |
[
{
"body": "<p>Your multiplication expressions aren't ideal; instead (which might be faster) you could add 4 and subtract srcStride from the previous value at the top of each loop.</p>\n\n<p>Apart from that (and this is just a guess) I guess some other things might in theory make this faster.</p>\n\n<ol>\n<li>Have three loops: write to Luma in the 1st loop, then write to ChromaV in the 2nd loop, and write to ChromaU in the 3rd loop.</li>\n<li>Calibrate the length of (number of bytes moved in) each loop, so that the chunk of input <code>data</code> stays in cache for each of the three loops</li>\n<li>Use some kind of read-ahead, to ensure that the byte is read before it needs to be written, for example:\n<ul>\n<li>Read 1st byte</li>\n<li>Read 2nd byte</li>\n<li>Read 3rd byte</li>\n<li>Read 4th byte</li>\n<li>Write 1st byte</li>\n<li>Read 5th byte</li>\n<li>Write 2nd byte</li>\n<li>etc.</li>\n</ul></li>\n<li>Read 4 or 8 bytes at a time, for example into a struct which contains 4 or 8 byte-fields and is a union with an int32 or int64 field.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:50:49.000",
"Id": "41481",
"ParentId": "41461",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41481",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:39:23.007",
"Id": "41461",
"Score": "6",
"Tags": [
"c++",
"optimization",
"array",
"image"
],
"Title": "Optimize YUV channel splitting function"
}
|
41461
|
<p>I'd like to get input on my approach of continuously receiving messages from an Azure Service Bus queue using the async part of the library.
My main concern being whether its "safe" to use Task.Factory.StartNew to process the incoming messages and then continue to call the Action's to continue receiving new messages.</p>
<p>The processor class is started like this:</p>
<pre><code>public void Start()
{
ThrowIfDisposed();
lock (_lockObject)
{
Trace.WriteLine(string.Format("Started '{0}' allocation.", _projectSettings.Name));
_cancellationSource = new CancellationTokenSource();
Task.Factory.StartNew(ReceiveAllocationMessages, _cancellationSource.Token);
}
}
</code></pre>
<p>And then the actual continuous receival of messages from the (Azure Service Bus) QueueClient (from the Microsoft.ServiceBus.Messaging namespace):</p>
<pre><code>private void ReceiveMessage()
{
Task.Run(async () =>
{
//Receive a new message async within 1 minute
return await _queueClient.ReceiveAsync(TimeSpan.FromMinutes(1));
})
.ContinueWith(t =>
{
if (t.Result != null)
{
//The result is not null so we process the Brokered Message
Task.Factory.StartNew(() =>
{
ProcessMessage(t.Result)
ReceiveNextMessage();
}, _cancellationSource.Token);
}
else
{
// Continue receiving and processing
// new messages until told to stop.
ReceiveNextMessage();
}
});
}
private void ReceiveNextMessage()
{
if (_cancellationSource.IsCancellationRequested == false)
{
//Continue to receive new messages every 1 minute
Task.Delay(TimeSpan.FromMinutes(1))
.ContinueWith(t => ReceiveMessage());
}
}
</code></pre>
<p>When the process is stopped or disposed the Stop method is called in order to cancel the CancellationTokenSource as shown here:</p>
<pre><code>public void Stop()
{
lock (_lockObject)
{
using (_cancellationSource)
{
if (_cancellationSource != null)
{
_cancellationSource.Cancel();
_cancellationSource = null;
}
}
Trace.WriteLine(string.Format("Stopped '{0}' allocation.", _projectSettings.Name));
}
}
</code></pre>
<p>Does this seem like a reasonable way to go about implementing continuous receival of messages in an async fashion?</p>
<p><strong>UPDATE</strong>: I posted a gist with the code from above polished and put into a class. Hopefully improves readability <a href="https://gist.github.com/sitereactor/8953583" rel="nofollow">Gist of the queue Processor class</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:37:03.510",
"Id": "72035",
"Score": "1",
"body": "Indent your code properly, please. ._."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:37:09.397",
"Id": "72036",
"Score": "0",
"body": "How is this continuous? As far as I can see, if you receive one message, you process it and stop, you don't try to receive another message."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T09:35:52.753",
"Id": "72245",
"Score": "0",
"body": "@kleinfreund I updated the code, so hopefully its a bit better now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T09:37:11.353",
"Id": "72246",
"Score": "0",
"body": "@svick Thanks for pointing that out. I had left out a ReceiveNextMessage call within the ContinueWith. Should be updated in the code sample."
}
] |
[
{
"body": "<p>First, some notes:</p>\n<ol>\n<li><p>You shouldn't be using <code>Task.Factory.StartNew()</code> unless you have to, <a href=\"http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html\" rel=\"nofollow noreferrer\"><code>Task.Run()</code> is better</a>.</p>\n</li>\n<li><p>I think you're using <code>Task.Run()</code> (and <code>Task.Factory.StartNew()</code>) and <code>ContinueWith()</code> too much. Only use <code>Task.Run()</code> when you actually need to run the code on another thread. And <code>ContinueWith()</code> is almost always better written using <code>await</code>.</p>\n<p>If you're using it to support cancellation, you can just use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.throwifcancellationrequested\" rel=\"nofollow noreferrer\"><code>ThrowIfCancellationRequested()</code></a> instead.</p>\n</li>\n<li><p>Don't use <code>== false</code>, <code>!</code> is much clearer.</p>\n</li>\n<li><p>Your your code, the processing can be <code>Start</code>ed two times. You should probably guard against that.</p>\n</li>\n<li><p>Your <code>Start()</code> and <code>Stop()</code> methods seems to be written with support for restarting in mind. It might be simpler to forbid that.</p>\n</li>\n</ol>\n<p>Now, about the structure of your code: I think a much clearer way to write your code would be to use a loop, instead of recursion. That way, your top level method can be made very clear:</p>\n<pre><code>while (!_cancellationSource.IsCancellationRequested)\n{\n await ReceiveMessageAsync();\n await Task.Delay(TimeSpan.FromMinutes(1));\n}\n</code></pre>\n<p>The <code>ReceiveMessageAsync()</code> method could then look like this, which is a lot shorter and much more readable:</p>\n<pre><code>private async Task ReceiveMessageAsync()\n{\n var message = await _queueClient.ReceiveAsync(TimeSpan.FromMinutes(1));\n\n if (message != null)\n {\n _cancellationSource.ThrowIfCancellationRequested();\n ProcessMessage(message);\n }\n}\n</code></pre>\n<p>Note that this version behaves differently than yours with regards to exceptions. In your code, if an exception happens, it's either silently ignored (if it's in <code>ReceiveAsync()</code>) or it just silently stops receiving (if it's in <code>ProcessMessage()</code>). Both are very bad and make errors hard to debug. With my code, any exception stops receiving and is reported to the top-level <code>Task</code>.</p>\n<p>You should then devise some way of reporting any exceptions on that <code>Task</code>.</p>\n<p>A simple solution would be to store the <code>Task</code> in <code>Start()</code> and then rethrow any exceptions in <code>Stop()</code>. A cleaner solution might be to change <code>void Start()</code> into something like <code>Task RunAsync()</code> and report exceptions using the returned <code>Task</code>.</p>\n<p>You could also consider not stopping if some specific exception happens (e.g the server is temporarily unavailable). But that should happen only for some specific exceptions and those exceptions should be logged anyway, to help with debugging.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:44:05.437",
"Id": "72491",
"Score": "0",
"body": "Thanks for taking the time to write this review. Appreciate the addition of the link to [Task.Factory.StartNew vs. Task.Run](http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html).\nI have started refactoring the code based on some feedback, which I got through the [gist on github](https://gist.github.com/agehrke/9046525), which is very much in-line with what you are suggesting.\nI'll post back with a link to the gist when I've done a bit more testing with this alternative approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-12T17:02:45.090",
"Id": "270219",
"Score": "1",
"body": "#3 is debatable. \" if (!IsAvailable)\" vs \" if (IsAvailable == false\" - its hard to see at times and has led to more than one bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-14T18:52:21.923",
"Id": "342519",
"Score": "0",
"body": "Agreed @StingyJack I hope none of my teammates see number #3! I think == false is a much more readable. I'd throw in that you should name your variables in a way that there isn't too much == false or ! involved, try to stay in the affirmative sense"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:41:30.253",
"Id": "41965",
"ParentId": "41462",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T09:51:33.350",
"Id": "41462",
"Score": "12",
"Tags": [
"c#",
"asynchronous",
"queue"
],
"Title": "Continuously receive messages async from Azure Service Bus Queues"
}
|
41462
|
<p>A friend of mine has a popular open source JavaScript library which is quite well used in the community. He is now going through a process of refactoring and applying best practices and conventions and is wanting to upper case all constructor functions. So in the past where he may have defined a <code>chart</code> object, he now wants it to be called <code>Chart</code> to stick with convention.</p>
<p>Because the library is well used, he would rather warn devs when they use the old function names and eventually deprecate them.</p>
<p>I've recommended using a helper function :</p>
<pre><code>var ObsoleteWithReplacement = function(replacementFunction, oldFnName, newFnName) {
var wrapper = function() {
console.warn("WARNING! Obsolete function called. Function '" + oldFnName + "' has been deprecated, please use the new '" + newFnName + "' function instead!");
replacementFunction.apply(this, arguments);
}
wrapper.prototype = replacementFunction.prototype;
return wrapper;
}
</code></pre>
<p>Which could be called as follows : <a href="http://jsfiddle.net/rLNep/1/">http://jsfiddle.net/rLNep/1/</a></p>
<p>Is this a good way to go about it? Can you recommend a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:56:28.707",
"Id": "71316",
"Score": "1",
"body": "You probably want to have wrapper return the result of `replacementFunction` to ensure its compatible with closure classes and prototypical ones. If this is only for prototypical class constructors you may want to choose a better name"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:27:13.600",
"Id": "71339",
"Score": "0",
"body": "There's also the option of not doing anything special and just releasing a new version. There's nothing to keep users of the library from just continuing to use the current version if they don't want to upgrade. And if they do want to upgrade, give them a proper changelog and maybe an upgrade guide."
}
] |
[
{
"body": "<p>From looking at your fiddle, the first thing I would do is make sure that your function is not anonymous:</p>\n\n<pre><code>// new function implementation\nvar Chart = function Chart(name, data) { //See what I did there?\n this.name = name;\n this.data = data;\n\n console.log(\"Chart > constructor\");\n}\n</code></pre>\n\n<p>Then, to keep it KISS, I would </p>\n\n<pre><code>// obsolete helper function\nvar ObsoleteWithReplacement = function( f ) {\n var wrapper = function() {\n console.warn(\"This function is now called \" + f.name );\n f.apply(this, arguments);\n }\n wrapper.prototype = f.prototype;\n return wrapper;\n}\n</code></pre>\n\n<p>Because the function is no longer anonymous, you can now use <code>f.name</code>, you no longer have to provide it. The drawback is that the new old function name is not logged, I think any JS developer could figure that one out.</p>\n\n<p>Then you can do this:</p>\n\n<pre><code>// old deprecated function\nvar chart = ObsoleteWithReplacement(Chart);\n</code></pre>\n\n<p>The name <code>ObsoleteWithReplacement</code> is unfortunate, I would use simply <code>Obsolete</code>. Also I think <code>function Obsolete(){..}</code> makes more sense than <code>var Obsolete = function Obsolete(){..}</code>, <code>var Obsolete = function (){..}</code> should be avoided since it creates an anonymous function.</p>\n\n<p>I forked this to <a href=\"http://jsfiddle.net/konijn_gmail_com/8a5Ax/\">http://jsfiddle.net/konijn_gmail_com/8a5Ax/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:03:06.727",
"Id": "71306",
"Score": "0",
"body": "Thanks! Valid points on the anonymous fn's and being able to access names programmatically. However clumsy passing in the old and new function name args is, it allows for the fully-qualified-name of the fn to be put in the message. Handy if we want to include namespace. Of course whether the dev needs a more meaningful message or not is debatable. If they don't, I agree your method is cleaner but will require named functions across the project. (Not a bad thing for debugging call stack!). As for fn naming I'm really not going to get into that, we all have preferences. great help :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:09:33.787",
"Id": "41483",
"ParentId": "41467",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41483",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T10:53:09.447",
"Id": "41467",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Creating a Deprecated/Obsolete behavior for methods in a JavaScript library"
}
|
41467
|
<p>I have implemented code for parsing annotation:</p>
<pre><code>/**
* @Route(path="sample \n test",code,value,boolean,test)
* @access(code=false)
* @sample as asdad asd
* asd
*/
function sample()
{
}
$refelection = new ReflectionFunction("sample");
$pattern = "/@(\w+?)(.*?)/U";
preg_match_all($pattern, $refelection->getDocComment(), $matches);
$matches = array_combine($matches[1], $matches[2]);
foreach ($matches as $key => $value)
{
$params = array();
$token = token_get_all("<?php " . trim($value) . "?>");
if (substr($value, 0, 1) !== "(" || substr($value, -2, -1) !== ")")
{
continue;
}
echo $key;
$limit = count($token) - 2;
for ($i = 2; $i < $limit; $i++)
{
if (array_key_exists($i + 1, $token) && $token[$i + 1] == "=")
{
if (!is_array($token[$i + 2]))
{
die("invalid");
}
$params[$token[$i][1]] = $token[$i + 2][1];
$i+=3;
}
else
{
if (!is_array($token[$i + 2]))
{
die("invalid");
}
$params[$token[$i][1]] = NULL;
$i+=1;
}
if ($token[$i] !== "," && $token[$i] !== ")")
{
die("invalid");
}
}
var_dump($params);
}
</code></pre>
<p>Please tell me if there are any cons, limitation or bug in this code or any alternatives.</p>
<p>Last annotation in doc comment is ignore, as you can see.</p>
|
[] |
[
{
"body": "<p>Focusing on the regex side only....</p>\n\n<p>The use of the <a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow\">UNGREEDY modifier</a> on your pattern, and then internally reversing that, is odd.</p>\n\n<blockquote>\n<pre><code>$pattern = \"/@(\\w+?)(.*?)/U\";\n</code></pre>\n</blockquote>\n\n<p>This can be written simpler, as:</p>\n\n<pre><code>$pattern = \"/@(\\w+)(.*)/\";\n</code></pre>\n\n<p>The above will work because regex will favour matching the full <code>\\w+</code> before it starts on the <code>.*</code>. If you want to make it explicit (and I would, for the record), you can force a zero-width word-break anchor (<code>\\b</code>) in there, and write the pattern as:</p>\n\n<pre><code>$pattern = \"/@(\\w+)\\b(.*)/\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T06:11:30.543",
"Id": "71390",
"Score": "0",
"body": "ok i have updated my code accordingly and thanks for correction. your answer appreciable but i still need review on actual parsing which is happening in `foreach` loop"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:08:14.593",
"Id": "41482",
"ParentId": "41470",
"Score": "4"
}
},
{
"body": "<p>Adding a second answer to address the parsing and PHP side of things.</p>\n\n<p>You have some inconsistencies in the parsing of the <code>$value</code>. You have two specific places where you expect contradictory values. First, you have:</p>\n\n<blockquote>\n<pre><code>$token = token_get_all(\"<?php \" . trim($value) . \"?>\");\n</code></pre>\n</blockquote>\n\n<p>where you <code>trim(...)</code> the value, which implies you expect white-space on it.</p>\n\n<p>The very next line you check to make sure the first and last characters are actually parenthesis <code>(</code> and <code>)</code>. You should trim the value before that check because trailing whitespace is surprisingly common, and would be legal. I cannot find a good reference on Annotation syntax, but it appears that there cannot be a space between the annotation name, and the opening parenthesis.... is this true?</p>\n\n<p>Still, the correct solution for the whitespace problem is to solve it in the regex. This can also solve the parenthesis checking poblem. Consider the regex:</p>\n\n<pre><code>$pattern = \"/@(\\w+)\\(\\s*([^\\(]*?)\\s*\\)/\";\n</code></pre>\n\n<p>I have <a href=\"http://regex101.com/r/qA9vU6\" rel=\"nofollow\">tested this out on regex101</a>, and it looks good, but I have had to add the <code>g</code> modifier to the expression. I am not sure whether this is required on the match statement.</p>\n\n<p>By using the pattern above you will:</p>\n\n<ul>\n<li>not need to trim the <code>$value</code></li>\n<li>you will only match annotations with parenthesis, so no need to check</li>\n<li>the value will be 'trimmed' as well.</li>\n</ul>\n\n<p>This will mean you will have to adjust the parsing part slightly so that it does not expect the \"(\" and \")\" tokens....</p>\n\n<p>The rest of the parsing does look fine (to my untrained eye).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:09:22.640",
"Id": "71552",
"Score": "0",
"body": "Try this `@Route(path=\"sample \\n )test\",code,value,boolean,test)` by updating your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:14:06.853",
"Id": "71553",
"Score": "0",
"body": "@user2907171 - you are right, but you also have bigger problems then, like the fact that the `()` parenthesis are optional, not required, for Annotations.. e.g. have you tried `@route path=\"sample\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:58:24.210",
"Id": "71576",
"Score": "0",
"body": "this is not valid annotation. have you seen any function without brackets?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:57:15.963",
"Id": "41550",
"ParentId": "41470",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:28:10.243",
"Id": "41470",
"Score": "3",
"Tags": [
"php",
"parsing",
"regex"
],
"Title": "Parsing annotation"
}
|
41470
|
<p>I've written this as part of my contact form on my website. It checks to see if required inputs are empty, if so adds a red warning color and text. It also checks the email field for a properly formatted email.</p>
<p>This code works 100%, but somehow I feel like I'm repeating myself and I am not sure how to eliminate the repetition. Most importantly I am not sure how to reference nested "this". What I mean is if my input is jQuery (this) and then I use traversing to get to its parent div.</p>
<p>How can I reference that DIV over and over again, without having to traverse over and over again?</p>
<pre><code>//Check current language and prepare warning text
var current_language = jQuery('html').attr('lang');
if (current_language == 'en-CA') {
var empty_field_message = 'This field is required.';
var invalid_email = 'This email address seems invalid.';
}
else {
var empty_field_message = 'Ce champ est requis.';
var invalid_email = 'L\'adresse email semble invalide.';
}
//Email validation script
function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) ) {
return false;
} else {
return true;
}
}
//Fire on all input elements of the form
jQuery( ':input' ).on( 'focus', function() {
//Add a highlight color to div containing the currently active form element
jQuery(this).closest( '.frm-holder' ).addClass( 'frm-field-focus' );
}).on('blur', function() {
//Remove the highlight once user moves off the input
jQuery(this).closest( '.frm-holder' ).removeClass( 'frm-field-focus' );
//Check if field was required
if ( jQuery(this).hasClass('wpcf7-validates-as-required') ) {
//Check if it was empty
if ( !jQuery.trim(jQuery(this).val()) ) {
//Add a red background to the wrapping DIV
jQuery(this).closest( '.frm-holder' ).addClass( 'frm-field-required' );
//Remove any other warning spans and put in empty field warning
jQuery(this).siblings( 'span.wpcf7-not-valid-tip' ).remove();
jQuery(this).after('<span class="wpcf7-not-valid-tip" role="alert">' + empty_field_message + '</span>');
}
//If it wasn't empty
else {
//Check if it's an email field
if ( jQuery(this).attr('type') == 'email') {
//If email is invalid
if( !validateEmail( jQuery(this).val() ) ) {
//Remove any other warning spans
jQuery(this).siblings( 'span.wpcf7-not-valid-tip' ).remove();
//Check if wrapping DIV does not have red background
if ( !jQuery(this).closest( '.frm-holder' ).hasClass( 'frm-field-required' ) ) {
//Add wrapping DIV red background
jQuery(this).closest( '.frm-holder' ).addClass( 'frm-field-required' );
}
//Add new warning span
jQuery(this).after('<span class="wpcf7-not-valid-tip" role="alert">' + invalid_email + '</span>');
}
//If email is valid
else {
//Remove wrapping DIV red background
jQuery(this).closest( '.frm-holder' ).removeClass( 'frm-field-required' );
//Remove warning span
jQuery(this).siblings( 'span.wpcf7-not-valid-tip' ).remove();
}
}
//If not email field
else {
//Check if wrapping DIV has red background
if ( jQuery(this).closest( '.frm-holder' ).hasClass( 'frm-field-required' ) ) {
//Remove wrapping DIV red background
jQuery(this).closest( '.frm-holder' ).removeClass( 'frm-field-required' );
//Check if warning span exists
if ( jQuery(this).siblings( jQuery('span.wpcf7-not-valid-tip').length ) ) {
//Remove warning span
jQuery(this).siblings( 'span.wpcf7-not-valid-tip' ).remove();
}
}
}
}
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:04:03.507",
"Id": "71275",
"Score": "0",
"body": "You should probably have a look at http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:26:40.887",
"Id": "71283",
"Score": "0",
"body": "@Josay thank you for that link. After reading through it, there still doesn't seem to be 100% agreement on what's best to implemennt. Seems like every solution has some upside and downsides. I decided to change my code to this, what do you think?"
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<p>I would do the languages like this:</p>\n\n<pre><code>var translations = {\n 'en-CA' : {\n emptyFieldMessage: 'This field is required.',\n invalidEmail : 'This email address seems invalid.'\n },\n 'fr-CA' : {\n emptyFieldMessage: 'Ce champ est requis.',\n invalidEmail : 'L\\'adresse email semble invalide.' \n }\n}\n\nvar messages = translations[ jQuery('html').attr('lang') ];\n</code></pre>\n\n<p>Then you can access <code>emptyFieldMessage</code> as <code>messages.emptyFieldMessage</code></p>\n\n<p>This:</p>\n\n<pre><code>if( !emailReg.test( $email ) ) {\n return false;\n} else {\n return true;\n}\n</code></pre>\n\n<p>can be this because you are evaluating a boolean to return a boolean:</p>\n\n<pre><code>return emailReg.test( $email );\n</code></pre>\n\n<p>The <code>//If not email field</code> <code>else</code> block can be reduced to:</p>\n\n<pre><code>//If not email field\nelse {\n //Remove wrapping DIV red background\n jQuery(this).closest( '.frm-holder' ).removeClass( 'frm-field-required' );\n //Remove warning span\n jQuery(this).siblings( 'span.wpcf7-not-valid-tip' ).remove();\n}\n</code></pre>\n\n<p>if you are going to remove a class, dont check for it's existence, just call <code>removeClass</code>, it will silently do nothing if the class was not there in the first place. The same goes for <code>remove()</code>, just call it, dont check prior.</p>\n\n<p>This is most likely <a href=\"https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address\">wrong</a> as per Josay:</p>\n\n<pre><code>var emailReg = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/;\n</code></pre>\n\n<p>Very important, create a <code>var $this = jQuery(this);</code> instead of calling over and over again <code>jQuery(this)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:47:02.733",
"Id": "71286",
"Score": "0",
"body": "Thank you for your suggestions, I've updated my code. I wasn't aware that removeClass and remove won't do any damage if just fired. That cleaned up a lot of the code. What about addClass, I have one more check in my code to make sure it doesn't keep adding the same class over and over again. Is that necessary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:48:37.697",
"Id": "71288",
"Score": "0",
"body": "@Amir Not needed indeed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:22:51.567",
"Id": "41477",
"ParentId": "41476",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41477",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T13:40:56.290",
"Id": "41476",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"validation",
"email"
],
"Title": "Checking input and email field"
}
|
41476
|
<p>I'd like this reviewed.</p>
<p><a href="http://jsbin.com/nehut/1/edit?html,css,output" rel="nofollow">Demo</a></p>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><body>
<!-- Introduction to the text shadow property -->
<div class="container one">
<h1>The Dark Knight</h1>
</div>
<!-- Show the inset shadow 'hack' -->
<div class="container two">
<h1>The Dark Knight Rises</h1>
</div>
</body>
</code></pre>
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code> body{
background: #424243;
margin: 0;
}
h1{
font-size: 5em;
font-family: Georgia;
}
.container{
padding: 20px 50px;
}
.one h1{
color: #fff;
text-shadow: 4px 3px #222;
}
.two{
background: #ccc;
}
.two h1{
background-color: #222;
color: transparent;
text-shadow: 0px 2px 2px rgba(255,255,255,0.6);
-webkit-background-clip: text;
-moz-background-clip: text;
background-clip: text;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:52:24.443",
"Id": "71289",
"Score": "3",
"body": "It would really help to have a description of what you have there, what its purpose is, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:59:47.267",
"Id": "71298",
"Score": "0",
"body": "@user1668270 What makes you think the use of text-shadow is a hack? Also, it is very helpful if you provide a demo (see: http://jsfiddle.net/, http://codepen.io/, etc.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:09:59.233",
"Id": "71301",
"Score": "0",
"body": "I've added a demo now. In light of the changes to the CSS it no longer seems like a hack. It did seem like one when I was clipping the h1 container background to fit the h1 text."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:11:47.013",
"Id": "71303",
"Score": "1",
"body": "@user1668270 This isn't a hack, too. This is the purpose of `background-clip`. ;) Please add a description to your question, because our ways of reviewing are limited without one."
}
] |
[
{
"body": "<ol>\n<li><p>You're using prefixed versions for the <code>background-clip</code> property. There is only a need for the <code>-webkit-</code> prefix here, so you have support for Android 2.x. You can omitt <code>-moz-</code>, unless you need to support Firefox 3.6.</p>\n\n<p><a href=\"http://caniuse.com/background-img-opts\" rel=\"nofollow\">Can I use CSS3 Background-image options?</a></p></li>\n<li><p>It looks like you're trying to illustrate the styling of text with <code>text-shadow</code>. You probably want to use example text with a higher <code>font-size</code>. Instead of heading elements, you should be using <code>span</code>'s:</p>\n\n<pre><code><span class=\"demo-snippet\">The Dark Knight</span>\n</code></pre>\n\n<p><code>h1</code>–<code>h6</code> are for headings and subheadings. In your case a heading would be something like <em>Usage of the text-shadow property</em>.</p></li>\n<li><p>Use <code>0</code> instead of <code>0px</code>. You don't need to add the unit for zero values.</p></li>\n</ol>\n\n<p>Other than that, I don't know what else one should review. I'll update my question, if you add some more information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:57:08.167",
"Id": "71296",
"Score": "0",
"body": "Thanks Kleinfreund. I've made some changes based on what you've said. I'm using the above for training material to demonstrate how to use the text-shadow property effectively."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:58:27.497",
"Id": "71297",
"Score": "0",
"body": "@kleinfreund There's not enough content here to say whether or not the use of the headline element is appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:59:59.573",
"Id": "71299",
"Score": "1",
"body": "@user1668270 I've rolled back your edit, because it would invalidate my answer. If you make some changes based on a review, you can update your question with new stuff, but only if you keep the old code as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T16:02:59.303",
"Id": "71300",
"Score": "0",
"body": "@cimmanon I didn't say it's necessarily inappropriate in his case, but when he is using it for demonstration purposes (e.g. illustrating the effect of `text-shadow` on an element with a higher font-size)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:00:15.383",
"Id": "41479",
"ParentId": "41478",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T14:48:46.193",
"Id": "41478",
"Score": "5",
"Tags": [
"html",
"css"
],
"Title": "Inset Text Shadow"
}
|
41478
|
<p>I solved <a href="http://www.sebnozzi.com/244/beginner-words-and-lines/">this problem</a> in Ruby:</p>
<blockquote>
<p>Write an utility that takes 3 command-line parameters P1, P2 and P3.
P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take
the values:</p>
<ul>
<li>“lines”</li>
<li>“words”</li>
<li>“find”</li>
</ul>
<p>Only P2 is “find”, then P3 is relevant/needed, otherwise it is not.</p>
<p>So, the utility does the following:</p>
<ul>
<li>If P2 is “rows” it says how many lines it has </li>
<li>If P2 is “words” it says how many words it has (the complete file) </li>
<li>If P2 is “find” it prints out the lines where P3 is present</li>
</ul>
</blockquote>
<p>My solution looks like this:</p>
<pre><code>#!/usr/bin/env ruby
def print_usage
puts "Usage: #{$0} <file> words|lines"
puts " #{$0} <file> find <what-to-find>"
end
class LineCounter
# Initialize instance variables
def initialize
@line_count = 0
end
def process(line)
@line_count += 1
end
def print_result
puts "#{@line_count} lines"
end
end
class WordCounter
# Initialize instance variables
def initialize
@word_count = 0
end
def process(line)
@word_count += line.scan(/\w+/).size
end
def print_result
puts "#{@word_count} words"
end
end
class WordMatcher
# Initialize instance variables, using constructor parameter
def initialize(word_to_find)
@matches = []
@word_to_find = word_to_find
end
def process(line)
if line.scan(/#{@word_to_find}/).size > 0
@matches << line
end
end
def print_result
@matches.each { |line|
puts line
}
end
end
# Main program
if __FILE__ == $PROGRAM_NAME
processor = nil
# Try to find a line-processor
if ARGV.length == 2
if ARGV[1] == "lines"
processor = LineCounter.new
elsif ARGV[1] == "words"
processor = WordCounter.new
end
elsif ARGV.length == 3 && ARGV[1] == "find"
word_to_find = ARGV[2]
processor = WordMatcher.new(word_to_find)
end
if not processor
# Print usage and exit if no processor found
print_usage
exit 1
else
# Process the lines and print result
File.readlines(ARGV[0]).each { |line|
processor.process(line)
}
processor.print_result
end
end
</code></pre>
<p>My questions are:</p>
<ul>
<li>Is there a more Ruby-esque way of solving it?</li>
<li>More compact, but still readable / elegant?</li>
</ul>
<p>It seems checking for correct command-line parameter combinations takes up a lot of space...</p>
<p>Contrast it to the Scala version found here:</p>
<p><a href="https://gist.github.com/anonymous/93a975cb7aba6dae5a91#file-counting-scala">https://gist.github.com/anonymous/93a975cb7aba6dae5a91#file-counting-scala</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:26:50.757",
"Id": "74111",
"Score": "0",
"body": "If you are satisfied with any of the answers, you should select the one that was most helpful to you."
}
] |
[
{
"body": "<h1>Formatting</h1>\n\n<p>Most Rubiest favor some white space between methods, such as:</p>\n\n<pre><code>class LineCounter\n\n # Initialize instance variables\n def initialize\n @line_count = 0\n end\n\n def process(line)\n @line_count += 1\n end\n\n def print_result\n puts \"#{@line_count} lines\"\n end\n\nend\n</code></pre>\n\n<h2>{...} vs do...end</h2>\n\n<p>For multi-line blocks, prefer do...end:</p>\n\n<pre><code>File.readlines(arguments.path).each do |line|\n arguments.processor.process(line)\nend\n</code></pre>\n\n<h1>Comments</h1>\n\n<p>Comments, when used, should say something the code doesn't already\nsay. This comment, and some of the others, can be eliminated without\ninjuring the reader's ability to understand the code:</p>\n\n<pre><code> # Initialize instance variables\n def initialize\n @line_count = 0\n end\n</code></pre>\n\n<h1>Argument parsing</h1>\n\n<p>You are correct that argument parsing in this script has the potential\nto be improved. There are a few different ideas that could help here.</p>\n\n<h2>Separate class</h2>\n\n<p>I usually like to put argument parsing in its own class:</p>\n\n<pre><code>class Arguments\n\n attr_reader :path\n attr_reader :processor\n\n def initialize(argv)\n @path = argv[0]\n if argv.length == 2\n if argv[1] == \"lines\"\n @processor = LineCounter.new\n elsif argv[1] == \"words\"\n @processor = WordCounter.new\n end\n elsif argv.length == 3 && argv[1] == \"find\"\n word_to_find = argv[2]\n @processor = WordMatcher.new(word_to_find)\n end\n if not @processor\n print_usage\n exit 1\n end\n end\n\n private\n\n def print_usage\n puts \"Usage: #{$0} <file> words|lines\"\n puts \" #{$0} <file> find <what-to-find>\"\n end\n\nend\n</code></pre>\n\n<p>The main program becomes:</p>\n\n<pre><code>if __FILE__ == $PROGRAM_NAME\n arguments = Arguments.new(ARGV)\n File.readlines(arguments.path).each { |line|\n arguments.processor.process(line)\n }\n arguments.processor.print_result\nend\n</code></pre>\n\n<p>I had more I was going to write, but after seeing the simplicity of @tokland's answer, I think the approaches I was going to take are not so good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T08:49:50.800",
"Id": "71403",
"Score": "0",
"body": "Thanks for the tips. Interesting approach with your Arguments class... Have you considered using a special library for command-line argument validation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:30:22.860",
"Id": "71425",
"Score": "0",
"body": "@Sebastian Yes, I did. optparse, of course, only takes care of switch (`--foo`) arguments, so it would be no help. I have often looked for libraries which do good handling of non-switch arguments; I am not aware of one that _just_ parses arguments. The ones I've seen have strong opinions on parts of your program that are not argument parsing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T18:55:33.180",
"Id": "41494",
"ParentId": "41480",
"Score": "5"
}
},
{
"body": "<p>Some notes: </p>\n\n<ul>\n<li>Those counter classes are probably overkill, keep it simple. </li>\n<li>Ruby is an OOP language, but it's not necessary to create a bunch of classes for simple scripts like this.</li>\n<li>Idiomatic: <code>if not x</code> -> <code>if !x</code></li>\n<li>Idiomatic: <code>{ ... }</code> for one-line blocks, <code>do</code>/<code>end</code> for multi-line.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>fail(\"Usage: #{0} PATH (lines|words|find REGEXP)\") unless ARGV.size >= 2\npath, mode, optional_regexp = ARGV\n\nopen(path) do |fd|\n case mode\n when \"lines\"\n puts(fd.lines.count)\n when \"words\"\n puts(fd.lines.map { |line| line.split.size }.reduce(0, :+))\n when \"find\"\n if optional_regexp\n fd.lines.each { |line| puts(line) if line.match(optional_regexp) }\n else\n fail(\"mode find requires a REGEXP argument\")\n end\n else\n fail(\"Unknown mode: #{mode}\")\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T08:48:54.763",
"Id": "71402",
"Score": "2",
"body": "Thanks for the tips about idiomatic Ruby code. And thanks for the example. I know there was a \"Ruby way\" of doing it... short, compact, pragmatic, to the point, yet readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:29:57.737",
"Id": "73632",
"Score": "0",
"body": "Upvoted. Great answer. One small suggestion for an improvement: Put all the argument checking and fail statements at the top. Then the program reads: 1. data validation 2. actual content. It has the added benefit of getting rid of all the \"if... else\" statements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:01:21.577",
"Id": "41495",
"ParentId": "41480",
"Score": "15"
}
},
{
"body": "<p>As you have not indicated whether you are looking for a quick and dirty--possibly one-off--solution, or production code, and have said nothing of file size, I decided to suggest something you could employ for the former purpose, when the file is not humongous (because I read it all into a string):</p>\n\n<pre><code>fname, op, regex = ARGV\ns = File.read(fname)\ncase op\nwhen 'rows'\n puts s[-1] == $/ ? s.count($/) : s.count($/) + 1\nwhen 'words'\n puts s.split.size\nwhen 'find' \n regex = /#{regex}/\n s.each_line {|l| puts l if l =~ regex}\nend\n</code></pre>\n\n<p>where <code>$/</code> is the end-of-line character(s). Let's create a file for demonstration purposes:</p>\n\n<pre><code>text =<<_\nNow is the time\nfor all good\nRubiests to\nspend some\ntime coding. \n_\nFile.write('f1', text)\n</code></pre>\n\n<p>If the above code is in the file 'file_op.rb', we get these results:</p>\n\n<pre><code>ruby 'file_op.rb' 'f1' 'rows' #=> 5\nruby 'file_op.rb' 'f1' 'words' #=> 13\nruby 'file_op.rb' 'f1' 'find' 'time'\n #=> Now is the time\n # time coding. \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T08:47:24.820",
"Id": "71401",
"Score": "0",
"body": "Thanks for the super-compact solution. It is a good example and serves me well, however I would like to show an \"usage\" text in case of missing / incorrect arguments. But please don't change your example! I like it that it's so short."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T10:04:35.410",
"Id": "71408",
"Score": "0",
"body": "I think you can remove the `+ [nil]`. Unlike Python, you can de-struct even if sizes do not match."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:48:53.523",
"Id": "71466",
"Score": "0",
"body": "Sebastian, I figured you could add whatever data checks you wanted. @tokland, thank you-good to know that, edited my answer--and I'd also like to thank Ruby."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T07:48:14.410",
"Id": "41541",
"ParentId": "41480",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41495",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T15:16:58.847",
"Id": "41480",
"Score": "13",
"Tags": [
"object-oriented",
"ruby",
"file"
],
"Title": "Counting words / lines in Ruby"
}
|
41480
|
<p>To test incoming data for string values that are too large for the "database" (MS Access), I could do this:</p>
<pre><code>private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
invItem = TruncateVerboseStringMembers(invItem);
. . .
}
private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;
if (invItem.Description.Trim().Length > DESC_MAX_LEN)
{
invItem.Description = invItem.Description.Substring(0, DESC_MAX_LEN);
}
if (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN)
{
invItem.vendor_id = invItem.vendor_id.Substring(0, VENDOR_ID_MAX_LEN);
}
if (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN)
{
invItem.vendor_item = invItem.vendor_item.Substring(0, VENDOR_ITEM_MAX_LEN);
}
return invItem;
}
</code></pre>
<p>...where <code>TruncateVerboseStringMembers()</code> is always called, even though normally all conditions will fail (strings will not be too long), or I could do it like this:</p>
<pre><code>const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;
private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
if ((invItem.Description.Trim().Length > DESC_MAX_LEN) ||
(invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN) ||
(invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN))
{
invItem = TruncateVerboseStringMembers(invItem);
}
. . .
}
private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
if (invItem.Description.Trim().Length > DESC_MAX_LEN)
{
. . .
</code></pre>
<p>...where <code>TruncateVerboseStringMembers()</code> is only called when it needs to swing into action.</p>
<p>Or something fancier, where, if any strings are too long, I pass an array of <code>bool</code> to <code>TruncateVerboseStringMembers()</code>.</p>
<p>Which is preferred?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:55:47.863",
"Id": "71378",
"Score": "2",
"body": "You are still doing the double check. There is no good reason to check the length of all the strings, only to re-check all of them if any of them should be truncated. You only get duplication of code which means more code to maintain and in this case also more work for the code to do."
}
] |
[
{
"body": "<p>Making duplicate testing just to avoid a method call doesn't make much sense. Method calls are not that expensive. On the contrary, they can help make the code cleaner.</p>\n\n<p>You can make a method that helps you clean up the strings, just pass in how long each string may be. I think that maked the code as DRY as possible:</p>\n\n<pre><code>private string TruncateString(string value, int maxLen) {\n value = value.Trim();\n if (value.Length > maxLen) {\n value = value.Substring(0, maxLen);\n }\n return value;\n}\n\nprivate InventoryItem TruncateVerboseStringMembers(InventoryItem invItem) {\n invItem.Description = TruncateString(invItem.Description, 35);\n invItem.vendor_id = TruncateString(invItem.vendor_id, 10);\n invItem.vendor_item = TruncateString(invItem.vendor_item, 12);\n return invItem;\n}\n</code></pre>\n\n<p>This will give you the overhead of always calling the method for each string and always assigning the reference back, but those are very cheap operations. Compared to any database call, it's negligible.</p>\n\n<p>If there is nothing in the string to trim, and nothing to truncate, you will actually be putting back the original string reference in the property, so there are no extra strings created in the usual case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:31:29.020",
"Id": "71334",
"Score": "0",
"body": "As the old cat in \"Never Cry Wolf\" said, \"Good idea!\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T20:21:11.280",
"Id": "41502",
"ParentId": "41489",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41502",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:26:46.687",
"Id": "41489",
"Score": "5",
"Tags": [
"c#",
"performance",
"database",
"comparative-review",
"ms-access"
],
"Title": "Truncating long strings when saving inventory items to database"
}
|
41489
|
<p>Example: <code>00010111</code> -> <code>11101000</code></p>
<pre><code>public long reverse(long x) {
long r = 0;
int i = 0;
while (x > 0) {
int bit = 0x0001 & x;
r += bit << (63 - i);
x >>= 1;
i++;
}
return r;
}
</code></pre>
<p>Can someone review my code and provide any comments or suggest a better way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:52:59.043",
"Id": "71328",
"Score": "0",
"body": "Greetings, your question can be put out of hold if you update it with code that does not contain an infinite loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T06:13:05.127",
"Id": "71391",
"Score": "0",
"body": "Hi, sorry about the bad code - I have updated the code to remove the infinite loop. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T07:21:18.267",
"Id": "71394",
"Score": "0",
"body": "It might be too early for me, but Eclispse still says that `int bit = 0x0001 & x;` needs a cast to `int`, so it still doesn't compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T10:26:32.850",
"Id": "71410",
"Score": "0",
"body": "If you care about performance, you should consider one of the alternative approaches listed at http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel"
}
] |
[
{
"body": "<p>This code does not work, right?</p>\n\n<p>What you have is an infinite loop, because <code>x >> 1;</code> does not do what you think it does.</p>\n\n<p>There are a number of things wrong in here....</p>\n\n<ol>\n<li>if the input long value is negative, you will never reverse it (it's < 0).</li>\n<li>you should read up on the zero-shifting operator <code>>>></code></li>\n<li>you will need to do all the 64 bits of shift otherwise the you will only reverse the set bits .... i.e. <code>0x00000000000001</code> should reverse to <code>0x8000000000000000</code> and not <code>0x00000000000001</code></li>\n</ol>\n\n<p>The code you probably want will look more like:</p>\n\n<pre><code>public long reverse(long x) {\n long r = 0;\n for (int i = 63; i >= 0; i--) {\n r |= ((x >>> i) & 0x1L) << (63 - i);\n }\n return r;\n}\n</code></pre>\n\n<p>Of course, you could always do:</p>\n\n<pre><code>public long reverse(long x) {\n return Long.reverse(x);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T06:13:38.347",
"Id": "71392",
"Score": "0",
"body": "Yes, there is infinite loop in the code - apologize for that. Thanks for your great answer though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:59:08.530",
"Id": "41491",
"ParentId": "41490",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41491",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:47:59.447",
"Id": "41490",
"Score": "0",
"Tags": [
"java"
],
"Title": "Reversing a 64 bit Integer"
}
|
41490
|
<p>I am writing a script which <code>checkout</code> a git repo to certain commit hash, do something and switch back to <code>master</code>. The purpose of this script is to take homework solutions of students from bitbucket. Note that all the repos are under same bitbucket account. There is a master bitbucket account which is admin of all these repos and students have the write access to their respective repo. The students must adhere to following directory structure in their repos:</p>
<pre><code>-assignments
|- assignment-1
|- assignment-2
.
.
.
|- assignment-X
</code></pre>
<p>The directories inside these contain the homework. Once the teacher has given the deadline, the students must commit their code before the deadline. The script will see the git log, find the commit which is made before deadline, switch to that revision and <code>rsync</code> the solutions to the local directory. </p>
<p>So, this script will:</p>
<ul>
<li>First get the list of bitbucket repo names from a file
(<code>students-info.json</code>)</li>
<li>For each repo, see if the repo already exists locally. If it does, then do a git pull to get the latest commit </li>
<li>If not do a git clone</li>
<li>Now, find a commit which is made before deadline </li>
<li>switch to that revision</li>
<li>do a <code>rsync</code> of the required assignment homework directory to <code>solutions-directory/assignment-x-deadline/student-id</code></li>
<li>switch back to master branch</li>
</ul>
<p>I am looking for any tips, suggestions, general code improvements, bugs, anything. </p>
<p>Here is my code:</p>
<pre><code>#!/bin/python
"""
This script will take assignment solutions from each student repository. Based
on the timestamp given, it finds out the last commit made before timestamp
(i.e. deadline) and it checks out that revision, rsyncs the solution folder
of the required assignment with the solutions-repo and resets to HEAD.
The timestamp should be of the format 'Month Date H:M:S Year'
eg. Dec 19 22:31:01 2013
Input : List of students ids, assignment-id, timestamp
Example usage: To take out solutions of assignment 11 whose deadline was
Dec 19 22:31:01 2013, run the following
$python take_solutions.py -d 'Dec 19 22:31:01 2013' -a 'assignment-11'
To do:
- git_log_cmd with format string in get_commit_hash()
- dest_path is ugly
- dest_path should be global?
-
"""
import string
import os
import time
import datetime
import subprocess
import json
import argparse
import shlex
import logging
import datetime
from logging.handlers import TimedRotatingFileHandler
from dir_settings import *
from bb_settings import *
parser = argparse.ArgumentParser(description='This script will take assignment solutions from each student repository. Based on the timestamp given, it finds out the last commit made before timestamp (i.e. deadline) and it checks out that revision, rsyncs the solution folder of the required assignment with the solutions-repo and resets to HEAD.')
parser.add_argument('-d','--deadline', help='The timestamp should be of the \
format "Month Date H:M:S Year" e.g. "Dec 19 22:31:01 2013"',
required=True)
parser.add_argument('-a','--assignment_id', help='Please provide assignment \
id of the solutions you want to copy. e.g. assignment-7',
required=True)
NITRO_LOGGER = logging.getLogger('NITRO')
LOG_FILENAME = 'nitro.log'
SOLUTIONS_DIRECTORY = 'solutions-directory/'
STUDENTS_REPO_DIRECTORY = 'students-repo-directory/'
students_info = json.loads(open(STUDENTS_INFO, 'r').read())
args = vars(parser.parse_args())
assignment_id = args['assignment_id']
deadline = args['deadline']
DEST_PATH = SOLUTIONS_DIRECTORY + assignment_id + '-' + '-'.join(deadline.split()) + '/'
def get_commit_hash(repo_name, timestamp):
git_log_cmd = shlex.split('git --git-dir=' + STUDENTS_REPO_DIRECTORY + repo_name + '/.git log --pretty=format:"%H %ad" --date=local')
try:
(output, error) = subprocess.Popen(git_log_cmd, stdout=subprocess.PIPE,
stderr=LOG_FD).communicate()
for git_log in string.split(output, os.linesep):
deadline = datetime.datetime.strptime(timestamp, "%b %d %H:%M:%S %Y")
# split the commit message by first white space, the returning list will
# have hash as its first element and timestamp as second element
commit_hash = git_log.split(' ', 1)[0]
commit_timestamp = git_log.split(' ', 1)[1]
if deadline > datetime.datetime.strptime(commit_timestamp, "%a %b %d %H:%M:%S %Y"):
return commit_hash
except Exception, e:
NITRO_LOGGER.error("Couldn't get commit hash before deadline for repo %s: %s" % (repo_name, str(e)))
#raise e
def sync_solutions(repo_name):
def repo_exists(repo_name):
return os.path.isdir(STUDENTS_REPO_DIRECTORY + repo_name)
def clone_repo(repo_name):
clone_cmd = shlex.split("git clone %s%s %s%s" % (BB_REPO_BASE_URL,
repo_name, STUDENTS_REPO_DIRECTORY, repo_name))
subprocess.check_call(clone_cmd, stdout=LOG_FD, stderr=LOG_FD)
def pull_repo(repo_name):
pull_cmd = shlex.split("git --git-dir=%s/.git pull" % \
(STUDENTS_REPO_DIRECTORY + repo_name))
subprocess.check_call(pull_cmd, stdout=LOG_FD, stderr=LOG_FD)
def checkout_version(repo_name, commit_hash='-'):
checkout_cmd = shlex.split("git --git-dir=%s/.git checkout %s" \
% ((STUDENTS_REPO_DIRECTORY + repo_name), commit_hash))
subprocess.check_call(checkout_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def rsync(repo_name):
src_path = STUDENTS_REPO_DIRECTORY + repo_name + '/assignments/' + assignment_id
if not os.path.isdir(src_path):
# either student messed up the dir structure or hasn't submitted his assignments
return
if not os.path.isdir(DEST_PATH + repo_name):
os.makedirs(DEST_PATH + repo_name)
rsync_cmd = shlex.split('rsync -rt %s %s' % (src_path, DEST_PATH + repo_name))
subprocess.check_call(rsync_cmd, stdout=LOG_FD, stderr=LOG_FD)
try:
if repo_exists(repo_name):
pull_repo(repo_name)
else:
clone_repo(repo_name)
except Exception, e:
NITRO_LOGGER.error('pull/clone repo failed for repo %s: %s', repo_name, str(e))
return
commit_hash = get_commit_hash(repo_name, deadline)
if commit_hash:
try:
checkout_version(repo_name, commit_hash)
rsync(repo_name)
checkout_version(repo_name)
except Exception, e:
NITRO_LOGGER.error('git checkout failed for repo %s: %s' % (repo_name, str(e)))
else:
NITRO_LOGGER.debug('No assignment found before deadline for ' + repo_name)
return
def setup_logging():
NITRO_LOGGER.setLevel(logging.DEBUG) # make log level a setting
# Add the log message handler to the logger
myhandler = TimedRotatingFileHandler(LOG_FILENAME, when='midnight',
backupCount=5)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %I:%M:%S %p')
myhandler.setFormatter(formatter)
NITRO_LOGGER.addHandler(myhandler)
def init():
if not os.path.isdir(STUDENTS_REPO_DIRECTORY):
os.makedirs(STUDENTS_REPO_DIRECTORY)
if not os.path.isdir(SOLUTIONS_DIRECTORY):
os.makedirs(SOLUTIONS_DIRECTORY)
if not os.path.isdir(DEST_PATH):
os.makedirs(DEST_PATH)
def main():
NITRO_LOGGER.debug('****Firing up NITRO***')
init()
for student_id, student_email in students_info.iteritems():
NITRO_LOGGER.debug(student_id)
sync_solutions(student_id)
NITRO_LOGGER.debug('****Done with NITRO***')
if __name__ == '__main__':
LOG_FD = open(LOG_FILENAME, 'a')
setup_logging()
main()
</code></pre>
|
[] |
[
{
"body": "<p>Your idea of inspecting the timestamps of the commits is conceptually flawed. Git is a distributed version control system, with no central server or any other means of notarizing timestamps. The timestamps are determined solely by the system clock on the machine on which the commit was created, and that clock can be trivially rolled back. Therefore, the only foolproof approach is to clone/pull all of the repositories at the time of the deadline.</p>\n\n<p>Then, there is the question of which branch you want to inspect. Do you want to consider only the <code>master</code> branch? If so, it would be a good idea to specify the <code>master</code> branch when running <code>git log</code>. Keep in mind that if you consider <em>all</em> commits that were created before the deadline, you may end up taking a commit that was rolled back by the student. In other words, if the student makes a commit, then changes her mind (using <code>git reset --hard HEAD^</code>), you may be misconstruing the discarded version as the submission, simply because it has a later timestamp. For that reason, I hope that you only inspect commits along an agreed-upon branch or tag, rather than everything that might happen to exist in the repository.</p>\n\n<p>In <code>get_commit_hash()</code>, you use the <code>%ad</code> pretty-printing format to obtain <code>commit_timestamp</code>. That's a misnomer, as <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-log.html#_pretty_formats\" rel=\"nofollow noreferrer\"><code>%ad</code></a> gets the authorship timestamp, not the commit timestamp. I believe you should be more interested in the commit timestamp. (Authorship times aren't even necessarily monotonic as you progress through the commit chain, since commits can be rearranged using <code>git rebase</code>.)</p>\n\n<p>Assuming that you still want to go through with your original plan, you're working too hard. This should get you the hash of the latest commit on the <code>master</code> branch with a commit date in 2013:</p>\n\n<pre><code>git log -n 1 --until='2013-12-31 23:59:59' --pretty=%H master\n</code></pre>\n\n<p>Better yet, read what <code>gitrevisions(1)</code> says about <a href=\"https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html#_specifying_revisions\" rel=\"nofollow noreferrer\">\"the value of the ref at a point in time\"</a>, and skip all that analysis.</p>\n\n<pre><code>git checkout 'master@{2013-12-31 23:59:59}'\n</code></pre>\n\n<hr>\n\n<p>By the way, I <em>strongly</em> recommend that you abandon your date format in favour of <a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a>.</p>\n\n<p><img src=\"https://imgs.xkcd.com/comics/iso_8601.png\" alt=\"XKCD 1179\"></p>\n\n<p>Credit: <a href=\"https://xkcd.com/1179/\" rel=\"nofollow noreferrer\">https://xkcd.com/1179/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T08:44:28.527",
"Id": "71400",
"Score": "0",
"body": "I already know that timestamps in git commits can be changed, still I went ahead with this. So yes, this is flawed. However I will be pulling/cloning right after deadline. And also I forgot to mention that I consider only master branch. You are right about `%ad`, it's a mistake, I will change it to `%cd`. And I had no idea about `git checkout 'master@{2013-12-31 23:59:59}'`. So cool! Makes my code so small!. I will also change my date format to ISO 8601. Thank you very much for your feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T07:26:59.810",
"Id": "41538",
"ParentId": "41492",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T18:36:48.070",
"Id": "41492",
"Score": "6",
"Tags": [
"python",
"git"
],
"Title": "Script to checkout multiple repositories to a certain commit hash"
}
|
41492
|
<p>I am trying to print the elements of an array into a table, but I'm having trouble formatting the array elements itself. Perhaps there is a better solution than what I'm currently using?</p>
<pre><code>import java.util.Scanner;
public class RainFall{
public static void main(String args[]) {
//create rainfall array
double[][]rainfall = new double[2][3];
double sum = 0;
double average = 0;
int count = 0;
Scanner in = new Scanner (System.in);
System.out.println("Please enter rainfall for Region 1 and Region 2 one after the other");
//Create For loop to read in data
for(int i=0;i<rainfall.length;i++){
for(int j=0;j<rainfall[0].length;j++){
System.out.println("Enter rainfall:: ");
rainfall[i][j]=in.nextDouble();
}
}
//create for loop to sum rainfall
for (int i=0; i < rainfall.length; i++){
for (int j=0; j < rainfall[0].length; j++){
sum += rainfall[i][j];
count++;
}//end nested for
}//end outer for
//calculate average
average = sum/count;
//Print table
System.out.printf( "%5s %10s %15s %20s %25s %n", "Region 1"," Jan", "Feb", "Mar", "Avg Rainfall");
System.out.printf( "%d", rainfall[0][0] );
//Print average
System.out.println("The average rainfall is: " + average);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You cannot use %d for double values.Try something like %3.2f for printing the rainfall values if you want to avoid the unnecessary precision.I am not sure why you are trying to print only one value while you have listed three months of rainfall.Try something like:</p>\n\n<pre><code> System.out.printf( \"\\t%3.2f\\t%3.2f\\t%3.2f\", rainfall[0][0],rainfall[0][1],rainfall[1][0] );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:34:15.937",
"Id": "41498",
"ParentId": "41496",
"Score": "2"
}
},
{
"body": "<p>If the array bounds are fixed, then there's no need for the <code>count</code> variable, since its value will always be the same. There's also no need to run a separate loop for the summation. You can do this at the same time as you're gathering the input. And since your output shows that you want to show the averages by region, you'll need to have somewhere to store those values, too.</p>\n\n<p>Also, try using more descriptive prompts for the user so they know how many inputs are expected.</p>\n\n<p>So the first part of your function becomes</p>\n\n<pre><code>//could also define these as constants\nint regions = 2;\nint months = 3;\nint count = regions * months;\n\ndouble[][]rainfall = new double[regions][months];\ndouble[] avgByRegion = new double[regions];\ndouble sum = 0;\ndouble average = 0;\n\nScanner in = new Scanner (System.in);\n\n//Create For loop to read in data\nfor(int i=0; i < regions; i++){\n double sumByRegion = 0;\n for(int j=0; j < months; j++){\n System.out.printf(\"Enter rainfall for Region %d, Month %d:: \", i+1,j+1);\n rainfall[i][j]=in.nextDouble();\n sumByRegion += rainfall[i][j];\n }\n avgByRegion[i] = sumByRegion/months;\n sum += sumByRegion;\n}\n\n//calculate average\naverage = sum/count;\n</code></pre>\n\n<p>Then you can format your output with another set of loops:</p>\n\n<pre><code>for(int i=0; i < regions; i++){\n System.out.printf(\"Region %d\\t Jan\\t Feb\\t Mar\\t Avg Rainfall%n\", i+1);\n for(int j=0; j < months; j++){\n System.out.printf(\"\\t%2.1f\",rainfall[i][j]);\n }\n System.out.printf(\"\\t%2.1f%n\", avgByRegion[i]);\n}\nSystem.out.println(\"The overall average rainfall is: \" + average);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:52:18.117",
"Id": "41500",
"ParentId": "41496",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:10:30.567",
"Id": "41496",
"Score": "1",
"Tags": [
"java",
"array"
],
"Title": "Print the elements of an array into a table"
}
|
41496
|
<p>Suggestions for improving coding style are greatly appreciated.</p>
<pre><code>import qualified Data.List as L
import qualified Data.Map.Strict as M
import qualified Data.Vector as V
type Queue a = ([a], [a])
emptyQueue = ([], [])
pushListToAnother fromLst toLst = L.foldl' (\ys x -> (x:ys)) toLst fromLst
enqueue :: Queue a -> a -> Queue a
enqueue (inList, outList) x = ((x:inList), outList)
dequeue :: Queue a -> Maybe (a, Queue a)
dequeue (inList, outList) = case outList of
(y:ys) -> Just (y, (inList, ys))
[] -> if (null inList) then Nothing else dequeue ([], reverse inList)
massEnqueue :: Queue a -> [a] -> Queue a
massEnqueue (inList, outList) items = ((pushListToAnother items inList), outList)
-- consider moving the above Queue code into a separate module.
type Grid a = V.Vector (V.Vector a)
type Indices = (Int, Int)
access grid (x, y) = (grid V.! x) V.! y
massInsert :: Ord k => [(k, v)] -> M.Map k v -> M.Map k v
massInsert elems theMap = L.foldl' (\m (k, v) -> M.insert k v m) theMap elems
validAndTraversable :: (a -> Bool) -> Grid a -> Indices -> Bool
validAndTraversable traversability grid xy@(x, y) = let xbound = V.length grid in
let ybound = V.length (V.head grid) in
let withinBounds = (x >= 0) && (x < xbound) && (y >= 0) && (y < ybound) in
withinBounds && (traversability (access grid xy))
getPath :: Ord a => M.Map a a -> a -> a -> [a]
getPath visitedFromMap start current = pathHelper visitedFromMap start current []
where pathHelper prevIndicesMap start current path = let newPath = (current:path) in
if current == start
then newPath
else case (M.lookup current prevIndicesMap) of
Nothing -> []
Just e -> (pathHelper prevIndicesMap start e) $! newPath
mazeSolverLoop :: Indices -> (Indices -> a -> Bool) -> (a -> Bool) -> Grid a -> Queue Indices -> M.Map Indices Indices -> [Indices]
mazeSolverLoop start isFinish traversability mazeGrid queue visitedFromMap = let item = dequeue queue in
case item of
Nothing -> []
Just (currentXY, rest) -> if isFinish currentXY (access mazeGrid currentXY)
then getPath visitedFromMap start currentXY
else let (x, y) = currentXY in
let potentialNeighbors = [(x+1, y), (x, y+1), (x-1, y), (x, y-1)] in
let isVisitable = \xy -> (validAndTraversable traversability mazeGrid xy) && (M.notMember xy visitedFromMap) in
let unvisitedNeighbors = filter isVisitable potentialNeighbors in
let newVisitedFromMap = massInsert (map (\xy -> (xy, currentXY)) unvisitedNeighbors) visitedFromMap in
let newQueue = massEnqueue rest unvisitedNeighbors in
(mazeSolverLoop start isFinish traversability mazeGrid newQueue) $! newVisitedFromMap
-- the solving functions
findUnknownFinish :: Indices -> (Indices -> a -> Bool) -> (a -> Bool) -> Grid a -> [Indices]
findUnknownFinish start isFinish traversability grid = let validityPredicate = validAndTraversable traversability grid in
if validityPredicate start
then let m = M.singleton start start in
let q = enqueue emptyQueue start in
mazeSolverLoop start isFinish traversability grid q m
else []
findKnownFinish :: Indices -> Indices -> (a -> Bool) -> Grid a -> [Indices]
findKnownFinish start finish traversability grid = let isFinish = (\xy _ -> xy == finish) in
findUnknownFinish start isFinish traversability grid
escapeMaze :: Indices -> (a -> Bool) -> Grid a -> [Indices]
escapeMaze start traversability grid = let isOnBounds = \b x -> (x == 0) || (x == (b-1)) in
let xbound = V.length grid in
let ybound = V.length (V.head grid) in
let isFinish = \(x, y) _ -> (isOnBounds xbound x) || (isOnBounds ybound y) in
findUnknownFinish start isFinish traversability grid
escapeMazeV2 :: Indices -> (a -> Bool) -> Grid a -> [Indices]
escapeMazeV2 start traversability grid = let isOnBounds = \b x -> (x == 0) || (x == (b-1)) in
let xbound = V.length grid in
let ybound = V.length (V.head grid) in
let isFinish = \(x, y) _ -> (isOnBounds xbound x) || (isOnBounds ybound y) in
let acceptableFinish = \xy a -> (isFinish xy a) && (xy /= start) in
findUnknownFinish start acceptableFinish traversability grid
maze1 = V.fromList [(V.fromList [1,1,1,1,1,1,0]),
(V.fromList [0,0,0,0,0,0,0]),
(V.fromList [1,1,1,1,1,1,0]),
(V.fromList [0,0,0,0,0,0,0]),
(V.fromList [0,1,1,1,1,1,1]),
(V.fromList [0,0,0,0,0,0,0]),
(V.fromList [1,1,1,0,1,1,1]),
(V.fromList [0,0,0,0,0,0,0]),
(V.fromList [0,1,1,1,1,1,0])]
show_solve_maze1 = let solve_maze1 = findKnownFinish (1,0) (8,6) (\a -> a == 0) maze1 in
mapM_ (putStrLn.show) solve_maze1
maze2 = V.fromList (map V.fromList ["xxxxxxxxxxxxxxxxxxxxx",
"x x x",
"xx xxxx xxxxxx xxx x",
"x x x x xx x",
"x xxxxx xxxxxxxx x x",
"x x xx x",
"xxxxxx xxxxx xxxx x",
"x xxxx x x x",
"x xx x x x x x x xxx",
"x xx x x x x x x",
"xx x x x xxx xxx xxx",
"x xx x x",
"xxxx x xxxxxx xxxx x",
"x xx x x x x",
"xxxxxx x x xxxxx xxx",
"x xx x x x x",
"xxx x xx xxx xxx x x",
"x x x x x x",
"x x xxxxxx xxxx xxx x",
"x x ox",
"x xxxxxxxxxxxxxxxxxxx"])
show_solve_maze2 = let solve_maze2 = findUnknownFinish (1,1) (\_ a -> a == 'o') (\a -> a /= 'x') maze2 in
mapM_ (putStrLn.show) solve_maze2
show_solve_maze2v2 = let solve_maze2 = escapeMaze (1,1) (\a -> a /= 'x') maze2 in
mapM_ (putStrLn.show) solve_maze2
maze3 = V.fromList (map V.fromList ["###########",
"# #",
"# ##### # #",
" # # #",
"### # ### #",
"# # #",
"# # ### ###",
"# # # ",
"# ### # # #",
"# # #",
"###########"])
show_solve_maze3_v1 = let solve_maze3_v1 = escapeMazeV2 (3,0) (\a -> a /= '#') maze3 in
mapM_ (putStrLn.show) solve_maze3_v1
show_solve_maze3_v2 = let solve_maze3_v2 = escapeMazeV2 (7,10) (\a -> a /= '#') maze3 in
mapM_ (putStrLn.show) solve_maze3_v2
</code></pre>
|
[] |
[
{
"body": "<p>Some general ideas:</p>\n\n<ul>\n<li>Always give types to top level functions. It improves readability of your code very much.</li>\n<li>Unless you really need to, it's better to use existing data structures than inventing your own. Instead of using <code>Queue</code>, you could as well use <code>Data.Sequence</code>.</li>\n<li><p>Some of the <code>Queue</code> functions can be simplified, often using <code>first</code> from Control.Arrow:</p>\n\n<pre><code>pushListToAnother :: [a] -> [a] -> [a]\npushListToAnother fromLst = (reverse fromLst ++)\n\nenqueue :: Queue a -> a -> Queue a\nenqueue q x = first (x :) q\n\nmassEnqueue :: Queue a -> [a] -> Queue a\nmassEnqueue q items = first (pushListToAnother items) q\n</code></pre></li>\n<li><p>Strictly adhere to having some maximum number of columns (often people use 72, 78 or 80). Code that goes too far to the right is very much unreadable.</p></li>\n<li><p>Instead of <code>let f = foo in let g = bar in boo</code> use just <code>let f = foo ; g = bar in boo</code>. For example:</p>\n\n<pre><code>validAndTraversable :: (a -> Bool) -> Grid a -> Indices -> Bool\nvalidAndTraversable traversability grid xy@(x, y) =\n let xbound = V.length grid\n ybound = V.length (V.head grid)\n withinBounds = (x >= 0) && (x < xbound) && (y >= 0) && (y < ybound)\n in withinBounds && (traversability (access grid xy))\n</code></pre></li>\n<li><p>Prefer guards over <code>if/then/else</code>. Usually it leads to more concise code and it's more idiomatic. <a href=\"http://www.haskell.org/haskellwiki/Pattern_guard\" rel=\"nofollow\">Pattern guards</a> can be even more helpful.</p>\n\n<pre><code>getPath :: Ord a => M.Map a a -> a -> a -> [a]\ngetPath visitedFromMap start current =\n pathHelper visitedFromMap start current []\n where\n pathHelper prevIndicesMap start current path\n | current == start\n = newPath\n | Just e <- M.lookup current prevIndicesMap\n = (pathHelper prevIndicesMap start e) $! newPath\n | otherwise\n = []\n where newPath = (current:path)\n</code></pre></li>\n<li><p>Avoid code repetition, for example multiple calls to the same function, if you can factor the call out:</p>\n\n<pre><code>maze1 = V.fromList . map V.fromList $\n [ [1,1,1,1,1,1,0]\n , [0,0,0,0,0,0,0]\n , [1,1,1,1,1,1,0]\n , [0,0,0,0,0,0,0]\n , [0,1,1,1,1,1,1]\n , [0,0,0,0,0,0,0]\n , [1,1,1,0,1,1,1]\n , [0,0,0,0,0,0,0]\n , [0,1,1,1,1,1,0]\n ]\n</code></pre></li>\n<li><p>Use <a href=\"http://hackage.haskell.org/package/hlint\" rel=\"nofollow\">hlint</a>, it'll give you a lot of useful hints.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:02:36.457",
"Id": "71825",
"Score": "0",
"body": "I will definitely check out Control.Arrow and Pattern Guards. (I only have a basic understanding of monads and have yet to learn about arrows.) Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:07:47.633",
"Id": "71826",
"Score": "0",
"body": "@dxh For using `first` you don't need to know anything about arrows. The point is that `->` is also an instance of `Arrow`, and so if `first` is specialized to `->` we get `(b -> c) -> ((b, d) -> (c, d))`. That is, it uses a function to act on the first part of a tuple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:26:48.497",
"Id": "71840",
"Score": "0",
"body": "We've been looking for a Haskell guru to join our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) for some time now, and it looks like you would be a good fit. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:13:46.390",
"Id": "41751",
"ParentId": "41503",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T20:22:59.490",
"Id": "41503",
"Score": "3",
"Tags": [
"haskell",
"breadth-first-search"
],
"Title": "Solve a maze in the form of a 2D array using BFS - Haskell"
}
|
41503
|
<p>I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.</p>
<p>Using <a href="https://codereview.meta.stackexchange.com/questions/62/homework-questions">Homework Questions</a> as reference, as this is a homework related question. This should fall into the second category. I know the code is working and that no memory is leaking. The implementation nor the <code>queue.h</code> can not be changed.</p>
<p><code>queue.h</code>:</p>
<pre><code>#define MAX_PRIO 100
typedef const char Datatyp;
#ifndef QUEUE_H
#define QUEUE_H
struct Qelement { // type of a queue
struct Qelement *next; // pointer to next element
int prio; // order in queue
Datatyp *dataptr; // pointer to data
};
typedef struct Qelement *Queue;
</code></pre>
<p><code>queue.c</code>: <strong>(This is were feedback is wanted)</strong></p>
<pre><code>// creating an empty queue
Queue new_queue ()
{
Queue q = (Queue)malloc(sizeof(struct Qelement));
q->next = NULL;
q->prio = MAX_PRIO;
q->dataptr = NULL;
return q;
}
// adding a new element to queue based on priority
// higher priority means earlier in queue
void add (Queue q, int priority, Datatyp *d)
{
// initiation
Queue previous = q;
Queue element = (Queue)malloc (sizeof(struct Qelement));
Queue tmp = NULL;
while (priority <= previous->prio)
{
if (previous->next != NULL)
{
tmp = previous;
previous = previous->next;
}
else if (tmp != NULL)
{
tmp = previous;
previous = previous->next;
break;
}
else
{
break;
}
}
element->prio = priority;
element->dataptr = d;
if (tmp == NULL)
{
element->next = NULL;
previous->next = element;
}
else
{
element->next = previous;
tmp->next = element;
}
}
</code></pre>
<p>The code is then used along these lines. (This part can not be changed)</p>
<pre><code>int main () {
const char *daniel = "Daniel";
const char *lisa = "Lisa";
const char *a[] = {"Kalle", "Olle", "Eva", lisa, "Stina",
"Peter", "Anna", daniel, "Johan", "Maria"};
Queue q = new_queue();
int i;
for (i=0; i<10; i++) {
add(q, i%4, a[i]);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:17:44.550",
"Id": "71331",
"Score": "0",
"body": "`typedef const char Datatyp;` *Datatyp*... is that a typo, or something you can't change?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:20:33.253",
"Id": "71332",
"Score": "0",
"body": "Something I can't change. I can't see any reason for having it. My teachers word is my law."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:27:14.160",
"Id": "71333",
"Score": "4",
"body": "Just a tiny note -- by convention, the method to add items to a queue is typically called `enqueue` and to remove is called `dequeue`. These are analogous to the `push` and `pop` conventions of a stack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:49:40.657",
"Id": "71335",
"Score": "0",
"body": "Tell me about it, if I could change them, I would. Wasn't easy finding material on the topic because of this standard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T08:50:02.193",
"Id": "71404",
"Score": "0",
"body": "`typedef struct Qelement *Queue;` To hide a pointer behind a typedef is considered very bad practice, because it makes the program bug-prone and hard to read. If this comes from your teacher, be aware that they are teaching you bad programming practice..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:31:25.073",
"Id": "71485",
"Score": "0",
"body": "@Corbin Based on the names (\"Kalle\", \"Olle\", etc.), I think that [\"typ\" is Swedish](http://translate.google.com/#en/sv/type), not a typo."
}
] |
[
{
"body": "<ol>\n<li><p>Your variable's names confused me; I'd suggest renaming 'previous' to 'current', and 'tmp' to 'previous'.</p></li>\n<li><p>You don't do anything sensible if malloc fails.</p></li>\n<li><p>The following ...</p>\n\n<pre><code>else if (tmp != NULL)\n{\n tmp = previous;\n previous = previous->next;\n break;\n}\nelse\n{\n break;\n} \n</code></pre>\n\n<p>... could be rewritten as ...</p>\n\n<pre><code>else\n{\n if (tmp != NULL)\n {\n tmp = previous;\n previous = NULL;\n }\n break;\n}\n</code></pre></li>\n<li><p>IMO you should ignore the alleged priority assigned to the head <code>q</code> element (because you never want to put anything in front of it).</p></li>\n</ol>\n\n<hr>\n\n<p><strong>1st version</strong></p>\n\n<p>In summary you could rewrite it to be something like this:</p>\n\n<pre><code>bool add (Queue q, int priority, Datatyp *d)\n{\n // initiation\n Queue element = (Queue)malloc (sizeof(struct Qelement));\n if (element == NULL)\n return false;\n element->prio = priority;\n element->dataptr = d;\n\n // loop until end of list or higher priority than next item\n for (; (q->next != NULL) && (q->next->prio >= priority); q = q->next)\n { } // an empty statement\n\n // insert element\n element->next = q->next;\n q->next = element;\n return true;\n}\n</code></pre>\n\n<p>Advantages of this version over your implementation:</p>\n\n<ul>\n<li>No danger of adding in front of the first, passed-in <code>q</code> element, even if the passed-in <code>priority</code> is greater than <code>MAX_PRIO</code></li>\n<li>No extra local variables (you have 2: <code>tmp</code> and <code>previous</code>)</li>\n<li>No <code>if</code> or <code>else</code> statements (you have 5)</li>\n<li>It's obvious what the algorithm is (search the list after the first node until you find the right spot, then insert into the list there)</li>\n</ul>\n\n<hr>\n\n<p><strong>2nd version</strong></p>\n\n<p>It's not clear whether your <code>Queue new_queue()</code> is part of the code which we're allowed to review.</p>\n\n<p>Assuming that we are allowed to review/change that, I would add, \"**Don't create \"first element\" which represents (contains a first pointer to) the queue: instead the queue should be represented by a pointer to the first real element.\"</p>\n\n<p>Your first node (allocated using <code>new_queue</code>) might be what's called a \"sentinel node\" (see references <a href=\"http://en.wikipedia.org/wiki/Sentinel_node\" rel=\"nofollow\">here</a> and <a href=\"http://en.wikipedia.org/wiki/Linked_list#Using_sentinel_nodes\" rel=\"nofollow\">here</a>). It's also possible to create a queue without using a sentinel node: the \"queue\" is simply a pointer to the first node (instead of being a pointer to a node which contains a pointer to the first real node).</p>\n\n<pre><code>void add (Queue* qptr, int priority, Datatyp *d)\n{\n // initiation\n Queue element = (Queue)malloc (sizeof(struct Qelement));\n element->prio = priority;\n element->dataptr = d;\n\n // get first element of queue\n Queue q = *qptr;\n if ((q == NULL) // queue was empty\n || (priority > q->prio)) // higher priority than first queue item\n {\n // insert at front of queue\n element->next = q;\n // caller's qptr now points to the new first node\n *qptr = element;\n return;\n }\n\n // else insert later in the queue using the same code as above \n for (; (q->next != NULL) && (q->next->prio >= priority); q = q->next)\n { }\n\n // insert element\n element->next = q->next;\n q->next = element;\n}\n</code></pre>\n\n<p>... used like this ...</p>\n\n<pre><code>int main () {\n const char *daniel = \"Daniel\";\n const char *lisa = \"Lisa\";\n const char *a[] = {\"Kalle\", \"Olle\", \"Eva\", lisa, \"Stina\", \n \"Peter\", \"Anna\", daniel, \"Johan\", \"Maria\"};\n\n // not q = new_queue()\n // instead let q be pointer to first real node\n // and q is null represent an empty list\n Queue q = NULL;\n\n for (int i=0; i<10; i++) {\n // pass Queue* qptr = &q (address of queue)\n // so that add can modify the value contained in q\n // (i.e. modify the node to which q is pointing)\n add(&q, i%4, a[i]); \n }\n\n // q is now a pointer to the first element\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Sadly, I can not change add to be a bool either. Is there any other way of handling it (except of very obscured ones) without changing add to a bool?</p>\n</blockquote>\n\n<p>Some C conventions are:</p>\n\n<ul>\n<li>return <code>int</code> (often 0 for success and -1 for failure)</li>\n<li>return something useful like 'Queue' (the most recently-added element) or 0 (if a new element couldn't be created</li>\n<li>throw an exception (if it's C++)</li>\n<li>Include <a href=\"http://pubs.opengroup.org/onlinepubs/009604499/basedefs/stdbool.h.html\" rel=\"nofollow\"><code><stdbool.h></code></a></li>\n<li>Ignore the fact that <code>malloc</code> might fail.</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Tell me about it, that is how I did it at first, and it turned out that the main function gave me a billion errors because apparently the first element of the queue should only be a pointer to the first real element.</p>\n</blockquote>\n\n<p>I tested the above code by adding the following statement to the end of main:</p>\n\n<pre><code>// q is now a pointer to the first element\n\nfor (;q;q=q->next)\n{\n printf(q->dataptr);\n printf(\"\\r\\n\");\n}\n</code></pre>\n\n<p>It generated the following output (which I think is correct):</p>\n\n<pre><code>Lisa\nDaniel\nEva\nAnna\nOlle\nPeter\nMaria\nKalle\nStina\nJohan\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:39:17.437",
"Id": "71357",
"Score": "0",
"body": "I will be trying this tomorrow. Sadly, I can not change add to be a bool either. Is there any other way of handling it (except of very obscured ones) without changing add to a bool? I almost want to show the teacher your first comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:43:01.537",
"Id": "71359",
"Score": "0",
"body": "Tell me about it, that is how I did it at first, and it turned out that the main function gave me a billion errors because apparently the first element of the queue should only be a pointer to the first real element. My getFirstelement function is sexy... return q->next->next; regarding the add by reference part, I was told that on numerous different places now... makes one wonder what I am being taught in school."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:55:58.800",
"Id": "71363",
"Score": "0",
"body": "@Emz I updated my answer with various options for a return code, and some test results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T09:41:21.080",
"Id": "71406",
"Score": "0",
"body": "As I thought, I have to ignore it. Last question! Can you provide some reliable source which I can reference to when I talk to the teacher about the structure of how to implement a more standard queue? So the teacher might share that with the other students. I now know how it is supposed to be done, but the other students do not. Must just want to get done with the exercise and get on to the next."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T10:05:28.460",
"Id": "71409",
"Score": "0",
"body": "Rereading your code again I see you added \"add at front\" which according to the specifics of the exercise should never happen, as the first queue element is initialized with the MAX_PRIO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:06:45.393",
"Id": "71412",
"Score": "0",
"body": "@Emz \"Add at front\" is in the 2nd version when there is no \"first queue element with initialized with the MAX_PRIO\". There's also a first version which does have a sentinel node with MAX_PRIO and which doesn't add before that sentinel node. I edited my answer to try to clarify the distinction between these two versions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:22:53.787",
"Id": "71414",
"Score": "0",
"body": "I don't know a \"reliable source\" which you can reference for data structure descriptions (I learned this before the World Wide Web). Wikipedia says that a [queue](http://en.wikipedia.org/wiki/Queue_(abstract_data_type)) can be implemented using various types of list, or a modified array. What you've implemented is a [singly-linked list](http://en.wikipedia.org/wiki/Linked_list) whose elements you ensure are 'sorted'. Wikipedia has a [list of data structures](http://en.wikipedia.org/wiki/List_of_data_structures): knowing the names of each structure might help you research more about them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:23:49.823",
"Id": "71415",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13018/discussion-between-chrisw-and-emz)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:18:45.847",
"Id": "41518",
"ParentId": "41504",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41518",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T21:11:04.417",
"Id": "41504",
"Score": "5",
"Tags": [
"optimization",
"c",
"homework",
"queue"
],
"Title": "Optimization for add function in queue"
}
|
41504
|
<p>This is my first more-than-1-line script. It takes an input folder and a file prefix and gets all the matching files. For the first of the files, the script grabs the first line and appends an extra label string and puts that into <code>$data</code>. For all files (including the first), it takes the second line, adds the timestamp found from the filename, and appends a that as new line to <code>$data</code>. When it's done, it writes the output.</p>
<p>The problem is it's pretty slow. 1 directory might have 10,000 files. In that case, the script takes about 3-4 minutes to complete. When doing this over 10 such directories, it begins to get quite annoying. </p>
<p>So, I'm hoping someone here could help speed things up, preferably with explanations so I also get better.</p>
<pre><code>for cs in {47..52}; do
csdirnm="CASE$cs";
tsdirnm="eta_at_x2";
label='flow-time';
dir="$csdirnm/$tsdirnm/";
files=$(ls -tr $dir); # -tr sort on time created, reversed (newest last).
i=0;
for f in $files ; do
fn=$dir$f;
if [[ $i = 0 ]]; then
data="$(sed -n 1p $fn) $label";
((i++));
fi
d=$(sed -n 2p $fn);
t=$(echo $fn | perl -pe 's|.*?(\d+\.\d+)|\1|');
data+="\n$d $t";
done;
echo -e "$data">"$csdirnm/${csdirnm}_${tsdirnm}_20T.time-series";
done;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:24:32.903",
"Id": "71484",
"Score": "0",
"body": "Are you running this on GNU/[tag:linux]? [tag:osx]? Or are you aiming for the code to be portable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:32:35.020",
"Id": "71486",
"Score": "0",
"body": "It's running in linux and I would expect it to also be usable on osx. For my part, I don't care about Windows, though a portable solution might be helpful to others using the same unhelpful software (that generates these files), as that runs on Windows also. But concretely, this question is about making it run faster in linux."
}
] |
[
{
"body": "<p>The problem is almost certainly this line here:</p>\n\n<pre><code>t=$(echo $fn | perl -pe 's|.*?(\\d+\\.\\d+)|\\1|');\n</code></pre>\n\n<p>If you are invoking the Perl interpreter for each line, you will struggle.</p>\n\n<p>A close second is that, for each file, you invoke 2 subshells, and two other program (sed and echo).</p>\n\n<p>My recommendation is for you to actually rewrite the whole thing in Perl...</p>\n\n<p>....</p>\n\n<p>but, you may find it faster to use <code>sed</code></p>\n\n<pre><code>t=$(echo $fn | sed -e '$s@.*[^0-9]\\([0-9]\\+\\.[0-9]\\+\\).*@\\1@g')\n</code></pre>\n\n<p>The above expression takes advantage of the fact that there has to be some non-digit character before the first date digit.</p>\n\n<p>But, as I say, it is my suggestion that you do the whole thing in Perl, and avoid having to do all the execs.</p>\n\n<hr>\n\n<p><strong>EDIT: In Perl</strong></p>\n\n<pre><code>#!/usr/bin/perl -w\n#\n#for cs in {47..52}; do\n# csdirnm=\"CASE$cs\";\n# tsdirnm=\"eta_at_x2\";\n# label='flow-time';\n# dir=\"$csdirnm/$tsdirnm/\";\n# files=$(ls -tr $dir); # -tr sort on time created, reversed (newest last).\n# i=0;\n# for f in $files ; do\n# fn=$dir$f;\n# if [[ $i = 0 ]]; then\n# data=\"$(sed -n 1p $fn) $label\";\n# ((i++));\n# fi\n# d=$(sed -n 2p $fn);\n# t=$(echo $fn | perl -pe 's|.*?(\\d+\\.\\d+)|\\1|');\n# data+=\"\\n$d $t\";\n# done;\n# echo -e \"$data\">\"$csdirnm/${csdirnm}_${tsdirnm}_20T.time-series\";\n#done;\n\nuse strict;\n\nforeach my $dirnum (47 .. 52) {\n my $csdirnm = \"CASE$dirnum\";\n print \"Processing Dir $csdirnm\\n\";\n my $tsdirnm = \"eta_at_x2\";\n # Use ls to get the file ordering right.\n my $subdir = \"$csdirnm/$tsdirnm\";\n next unless -d $subdir; #Skiip non-existant dirs\n open DIRLIST, \"-|\", \"ls -tr $subdir\" or die \"Unable to list files in $subdir\";\n my $outfile = \"${csdirnm}/${csdirnm}_${tsdirnm}_20T.time-series\";\n open REPORTFILE, \">\", $outfile or die \"Unable to write to report file $outfile\";\n\n my $file;\n my $cnt = 0;\n while ($file = <DIRLIST>) {\n chomp $file;\n print \"Processing $file\\n\";\n my $datafile = \"$subdir/$file\";\n open DATA, \"<\", $datafile or die \"Unable to read file $datafile\";\n my $line1 = <DATA>;\n my $line2 = <DATA>;\n close DATA;\n print REPORTFILE $line1 unless $cnt;\n print REPORTFILE $line2;\n $cnt++;\n }\n\n close DIRLIST;\n close REPORTFILE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:22:19.293",
"Id": "71463",
"Score": "0",
"body": "Re. perl/sed. on my searches to asseble the script, I came across [this comparison of perl/sed performance](http://nixtip.wordpress.com/2011/06/14/text-processing-performance-perl-vs-sed/), which indicates that the difference between the two is negligible. Is what you are referring to the 'initilization' if you will? His comparison is using a single call. This is also more in line with my hopes for improving this script. I.e. clever piping, cat'ing and whatnot (which I did try at first, but couldn't get to work with my limited XP)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:23:05.203",
"Id": "71464",
"Score": "0",
"body": "Re. rewriting completely in perl, I don't think that time saved would weigh up for starting over in yet a new language, that I have little to no knowledge of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:45:38.723",
"Id": "71465",
"Score": "0",
"body": "Why don't you try it... I have edited the answer...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T07:48:30.497",
"Id": "71596",
"Score": "1",
"body": "Thanks a lot! This is about an order of magnitude (10x) faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:53:10.357",
"Id": "71601",
"Score": "0",
"body": "You forgot the match time-step-in-file-name part. I managed to work it out myself. Was a very good starting point to have your draft to see how thing behave. I'll edit your answer with my modifications."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:24:27.553",
"Id": "41520",
"ParentId": "41508",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41520",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:15:28.880",
"Id": "41508",
"Score": "10",
"Tags": [
"optimization",
"performance",
"beginner",
"regex",
"bash"
],
"Title": "Locating matching files with input folder and file prefix"
}
|
41508
|
<p>Could this script be shortened?</p>
<pre><code>import random
def var():
strength = 10
skill = 10
dice4 = 0
dice12 = 0
dice_score = 0
character_name = ""
attr_list = [character_name, strength, skill]
character_name = str(input("Please enter your characters name: "))
skill_func(strength,skill,dice4,dice12,character_name,dice_score,attr_list)
def skill_func(strength,skill,dice4,dice12,character_name,dice_score,attr_list):
print(character_name + "'s attributes are being generated! ... ")
dice4, dice12 = random.randrange(1,4),random.randrange(1,12)
dice_score = dice12//dice4
skill+= dice_score
print("Skill: ", skill)
strength_func(strength,skill,dice4,dice12,character_name,dice_score,attr_list)
def strength_func(strength,skill,dice4,dice12,character_name,dice_score,attr_list):
dice4, dice12 = random.randrange(1,4),random.randrange(1,12)
dice_score = dice12//dice4
strength+= dice_score
print("Strength: ", strength)
file(attr_list, character_name)
def file(attr_list, character_name):
file = open("attributes.txt", "a")
file.write(character_name + " - Strength = " + str(attr_list[1]) + ", Skill = " + str(attr_list[2]) + "\n")
print("Your scores have been wrote to a file. ")
var()
</code></pre>
|
[] |
[
{
"body": "<p>You can start with multi-assignment: </p>\n\n<pre><code>strength = skill = 10\nstrength, skill = 10, 10\nstrength, skill = (10,10)\nstrength, skill = [10]*2\n</code></pre>\n\n<p>I prefer the first way as long as the thing you are assining is immutable / constant literal. If you are assigning two empty lists to two vars, and they need to be distinct, don't do the first way.</p>\n\n<p>Now ask yourself why do you need to repeat the random number generation and algebraic operations (addition and division) in <code>skill_func</code> and <code>strength_func</code>. I am not going to figure out the reason for you, but if they can be reused, then eliminate the repeated lines from <code>strength_func</code> since <code>skill_func</code> will call <code>strength_func</code>.</p>\n\n<p>If they have to be repeated, you can create another function called <code>get_dice_score</code> just to do the random number generation and return the <code>dice_score</code> so that <code>*_func</code> can call the new function. Example:</p>\n\n<pre><code>def skill_func(...):\n // do stuff\n dice_score = get_dice_score(...)\n\ndef strength_func(...):\n // do_stuff\n dice_score = get_dice_score(...)\n</code></pre>\n\n<p>Finally, both <code>strength_func</code> and <code>skill_func</code> are so similar. They have almost, if not, exactly the same function signature. They do almost the same thing. Can we combine them?</p>\n\n<p>Idea:</p>\n\n<pre><code>def skill_and_strength(strength, skill, ......):\n\n dice_score1 = get_dice_score(..)\n dice_score2 = get_dice_score(..)\n strength += dice_score1\n skill += dice_score2\n</code></pre>\n\n<p>This works as long as skill and strength don't depend on each other.</p>\n\n<p>Modularity only makes sense if they do distinct task. If they share most of the logic, you extract the common logic into separate function(s). If they call similar signature and they are usually used together, you can make a general function with the long signature and then \"dispatch\" to the more specific function.</p>\n\n<p>Idea (may not be applicable):</p>\n\n<pre><code>def say_stuff(function, text):\n return function(text)\n\ndef say_hello(name):\n print \"Hello, \" + name\n\ndef say_goodbye(name):\n print \"Goodbye, \" + name\n\ndef main():\n say_stuff(say_hello, \"John\")\n say_stuff(say_goodbye, \"Ben\")\n say_stuff(say_goodbye, \"Alice\")\n</code></pre>\n\n<p>This works because function and classes are objects! I pass the function object and inside <code>say_stuff</code> I invoke in callable manner. This is one way to dispatch.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:50:42.240",
"Id": "41513",
"ParentId": "41509",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:36:23.003",
"Id": "41509",
"Score": "4",
"Tags": [
"python",
"random",
"dice",
"battle-simulation"
],
"Title": "Dice game in Python"
}
|
41509
|
<p>I was asked in my textbook <em>Lectures on Discrete Mathematics for Computer Science</em> to construct a program that would take an alphabet (<code>{a,b,c}</code> or any combination of characters <code>{1,4,s,a}</code>) as well as a length value and calculate all possible combinations of this alphabet.</p>
<p>For example:</p>
<pre><code>char[] alphabet = new char[] {'a','b'};
possibleStrings(3, alphabet,"");
</code></pre>
<p>This will output:</p>
<pre><code>aaa
aab
aba
abb
baa
bab
bba
bbb
</code></pre>
<p>That is all combinations of the alphabet {a,b,c} with the string length set to 3.</p>
<p>The code I have written is functional, however I'd like to read what things I am doing wrong or could be doing better. The book didn't give an example program, so I only hope this is what it was looking for, but maybe there's a much better way to do it or way to improve how I'm doing it. Maybe this is fine, but I just need someone to look at it and tell me in that case.</p>
<pre><code>public class Program {
public static void main(String[] args) {
// Create an alphabet to work with
char[] alphabet = new char[] {'a','b'};
// Find all possible combinations of this alphabet in the string size of 3
StringExcersise.possibleStrings(3, alphabet,"");
}
} class StringExcersise {
public static void possibleStrings(int maxLength, char[] alphabet, String curr) {
// If the current string has reached it's maximum length
if(curr.length() == maxLength) {
System.out.println(curr);
// Else add each letter from the alphabet to new strings and process these new strings again
} else {
for(int i = 0; i < alphabet.length; i++) {
String oldCurr = curr;
curr += alphabet[i];
possibleStrings(maxLength,alphabet,curr);
curr = oldCurr;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>your code looks fine.</p>\n\n<ul>\n<li>a slight performance improvement i'd do is pass a StringBuilder instead of a String - a String in java is immutable so every time you call <code>curr += alphabet[i]</code> youre actually allocating a new String object. instead you could append the character to a StringBuilder (and delete the last character when you leave) to save on the number of Objects created during the run</li>\n<li><code>for(int i = 0; i < alphabet.length; i++) {}</code> could be re-written as a more modern loop: <code>for (char c : alphabet) {}</code>, which would make for a more readable result</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:39:14.513",
"Id": "71340",
"Score": "0",
"body": "I believe compiler optimization would convert String into StringBuilder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:40:41.220",
"Id": "71341",
"Score": "1",
"body": "@Vinay - if it was a straight-up long list of \"+\" ops youre right. im not so certain in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T14:23:38.637",
"Id": "71786",
"Score": "0",
"body": "@Vinay I doubt it too in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-05T12:32:32.397",
"Id": "302953",
"Score": "0",
"body": "Depends on the implementation of the compiler, Some wouldn't convert for Java"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:43:48.867",
"Id": "416874",
"Score": "0",
"body": "Can you suggest changes if repetition of characters is not allowed"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:36:44.857",
"Id": "41511",
"ParentId": "41510",
"Score": "4"
}
},
{
"body": "<p>Instead of the oldCurr stuff, just create a newCurr each time. e.g.</p>\n\n<pre><code>String newCurr = curr + alphabet[i];\npossibleStrings(maxLength, alphabet, newCurr);\n</code></pre>\n\n<p>Would be shorter and, at least to my eyes, is much clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:26:40.167",
"Id": "71342",
"Score": "0",
"body": "Thanks, this was also very helpful. I've never thought about it like that. Cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T17:47:46.543",
"Id": "117224",
"Score": "0",
"body": "That would cause it to create TWO new strings each time it runs: `newCurr` and `curr + alphabet[i]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-16T16:51:09.460",
"Id": "157326",
"Score": "0",
"body": "@Manny Meng First, it only creates one new String, newCurr. Second, because Strings are immutable, _you can't avoid this_. In the OP's code `curr += alphabet[i]` _also creates a new String_. So your comment and downvote are incorrect. Finally even if one extra object were created, in this example nobody cares, it's only like 10 extra objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-16T22:58:19.400",
"Id": "157423",
"Score": "0",
"body": "Good first point, but for the second point, `curr += alphabet[i]` can easily be solved using a `StringBuilder`, as the accepted answer suggested. Also, 10 extra objects is a lot if you run this thousands or millions of times. For example, if the most optimized (i.e. no extra objects) method runs in, lets say, 10 milliseconds, and the other one takes 11 milliseconds, that's a 1,000 to 1,000,000 millisecond difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-17T03:41:32.663",
"Id": "157446",
"Score": "0",
"body": "The StringBuilder will eventually be accessed via`toString()`, creating an Object. Nowhere does OP suggest that this will be called thousands of times, let alone thousands of millions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-17T22:28:36.660",
"Id": "157670",
"Score": "0",
"body": "It might be called multiple times, and sometimes the small time difference is vital. And one object is better that 10."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:51:56.957",
"Id": "41512",
"ParentId": "41510",
"Score": "-1"
}
},
{
"body": "<p>If the sequence is quite large then recursive methods can use up too much memory. This iterative approach works quite well.</p>\n\n<pre><code>private void generateCombinations(int arraySize, ArrayList<String> possibleValues)\n{\n int carry;\n int[] indices = new int[arraySize];\n do\n {\n for(int index : indices)\n System.out.print(possibleValues.get(index) + \" \");\n System.out.println(\"\");\n\n carry = 1;\n for(int i = indices.length - 1; i >= 0; i--)\n {\n if(carry == 0)\n break;\n\n indices[i] += carry;\n carry = 0;\n\n if(indices[i] == possibleValues.size())\n {\n carry = 1;\n indices[i] = 0;\n }\n }\n }\n while(carry != 1); // Call this method iteratively until a carry is left over\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T11:42:21.977",
"Id": "504945",
"Score": "0",
"body": "Throwing wrong response. Try with 3 character"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T08:31:28.080",
"Id": "51121",
"ParentId": "41510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:32:12.227",
"Id": "41510",
"Score": "6",
"Tags": [
"java",
"strings",
"combinatorics"
],
"Title": "Calculate all possible combinations of given characters"
}
|
41510
|
<p>I have a long set of IF statements that basically set a null object Value to <code>0</code>, I feel that because i am doing the same action each time their has to be a simple way to make this allot shorter. It just looks like something I wouldn't normally see in code.</p>
<p>My code looks like this:</p>
<pre><code>if ($data->sl1 === NULL){ $data->sl1 = "0";}
if ($data->sl2 === NULL){ $data->sl2 = "0";}
if ($data->sl3 === NULL){ $data->sl3 = "0";}
if ($data->sl4 === NULL){ $data->sl4 = "0";}
if ($data->sl5 === NULL){ $data->sl5 = "0";}
if ($data->sl6 === NULL){ $data->sl6 = "0";}
if ($data->sl7 === NULL){ $data->sl7 = "0";}
if ($data->sl8 === NULL){ $data->sl8 = "0";}
if ($data->sl9 === NULL){ $data->sl9 = "0";}
if ($data->sl10 === NULL){ $data->sl10 = "0";}
if ($data->sl11 === NULL){ $data->sl11 = "0";}
if ($data->sl12 === NULL){ $data->sl12 = "0";}
if ($data->sn1 === NULL){ $data->sn1 = "0";}
if ($data->sn2 === NULL){ $data->sn2 = "0";}
if ($data->sn3 === NULL){ $data->sn3 = "0";}
if ($data->sn4 === NULL){ $data->sn4 = "0";}
if ($data->sn5 === NULL){ $data->sn5 = "0";}
if ($data->sn6 === NULL){ $data->sn6 = "0";}
if ($data->sn7 === NULL){ $data->sn7 = "0";}
if ($data->sn8 === NULL){ $data->sn8 = "0";}
if ($data->sn9 === NULL){ $data->sn9 = "0";}
if ($data->sn10 === NULL){ $data->sn10 = "0";}
if ($data->sn11 === NULL){ $data->sn11 = "0";}
if ($data->sn12 === NULL){ $data->sn12 = "0";}
if ($data->sr1 === NULL){ $data->sr1 = "0";}
if ($data->sr2 === NULL){ $data->sr2 = "0";}
if ($data->sr3 === NULL){ $data->sr3 = "0";}
if ($data->sr4 === NULL){ $data->sr4 = "0";}
if ($data->sr5 === NULL){ $data->sr5 = "0";}
if ($data->sr6 === NULL){ $data->sr6 = "0";}
if ($data->sr7 === NULL){ $data->sr7 = "0";}
if ($data->sr8 === NULL){ $data->sr8 = "0";}
if ($data->sr9 === NULL){ $data->sr9 = "0";}
if ($data->sr10 === NULL){ $data->sr10 = "0";}
if ($data->sr11 === NULL){ $data->sr11 = "0";}
if ($data->sr12 === NULL){ $data->sr12 = "0";}
</code></pre>
<p>One way I know could work would simply be to iterate through the entire object with a simple <code>foreach</code> like this:</p>
<pre><code>foreach ($data as $item) {
if ($item === NULL){ $item = "0";}
}
</code></pre>
<p>But let's say I don't want to change every single null object to <code>0</code>. Do I have any other option?</p>
<p>I am using PHP in my example, but I am curious to hear answers for other languages as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:03:39.923",
"Id": "71346",
"Score": "0",
"body": "So there are some conditions? A subset of lists matching certain conditions? It's hard to make one up with no background."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:05:29.520",
"Id": "96295",
"Score": "0",
"body": "The variable names could be a little more descriptive, but take a look at [get_object_vars](http://us3.php.net/get_object_vars)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:06:47.600",
"Id": "96296",
"Score": "0",
"body": "I wish they could be, but these are names from a parsed CSV provided by our client, my current solution is fine for them, but i am curious for future projects if i can do this in a quicker way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:08:29.250",
"Id": "96297",
"Score": "0",
"body": "I might be wrong but it seems get_object_vars still iterates through the entire object doesn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:11:18.993",
"Id": "96298",
"Score": "0",
"body": "It does - it gives you all of the public members in an array. You can take the result and loop over it. C# gives similar functionality through reflection, but has the advantage of being strongly typed (so you can check what type of parameter it is)."
}
] |
[
{
"body": "<p>In short, the CSV parser is using the wrong data types. Whenever you have contiguous variable names, it screams \"use an array!\" If you at all, possibly can, use an array. That allows you to operate on it much, much more naturally, it's more flexible, and it's way less prone to human error.</p>\n\n<hr>\n\n<p>If you used an array, this would be much, much simpler:</p>\n\n<pre><code>foreach ($this->sl as $k => $sl) {\n $this->sl = ($sl === null) ? \"0\" : $sl;\n}\n</code></pre>\n\n<hr>\n\n<p>Since you seemingly can't use an array, your best bet is probably to either process it into an array, or use some nasty variable-variable hackiness to pretend it's an array.</p>\n\n<pre><code>$sl = array();\nfor ($i = 1; isset($this->{'sl' . $i}; ++$i) {\n $sl[] = $this->{'sl' . $i};\n}\n</code></pre>\n\n<hr>\n\n<p>Or if (for some reason) you don't want to use an array:</p>\n\n<pre><code>for ($i = 1; isset($this->{'sl' . $i}; ++$i) {\n $this->{'sl' . $i} = ($this->{'sl' . $i} === null) ? \"0\" : $this->{'sl' . $i};\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:16:49.700",
"Id": "71352",
"Score": "0",
"body": "The reason i can't use an array is because each item (ss1 ss2 ss3) is a unique column in the database, so each one is returned separately. I agree the names are very stupid, but the mutual fund we are working with prefers to use a shorthand to represent their data like that. How ever your last solution would indeed work, i hadn't thought to treat the object name as a string like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:18:35.020",
"Id": "71353",
"Score": "2",
"body": "@AndrewFont You could always unpack the array back into columns. That is an unfortunate situation though. It sounds like it's likely badly normalized database. I'm sure that's completely unchangeable though :/."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:18:38.863",
"Id": "71354",
"Score": "0",
"body": "Also i made that terrible parser =(, but i was forced to feed the data to the specific columns in the database, so i was not able to change the naming scheme for them, so i chopped it up and saved each piece of information where it needed to go"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:20:14.420",
"Id": "71355",
"Score": "0",
"body": "Yea this project was kind of a data nightmare because everything had strange shorthand names and the database schema for each and every CSV i had to parse was made by a different developer then the last."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:09:48.907",
"Id": "41516",
"ParentId": "41514",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41516",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T22:51:23.070",
"Id": "41514",
"Score": "4",
"Tags": [
"php",
"iteration"
],
"Title": "Is there a way to shorten a set of conditionals like this?"
}
|
41514
|
<p>I have a bit of trouble simplifying the binary search code. This is different from the traditional binary search because we effectively want to find the location for which <code>A[j]</code> is the least element larger than the current unsorted value.</p>
<p>Thoughts?</p>
<pre><code>def binary_search(A, value, start, end):
# we need to distinugish whether we should insert
# before or after the left boundary.
# imagine [0] is the last step of the binary search
# and we need to decide where to insert -1
if start == end:
if A[start] > value:
return start
else:
return start+1
# this occurs if we are moving beyond left's boundary
# meaning the left boundary is the least position to
# find a number greater than value
if start > end:
return start
mid = (start+end)/2
if A[mid] < value:
return binary_search(A, value, mid+1, end)
elif A[mid] > value:
return binary_search(A, value, start, mid-1)
else:
return mid
def insertion_sort(A):
for i in xrange(1, len(A)):
value = A[i]
j = binary_search(A, value, 0, i-1)
A = A[:j] + [value] + A[j:i] + A[i+1:]
return A
print insertion_sort([0,1,-1])
print insertion_sort([0,1,2,3,9,-1])
print insertion_sort([1,2,3,4,5,6,7,8,11,10,0])
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>binary_search</code> is the same as the built-in function <a href=\"http://docs.python.org/3/library/bisect.html#bisect.bisect\" rel=\"nofollow\"><code>bisect.bisect</code></a>, and you might find <a href=\"http://hg.python.org/cpython/file/1166b3321012/Lib/bisect.py#l24\" rel=\"nofollow\">the implementation</a> helpful to study.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:34:48.327",
"Id": "71505",
"Score": "0",
"body": "Thanks. I always knew bisect has the binary search, didn't think of checking it out first. Thanks though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:28:54.550",
"Id": "41592",
"ParentId": "41517",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:14:57.817",
"Id": "41517",
"Score": "3",
"Tags": [
"python",
"algorithm",
"sorting",
"insertion-sort"
],
"Title": "Insertion sort with binary search in Python"
}
|
41517
|
<p>A little background first - I'm working on a server application that requires the ability to use multiple data access class libraries based on the resources available on the server it is installed on (MySQL, SQL Server, XML, etc.). The are currently implemented as modular plugins, where the executable is paired with the appropriate class library on the server and interacts with it through a defined interface (IDataAccess).</p>
<p>The following code is the constructor for a singleton class on the server that exposes the backend:</p>
<pre><code>private IDataAccess mDB;
private MudData()
{
List<String> files = new List<String>(Directory.GetFiles(".", "*.dll"));
List<Type> accessors = new List<Type>();
foreach (String file in files)
{
try
{
Assembly test = Assembly.UnsafeLoadFrom(file);
System.Type[] types = test.GetTypes();
//See if any of the located types implement IDataAccess.
foreach (System.Type candidate in types)
{
if (candidate.GetInterface("IDataAccess") != null)
{
accessors.Add(candidate);
}
}
}
catch
{
//Eat this on purpose - still need to check the rest of the matches.
}
}
if (accessors.Count == 0)
{
throw new ApplicationException("No supported data access .dll was found.");
}
//TODO: Select from multiples if found, but for now just take the first match.
PropertyInfo target = accessors.First().GetProperty("Instance");
MethodInfo getter = target.GetGetMethod();
//Create a delegate for the reflected assembly so any exceptions propagate correctly.
Func<IDataAccess> dataDelegate = (Func<IDataAccess>)Delegate.CreateDelegate(typeof(Func<IDataAccess>), null, getter);
Object found = dataDelegate();
if (found != null)
{
mDB = (IDataAccess)found;
}
else
{
throw new ApplicationException("Attempt to load an instance of IDataAccess failed.");
}
}
</code></pre>
<p>Any exceptions at this point will be fatal, and are trapped and logged in the calling code before a (hopefully) graceful exit. This code is only called once at startup and the object it obtains isn't released until the application exits. I've been having a hard time finding information about the performance implications of using an object reference obtained this way, so I'd especially welcome comments from that direction. My assumption is that the main performance penalty is in obtaining the reference, but I haven't been able to find out whether or not that is true in practice.</p>
<p>I'm mainly looking for feedback on my method of connecting with the back-end, but am certainly open to comments/criticism of code style, practices, etc. </p>
<p>Thoughts?</p>
|
[] |
[
{
"body": "<p>You're loading every DLL in the directory even if you find what you want in the first one.</p>\n\n<p>I'd guess that loading an assembly is what takes more time and resources than looking for what you want in the assembly-after-it's-loaded.</p>\n\n<p>You code will fail if there's a type which implements IDataAccess but which doesn't have an Instance property.</p>\n\n<p>You might want to load into a different <a href=\"https://stackoverflow.com/a/574711/49942\">AppDomain</a> if you want to <a href=\"http://blogs.msdn.com/b/jasonz/archive/2004/05/31/145105.aspx\" rel=\"nofollow noreferrer\">unload the assembly</a> which you loaded.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:37:00.677",
"Id": "71372",
"Score": "0",
"body": "Yeah, the Instance property is something I've been trying to sort out. I can't add it to the interface because it is meant to be static in the implementation. I'm loading everything currently because the original intent of allowing the targeted library to change at run-time. This has since gone *way* down on the priority list. Thanks for the heads up on AppDomain. I hadn't looked into it too far but I think you're probably right, especially once I get to the point of allowing run-time changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:43:46.600",
"Id": "71373",
"Score": "0",
"body": "A slightly better algrithm might be: foreach file { load assembly; foreach type which implements IDataAccess { if type has a public Instance property { hope we found the right instance } else look for another type, else look for another assembly. A more deterministic method might be to use a config file which names the DLL and the desired type within the DLL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T04:10:39.303",
"Id": "71382",
"Score": "0",
"body": "That blog post about unloading assemblies is from 2004... before even .NET 2. I wonder if anything has changed that could make unloading assemblies easier or more difficult to implement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:18:13.170",
"Id": "41526",
"ParentId": "41524",
"Score": "10"
}
},
{
"body": "<blockquote>\n<p><em>Any exceptions at this point will be fatal, and are trapped and logged in the calling code before a (hopefully) graceful exit.</em></p>\n</blockquote>\n<p>I think you have a use case for a custom exception type here. Throwing <code>System.ApplicationException</code> isn't much better than throwing <code>System.Exception</code> directly. It's actually a relic from the early days of .net; <code>System.ApplicationException</code> was originally intended to be the <em>base class</em> for all custom exceptions (i.e. not thrown directly).</p>\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.applicationexception(v=vs.110).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n<blockquote>\n<h2>ApplicationException Class</h2>\n<p>The exception that is thrown when a non-fatal application error occurs.</p>\n<h3>Remarks</h3>\n<p>If you are designing an application that needs to create its own exceptions, you should derive custom exceptions from the <code>Exception</code> class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.</p>\n</blockquote>\n<p>Thus, I find this:</p>\n<pre><code>throw new ApplicationException("No supported data access .dll was found.");\n</code></pre>\n<p>Could be replaced with something like this:</p>\n<pre><code>throw new DataAccessLibraryNotFoundException();\n</code></pre>\n<p>And this:</p>\n<pre><code>throw new ApplicationException("Attempt to load an instance of IDataAccess failed.");\n</code></pre>\n<p>Could be replaced with something like this:</p>\n<pre><code>throw new DataAccessLibraryLoadException();\n</code></pre>\n<p>Also I'm not sure I'd "eat" an exception thrown from the loop. At least keep a trace-level log entry for it, so you have a trace of what the application tried to do. Logging frameworks such as NLog allow you to configure a logger's minimum level without redeploying the app, so your code can log at <code>TRACE</code> level, and then you can deploy and configure the logger's minimum level to, say, <code>DEBUG</code> or <code>INFO</code>, so <code>TRACE</code> entries wouldn't be actually logged. But your code wouldn't be swallowing exceptions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T02:41:47.243",
"Id": "71381",
"Score": "0",
"body": "Both valid points, thanks. Custom exception types have always been something that I tell myself I'll implement but never get around to doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:08:50.147",
"Id": "71418",
"Score": "0",
"body": "@Comintern When debugging ASP.NET I can't set it to break into the debugger when an exception is thrown-and-caught. So I have a single `MyException` class which I use for all exceptions I throw, and I put a break point on the `MyException` constructor. Thus having even one custom exception type might be more useful than none."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T02:27:17.687",
"Id": "41528",
"ParentId": "41524",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41526",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T00:59:37.867",
"Id": "41524",
"Score": "6",
"Tags": [
"c#",
"reflection"
],
"Title": "Using reflection to connect to an arbitrary backend"
}
|
41524
|
<p>I am writing small roguelike game where I spawn some items and put them into the <code>std::list</code>. Is this the right way to do it?</p>
<p>The <code>Item</code> class is as followed (I know it has public <code>id</code> property):</p>
<pre><code>class Item {
public:
Item();
~Item();
unsigned int id;
};
</code></pre>
<p>Somewhere in the code I also defined:</p>
<pre><code>list<Item*> listOfItems;
list<Item*>::iterator it;
</code></pre>
<p>Now I am using this code to create an item:</p>
<pre><code>Item *p = new Item();
p->id = itemCrowbar;
listOfItems.push_back(p);
</code></pre>
<p>At the end of the program I use small loop to delete all items:</p>
<pre><code>for (it = listOfItems.begin(); it!=listOfItems.end(); it++) {
delete *it;
}
</code></pre>
<p>Is this approach for creating objects, putting them in <code>std::list</code> and
at the end deleting them correct, or am I missing something important here?</p>
|
[] |
[
{
"body": "<p>If <code>Item</code> has subclasses, then make the <code>~Item()</code> destructor virtual.</p>\n\n<p>If <code>Item</code> has a copy constructor, and is not a superclass of a subclass, then you can store a copy of the item (not pointer to the item) in the list:</p>\n\n<pre><code>list<Item> listOfItems;\n\nItem item;\nitem.id = itemCrowbar;\nlistOfItems.push_back(item);\n</code></pre>\n\n<p>In that case, you won't need to delete <code>Item</code> pointers before the list is destroyed.</p>\n\n<p>However, if <code>Item</code> has subclasses, then this might be legal but a bug (called '<a href=\"http://en.wikipedia.org/wiki/Object_slicing\" rel=\"nofollow\">object slicing</a>'):</p>\n\n<pre><code>list<Item> listOfItems;\n\nSubclassOfItem item;\nitem.id = itemCrowbar;\nitem.extra = \"hello\";\nlistOfItems.push_back(item);\n</code></pre>\n\n<p>Or you can create a list of 'smart pointers' (<code>std::unique_ptr</code>) to items: which behave like pointers to <code>Item</code>s except that you don't need to delete the <code>Item</code> (the <code>Item</code> is deleted when the smart pointer which contains it is destroyed).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:49:17.963",
"Id": "71374",
"Score": "4",
"body": "Never, ever store `std::auto_ptr` in a container. Further, `auto_ptr` is deprecated, so it shouldn't be used anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:52:08.867",
"Id": "71375",
"Score": "0",
"body": "@Yuushi Not even in a std::list? I imagined that list nodes would be immobile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:53:48.870",
"Id": "71377",
"Score": "1",
"body": "\"Copying an auto_ptr copies the pointer and transfers ownership to the destination: both copy construction and copy assignment of auto_ptr modify their right hand arguments, and the \"copy\" is not equal to the original. Because of these unusual copy semantics, auto_ptr may not be placed in standard containers.\" See [here](http://en.cppreference.com/w/cpp/memory/auto_ptr)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T02:22:13.357",
"Id": "71379",
"Score": "0",
"body": "Item will have subclasses and won't have any copy constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:04:31.933",
"Id": "71417",
"Score": "0",
"body": "@MichalPrzybylowicz Even without a copy-constructor there might (in modern C++) be a [move constructor](http://en.cppreference.com/w/cpp/language/move_constructor); but if there are several subclasses then you're right that you need to store by pointer, not by value. **Don't forget to make your destructor virtual**. And consider using a mart pointer to avoid the need to do explicit destruction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:47:03.423",
"Id": "71421",
"Score": "0",
"body": "@ChrisW is \"shared_ptr\" ok for this job ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:52:55.527",
"Id": "71500",
"Score": "0",
"body": "personally I prefer `pointer container` over a `container of pointers`. The difference is the data is exposed as reference to objects rather than pointers to objects. This makes using the standard algorithms easier. But the advent of lambdas has made this argument slightly (though not entirely) moot. See [boost::ptr_list](http://www.boost.org/doc/libs/1_55_0/libs/ptr_container/doc/ptr_list.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:58:23.590",
"Id": "71625",
"Score": "0",
"body": "I have created some small piece of code with shared_ptr and list (I am not sure if it's correct although its working fine) should I post it here of make a new *question* similar to this one for review ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:07:45.873",
"Id": "71631",
"Score": "0",
"body": "@MichalPrzybylowicz Please post a follow-up question: see [How to post a follow-up question?](http://meta.codereview.stackexchange.com/a/1066/34757)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:31:06.430",
"Id": "41527",
"ParentId": "41525",
"Score": "6"
}
},
{
"body": "<p>No, it is not correct.</p>\n\n<p>For such classes, you should do not need to create objects on the heap. This should do :</p>\n\n<pre><code>Item p;\np.id = itemCrowbar;\nlistOfItems.push_back(p);\n</code></pre>\n\n<p>If you add a constructor with a parameter like this ...</p>\n\n<pre><code>class Item {\n\npublic:\n Item(unsigned int id_):id(id_){}\n\n unsigned int id;\n};\n</code></pre>\n\n<p>... then you could even do this :</p>\n\n<pre><code>int main()\n{\n std::list<Item> items;\n\n unsigned int someId = 5;\n\n items.push_back( {someId} );\n}\n</code></pre>\n\n<p>This way you do not have to wory about memory leaks, and you can remove the loop releasing created objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:04:34.257",
"Id": "41545",
"ParentId": "41525",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "41527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T01:00:47.813",
"Id": "41525",
"Score": "7",
"Tags": [
"c++"
],
"Title": "Creating objects and putting them into std::list"
}
|
41525
|
<p>A little disclaimer: you're going to have a field day with this. It's horrible. Looking at it makes me want to vomit, and don't ask me to explain it, because I've long forgotten what I was thinking when I wrote it. That being said, I can't really find a way to shorten it of make it make sense. Perhaps someone could help me out?</p>
<p>A bit of a background:</p>
<p>This program is meant to install mods for a game called Supreme Commander 2. It is meant to install ANY mod. The following is true of all the mods:</p>
<ul>
<li>The only archive type is the <code>.scd</code>. SCD's have the same encoding as <code>.zip</code>'s, but with a 0% compression rate.</li>
<li><p>The way to install the mod is simple: There will always be at least one scd inside the first, and there may be more scd's inside that one. Any scd with folders inside it should be moved to</p>
<blockquote>
<p>C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata</p>
</blockquote>
<p>There may be more than one scd to be moved per mod.</p></li>
</ul>
<p>And that's it. This is something of a "programming challenge," but I am really looking for improvements upon the following code:</p>
<pre><code>import os, zipfile
def installfromdownload(filename):
global scdlist
targetfolder = r"C:\Program Files (x86)\Mod Manager\Mods\f_" + filename[:-4]
lentf = len(targetfolder)
unzip(r"C:\Program Files (x86)\Mod Manager\Mods\z_" + filename + ".scd", targetfolder)
if checkdirs(targetfolder) == False:
os.system("copy C:\Program Files (x86)\Mod Manager\Mods\z_" + filename + ".scd" " C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata")
else:
newfolderonelist = []
getscds(targetfolder)
for file in scdlist:
newfolderone = targetfolder + "\f_" + file[:-4]
filepath = targetfolder + "\\" + file
unzip(filepath, newfolderone)
newfolderonelist.append(newfolderone)
for newfolders in newfolderonelist:
if os.checkdirs(newfolders) == False:
newfolders = newfolders[lentf + 1:]
for scds in scdlist:
if newfolder in scds == True:
scdpath = targetfolder + "\\" + scds
os.system("copy " + scdpath + " C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata")
</code></pre>
<p>Note that there is no error handling here, that is done when I call the function. The function <code>unzip()</code> is here:</p>
<pre><code>def unzip(file, target):
modscd = zipfile.ZipFile(file)
makepath(target)
modscd.extractall(target)
</code></pre>
<p>The function <code>checkdirs()</code> is here (note this is pretty bad, it only checks for periods in the file name, so please submit suggestions):</p>
<pre><code>def checkdirs(target):
isfile = 0
targetlist = os.listdir(target)
for files in targetlist:
for letters in files:
if letters == ".":
isfile = isfile + 1
if isfile == len(os.listdir(target)):
return False
else:
return True
</code></pre>
<p>The <code>getscds()</code> function just checks a filename for ".scd".</p>
|
[] |
[
{
"body": "<p>Firstly, your <code>installfromdownload</code> function should be <code>install_from_download</code> (and have a docstring to go with it explaining what it does).</p>\n\n<p>This line:</p>\n\n<pre><code>targetfolder = r\"C:\\Program Files (x86)\\Mod Manager\\Mods\\f_\" + filename[:-4]\n</code></pre>\n\n<p>should probably check and make sure that the file actually ends with <code>.zip</code> (or whatever format you're actually expecting it to come in):</p>\n\n<pre><code>if filename.endswith('.zip'):\n target_folder = ...\n</code></pre>\n\n<p>Something doesn't seem quite right with:</p>\n\n<pre><code>unzip(r\"C:\\Program Files (x86)\\Mod Manager\\Mods\\z_\" + filename + \".scd\", targetfolder)\n</code></pre>\n\n<p>You're stripping the last 4 characters off filename before, and here you're appending '.scd'. I assumed you were stripping <code>.scd</code> off above, but then realized you're unzipping it, so it's actually a <code>.zip</code> (or something like that). Either way, it's confusing and something like:</p>\n\n<pre><code>target_folder = r\"...\" + filename.split('.zip')[0] \n</code></pre>\n\n<p>would make it much more clear what you're actually doing (commenting would help a bit too).</p>\n\n<p>Don't explicitly check against <code>False</code>:</p>\n\n<pre><code>if checkdirs(targetfolder) == False:\n</code></pre>\n\n<p>This should be:</p>\n\n<pre><code>if not checkdirs(targetfolder):\n</code></pre>\n\n<p>Don't join paths together with \"\\\\\" (which is OS specific anyway):</p>\n\n<pre><code> filepath = targetfolder + \"\\\\\" + file\n</code></pre>\n\n<p>Use <code>os.path.join</code> instead:</p>\n\n<pre><code> filepath = os.path.join(target_folder, file)\n</code></pre>\n\n<p>Some of the variable names here make your code really, really hard to follow (<code>newfolderonelist</code>, <code>newfolderone</code>). </p>\n\n<p>This line should make your script crash:</p>\n\n<pre><code>if os.checkdirs(newfolders) == False:\n</code></pre>\n\n<p>As you're trying to call your <code>checkdirs</code> function (<code>os.checkdirs</code> doesn't exist).</p>\n\n<p>Let's look at the <code>checkdirs</code> function:</p>\n\n<pre><code>def checkdirs(target):\n isfile = 0\n targetlist = os.listdir(target)\n for files in targetlist:\n for letters in files:\n if letters == \".\":\n isfile = isfile + 1\nif isfile == len(os.listdir(target)):\n return False\nelse:\n return True\n</code></pre>\n\n<p>Again following Python naming convention, this should be <code>check_dirs</code> (although the name needs a lot of work - what's it checking them for?). Further, a lot of the work here can replaced with <code>os.path.isfile</code>. From reading it, it looks like you're checking that everything in a given directory is not a file, so I'm going to call it <code>not_all_files</code>:</p>\n\n<pre><code>def not_all_files(directory):\n '''Checks the given directory, returning False if it contains only files,\n and True otherwise. If the argument given is not a directory, \n raises IOError.\n '''\n\n if not os.path.isdir(directory)\n # Oops, passed in something that wasn't a directory\n # Handle this error\n raise IOError('....')\n return not all((os.path.isfile(f) for f in os.listdir(directory)))\n</code></pre>\n\n<p>Given how you're using it above, I'd rather swap around what it returns: have it return <code>True</code> if everything in the directory is a file, <code>False</code> otherwise. This would then be:</p>\n\n<pre><code>def all_files(directory):\n '''Checks the given directory, returning True if it contains only files,\n and False otherwise. If the argument given is not a directory, \n raises IOError.\n '''\n\n if not os.path.isdir(directory)\n # Oops, passed in something that wasn't a directory\n # Handle this error\n raise IOError('....')\n return all((os.path.isfile(f) for f in os.listdir(directory)))\n</code></pre>\n\n<p>Your code in <code>install_from_download</code> would then become:</p>\n\n<pre><code> if all_files(target_folder):\n</code></pre>\n\n<p>which I think is much easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:49:07.403",
"Id": "71520",
"Score": "0",
"body": "OK, some good stuff here. Thanks for taking the time you obviously took on this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:51:59.767",
"Id": "74779",
"Score": "0",
"body": "Ah, also, `.scd` uses the same encoding as `.zip`, but has no compression. Just FYI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:24:29.387",
"Id": "75675",
"Score": "0",
"body": "And now, having just re-read my question and seen that I already said that, I feel like an idiot ;)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T04:58:13.743",
"Id": "41533",
"ParentId": "41531",
"Score": "13"
}
},
{
"body": "<p>In addition to Yuushi's answer, I notice is that you're using <code>os.system</code> for copying files. This is insecure and unnecessary. If all you need to do is copy a file, use <a href=\"http://docs.python.org/3/library/shutil.html#shutil.copy\"><code>shutil.copy</code></a>.</p>\n\n<p>Translated, a bit of your code might look like this:</p>\n\n<pre><code># assuming shutil is imported\nshutil.copy(r\"C:\\Program Files (x86)\\Mod Manager\\Mods\\z_\" + filename + \".scd\",\n r\"C:\\Program Files (x86)\\Steam\\steamapps\\common\\supreme commander 2\\gamedata\")\n</code></pre>\n\n<p>Of course, you'd then want to change that code to use <code>os.path.join</code>, as suggested in Yuushi's answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:43:46.857",
"Id": "71458",
"Score": "0",
"body": "[`shutil.copytree`](http://docs.python.org/3/library/shutil.html#shutil.copytree) might be useful in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:47:31.400",
"Id": "71519",
"Score": "0",
"body": "Huh. I actually made an installer for this manager that uses that function, and thought I had modified this one too. Thanks for the tip."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T05:12:37.497",
"Id": "41534",
"ParentId": "41531",
"Score": "8"
}
},
{
"body": "<p>Your main function is hard to follow, but it seems to repeat its logic with subfolders. Generally something like that should be implemented as a recursive function. In pseudo-code, the basic structure of the recursive function would be:</p>\n\n<pre><code>def copy_scds(scd, target_folder):\n unzip scd to target_folder\n\n if target_folder has scds:\n for each inner_scd:\n subfolder = new folder under target_folder\n copy_scds(inner_scd, subfolder)\n else:\n copy scd to gamedata\n</code></pre>\n\n<p>As you can see, the unzip and copy parts are only written once, as opposed to repeated in nested for loops. The additional scds and subfolders are simply passed in as new arguments for <code>scd</code> and <code>target_folder</code>.</p>\n\n<p>The main function then only needs to determine the initial \"root\" <code>scd</code> and <code>target_folder</code> and begin the process:</p>\n\n<pre><code>def install(filename):\n scd = r\"C:\\Program Files (x86)\\Mod Manager\\Mods\\z_\" + filename + \".scd\"\n target_folder = r\"C:\\Program Files (x86)\\Mod Manager\\Mods\\f_\" + filename[:-4]\n\n copy_scds(scd, target_folder)\n</code></pre>\n\n<p>My only other suggestion other than what was given in the other answers is to store the paths to make them more easily configurable and eliminate repetition in the code. For example:</p>\n\n<pre><code>mods_folder = r\"C:\\Program Files (x86)\\Mod Manager\\Mods\"\nzip_prefix = \"z_\"\noutput_prefix = \"f_\"\ngamedata_folder = r\"C:\\Program Files (x86)\\Steam\\steamapps\\common\\supreme commander 2\\gamedata\"\n</code></pre>\n\n<p>In fact, it may be possible to completely remove the need to configure the game folder. Steam knows how to launch any game based only on a <a href=\"https://developer.valvesoftware.com/wiki/Steam_Application_IDs\">unique AppID</a>, so theoretically there must be some way to determine the path automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:46:25.083",
"Id": "71518",
"Score": "0",
"body": "Beautiful. This is wonderful, no convoluted code to desperately try to shave off a couple lines. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:59:50.090",
"Id": "41558",
"ParentId": "41531",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41558",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T04:11:49.337",
"Id": "41531",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"installer"
],
"Title": "Installing \"mods\" with Python"
}
|
41531
|
<p>I've written the following code, but I need some review on design style. I want to develop a library/module and expose an API to client programs. How do I do that?</p>
<p>The code just runs a TCP server listening for incoming messages and another thread accepting user input to send messages. </p>
<pre><code>from socket import AF_INET, SOCK_DGRAM
import sys;
import socket;
import select;
import thread;
import pickle;
import struct;
import time;
import threading;
class AgTime:
lClock=0;
pClock=0;
count=0;
#NTP client object that queries NTP server for time.
class Ntp:
def __init__(self):
# # Set the socket parameters
self.host = "pool.ntp.org"
self.port = 123
self.buf = 1024
self.address = (self.host,self.port)
self.msg = '\x1b'+47*'\0'
# reference time (in seconds since 1900-01-01 00:00:00)
self.TIME1970 = 2208988800 # 1970-01-01 00:00:00
def time(self):
# connect to server
client = socket.socket( AF_INET, SOCK_DGRAM)
client.sendto(self.msg, self.address)
data, address = client.recvfrom( self.buf )
retval=struct.unpack("!12I",data);
t = retval[10]
t -= self.TIME1970
return t;
class server(threading.Thread):
def __init__(self,portNo):
threading.Thread.__init__(self);
self.PORTNO=portNo;
self.server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
self.server_socket.bind(("",self.PORTNO));
self.CONNECTION_LIST=[];
self.RECV_BUFFER=4096;
def run(self):
self.server_socket.listen(10);
self.CONNECTION_LIST.append(self.server_socket);
print "Server started on port :"+str(self.PORTNO);
while(1):
read_sockets,write_sockets,error_sockets=select.select(self.CONNECTION_LIST,[],[]);
for sock in read_sockets:
if sock==self.server_socket:
sockfd, addr= self.server_socket.accept();
self.CONNECTION_LIST.append(sockfd);
print "Message rxd from (%s %s)",addr
else:
try:
data=pickle.loads(sock.recv(self.RECV_BUFFER));
if data:
thread.start_new_thread(recv,(data,));
except:
sock.close();
self.CONNECTION_LIST.remove(sock);
continue;
self.server_socket.close();
def recv(data):
lock.acquire();
global time_stamp;
t_message=data;
t_stamp= {'pClock':0, 'lClock':0,'count':0};
#recv part of algorithm starts from here
t_stamp['lClock']=max(time_stamp['lClock'],t_message['lClock'],time_stamp['pClock']);
if(t_stamp['lClock']==t_message['lClock'] and t_stamp['lClock']==time_stamp['lClock']):
t_stamp['count']=max(time_stamp['count'],t_message['count'])+1;
elif (t_stamp['lClock']==time_stamp['lClock']):
t_stamp['count']=time_stamp['count']+1;
elif(t_stamp['lClock']==t_message['lClock']):
t_stamp['count']=t_message['count']+1;
else:
t_stamp['count']=0;
time_stamp['lClock']=t_stamp['lClock'];
time_stamp['pClock']=t_stamp['pClock'];
time_stamp['count']=t_stamp['count'];
print data;
lock.release();
def send(data,portno):
lock.acquire();
global time_stamp;
t_stamp={'pClock':0, 'lClock':0,'count':0};
t_stamp['lClock']=max(time_stamp['lClock'],time_stamp['pClock']);
if(t_stamp['lClock']==time_stamp['lClock']):
time_stamp['count']=time_stamp['count']+1;
else:
time_stamp['count']=0;
t_stamp['pClock']=time_stamp['pClock'];
t_stamp['count']=time_stamp['count'];
#update the time_stamp object to hold the event timestamp
time_stamp['lClock']=t_stamp['lClock'];
time_stamp['pClock']=t_stamp['pClock'];
time_stamp['count']=t_stamp['count'];
client_socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM);
client_socket.connect(("localhost",portno));
client_socket.send(pickle.dumps(t_stamp));
client_socket.close();
lock.release();
if __name__ == "__main__":
#create a global lock for mutual exclusion
global lock;
lock=threading.RLock();
#create an ntp object
ntp=Ntp();
#create a time-stamp object
global time_stamp;
time_stamp= {'pClock':0, 'lClock':0,'count':0};
#launch a server thread
server_thread=server(int(sys.argv[1]));
server_thread.start();
while 1:
data=raw_input("Enter some text to send");
portno=raw_input("Enter portno");
if(data!="quit"):
thread.start_new_thread(send,(data,int(portno)));
else:
break;
print "Exiting";
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T09:30:34.693",
"Id": "71405",
"Score": "1",
"body": "I have the feeling that the AgTime and the Ntp classes are not actually useful. Also, the indentation of the last line looks wrong to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:57:13.883",
"Id": "71533",
"Score": "0",
"body": "AgTime is not useful but NTP class is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:47:32.997",
"Id": "71600",
"Score": "0",
"body": "I do see where we create an instance of ntp but I cannot see where the time() fonction is used. (If I missed something, let's pretend it's because I am not fully awaken yet)."
}
] |
[
{
"body": "<p>I'm just going to review the <code>Ntp</code> class. As you'll see, there's plenty here for one answer.</p>\n<ol>\n<li><p>There's no documentation. What is this class supposed to do? What value does the <code>time</code> method return?</p>\n</li>\n<li><p>There are some "tells" that you have come from a C background, and are not yet a fluent Python programmer: you have unnecessary semi-colons at the ends of lines, and unnecessary parentheses around the condition in <code>if</code> statements.</p>\n</li>\n<li><p>The code is not portable to Python 3:</p>\n<pre><code> >>> Ntp().time()\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n File "cr41537.py", line 20, in time\n client.sendto(self.msg, self.address)\n TypeError: 'str' does not support the buffer interface\n</code></pre>\n</li>\n</ol>\n<p>For portability to Python 3 you need <code>msg</code> to be a <code>bytes</code> object, not a <code>str</code>.</p>\n<ol>\n<li><p><code>Ntp</code> is a <a href=\"http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes\" rel=\"nofollow noreferrer\">"classic" or "old-style" class</a>. This means that it doesn't support the <a href=\"http://docs.python.org/3/library/functions.html#super\" rel=\"nofollow noreferrer\"><code>super</code></a> function, making it inconvenient to subclass. You should make new-style classes unless you have a good reason not to, by inheriting from <code>object</code>:</p>\n<pre><code> class Ntp(object):\n</code></pre>\n</li>\n<li><p>It's not clear that there's any need for a class here. There's no persistent state, and just one method, so a function would work just as well and be simpler.</p>\n</li>\n<li><p>In this line:</p>\n<pre><code> self.msg = '\\x1b'+47*'\\0'\n</code></pre>\n</li>\n</ol>\n<p>it is not at all clear where the expression comes from. What does it mean, and how can I check that you got it right?</p>\n<p>By reference to the NTP standard in <a href=\"https://www.rfc-editor.org/rfc/rfc5905\" rel=\"nofollow noreferrer\">RFC 5905</a>, it looks as though this decodes as version = 3 and mode = client. I would try to be much more explicit here as to how this packet is constructed, for example like this:</p>\n<pre><code> # See section 7 of RFC 5905 for the structure of an NTP packet.\n fmt = '!BBbb3I4Q'\n version = 3\n mode = 3 # client mode\n msg = struct.pack(fmt, (version << 3) + mode, *[0]*10)\n</code></pre>\n<p>Note that <code>msg</code> is now a <code>bytes</code> object as required by Python 3.</p>\n<ol>\n<li><p>You call <a href=\"http://docs.python.org/3/library/socket.html#socket.socket.recvfrom\" rel=\"nofollow noreferrer\"><code>socket.recvfrom</code></a> to get the address of the socket sending the data, but then you never use it. So why not just use <a href=\"http://docs.python.org/3/library/socket.html#socket.socket.recv\" rel=\"nofollow noreferrer\"><code>socket.recv</code></a>?</p>\n</li>\n<li><p>You are only going to use the first 48 bytes of the returned packet, so there is no point in setting the <code>bufsize</code> argument to <code>socket.recv</code> to be any larger.</p>\n</li>\n<li><p>You decode the result like this:</p>\n<pre><code> retval=struct.unpack("!12I",data);\n t = retval[10]\n</code></pre>\n</li>\n</ol>\n<p>but looking at <a href=\"https://www.rfc-editor.org/rfc/rfc5905\" rel=\"nofollow noreferrer\">RFC 5905</a>, this gets you the top 32 bits of the 64-bit transmit timestamp (the integer part). Why are you throwing away the bottom 32 bits? Python's <a href=\"http://docs.python.org/3/library/datetime.html#module-datetime\" rel=\"nofollow noreferrer\"><code>datetime</code></a> module supports computation with microseconds, so it is worth having both. I would decode like it this:</p>\n<pre><code> fmt = '!BBbb3I4Q'\n results = struct.unpack(fmt, data)\n tx_timestamp = results[10]\n</code></pre>\n<p>and then if I need to convert to seconds I can divide by 2<sup>32</sup>. Note also that I used the same format for decoding the received packet as I did for encoding the sent packet. This ensures consistency.</p>\n<ol>\n<li><p>In this code:</p>\n<pre><code> # reference time (in seconds since 1900-01-01 00:00:00)\n TIME1970 = 2208988800 # 1970-01-01 00:00:00\n</code></pre>\n</li>\n</ol>\n<p>it is not clear where this value comes from. How would I check that you got it right? I would refer to figure 4 of RFC 5905 in the comment.</p>\n<p>You could also consider computing this constant explicitly using Python's <a href=\"http://docs.python.org/3/library/datetime.html#module-datetime\" rel=\"nofollow noreferrer\"><code>datetime</code></a> module, which would make its meaning clear:</p>\n<pre><code> from datetime import datetime\n\n # Offset between NTP time and Unix epoch time in seconds.\n # See figure 4 of RFC 5905.\n TIME1970 = (datetime(1970, 1, 1) - datetime(1900, 1, 1)).total_seconds()\n</code></pre>\n<ol>\n<li><p>There is no attempt to correct for the transmission delay as described in section 8 of RFC 5905. You need something like this:</p>\n<pre><code> import time\n\n # Make sure DNS lookup time is not included in delay calculation.\n address = socket.getaddrinfo(host, port, AF_INET, SOCK_DGRAM)\n\n orig_time = time.time()\n client.sendto(msg, address[0][4])\n data = client.recv(48)\n dst_time = time.time()\n results = struct.unpack(fmt, data)\n recv_time = results[9] / 2.0**32\n tx_time = results[10] / 2.0**32\n\n # Estimate transmission delay: see section 8 of RFC 5905.\n delay = ((dst_time - orig_time) - (tx_time - recv_time)) / 2\n</code></pre>\n</li>\n</ol>\n<p>Note that the purpose of calling <a href=\"http://docs.python.org/3/library/socket.html#socket.getaddrinfo\" rel=\"nofollow noreferrer\"><code>socket.getaddrinfo</code></a> here (instead of passing <code>(host, port)</code> directly to <code>client.sendto</code>) is to avoid the time for the DNS lookup of <code>host</code> being included in the delay calculation.</p>\n<ol>\n<li><p>The <code>time</code> method returns the result in an inconvenient format (as the number of seconds since the epoch). It would be more generally useful to Python programmers to return a <a href=\"http://docs.python.org/3/library/datetime.html#datetime-objects\" rel=\"nofollow noreferrer\"><code>datetime.datetime</code></a> object, like this:</p>\n<pre><code> from datetime import datetime\n\n return datetime.utcfromtimestamp(tx_time - TIME1970 + delay)\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:55:49.157",
"Id": "71532",
"Score": "0",
"body": "Thank you for your generous feed back. I've incorporated all the changes you have mentioned here into my code. I should be looking at some code base on github to pick up in python and proper design styles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:00:11.177",
"Id": "71534",
"Score": "0",
"body": "And yeah your guessed it right about my C background."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:02:38.423",
"Id": "41555",
"ParentId": "41537",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41555",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T07:02:34.197",
"Id": "41537",
"Score": "3",
"Tags": [
"python",
"design-patterns",
"multithreading",
"socket"
],
"Title": "Run a TCP server listening for incoming messages"
}
|
41537
|
<p>I'm using two category filters from this <a href="http://demo.webcodo.net/switch-products-view-grid-list-jquery-with-filter-and-cookie/" rel="nofollow">demo</a>. I give the filters two different sets of classes so they won't affect each other. Since I'm very new to jQuery, all I can come up with is repeating the same code with a different set of classes. I wonder if there's a shorter way to write this:</p>
<pre><code>$(function(){
/* filter1 */
$(".category-menu ul li").click(function(){
var CategoryID = $(this).data('category');
$('.category-menu ul li').removeClass('cat-active');
$(this).addClass('cat-active');
$('.prod-cnt').each(function(){
if(($(this).hasClass(CategoryID)) == false){
$(this).css({'display':'none'});
};
});
$('.'+CategoryID).fadeIn();
});
$('.category-menu select').change(function(){
var CategoryID = $(this).find('option:selected').data('category');
$('.prod-cnt').each(function(){
if(($(this).hasClass(CategoryID)) == false){
$(this).css({'display':'none'});
};
});
$('.'+CategoryID).fadeIn();
});
/* filter2 */
$(".category-menu2 ul li").click(function(){
var CategoryID = $(this).data('category');
$('.category-menu2 ul li').removeClass('cat-active2');
$(this).addClass('cat-active2');
$('.prod-cnt2').each(function(){
if(($(this).hasClass(CategoryID)) == false){
$(this).css({'display':'none'});
};
});
$('.'+CategoryID).fadeIn();
});
$('.category-menu2 select').change(function(){
var CategoryID = $(this).find('option:selected').data('category');
$('.prod-cnt2').each(function(){
if(($(this).hasClass(CategoryID)) == false){
$(this).css({'display':'none'});
};
});
$('.'+CategoryID).fadeIn();
});
});
</code></pre>
<p>Please check out this <a href="http://jsfiddle.net/UfVAH/570/" rel="nofollow">demo</a>.</p>
|
[] |
[
{
"body": "<p>When you see that you're basically copy-pasting the code and changing a few values, you can usually encapsulate all the common stuff inside a function. Here:</p>\n\n<pre><code>var registerStuff = function(category, active, prod, select) {\n $(category).click(function(){\n var CategoryID = $(this).data('category');\n $(category).removeClass(active);\n $(this).addClass(active);\n\n $(prod).each(function(){\n if(($(this).hasClass(CategoryID)) == false){\n $(this).css({'display':'none'});\n };\n });\n $('.'+CategoryID).fadeIn(); \n });\n\n $(select).change(function(){\n var CategoryID = $(this).find('option:selected').data('category');\n $(prod).each(function(){\n if(($(this).hasClass(CategoryID)) == false){\n $(this).css({'display':'none'});\n };\n });\n $('.'+CategoryID).fadeIn(); \n });\n};\n\nregisterStuff(\".category-menu ul li\", 'cat-active', '.prod-cnt', '.category-menu select');\nregisterStuff(\".category-menu2 ul li\", 'cat-active2', '.prod-cnt2', '.category-menu2 select');\n</code></pre>\n\n<p>We can now clean up the inside of that function further. For example, some things could be cached, and the second <code>$(category)</code> is uneccessary. The <code>== false</code> is a code smell, rather use a negation. The jQuery <code>hide()</code> method is better than spelling out the <code>css()</code>. Blending out the prods of the wrong category is common code, and can be factored out as well.</p>\n\n<pre><code>var registerStuff = function(category, active, prod, select) {\n var displayOnlyWantedCategory = function($prods, categoryId) {\n $prods.each(function() {\n var $this = $(this);\n if (! $this.hasClass(categoryId)) {\n $this.hide();\n }\n });\n $('.' + categoryId).fadeIn(); \n };\n\n var $category = $(category);\n $category.click(function() {\n var $this = $(this);\n $category.removeClass(active);\n $this.addClass(active);\n\n displayOnlyWantedCategory($(prod), $this.data('category'));\n });\n\n $(select).change(function() {\n displayOnlyWantedCategory($(prod), $(this).find('option:selected').data('category'));\n });\n};\n</code></pre>\n\n<p>The next thing to consider is your usage of classes. Your <code>category-menu</code> and <code>category-menu2</code> are visually and functionally identical, they're only two instances of the same idea. What happens when you want to have fifteen <code>category-menu</code>s on the same page? I wouldn't want to see the CSS for that:</p>\n\n<pre><code> .category-menu,\n .category-menu2,\n .category-menu3,\n ...\n .category-menu14,\n .category-menu15 {\n ...\n }\n</code></pre>\n\n<p>Your solution <em>does not scale</em>. Instead, let's think about a <code>product-collection</code> element, which contains a few buttons to select a category, and a few items which can be displayed. We want to limit the effect of selecting a category to the current collection only.</p>\n\n<p>The resulting HTML might look like:</p>\n\n<pre><code><div class=\"product-collection\">\n <ul>\n <li class=\"product-collection__selector\n product-collection__selector--active\"\n data-product-collection__category=\"\">All</li>\n <li class=\"product-collection__selector\"\n data-product-collection__category=\"cat1\">Category 1</li>\n <li class=\"product-collection__selector\"\n data-product-collection__category=\"cat2\">Category 2</li>\n </ul>\n <ul>\n <li class=\"product-collection__item\"\n data-product-collection__category=\"cat1\">Item 1 [cat 1]</li>\n <li class=\"product-collection__item\"\n data-product-collection__category=\"cat2\">Item 2 [cat 2]</li>\n <li class=\"product-collection__item\"\n data-product-collection__category=\"cat1\">Item 3 [cat 1]</li>\n </ul>\n</div>\n</code></pre>\n\n<p>The jQuery initialization must take care to install the handlers only in the elements of the current collection:</p>\n\n<pre><code>$(function() {\n $('.product-collection').each(function() {\n var $collection = $(this);\n var $selectors = $collection.find('.product-collection__selector');\n var $items = $collection.find('.product-collection__item');\n\n $selectors.click(function() {\n var $selector = $(this);\n var cat = $selector.data('product-collection__category');\n\n $selectors.removeClass('product-collection__selector--active');\n $selector.addClass('product-collection__selector--active');\n\n if (cat) {\n $items.each(function() {\n var $item = $(this);\n if ($item.data('product-collection__category') == cat)\n $item.fadeIn();\n else\n $item.hide();\n });\n }\n else {\n $items.fadeIn();\n }\n });\n });\n});\n</code></pre>\n\n<p>See it in action here: <a href=\"http://jsfiddle.net/Qv6QE/3/\">http://jsfiddle.net/Qv6QE/3/</a></p>\n\n<p>My class names may seem excessively verbose, but they avoid namespace conflicts by following the <a href=\"http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/\">Block-Element-Modifier naming scheme</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:59:28.527",
"Id": "71422",
"Score": "0",
"body": "excellent answer! Easy to understand for a novice like me! I'll need some time to digest and make a few tries. I'll give you a vote up as soon as I have 15 reputation. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:07:59.230",
"Id": "71449",
"Score": "3",
"body": "Quite a nice review, only last thing I'd change is I would probably write `$item.css({ display: 'none' });` as `$item.hide()`. Good stuff! Also I would probably write you `product-collection__selector--active` as two classes `product-collection` and `active`, I'm not a fan of the BEM scheme for non enterprise size projects/plugins"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:50:17.067",
"Id": "71482",
"Score": "0",
"body": "@amon The only thing I miss about the old one is that the posts can be filtered by classes, which means that as long as the word is one of the classes, the posts can be filtered, which allows me to have different types of filters. But in your version, the data-product-collection__categories of the filters and posts have to be the exact match. Is there any way to change it back to \"lazy match\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:14:30.300",
"Id": "71503",
"Score": "1",
"body": "@user35295 It's still quite straightforward to have multiple categories per item, you just have to spell out the necessary JS yourself. See http://jsfiddle.net/cYFLe/ for an example. Do not use classes when they are not appropriate. The category of an item is *data*, and it is in no way relevant to styling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:39:20.790",
"Id": "71607",
"Score": "0",
"body": "@amon Thanks a lot. I've been trying to add a few select boxes as additional filters. But I'm struggling to make it change its background color on click like the old buttons and then back to its original color when I click on any other button or select box. The effect is the same as in this **[example](http://jsfiddle.net/vNZ49/1/)**. Do you know what's wrong with this **[fiddle](http://jsfiddle.net/cYFLe/17/)**? I've tried creating another var for the select boxes but no joy..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:19:32.583",
"Id": "71619",
"Score": "0",
"body": "@user35295 That's a bit outside of the scope of a code review, and actually outside of my area of expertise (I don't actually know jQuery that well). It may be better to ask on [so]."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:03:04.957",
"Id": "41547",
"ParentId": "41544",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41547",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T10:22:16.270",
"Id": "41544",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"jquery",
"html",
"css"
],
"Title": "Two filters for products on a page"
}
|
41544
|
<p>I have a Java dynamic proxy with an invoke method that looks like this:</p>
<pre><code> @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
//Not sure if this line is ok?
Token token = (Token) args[0];
System.out.println("Token with id: "+token.getId()+ " was passed");
result = method.invoke(realObject, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
} finally {
System.out.println("after method " + method.getName());
}
return result;
}
</code></pre>
<p>Would it be considered bad practice to pull out and cast that Token object from the args array?</p>
<p>The problem I can see is that it means the proxy isn't generic and in fact will only work for method invocations that pass an instance of a Token object as the first parameter.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:34:54.707",
"Id": "71419",
"Score": "2",
"body": "Why the hassle to have a single return, while you have those throws in between?"
}
] |
[
{
"body": "<p>Casting is never 'pretty'.... But, in a proxy situation like this (assuming you really need the proxy), it is possibly unavoidable.</p>\n\n<p>I can recommend though that you do it defensively... you should really do:</p>\n\n<pre><code>if (args.length > 0) {\n if (args[0] instanceof Token) {\n System.out.println(\"Token with id: \"+((Token)args[0]).getId()+ \" was passed\");\n } else {\n System.out.println(\"Proxy for a method which does not have an initial token: \" + args[0]);\n }\n} else {\n System.out.println(\"Proxy for a method that is being passed no arguments.\");\n}\n</code></pre>\n\n<p>If your situation requires that these values are populated, then you should throw exceptions instead of the other println methods.</p>\n\n<p>Also, you should consider checking that the number of arguments in the <code>args</code> matches the number of arguments expected in <code>method.getParameterTypes()</code>, but with var-args, that can be hard.</p>\n\n<p>Additionally, this line:</p>\n\n<blockquote>\n<pre><code>throw new RuntimeException(\"unexpected invocation exception: \" + e.getMessage());\n</code></pre>\n</blockquote>\n\n<p>Should incorporate the actual cause.... when you get an exception through this catch block, it will be one of those times when the cause is critical, and you are throwing the cause away! That exception should look like:</p>\n\n<pre><code>throw new RuntimeException(\"unexpected invocation exception: \" + e.getMessage(), e);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:22:29.673",
"Id": "41548",
"ParentId": "41546",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:54:47.237",
"Id": "41546",
"Score": "3",
"Tags": [
"java"
],
"Title": "Is it ok to pull out specific arguments from a Java dynamic proxy invocation?"
}
|
41546
|
<p>The following two functions are used to compress arbitrary Python objects and send them safely via socket or email, using only printable chars. In my specific message protocol, '=' signs are also not allowed; I could have replaced them or truncate them - I chose to truncate them.</p>
<p>I think they work quite well speed-wise and have no unpredicted errors. I post it here for your judgement.</p>
<pre><code>## Framework
import cPickle as pickle
import zlib as zl
import base64 as b64
def compress(o):
## First pickle
p = pickle.dumps(o, pickle.HIGHEST_PROTOCOL)
## Then zip
z = zl.compress(p, zl.Z_BEST_COMPRESSION)
## Then encode
e = b64.b64encode(z)
## Then truncate
t = e.rstrip("=")
## Then return
return t
def decompress(s):
## First pad
e = s + "=" * (-len(s) % 4)
## Then decode
z = b64.b64decode(e)
## Then unzip
p = zl.decompress(z)
## Then unpickle
o = pickle.loads(p)
## Then return
return o
</code></pre>
|
[] |
[
{
"body": "<p>Avoid single letter variable names. Spell out the words they stand for to make your code easier to read.</p>\n\n<p>Your comments are useless. You are just restating the code in less detail. The only comment you should have is explaining about the '=' like you did in your post.</p>\n\n<p>Don't double-space your code. </p>\n\n<p>Pickle isn't safe. You can construct a pickle that does arbitrary things like delete files or what-not. So you should pretty much never be sending them over a socket.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:06:27.703",
"Id": "71471",
"Score": "0",
"body": "[pep8](http://www.python.org/dev/peps/pep-0008/#blank-lines) says \"Separate top-level function and class definitions with two blank lines.\"; that's why I am double-spacing my code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T00:49:25.677",
"Id": "71526",
"Score": "1",
"body": "I'm referring to all the newlines in your function. Not the top level space."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:18:06.620",
"Id": "41566",
"ParentId": "41549",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "41566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T12:49:47.840",
"Id": "41549",
"Score": "7",
"Tags": [
"python",
"strings",
"serialization"
],
"Title": "Python compress and send"
}
|
41549
|
<p>I am retrieving information from an <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> database that gives me back around 20 million rows that I need to process. This information is then transformed into a dict of lists which I need to use. I am trying to use generators wherever possible.</p>
<p>What optimizations can be done?</p>
<p>I am either getting a “Killed” message or it takes a really long time to run. The SQL result set part is working fine. I tested the generator code in the Python interpreter, and it doesn’t have any problems. I am guessing the problem is with the dict generation.</p>
<p><strong>Update for clarity:</strong></p>
<p>I have 20 million rows in my result set from my SQLite database. Each row is of the form:</p>
<pre><code>(2786972, 486255.0, 4125992.0, 'AACAGA', '2005’)
</code></pre>
<p>I now need to create a dict that is keyed with the fourth element ‘AACAGA’ of the row. The value that the dict will hold is the third element, but it has to hold the values for all the occurences in the result set.</p>
<p>So, in our case here, ‘AACAGA’ will hold a list containing multiple values from the SQL result set. The problem here is to find tandem repeats in a genome sequence. A tandem repeat is a genome read (‘AACAGA’) that is repeated at least three times in succession.</p>
<p>For me to calculate this, I need all the values in the third index as a list keyed by the genome read, in our case ‘AACAGA’. Once I have the list, I can subtract successive values in the list to see if there are three consecutive matches to the length of the read. This is what I aim to accomplish with the dictionary and lists as values.</p>
<pre><code>#!/usr/bin/python3.3
import sqlite3 as sql
sequence_dict = {}
tandem_repeat = {}
def dict_generator(large_dict):
dkeys = large_dict.keys()
for k in dkeys:
yield(k, large_dict[k])
def create_result_generator():
conn = sql.connect('sequences_mt_test.sqlite', timeout=20)
c = conn.cursor()
try:
conn.row_factory = sql.Row
sql_string = "select * from sequence_info where kmer_length > 2"
c.execute(sql_string)
except sql.Error as error:
print("Error retrieving information from the database : ", error.args[0])
result_set = c.fetchall()
if result_set:
conn.close()
return(row for row in result_set)
def find_longest_tandem_repeat():
sortList = []
for entry in create_result_generator():
sequence_dict.setdefault(entry[3], []).append(entry[2])
for key,value in dict_generator(sequence_dict):
sortList = sorted(value)
for i in range (0, (len(sortList)-1)):
if((sortList[i+1]-sortList[i]) == (sortList[i+2]-sortList[i+1])
== (sortList[i+3]-sortList[i+2]) == (len(key))):
tandem_repeat[key] = True
break
print(max(k for k, v in tandem_repeat.items() if v))
if __name__ == "__main__":
find_longest_tandem_repeat()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:02:54.533",
"Id": "71433",
"Score": "3",
"body": "Despite your comment to my answer, I can still spot errors in your code. Can you please provide a working version of your code and some tests ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:15:33.213",
"Id": "71438",
"Score": "0",
"body": "@Josay: The problem is that I can’t point out whether this code is working properly or not. I have tested each part of this on small sets and the logic is correct, but when put together, because of the large result set, it is taking a long time to run. If it isn’t taking a long time, I get a “Killed” message, mostly due to memory overflow, I am guessing? So I don’t know how to give you test results. The create_result_generator() part works perfectly fine after a long-ish delay for retrieval and then is very fast. Other logic is fine too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:41:51.500",
"Id": "71443",
"Score": "0",
"body": "Please double-check your code — `try` without `except`? Mismatched `[`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:48:11.557",
"Id": "71445",
"Score": "0",
"body": "Rev 5 is still broken. Please ensure that your code works when asking for a review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:53:27.230",
"Id": "71448",
"Score": "0",
"body": "@200_success - My code is working, as in, I am not getting any syntactical errors. I did not copy paste my code here after the first go. I was just editing it in place here to incorporate all comments. I am making sure it is in place where I am running it. Sorry about that."
}
] |
[
{
"body": "<p>I have missed the whole point of your program but these comments might be useful to you anyway :</p>\n\n<p><strong>dict_generator</strong></p>\n\n<p>I might be wrong but <code>dict_generator(large_dict)</code> looks like <code>large_dict.iteritems()</code> (Python 2) / <code>large_dict.items()</code> (Python 3).</p>\n\n<p><strong>create_result_generator</strong></p>\n\n<pre><code> while True:\n result_set = c.fetchall()\n if not result_set:\n break\n else:\n return(row for row in result_set)\n</code></pre>\n\n<p>This loop does not seem very loopy to me. What about :</p>\n\n<pre><code> result_set = c.fetchall()\n if result_set:\n return(row for row in result_set)\n</code></pre>\n\n<p>Also, it seems to hilight a bigger issue about the fact that the connection might not be closed.</p>\n\n<p><strong>find_longest_tandem_repeat</strong></p>\n\n<p>In :</p>\n\n<pre><code> try:\n sequence_dict[row[3]].append(row[2])\n except KeyError:\n sequence_dict[row[3]] = []\n sequence_dict[row[3]].append(row[2])\n</code></pre>\n\n<p>seems to be equivalent to</p>\n\n<pre><code> sequence_dict.setdefault(row[3],[]).append(row[2])\n</code></pre>\n\n<p>Also, I don't know where <code>row</code> is coming from at this stage.</p>\n\n<p>In :</p>\n\n<pre><code> for key,value in dict_generator(sequence_dict):\n sortList = sorted(value)\n for i in range (0, (len(sortList)-1)):\n if((sorList[i+1]-sorList[i]) == (sorList[i+2]-sorList[i+1])\n == (sorList[i+3]-sorList[i+2]) == (len(key))):\n tandem_repeat[key] = True\n sortList = []\n</code></pre>\n\n<p>Naming (<code>sortList</code>/<code>sorList</code>) is either wrong or very confusing.\nThere is no point in doing <code>sortList = []</code>.\nYou can probably <code>break</code> once you've done <code>tandem_repeat[key] = True</code> because new iterations won't do much anyway.</p>\n\n<pre><code> print(max(k for k in tandem_repeat.keys() if tandem_repeat[k] is True))\n</code></pre>\n\n<p>might as well be :</p>\n\n<pre><code> print(max(k for k,v in tandem_repeat.items() if v))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:09:57.587",
"Id": "71436",
"Score": "0",
"body": "I have edited the post to provide more clarification and use case scenarios. I have made most of the changes that you have suggested. Sorry about the typos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:11:19.890",
"Id": "71437",
"Score": "0",
"body": "Seems better indeed :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:26:03.773",
"Id": "71441",
"Score": "0",
"body": "Josay: About dict_generator - I don’t know if this [link](http://dhruvbird.blogspot.com/2010/06/python-generators-and-dictitems.html) is correct or not. That is what I used for the large dict."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:51:39.073",
"Id": "41554",
"ParentId": "41551",
"Score": "3"
}
},
{
"body": "<p>Your SQL is not working as well as you think it is.</p>\n\n<p>Any time you do any significant amount of post-processing on an SQL result set, that is an indicator that your query is weakly formulated. The point of the database is that it lets you query it for exactly the data that you are interested in. The way your code treats the database as a passive storage format, you could just as well have stored everything in a CSV file.</p>\n\n<p><del>You didn't provide any details about your database schema, so I can only guess that your third column is named <code>position</code> and the fourth column is named <code>genome</code>.</del> (Had you explicitly specified which columns you were selecting, instead of just <code>SELECT *</code>, your code would be more self-documenting.) A query such as the following should extract the relevant rows:</p>\n\n<pre><code>SELECT *\n FROM sequence_info AS middle\n JOIN sequence_info AS preceding\n ON preceding.sequence_info = middle.sequence_info\n AND preceding.sequence_offset = middle.sequence_offset - length(middle.sequence_info)\n JOIN sequence_info AS following\n ON following.sequence_info = middle.sequence_info\n AND following.sequence_offset = middle.sequence_offset + length(middle.sequence_info)\n WHERE middle.kmer_length > 2\n ORDER BY length(middle.sequence_info) DESC, middle.sequence_info, middle.sequence_offset;\n</code></pre>\n\n<p>For performance, be sure to <a href=\"http://www.sqlite.org/lang_createindex.html\" rel=\"nofollow\">create index</a>es on the <code>genome</code> and <code>position</code> columns of your table.</p>\n\n<h3>Addendum: Suggestion for performance</h3>\n\n<p>The following query should run faster than my original suggestion, since it only performs joins by equality on indexed column values.</p>\n\n<pre><code>SELECT first.*\n FROM sequence_info AS first\n JOIN sequence_info AS second\n ON second.sequence_info = first.sequence_info\n AND second.sequence_offset = first.next_offset\n JOIN sequence_info AS third\n ON third.sequence_info = second.sequence_info\n AND third.sequence_offset = second.next_offset\n WHERE first.kmer_length > 2\n ORDER BY (first.next_offset - first.sequence_offset) DESC\n , first.sequence_info\n , first.sequence_offset;\n</code></pre>\n\n<p>The implementation of such joins should be extremely well optimized in any relational database, since they are very common operations. You probably wouldn't be able to implement anything faster yourself in any language, much less in Python. You might be able to squeeze out better performance by using an <code>INTEGER</code> type for <code>sequence_offset</code> instead of a <code>REAL</code>.</p>\n\n<p>To be able to run that query, you'll have to augment the <code>sequence_info</code> table with a <code>next_offset</code> column…</p>\n\n<pre><code>ALTER TABLE sequence_info ADD COLUMN next_offset REAL;\n\nUPDATE sequence_info SET next_offset = sequence_offset + length(sequence_info);\n\nCREATE UNIQUE INDEX sequence_index ON sequence_info (sequence_offset, sequence_info);\nCREATE UNIQUE INDEX next_index ON sequence_info (next_offset, sequence_info);\n</code></pre>\n\n<p>If you <em>still</em> aren't satisfied with the performance after that change, you would probably have to consider trying another RDMS (such as PostgreSQL), tuning the database, or throwing more RAM/CPU at the problem — in other words, factors beyond the scope of Code Review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:47:36.280",
"Id": "71451",
"Score": "0",
"body": "@success_200: I apologize for that. Yes, I missed out providing the schema. The third column is sequence_offset(position that you mentioned) and the fourth column is sequence_info(I made a mistake when naming the column). I am just getting into complex SQL and hence don’t have the knowledge to write queries such as these and hence was relying on post processing to do my job. I will test this query and get back on that. Thanks a ton for the help. It was really insightful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:18:32.500",
"Id": "71495",
"Score": "0",
"body": "I made the changes that you suggested and the query is working fine on small data sets. I was just testing it to see if the logic was working of course. I ran it on my original result set and it is taking a long time to complete. This was after I built the indexes on the columns as you suggested. The query has been running for 1.5 hours as of now. Does it usual take that long for a query such as this to run? Any other optimizations on SQL that I can do? Or is the SQLite database not suitable for such things? Would a CSV file parsed into a dict work better in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T09:50:18.843",
"Id": "71754",
"Score": "0",
"body": "SQL is perfectly suited to these kinds of queries, though SQLite might not be your best bet for performance. See the addendum to my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-26T00:57:21.380",
"Id": "380133",
"Score": "0",
"body": "@200_success postgres will be slower than sqlite no matter what you do given it has TCP overhead"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:34:01.033",
"Id": "41560",
"ParentId": "41551",
"Score": "2"
}
},
{
"body": "<p>I would expect this code to raise an <code>IndexError</code> when <code>i</code> equals <code>len(sortList)-2</code>.</p>\n\n<pre><code> for i in range (0, (len(sortList)-1)):\n if((sortList[i+1]-sortList[i]) == (sortList[i+2]-sortList[i+1])\n == (sortList[i+3]-sortList[i+2]) == (len(key))):\n tandem_repeat[key] = True\n break\n</code></pre>\n\n<p>Your function is named <code>find_longest_tandem_repeat()</code>, but I think it actually prints the tandem sequence that would occur last when sorted alphabetically:</p>\n\n<pre><code>print(max(k for k, v in tandem_repeat.items() if v))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:39:53.777",
"Id": "41561",
"ParentId": "41551",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41560",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:19:52.903",
"Id": "41551",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"sqlite",
"generator",
"bioinformatics"
],
"Title": "Optimization for SQLite result set parsing"
}
|
41551
|
<p>I am making a program to find primes between the given range of numbers. Unfortunately, the algorithm I created is too slow. Do you have any ideas of how to optimize the code? </p>
<pre><code>import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(System.in);
int numberOfTests;
int l, n;
numberOfTests = s.nextInt();
for (int q = 0; q < numberOfTests; q++) {
l = s.nextInt();
n = s.nextInt();
if (l==1)l++;
BitSet primeBitSet = new BitSet((int) (Math.sqrt(n) + 1));
ArrayList <Integer> primeTable = new ArrayList <Integer>((int) Math.sqrt(n));
if (l < 1 || n < 1 || l > n || n > 1000000000) {
System.exit(0);
}
//classic sieve from 1 to sqrt(n)
for (int j = 2; j * j <= n; j++) {
if (primeBitSet.get(j - 1) == true) {
continue;
} else {
primeTable.add(j);
for (int k = 2 * j; k <= n; k += j) {
primeBitSet.set(k - 1);
}
}
}
//sieve in the expected range using primes generated by the classic sieve
BitSet primesInRangeBitSet = new BitSet(n - l + 1);
int pomoc;
for (int i = 0; i < primeTable.size(); ++i) {
pomoc = l / ((int) primeTable.get(i));
pomoc = pomoc * ((int) primeTable.get(i));
for (int j = pomoc; j <= n; j = j + (int) primeTable.get(i)) {
if (j < l || primesInRangeBitSet.get(j - l) == true ) {
continue;
} else {
primesInRangeBitSet.set(j - l);
}
}
}
//outputting the primes
for (int k = 0; k < primeTable.size(); k++){
if((int)primeTable.get(k)>= l &&(int) primeTable.get(k) <= n)
System.out.println(primeTable.get(k));
}
for (int k = 0; k < primesInRangeBitSet.size(); k++) {
if (primesInRangeBitSet.get(k) == false && k <= n - l ) {
System.out.println((k + l));
}
}
System.out.println("");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T11:47:28.267",
"Id": "71612",
"Score": "0",
"body": "see http://stackoverflow.com/search?tab=newest&q=user%3a849891%20%22offset%20sieve%22"
}
] |
[
{
"body": "<p>Firstly, let's take a look at minor issues:</p>\n\n<ol>\n<li><p>Whenever you do a <code>scanner.nextInt()</code>, there is a possibility of exception been thrown when an invalid input is given. You should always check if a valid <code>int</code> value is available to read before actually reading it. So:</p>\n\n<pre><code>int numberOfTests = s.nextInt();\n</code></pre>\n\n<p>should be changed to:</p>\n\n<pre><code>// Iterate till the next input is not an int\nwhile (!s.hasNextInt()) {\n // Consume this input, and discard it\n s.next();\n}\n// Read the next input, as it's an integer\nint numberOfTests = s.nextInt();\n</code></pre>\n\n<p>Also, you might want to consider giving certain number of chances to pass valid integer value.</p></li>\n<li><p>Similarly for the other two inputs you read in the <code>for</code> loop should be changed. Now you would sense some sort of code duplication there. What I would suggest is, create a <code>static</code> method, that reads an integer from user, and invoke it whenever you want an <code>int</code> value, and do the above stuff in that method:</p>\n\n<pre><code>public static int readInt() {\n while (!scanner.hasNextInt()) {\n scanner.next();\n }\n return scanner.nextInt();\n}\n</code></pre>\n\n<p>make sure to make the <code>scanner</code> a field of the class.</p>\n\n<p>And then replace that code in first point to:</p>\n\n<pre><code>int numberOfTests = readInt();\n</code></pre></li>\n<li><p>The <code>if</code> condition in your code:</p>\n\n<pre><code>if (primeBitSet.get(j - 1) == true)\n</code></pre>\n\n<p>is always a bad idea of comparing <code>boolean</code>. It is better written as:</p>\n\n<pre><code>if (primeBitSet.get(j - 1))\n</code></pre></li>\n<li><p>Note, I've changed the variable name from <code>s</code> to <code>scanner</code>. It makes more sense that way. You should really choose your variable names very cleverly. <code>s</code> and <code>l</code> are not really good variable names. They don't signify any meaning.</p></li>\n<li><p>Also, you should try to minimize the scope of variables. <code>l</code> and <code>n</code> can be declared inside the <code>for</code> loop only. You aren't really using it outside.</p></li>\n</ol>\n\n<p>Now, coming to the concrete issue, you don't seem to be following the algorithm correctly. In fact, you wouldn't need an <code>ArrayList</code>. The point of Sieve is, it just sets all the non-prime values to <code>false</code> in the given array of size <code>n</code>. And then finally, whatever index is set to <code>true</code> are primes. So you don't need to store the prime numbers separately. You can get them from that array only (In your case, it's a <code>BitSet</code> instead).</p>\n\n<p>Given the value of <code>l</code> and <code>n</code>, just the below code should work fine:</p>\n\n<pre><code>Scanner scanner = new Scanner(System.in);\nprivate static final int MAX_ATTEMPT = 3;\n\npublic static void main(String[] args) {\n\n int numberOfTests = readInt();\n\n for (int q = 0; q < numberOfTests; q++) {\n int start = readInt();\n int end = readInt();\n\n /* \n * Create a BitSet of size `n`, and set all values from index 2 to end as true\n * assuming that all are primes. Index 0, and 1 are anyways not prime, so leave\n * them as false\n * Then in the course of moving along the algorithm,\n * we'll set all multiples of prime numbers to false\n */\n BitSet primeBitSet = new BitSet(end);\n primeBitSet.set(2, primeBitSet.size());\n\n // From index 2, run Sieve of Erathosthenes\n for (int j = 2; j < end; j++) {\n if (primeBitSet.get(j)) {\n // This bit is set. That means this is prime. Set all multiples of \n // this bit as false\n for (int k = 2 * j; k < end; k += j) {\n primeBitSet.set(k, false);\n }\n }\n }\n\n // Starting from `start`, print all the bits that are set\n for (int i = start; i < end; ++i) {\n if (primeBitSet.get(i)) {\n System.out.println(i);\n }\n }\n }\n\n}\n\npublic static int readInt() {\n int attempt = 0;\n\n while (attempt < MAX_ATTEMPT && !scanner.hasNextInt()) {\n scanner.next();\n attempt++;\n }\n\n if (attempt == MAX_ATTEMPT) {\n // throw exception;\n }\n\n return scanner.nextInt();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:52:09.283",
"Id": "71452",
"Score": "0",
"body": "IIRC the loop could be improved to `for(int k = j*j; k < n; k += 2*j)`. Didn't test it, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:03:12.743",
"Id": "71455",
"Score": "0",
"body": "@Landei No. That doesn't give the correct result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:13:20.217",
"Id": "71456",
"Score": "1",
"body": "OK, you have to remove the even numbers (except 2) first, then it works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:20:02.023",
"Id": "71457",
"Score": "0",
"body": "@Landei Hmm. Right :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:53:02.893",
"Id": "71460",
"Score": "0",
"body": "@Landei - the k has to start on an odd number, you typically want to start k at `k = j + 2*j` and then you can increment with the even value `2*j`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T11:43:04.367",
"Id": "71611",
"Score": "0",
"body": "how *fast* will this work for `start = 1,234,500,000` and `end = 1,234,560,000`?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:47:54.193",
"Id": "41562",
"ParentId": "41559",
"Score": "6"
}
},
{
"body": "<p>I have to say it's really hard to follow your code. Why do you have no sub-methods? What does \"pomoc\" mean? Why do you use <code>continue</code> if flipping the condition would avoid it? And <code>if (x == true)...</code> can be written as <code>if(x)...</code> </p>\n\n<p>An <code>ArrayList</code> can be slow because of boxing/unboxing, maybe a specialized structure is faster (e.g. from <a href=\"http://trove.starlight-systems.com/\" rel=\"nofollow\">gnu-trove</a>) </p>\n\n<p>But the main questions is if you really use the correct algorithm. I can't tell without looking deeper, but if you're unsure, read <a href=\"http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf\" rel=\"nofollow\">\"The Genuine Sieve of Eratosthenes\"</a> (it's Haskell, but you'll get the idea).</p>\n\n<p>Note that from a theoretical point of view there are <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow\">\"faster\" sieves</a>, but I think they are much harder to implement, and it's hard to say if you really see a speed-up.</p>\n\n<p><strong>[Edit]</strong></p>\n\n<p>Based on @Rohit Jain's solution, special-casing the even numbers and skipping unnecessary tests:</p>\n\n<pre><code> BitSet primeBitSet = new BitSet(end);\n primeBitSet.set(2, primeBitSet.size());\n\n for (int j = 4; j < end; j += 2) {\n primeBitSet.set(j, false);\n }\n for (int j = 3; j < end; j += 2) {\n if (primeBitSet.get(j)) {\n for (int k = j * j; k < end; k += 2*j) {\n primeBitSet.set(k, false);\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:55:06.593",
"Id": "71461",
"Score": "0",
"body": "The inner `k` loop should be removing all the multiples of `j`, but j*j is even, and 2*j is even so it will only loop on the even multiples. you need to make the initial k value odd, often starting with just `k = 3*j; k < end; k+= 2*j`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:02:00.247",
"Id": "71462",
"Score": "0",
"body": "Also, because of the way the inner loop works, I guess you can stop the outter loop much earlier (`j*j < end`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:45:59.707",
"Id": "71497",
"Score": "1",
"body": "@rolfl j starts with 3 (in my version) and increases by 2, so j*j is always odd, and j*j is the first number to strike out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:47:17.917",
"Id": "71498",
"Score": "0",
"body": "@Josay That's correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:01:09.480",
"Id": "71501",
"Score": "0",
"body": "@Landei I see that now. interesting optimization. I have previously implemented it as 3j, not j^2, but I see that will work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T11:30:04.070",
"Id": "71608",
"Score": "0",
"body": "@rolfl if `j*j` is even then `j` is even then `3*j` is also even. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T11:33:40.653",
"Id": "71609",
"Score": "0",
"body": "@Landei https://en.wiktionary.org/wiki/pomoc says \"Noun -- pomoc (f) -- help, aid, assistance. Cognate with Upper Sorbian pomoc, Polish pomoc, Czech pomoc, Russian помощь (pomoščʹ), and Serbo-Croatian pomoć.\" Googled it for you. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:16:46.223",
"Id": "71618",
"Score": "0",
"body": "@WillNess Thank you, I didn't think of that, even though I learned Russian at School and actually remember the Russian version..."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:48:46.817",
"Id": "41563",
"ParentId": "41559",
"Score": "4"
}
},
{
"body": "<p><strong>Variable scope</strong></p>\n\n<p>In order to make things easier to read/write, it is prefered to declare local variables as late as possible and in the smallest possible scope.</p>\n\n<p>In your case, this holds for :</p>\n\n<pre><code>int numberOfTests = s.nextInt();\n</code></pre>\n\n<p></p>\n\n<pre><code>int l = s.nextInt();\n</code></pre>\n\n<p></p>\n\n<pre><code>int n = s.nextInt();\n</code></pre>\n\n<p></p>\n\n<pre><code>int pomoc = l / ((int) primeTable.get(i));\n</code></pre>\n\n<p>Also, <code>BitSet primeBitSet</code> can be declared just before the loop using it.</p>\n\n<p><strong>Continue</strong></p>\n\n<p>The way you use <code>continue</code> make things complicated for no obvious reasons.</p>\n\n<pre><code> if (primeBitSet.get(j - 1) == true) {\n continue;\n } else {\n primeTable.add(j);\n for (int k = 2 * j; k <= n; k += j) {\n primeBitSet.set(k - 1);\n }\n }\n</code></pre>\n\n<p>can be written :</p>\n\n<pre><code> if (!primeBitSet.get(j - 1)) {\n primeTable.add(j);\n for (int k = 2 * j; k <= n; k += j) {\n primeBitSet.set(k - 1);\n }\n }\n</code></pre>\n\n<p><strong>New lines</strong></p>\n\n<p>The way you use new lines does not seem to make much sense. You should try to separate things into different \"paragraphs\".</p>\n\n<p>After taking into accounts these comments about style, here's what the code would be like :</p>\n\n<pre><code>public class Main {\n\n public static void main(String[] args)throws IOException {\n Scanner s = new Scanner(System.in);\n int numberOfTests = s.nextInt();\n\n for (int q = 0; q < numberOfTests; q++) {\n int l = s.nextInt();\n int n = s.nextInt();\n if (l==1)l++;\n ArrayList <Integer> primeTable = new ArrayList <Integer>((int) Math.sqrt(n));\n if (l < 1 || n < 1 || l > n || n > 1000000000) {\n System.exit(0);\n }\n\n //classic sieve from 1 to sqrt(n)\n BitSet primeBitSet = new BitSet((int) (Math.sqrt(n) + 1));\n for (int j = 2; j * j <= n; j++) {\n if (!primeBitSet.get(j - 1)) {\n primeTable.add(j);\n for (int k = 2 * j; k <= n; k += j) {\n primeBitSet.set(k - 1);\n }\n }\n }\n\n //sieve in the expected range using primes generated by the classic sieve\n BitSet primesInRangeBitSet = new BitSet(n - l + 1);\n for (int i = 0; i < primeTable.size(); ++i) {\n int pomoc = (l / ((int) primeTable.get(i))) * ((int) primeTable.get(i));\n for (int j = pomoc; j <= n; j = j + (int) primeTable.get(i)) {\n if (j >= l && !primesInRangeBitSet.get(j - l)) {\n primesInRangeBitSet.set(j - l);\n }\n }\n }\n\n //outputting the primes\n for (int k = 0; k < primeTable.size(); k++){\n if((int)primeTable.get(k)>= l &&(int) primeTable.get(k) <= n)\n System.out.println(primeTable.get(k));\n }\n for (int k = 0; k < primesInRangeBitSet.size(); k++) {\n if (primesInRangeBitSet.get(k) == false && k <= n - l ) {\n System.out.println((k + l));\n }\n }\n System.out.println(\"\");\n }\n }\n}\n</code></pre>\n\n<p><strong>Algorithm</strong></p>\n\n<p>Now, this being said, there is a much bigger issue here. If tou want to implement <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthene</a> properly, everything you need is just a BitSet of size 1.\nIf you really want to (but I don't really see the point), you can add primes numbers in a list as you detect them. If you just need to print them, you can print them as you detect them. In any case, I guess that from a performance point of view, it is not such a big deal to reiterate over the whole BitSet looking from prime numbers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:54:13.397",
"Id": "41564",
"ParentId": "41559",
"Score": "9"
}
},
{
"body": "<p>The sieve can also end when you reach the square root of your maximum index. This is because at that point, you will have marked out all of the non-primes in the BitSet and you can then use the BitSet as your list of primes. Of course, this assumes that you're not counting the primes as you go. If you are, then you'd have to go through the rest of the BitSet to count the other primes. Also, you say your code is 'too slow' but you don't say how fast it needs to be. This information would be helpful in creating an answer for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T06:02:44.307",
"Id": "55297",
"ParentId": "41559",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41564",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T15:27:21.503",
"Id": "41559",
"Score": "10",
"Tags": [
"java",
"performance",
"algorithm",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes optimization"
}
|
41559
|
<p>I'm starting to learn Clojure, and would like feedback on some code I wrote to manage database migrations. Any recommendations to make it more robust, efficient, idiomatic, elegant, etc... are welcome!</p>
<pre><code>(ns myapp.models.migrations
(:require [clojure.java.jdbc :as sql]
[myapp.models.database :as db]))
;;;; Manages database migrations.
;;;;
;;;; Usage:
;;;;
;;;; user=> (migrate!) ; migrate to the latest version
;;;; user=> (migrate! 20140208) ; migrate to a specific version
(let [db-spec db/spec]
;; WARNING: Only works with PostgreSQL!
;;
;; TODO: Can this be made generic to all databases? Look into using the
;; JDBC database metadata to determine if a table exists.
(defn table-exists? [table-name]
(-> (sql/query db-spec
["select count(*) from pg_tables where tablename = ?" table-name])
first :count pos?))
;;; The migrations to apply
;;;
;;; The order in which migrations are apply is determined by the :version property.
;;; Each migration must have :apply and :remove functions so we can migrate up or down.
(def migration-0 {:version 0
:description "Starting point. Does nothing, but allows us to remove all other migrations if we want to."
:apply (fn [] nil)
:remove (fn [] nil)})
(def migration-20140208 {:version 20140208
:description "Create the articles table."
:apply (fn []
(when (not (table-exists? "articles"))
(sql/db-do-commands db-spec (sql/create-table-ddl :articles
[:title "varchar(32)"]
[:content "text"]))))
:remove (fn []
(when (table-exists? "articles")
(sql/db-do-commands db-spec (sql/drop-table-ddl :articles))))})
(def db-migrations [ migration-0
migration-20140208 ])
;;; Forms for processing the migrations.
(defn create-migrations-table! []
(when (not (table-exists? "migrations"))
(sql/db-do-commands db-spec
(sql/create-table-ddl :migrations [:version :int]))))
(defn drop-migrations-table! []
(when (table-exists? "migrations")
(sql/db-do-commands db-spec
(sql/drop-table-ddl :migrations))))
(defn migration-recorded? [migration]
(create-migrations-table!)
(-> (sql/query db-spec ["select count(*) from migrations where version = ?" (:version migration)])
first :count pos?))
(defn record-migration! [migration]
(create-migrations-table!)
(when (not (migration-recorded? migration))
(sql/insert! db-spec :migrations {:version (:version migration)})))
(defn erase-migration! [migration]
(create-migrations-table!)
(when (migration-recorded? migration)
(sql/delete! db-spec :migrations ["version = ?" (:version migration)])))
(defn migrate-up! [to-version]
(let [filtered-migrations (sort-by :version (filter #(<= (:version %) to-version) db-migrations))]
(doseq [m filtered-migrations]
(when (not (migration-recorded? m))
((:apply m))
(record-migration! m)))))
(defn migrate-down! [to-version]
(let [filtered-migrations (reverse (sort-by :version (filter #(> (:version %) to-version) db-migrations)))]
(doseq [m filtered-migrations]
(when (migration-recorded? m)
((:remove m))
(erase-migration! m)))))
(defn migrate!
([]
(let [last-migration (last (sort-by :version db-migrations))]
(when last-migration (migrate! (:version last-migration)))))
([to-version]
(let [version (or to-version 0)
migration-exists (not (nil? (some #(= (:version %) version) db-migrations)))
already-applied (migration-recorded? {:version version})]
(cond
(not migration-exists)
(println (format "migration %s was not found" version))
already-applied
(migrate-down! version)
:else
(migrate-up! version))))))
</code></pre>
|
[] |
[
{
"body": "<p>Honestly, I think this code looks great! Kudos -- this looks especially good for a beginner to Clojure. I have just a few minor improvements:</p>\n\n<pre><code>(defn create-migrations-table! []\n (when-not (table-exists? \"migrations\")\n (sql/db-do-commands db-spec\n (sql/create-table-ddl :migrations [:version :int]))))\n</code></pre>\n\n<p>Use <code>(when-not x)</code> instead of <code>(when (not x))</code> -- it'll save you a couple parentheses :)</p>\n\n<pre><code>(defn record-migration! [migration]\n (create-migrations-table!)\n (when-not (migration-recorded? migration)\n (sql/insert! db-spec :migrations {:version (:version migration)})))\n</code></pre>\n\n<p>(same thing with <code>when-not</code>)</p>\n\n<pre><code>(defn migrate-up! [to-version]\n (let [filtered-migrations (sort-by :version (filter #(<= (:version %) to-version) db-migrations))]\n (doseq [m filtered-migrations]\n (when-not (migration-recorded? m)\n ((:apply m))\n (record-migration! m)))))\n</code></pre>\n\n<p>(another opportunity to use <code>when-not</code>)</p>\n\n<pre><code>(defn migrate! \n ([]\n (when-let [last-migration (last (sort-by :version db-migrations))]\n (migrate! (:version last-migration))))\n...\n</code></pre>\n\n<p>Anytime you have a statement of the form <code>(let [x (something)] (when x (do-something)))</code>, you can simplify it to <code>(when-let [x (something)] (do-something))</code>.</p>\n\n<p>At the end, I would consider calling <code>migration-exists</code> <code>migration-exists?</code>, since it represents a boolean value.</p>\n\n<p>The only other thing that stood out for me is your inclusion of <code>(create-migrations-table!)</code> in a few of the other functions as the first line... this seems like kind of a work-around, and might potentially cause problems from a functional programming perspective. You might consider taking the <code>(when-not (table-exists? \"migrations\" ...</code> out of the function definition for <code>create-migrations-table!</code> and including it as a check in the other 3 functions, like this:</p>\n\n<pre><code>(defn create-migrations-table! []\n (sql/db-do-commands db-spec\n (sql/create-table-ddl :migrations [:version :int])))\n\n(defn record-migration! [migration]\n (when-not (table-exists? \"migrations\") \n (create-migrations-table!))\n (when-not (migration-recorded? migration)\n (sql/insert! db-spec :migrations {:version (:version migration)}))) \n</code></pre>\n\n<p>This way seems more intuitive to me -- the <code>create-migrations-table!</code> ought to assume that there isn't already one in existence, and you would expect not to use it unless you're checking <code>(table-exists? \"migrations\")</code> as a condition. On the other hand, this is wordier, so you may prefer to leave it the way it is for the sake of simplicity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:05:40.937",
"Id": "44754",
"ParentId": "41568",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "44754",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:49:12.287",
"Id": "41568",
"Score": "6",
"Tags": [
"sql",
"clojure"
],
"Title": "Database Migrations"
}
|
41568
|
<p>I am using RequireJS JavaScript library. I have the following JavaScript module define for dataservice:</p>
<pre><code>define(['jquery'], function ($) {
var callApi = function (url, type, dataType, data, callback) {
$.ajax({
url: url,
type: type,
data: data,
dataType: dataType,
contentType: "application/json",
success: function (data) {
callback(data);
}
});
};
var getData = function (url, dataType, data, callback) {
callApi(url, 'GET', dataType, data, callback);
};
var postData = function (url, data, callback) {
callApi(url, 'POST', 'json', data, callback)
};
return {
getData: getData,
postData: postData
};
});
</code></pre>
<p>Is there anything which can be improved in this module?</p>
|
[] |
[
{
"body": "<p>I really like this code.</p>\n\n<p>Still, 2 observations:</p>\n\n<ul>\n<li>The code is awfully optimistic, no default error handling ?</li>\n<li><code>success</code> gets <code>data</code>, <code>textStatus</code>, and <code>jqXHR</code>. I would pass all 3 to the callback function.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:44:21.953",
"Id": "41586",
"ParentId": "41570",
"Score": "4"
}
},
{
"body": "<p>Very nice. I like to see some <code>require.js</code> around here.</p>\n\n<ul>\n<li><p>As konijn said, you shouldn't be only passing <code>data</code> to the callback. In fact, you don't need an extra function here at all. </p>\n\n<pre><code>$.ajax({\n [...]\n success: callback\n});\n</code></pre></li>\n<li><p>Since <code>getData</code> and <code>postData</code> are not used anywhere else and are public I would just include them in the return statement.</p>\n\n<pre><code> return {\n getData: function (url, dataType, data, callback) {\n callApi(url, 'GET', dataType, data, callback);\n },\n postData: function (url, data, callback) {\n callApi(url, 'POST', 'json', data, callback)\n }\n };\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:21:13.617",
"Id": "71556",
"Score": "0",
"body": "To the second point, I agree in this two-method case, but I wouldn't once the methods grew by a line or two or if you added a method. Because that can happen easily, I would probably avoid merging them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:54:37.613",
"Id": "71662",
"Score": "0",
"body": "@DavidHarkness Agreed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:06:15.367",
"Id": "41588",
"ParentId": "41570",
"Score": "3"
}
},
{
"body": "<p>You're passing in a lot of parameters to all of these functions. This might present a usability issue as the developer who uses the functions has to remember the order in which to pass the parameters.</p>\n\n<p>It might be easier to use if the functions accepted a single object parameter:</p>\n\n<pre><code>var callApi = function (options) {\n $.ajax({\n url: options.url,\n type: options.type,\n data: options.data,\n dataType: options.dataType,\n contentType: \"application/json\",\n success: function (data) {\n options.callback(data);\n }\n });\n};\n\nvar getData = function (options) {\n options.type = 'GET';\n callApi(options);\n};\n\nvar postData = function (options) {\n options.type = 'POST';\n options.dataType = 'json';\n callApi(options);\n};\n</code></pre>\n\n<p>And then you'd call your functions like:</p>\n\n<pre><code>var options = {\n url: 'http://api.example.com/post.svc',\n data: { \"id\": 34021 },\n callback: success\n};\ndataservice.postData(options);\n</code></pre>\n\n<p>This also means that if the developer misses a variable, you can fall back to default options in the public facing functions without breaking the order in which parameters are passed.</p>\n\n<pre><code>var postData = function (options) {\n options.type = 'POST';\n options.dataType = 'json';\n\n if (!options.callback) {\n options.callback = genericSuccess;\n }\n\n callApi(options);\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:36:08.410",
"Id": "41638",
"ParentId": "41570",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:07:31.377",
"Id": "41570",
"Score": "4",
"Tags": [
"javascript",
"require.js"
],
"Title": "Is there anything can be improved in this JavaScript module?"
}
|
41570
|
<p>I am having some issue to use PHP5 <code>password_hash()</code> function. My server is not supporting it, so I am using a function to hash. Is this one secure?</p>
<pre><code>public function Pass_Hash ($password) {
$blowfish_salt = bin2hex(openssl_random_pseudo_bytes(22));
$hash = md5(crypt($password, "X1;G^COU8U`Bo*A6@9<on5yQ6P87M]".$blowfish_salt));
return $hash;
}
</code></pre>
<p>I read lot of articles regarding password hashing. Can anyone help me rewrite it more securely?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:51:59.890",
"Id": "71467",
"Score": "2",
"body": "Why do you hash the `crypt` hash with `md5`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:53:38.423",
"Id": "71469",
"Score": "0",
"body": "To make it look like Md5 only any issues?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:01:25.980",
"Id": "71470",
"Score": "4",
"body": "I don't know about any issues, but I would rather use one strong hash algorithm, than mixing two. Mixing can only reduce the security."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:42:01.737",
"Id": "71513",
"Score": "1",
"body": "Relevant article: https://crackstation.net/hashing-security.htm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:18:01.763",
"Id": "71633",
"Score": "0",
"body": "The PHP5 password_hash() function isn't available everywhere, but there are some drop-in replacements for it. I recommend you use one of those; then you can upgrade to the real password_hash() function without difficulty when it becomes available."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T15:47:55.863",
"Id": "74306",
"Score": "1",
"body": "Can you use the [`password_compat` library](https://github.com/ircmaxell/password_compat) It's a drop in replacement for `password_hash` by the same author."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:12:12.137",
"Id": "109766",
"Score": "2",
"body": "Cryptography is hard. Doing it yourself will only cause security issues. It is better to use a library made by experts. You can take a look at http://stackoverflow.com/a/17073604/393157 to find a suitable library."
}
] |
[
{
"body": "<p>No.</p>\n\n<h2>Concern 1:</h2>\n\n<p>Most password hashing libraries will perform a hash recursively 2<sup>n</sup> times. On modern systems, they choose 2<sup>8</sup> or higher (resulting in 512 hashes).</p>\n\n<p>While you are using a salt, you're only hashing the password once. This would allow a hacker to create a rainbow table with considerably less effort.</p>\n\n<h2>Concern 2:</h2>\n\n<p>If you're creating a random salt everytime, you'll never be able to verify the password. I would pass the salt in (or return the salt with the hash), that way the hash is repeatable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:39:23.803",
"Id": "71488",
"Score": "1",
"body": "Actually, the salt isn't really random. Only the constant part is used over and over. See my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:47:12.033",
"Id": "41578",
"ParentId": "41571",
"Score": "6"
}
},
{
"body": "<p>NO NO NO NO NO!</p>\n\n<p>Besides what others have pointed out, I find some serious flaws in your code.</p>\n\n<ul>\n<li>You are <strong>not</strong> actually using blowfish. To use blowfish, your salt must begin with something like <code>$2y$07$</code> see the <a href=\"http://www.php.net/crypt\" rel=\"nofollow noreferrer\">PHP Documentation</a></li>\n<li>Removing your <code>$blowfish_salt</code> variable from the code <strong>makes no difference!</strong> This will produce <strong>the same output</strong>. Therefore, we conclude that you are actually using a <strong>constant</strong> salt in your code.</li>\n<li>The output of <code>crypt</code> is more secure than MD5. MD5 is an algorithm that is known to have a lot of duplicates. Many different inputs will produce the same results. That's not optimal. Using <strong>real blowfish algorithm</strong> is even more secure than what you currently have.</li>\n</ul>\n\n<p>Here is some testing code I used to come to my conclusions:</p>\n\n<pre><code><?php\n$password = \"bubu\";\n $blowfish_salt = bin2hex(openssl_random_pseudo_bytes(22));\n\n$blowfish_salt = \"11b19e4e03d32f27f9db5646e56f63458113e9da56f7\"; // Since this is the only randomness, I have replaced the randomness with this constant.\n\necho \"salt is $blowfish_salt<br />\";\n\n$first = crypt($password, \"X1;G^COU8U`Bo*A6@9<on5yQ6P87M]\".$blowfish_salt);\necho $first . \" ... constant with what you call blowfish<br />\";\n\n$hash = md5($first); \necho $hash . \" ... md5-ed version of above. This is the result of your current code<br />\";\necho md5(crypt($password, \"X1;G^COU8U`Bo*A6@9<on5yQ6P87M]\")) . \" ... and oops, that was exactly the same!<br />\";\n\n$first = crypt($password, \"X1;G^COU8U`Bo*A6@9<on5yQ6P87M]\");\necho $first . \" ... constant salt<br />\";\n\n$first = crypt($password, $blowfish_salt);\necho $first . \" ... only blowfish salt<br />\";\necho \"<br />\";\necho \"BELOW USING 2Y PADDING:<br />\";\necho \"<br />\";\n$first = crypt($password, \"\\$2y\\$07\\$X1;G^COU8U`Bo*A6@9<on5yQ6P87M]\".$blowfish_salt);\necho $first . \" ... a lot, with blowfish. Causes error because salt is too long<br />\";\n\n$first = crypt($password, \"\\$2y\\$07$\\X1;G^COU8U`Bo*A6@9<on5yQ6P87M]\");\necho $first . \" ... constant salt. Still causes error because salt is too long<br />\";\n\n$first = crypt($password, \"\\$2y\\$07\\$\".$blowfish_salt);\necho $first . \" ... only blowfish salt. And now THAT is blowfish!<br />\";\n\necho \"<br />\";\necho \"Now back to md5 with this result again:<br />\";\n\n$hash = md5($first); \necho $hash;\n?>\n</code></pre>\n\n<p>The output of this is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>salt is 11b19e4e03d32f27f9db5646e56f63458113e9da56f7\nX154A2VqJVf4I ... constant with what you call blowfish\n7b5f3730488255efcff9441a238d5c5d ... md5-ed version of above. This is the result of your current code\n7b5f3730488255efcff9441a238d5c5d ... and oops, that was exactly the same!\nX154A2VqJVf4I ... constant salt\n11Xw1fe5HDjyo ... only blowfish salt\n\nBELOW USING 2Y PADDING:\n\n*0 ... a lot, with blowfish. Causes error because salt is too long\n*0 ... constant salt. Still causes error because salt is too long\n$2y$07$11b19e4e03d32f27f9db5uyeLJeUJh/VUoi1RFtAoDAE.eegj4bwO ... only blowfish salt. And now THAT is blowfish!\n\nNow back to md5 with this result again:\ne35cb490b47d3211dac9f85acfc2fb15\n</code></pre>\n\n<p>Please, take your time and study these results. Look at the code. Look at the results. Look at the code again. Look at the results again. Now look at the code one more time: Do you see the flaws? If you don't, I pointed them out at the beginning of my answer.</p>\n\n<p>What you should do:</p>\n\n<ol>\n<li>Generate a salt, store that somewhere (as suggested by Chris). Get rid of that constant-salt you have.</li>\n<li><p><strong>Use the real blowfish, and don't use MD5 afterwards</strong></p>\n\n<pre><code>public function Pass_Hash ($password, $blowfish_salt) {\n $hash = crypt($password, \"\\$2y\\$07\\$\" . $blowfish_salt)); \n return $hash;\n}\n$generated_salt = bin2hex(openssl_random_pseudo_bytes(22));\nPass_Hash(\"a very secret password\", $generated_salt);\n</code></pre></li>\n</ol>\n\n<p>Now we're talking.</p>\n\n<p>However, I should add that I am not a security experts. There are likely several more aspects that one can think of. If you are interested in security and secure stuff, I recommend paying our StackExchange friends at <a href=\"https://security.stackexchange.com/\">Information Security</a> a visit. But in the end I think that the question is: <em>How secure do you want to be?</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:42:44.660",
"Id": "71572",
"Score": "0",
"body": "Thank you very much... I rewrite as per your suggestions and findings its now public function Pass_Hash ($password) {\n \n $generated_salt = bin2hex(openssl_random_pseudo_bytes(22));\n $hash = crypt($password, \"\\$2y\\$07\\$\" . $blowfish_salt); \n \n return $hash;\n} Is this ok now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:51:03.363",
"Id": "71574",
"Score": "0",
"body": "I am planning to use https://crackstation.net/hashing-security.htm#phpsourcecode this library. But while i try to hash a password using $mypass = create_hash(\"Password123\"); its generating sha256:1000:EzeYvaE4tVPzpWJ51l+etMvcj1qKZF26:G3GncF0rC4q86yWh7A0GTdrXLuciXGMw you mean i have to store this hash to DB? But in every refresh it changes why its changing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:35:15.403",
"Id": "71603",
"Score": "0",
"body": "@BANNA It seems like you are lacking a lot of understanding about the available hashing methods. Please read the documentation for the functions that you are using. Whether your functions are \"ok\" or not really depends on one thing: Are you able to use them? Do they work for you? Can you compare if an entered password is the same as a stored password with them? If you are unable to do that, I suggest showing what you have tried and explaining what the problem is and ask on [so]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T15:49:30.637",
"Id": "74307",
"Score": "0",
"body": "`bin2hex(openssl_random_pseudo_bytes(22))` is still clearly wrong. The salt bcrypt salt is 16 bytes encoded with a Base64 variant (not hex), producing 22 characters."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:38:54.847",
"Id": "41582",
"ParentId": "41571",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "41582",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:21:46.380",
"Id": "41571",
"Score": "12",
"Tags": [
"php",
"security",
"cryptography"
],
"Title": "Password hashing method"
}
|
41571
|
<p><strong>Scenario:</strong> I am using a helper class called 'OutputHelper' to add a new record to the table 'Output'. My 'Output' object contains the following:</p>
<ul>
<li>ShiftID </li>
<li>Model</li>
<li>WorksOrder</li>
<li>LotNo</li>
<li>Quantity</li>
<li>ShiftHour</li>
</ul>
<p>I do not want a record to be added if a record already exists with the ShiftID and ShiftHour of the record that I am trying to add.</p>
<p>The way I am achieving this currently is having the property 'RecordOutput' in the helper class try and add the record then return a string which I handle with a switch statement and provide feedback to the user accordingly.</p>
<p>This seems to be working fine but I can't help but think it's a terrible way of doing things. Can anyone provide any feedback and suggestions for improvement? </p>
<p><strong>Output helper class:</strong></p>
<pre><code>public class OutputHelper
{
public string RecordOutput(Models.Output output)
{
var shiftId = output.ShiftID;
var shiftHour = output.ShiftHour;
using (var db = new TestContext())
{
try
{
if (db.Outputs.Any(x => x.ShiftID == shiftId && x.ShiftHour == shiftHour))
{
return "Exists";
}
db.Outputs.Add(output);
db.SaveChanges();
}
catch (Exception)
{
return "NotSaved";
}
return "Success";
}
}
}
</code></pre>
<p><strong>Code from button click on form</strong></p>
<pre><code> var outputHelper = new OutputHelper();
switch (outputHelper.RecordOutput(output))
{
case "Exists":
lblErrorMessage.Text = "Output already recorded for this timeframe";
failMessage.Visible = true;
break;
case "Not Saved":
lblErrorMessage.Text = "There was a problem saving this record. Please try again";
failMessage.Visible = true;
break;
default:
lblSuccess.Text = "Output record added to database";
successMessage.Visible = true;
ResetForm();
break;
}
</code></pre>
|
[] |
[
{
"body": "<h3>String literals vs. constants vs. enums</h3>\n<p>I think that the biggest terrible thing that you are doing here is 1) using magic string literals that are not defined as constants. 2) using a string when you can use an <code>enum</code> instead.</p>\n<pre><code>public enum SaveResult\n{\n Exists, NotSaved, Success\n}\n</code></pre>\n<p>In fact, your current code returns <code>"NotSaved"</code>, while you check for <code>case "Not Saved":</code>. <strong>That's why you should use constants or an enum!</strong> Also, having success as the "default" case is not something I would recommend. It'd be better to assume failure unless success has been explicitly confirmed. Or even better, default is for "Oops, I forgot to check this case explicitly!", which would help you notice that you had written <code>"Not Saved"</code> instead of <code>"NotSaved"</code>.</p>\n<p>In the end, an enum is the choice I would recommend here.</p>\n<h3>Catching</h3>\n<p>That said and done, I really question the <code>catch (Exception)</code>. In my experience, you should only catch the exceptions that you really need to catch. If the code would throw a <code>NullReferenceException</code> for example, that should propagate upwards and tell you that there is a serious bug in the code that needs to be fixed. Some Exceptions are just not meant to be caught.</p>\n<h3>Your question, and the database aspect</h3>\n<p>Besides this, I think that what you are doing here is reasonable. I think that it is However, I would also like to point out that if you are using a RDMS here, then you might want to make your table have a primary key - or another unique index - over two columns: Both <code>ShiftId</code> and <code>ShiftHour</code>. Technically, that's the only way to really make sure that your table will not have duplicates over these values. Personally, I think it is perfectly OK to do a select-before-insert though. I think that is better than inserting without knowing if things go wrong or not, and catching the appropriate exception if things actually have gone wrong - i.e. a duplicate existed.</p>\n<p>Be aware though, that after your <code>SELECT</code> query checking for a duplicate and before your <code>INSERT</code> query, there can theoretically be another query that just inserted a duplicate, effectively causing a race-condition. If such a situation would occur, the catch would still catch it of course (assuming you have the appropriate indexes in your table set up).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T06:40:18.440",
"Id": "71580",
"Score": "1",
"body": "I agree on the catch, it is better to have your exceptions bubble up to the UI layer and have the UI layer display the exception. In fact, I would in the Data Layer wrap expected exceptions, then have the UI display the exception (knowing that you have no write permissions is much nicer than , \"ERROR\"). Also, NEVER use a string when an Enum can do the job. Finally, I would write bulk insert methods, as your code will do 3/4 queries over 2 or so round trips per insert."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:29:45.010",
"Id": "41575",
"ParentId": "41572",
"Score": "8"
}
},
{
"body": "<p>Instead of a string, return a boolean. This simplifies the testing on the outside. For the exception case, add the information you want and then rethrow and catch in the outer method. Also, if OutputHelper is only a wrapper for the database functions, you can make the class static, which would save you from having to create an instance of it in the click method</p>\n\n<pre><code>public static class OutputHelper\n{\n public static bool RecordOutput(Models.Output output)\n {\n var shiftId = output.ShiftID;\n var shiftHour = output.ShiftHour;\n\n using (var db = new TestContext())\n {\n try\n {\n if (db.Outputs.Any(x => x.ShiftID == shiftId && x.ShiftHour == shiftHour))\n {\n return false;\n }\n db.Outputs.Add(output);\n db.SaveChanges();\n return true;\n }\n catch (Exception e)\n {\n throw new Exception(\"There was a problem saving this record: \" + e.Message);\n }\n }\n }\n}\n</code></pre>\n\n<p>Then the button click code becomes:</p>\n\n<pre><code>try\n{\n if (OutputHelper.RecordOutput(output))\n {\n lblSuccess.Text = \"Output record added to database.\";\n successMessage.Visible = true;\n ResetForm();\n }\n else {\n //to keep from duplicating the code to display the error message\n throw new Exception(\"Output already recorded for this timeframe.\");\n }\n}\ncatch (Exception e)\n{\n lblErrorMessage.Text = e.Message;\n failMessage.Visible = true;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:36:46.110",
"Id": "41576",
"ParentId": "41572",
"Score": "6"
}
},
{
"body": "<p>To piggy-back on @Simon André Forsberg answer...</p>\n\n<p>Ditto, with a caveat:</p>\n\n<blockquote>\n <p>Personally, I think it is perfectly OK to do a select-before-insert though.</p>\n</blockquote>\n\n<p>because as soon as you read records into memory the data is stale - some other query could have added or deleted a row w/ that key an instant after you looked. So to read from the DB then test for existence in memory then attempt a DB insert is problematic. </p>\n\n<p>SO... do the checking in the database. Just send the record without checking first but do something like this in the database:</p>\n\n<pre><code>IF NOT EXISTS (select * from outputTable where shiftid = passedInShiftid)\n INSERT ....\nELSE\n UPDATE ....\nEND IF\n</code></pre>\n\n<p>And as noted by Simon, the above assumes <code>shiftid</code> is a primary key or at least unique. Of course you can use any combination of value(s) that defines a unique record in your table.</p>\n\n<p>And of course this also means that when you read a record, read the key as well, whatever it is so the above sql can be done when sending records back.</p>\n\n<p>Finally whatever field(s) you use for a key, DO NOT let those values be modified in the user interface once they are created.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:39:56.857",
"Id": "41603",
"ParentId": "41572",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41576",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T17:41:44.247",
"Id": "41572",
"Score": "10",
"Tags": [
"c#",
"entity-framework"
],
"Title": "'Better' way to handle adding a record"
}
|
41572
|
<p>In researching the new .NET Async and Await keywords in .NET 4.5, I created a simple example showing how to update a progress bar and a label while an async function is running. I also included how to cancel the process while it is taking place.</p>
<p>To use the code below, create a Windows form and include two buttons:</p>
<ol>
<li><code>Button1</code> = start button</li>
<li><code>Button2</code> = stop button</li>
</ol>
<p>Also add a progress bar called <code>ProgressBar1</code> and a label called <code>Label1</code>.</p>
<p>A few things to note:</p>
<ol>
<li><p>The functions use ASYNC and AWAIT "all the way down" from the initial button click to the final VB function that supports asynchronous support;</p></li>
<li><p>Note the use of the <code>cancellationtokensource</code> to signal that we want to cancel things;</p></li>
<li><p>The final asynchronous VB function we use is <code>WebClient.DownloadStringTaskAsync()</code>. This is arbitrary, and is used for example purposes only.</p></li>
</ol>
<p>Please let me know if you have any questions or problems with this code.</p>
<pre><code>' Simple progress bar example with cancellation and label updating
' Using the ASYNC and AWAIT keywords available through .Net 4.5
' Helpful sources include:
' - http://msdn.microsoft.com/en-us/library/hh191443.aspx
' - http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx
Imports System.Net
Imports System.Threading
Public Class Form1
Dim test As WebClient = New WebClient ' This is specific to the type of async function we're doing. Yours may be different.
Dim myToken As CancellationTokenSource ' This is used to notify the async function that we want to cancel it.
Dim myProgress As Progress(Of Integer) ' We use this as the vehicle for reporting progress back to our GUI thread
Dim Counter As Integer = 0 ' This is a variable that we use to track our progress (specific to this example)
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ProgressBar1.Value = 0
Counter = 0
myToken = New CancellationTokenSource
Await startProgressBar(myToken) ' Note that the signature of our startprogressbar method includes the cancellationtokensource
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If Not myToken Is Nothing Then
myToken.Cancel() ' We tell our token to cancel
End If
End Sub
Public Async Function startProgressBar(ct As CancellationTokenSource) As Task
Dim progressTarget As Action(Of Integer) ' We have to create an event handler for the function we use to report progress
progressTarget = AddressOf ReportProgress ' We assign the handler to our specific function (see below)
myProgress = New Progress(Of Integer)(progressTarget) ' When we initialize our progress reporter, we pass our handler to it
For I = 0 To 9
If ct.IsCancellationRequested = True Then
Exit For ' We then break out of the loop
End If
Dim myString As String = Await RetrieveString(myProgress) ' We don't do anything with this string, just so we can run our async function
Next
End Function
Public Async Function RetrieveString(ByVal myProgress As IProgress(Of Integer)) As Task(Of String)
Dim myString As String = ""
If Not myProgress Is Nothing Then 'If we have a valid progress object, report our progress using it
Counter = Counter + 10
myProgress.Report(Counter)
End If
myString = Await test.DownloadStringTaskAsync("http://www.cnn.com") ' This is a throwaway function - just something that uses async
Return myString ' We are really not doing anything with the results of this function, just returning it
End Function
Private Sub ReportProgress(ByVal myInt As Integer)
Label1.Text = "Step Number: " & myInt.ToString
ProgressBar1.Value = myInt
End Sub
End Class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:06:45.963",
"Id": "71472",
"Score": "2",
"body": "Why not name `Button1` as `StartButton` and `Button2` as `StopButton`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:12:25.960",
"Id": "71473",
"Score": "0",
"body": "Are these comments in your actual code or you added them in to the reviewers' attention? Comments can also be part of a code review, if they're not in your actual code I'd recommend you remove them from the code blocks and include that context in your question instead - even if it means breaking up your code block into multiple ones. See [this question](http://codereview.stackexchange.com/questions/41295/backgroundworker-vs-tpl-progressbar-exercise) for an example ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:25:26.033",
"Id": "71475",
"Score": "0",
"body": "Thank you for your feedback. Good catch - I noted too the issue with Button1 and Button2 as well. Also, the comments are simply there to explain what is happening. The reason I put this example together is that when I looked online for examples of how to update a progress bar, they almost all used BackgroundWorker. However, with .Net 4.5, I think the async and await methods are a bit easier to use."
}
] |
[
{
"body": "<blockquote>\n <p>The final asynchronous VB function we use is <code>WebClient.DownloadStringTaskAsync()</code>. This is arbitrary, and is used for example purposes only.</p>\n</blockquote>\n\n<p>This indicates to me that you should think about making this reusable, so that when you need to use the progress bar somewhere else, you don't need to copy & paste the code.</p>\n\n<hr>\n\n<pre><code>Dim progressTarget As Action(Of Integer) ' We have to create an event handler for the function we use to report progress\nprogressTarget = AddressOf ReportProgress ' We assign the handler to our specific function (see below)\nmyProgress = New Progress(Of Integer)(progressTarget) ' When we initialize our progress reporter, we pass our handler to it\n</code></pre>\n\n<p>This is way too verbose. What's wrong with just the following line?</p>\n\n<pre><code>myProgress = New Progress(Of Integer)(AddressOf ReportProgress)\n</code></pre>\n\n<p>You don't need to comment every single thing you do, that's obvious from the code.</p>\n\n<hr>\n\n<p>You should disable the button that doesn't make sense at the moment. This is especially important for the <code>StartButton</code>, because right now, the user can start the download multiple times.</p>\n\n<hr>\n\n<pre><code>Dim myString As String = \"\"\n\n' code that doesn't use myString\n\nmyString = …\n\nReturn myString\n</code></pre>\n\n<p>There is no need to declare the variable early or to set it to <code>\"\"</code>. Actually, there is no need to declare the variable at all, you can just return the expression directly.</p>\n\n<hr>\n\n<p>Names like <code>Label1</code> and <code>myInt</code> are very unhelpful. Use descriptive names like <code>ProgressLabel</code> (though that's not great either) and <code>stepNumber</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:40:06.853",
"Id": "41984",
"ParentId": "41573",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:03:32.347",
"Id": "41573",
"Score": "1",
"Tags": [
".net",
"vb.net",
"async-await"
],
"Title": "Simple async/await progress bar"
}
|
41573
|
<p>For example, with this differential equation, how can I do it in a pythonic way?</p>
<pre><code>dx/dt=f(x,t)
</code></pre>
<p>I have a way to do it, but I think this is not the most pythonic way:</p>
<pre><code>import numpy as np
dt=0.01
N_iter=10./dt
def f(x,t):
return x**2*t#insert your favorite function here
x=np.zeros(N_iter)
for i in range(N_iter-1):
x[i+1]=x[i]+dt*f(x[i],i*dt)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:50:15.710",
"Id": "71499",
"Score": "2",
"body": "What was wrong with [`scipy.integrate`](http://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:25:50.163",
"Id": "71605",
"Score": "0",
"body": "What makes you think the code isn't Pythonic? (apart from PEP8 issues)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:01:54.457",
"Id": "71641",
"Score": "0",
"body": "Well I thought that there was only one pythonic way to do something and I was wondering if I was doing it right. The problem with 'scipy.integrate' is that I must do each step in turn inside a loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:46:29.550",
"Id": "72542",
"Score": "1",
"body": "@NunoCalaim: Have you looked at [`scipy.integrate.odeint`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html)?"
}
] |
[
{
"body": "<p>Using a <code>for</code> loop is not an <em>unpythonic</em> way at all. Instead, an Euler method could be implemented with a recursive function, but it not necessary and less optimized in Python.</p>\n\n<p>However, methods for <a href=\"http://numpy-discussion.10968.n7.nabble.com/vectorizing-recursive-sequences-td35532.html\" rel=\"nofollow\">vectorizing recursive sequences</a> are discussed on the numpy-discussion mailing-list. I encourage you to use structures like <code>for</code> loops in such situations. You will minimize the risk of errors by writing simple and concise codes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T04:17:51.980",
"Id": "44226",
"ParentId": "41580",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:14:41.450",
"Id": "41580",
"Score": "6",
"Tags": [
"python",
"mathematics",
"numpy"
],
"Title": "What is the most pythonic way to solve a differential equation using the Euler method?"
}
|
41580
|
<p>I was using brute force to remove duplicate words since the lists were really small. But I want a solution that won't become too slow if the input grows.</p>
<p>This function creates a binary tree and inserts all words appearing on the list, then collects the unique words without sorting. Duplicate words are handled during insertion. For the tree, I'm using about the same code from <a href="https://codereview.stackexchange.com/questions/39282/unbalanced-binary-search-tree">Unbalanced binary search tree</a>.</p>
<pre><code>#include "bst.h"
#include <strings.h>
#include <stdlib.h>
#define LIST_TERMINATOR 1
static size_t i = 0;
static char **final_list;
static void insert(void *word)
{
final_list[i++] = word;
}
char **unique_words(const char **words)
{
//Binary tree containing the words
BST unique;
bst_init(&unique, (int(*)(const void *, const void *))strcasecmp);
//Every word will be inserted at most 1 time
while(*words != NULL){
if(bst_insert(&unique, (void *)*words) == BST_NO_MEMORY){
bst_free(&unique);
return NULL;
}
++words;
}
//Array to return
final_list = malloc(sizeof(char *) * (unique.node_count + LIST_TERMINATOR));
if(final_list == NULL){
bst_free(&unique);
return NULL;
}
//Collect words without sorting, so if the list is merged with another
//and passed again, the tree won't become a linked list
if(bst_iterate_top_down(&unique, insert) == BST_NO_MEMORY){
free(final_list);
bst_free(&unique);
return NULL;
}
final_list[i] = NULL;
bst_free(&unique);
//Clear state
i = 0;
return final_list;
}
</code></pre>
<p>Would sorting the input then removing duplicates be faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-14T17:54:26.457",
"Id": "191482",
"Score": "0",
"body": "If I'm not mistaken, isn't adding them to the Binary Search Tree somehow a sort?"
}
] |
[
{
"body": "<p>This question boils down to the number and sequence of operations. If you are building one large list but removing lots of duplicates, use a hash table or sort and uniquify the list.</p>\n\n<p>Sorting and making the list unique is <em>O(n log n)</em> at best. Removing a duplicate is <em>O(n)</em> at worst so removing <em>m</em> duplicates is <em>O(m * n)</em>. While in general <em>O(k * n) = O(n)</em>, once <em>m</em> exceeds <em>log n</em> the one-time cost of sorting the set pays for itself. And additional lookups remain <em>O(1)</em>.</p>\n\n<p>You must evaluate the costs with realistic values for <em>m</em> and <em>n</em> to decide which method is better. Of course, their values will vary over time along with the relative costs of CPU versus RAM versus disk. But for most \"probable\" values of <em>m</em> and <em>n</em> over time, relying on standard library collection classes--with a sprinkle of tuned variations from Guava and the like--is the hands-down winner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:45:04.850",
"Id": "41616",
"ParentId": "41581",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41616",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:34:29.620",
"Id": "41581",
"Score": "6",
"Tags": [
"performance",
"algorithm",
"c"
],
"Title": "Removing duplicate words from an unsorted list"
}
|
41581
|
<p>For exercise, I wrote this code:</p>
<pre><code>def BigPrime(numP, plist = [], x = 1, counter =0):
while len(plist) <= numP:
if x == 1 or x == 2 or x == 5:
plist.append(x)
elif x % 2 is not 0 and int(str(x)[-1]) is not 5:
for div in plist[1:]:
if x % div == 0:
break
else:
plist.append(x)
counter += 1
x += 1
return plist, counter
</code></pre>
<p>It is a simple algorithm that should return a list of the first <em>n</em> primes. When I tried to optimize it, I wanted to cut down all the possible already know not primes from the range. That brought me to:</p>
<pre><code>int(str(x)[-1]) is not 5
</code></pre>
<p>But then when I timed it, I saw that the code ran slower. Why? It worked, and the <code>for</code> iterations were less indeed, but yet it was slower.</p>
<p>Also, when it comes to optimization, I'm a black hole of ignorance. Any further way I could improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:43:38.543",
"Id": "71506",
"Score": "0",
"body": "1 is not a prime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:28:27.320",
"Id": "71508",
"Score": "0",
"body": "Yeah you're right, the number 1 has been excluded from the prime numbers. We can say that the number 1 is kind of inconvenient for the mathematical pattern of prime numbers, we can say that you can factor any non prime number into a product of primes, like: 24 = 3 * 2^3. If we include the 1 we can write it like: 24 = 3 * 2^3 * 1^153 and nothing would change. But 1 still remains a prime afterall because he follow the general rules nPrime = 1 x nPrime ( 1 = 1 x 1 ).\nI just don't care being this formal for this little algorithm :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:33:23.753",
"Id": "71510",
"Score": "0",
"body": "Putting 1 into `plist` forces you to write the loop as `for div in plist[1:]:` whereas if you left it out you could write `for div in plist:` and avoid the copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:36:02.120",
"Id": "71512",
"Score": "0",
"body": "True that! Being lazy almost never pays back. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:15:01.683",
"Id": "71554",
"Score": "0",
"body": "Aside: don't use `is not 0`, use `!= 0`; `is` tests identity, and you want to test equality. It's only an implementation detail that it works at all."
}
] |
[
{
"body": "<p>Well for starters:</p>\n\n<p><code>int(str(x)[-1])</code> is a really expensive operation:</p>\n\n<ol>\n<li>Go from integer (x) to a string that represents X</li>\n<li>Get the last element as a char [-1]</li>\n<li>Transform that char back to an integer</li>\n</ol>\n\n<p>Given what you're trying to do (find if the last digit is a 5), the same operation can be achieved with <code>x%10==5</code> or <code>x%51=5</code> (all integer operations, way less expensive). This could be damaging your performance a lot.</p>\n\n<p>Doing a quick experiment:</p>\n\n<pre><code>$> def test1():\n k = time.clock()\n s = int(str(55)[-1]) is not 4\n t = time.clock()\n print(t-k)\n\n$> def test2():\n k = time.clock()\n s = (55%10 != 4)\n t = time.clock()\n print(t-k)\n</code></pre>\n\n<hr>\n\n<pre><code>$> test1()\n1.682255089008322e-05\n$> test2()\n1.7107678900174506e-06\n</code></pre>\n\n<p><code>test2()</code> takes one order of magnitude less than <code>test1()</code> just because of the type of operations.</p>\n\n<p>For your problem space, I think trying to find useful properties of prime numbers that you can exploit is the best way to optimize. For example, a number <code>N</code> doesn't have a prime divisor greater than <code>Sqrt(N)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:34:11.440",
"Id": "71511",
"Score": "0",
"body": "Well, that's what i feared. I tried that way because i thought that as it went further and further with the numbers it would become harder simply dividing by 5 than just looking at the last digit. Is that option always faster than the other? At what order of magnitude could change?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:14:13.413",
"Id": "71515",
"Score": "0",
"body": "I can't answer all of the details as it would depend a lot on how Python implements some operations internally, but I think I can guarantee you that dividing by 5 will always be cheaper, because going from an integer to a string always requires at least 1 modulus (division) operation, making it at least as expensive as the original division anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:26:15.410",
"Id": "71517",
"Score": "0",
"body": "Awesome! Thank you, then it's never going to be cheaper if i have to do two divisions at least for that instruction, plus the iteration for the [-1] part, as you said. You've been of great help!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:39:04.500",
"Id": "41593",
"ParentId": "41583",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41593",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:45:13.327",
"Id": "41583",
"Score": "7",
"Tags": [
"python",
"optimization",
"primes"
],
"Title": "Strange performance difference"
}
|
41583
|
<p>I have a Factory class for a queuing system I'm playing around with.</p>
<p>Consuming classes only care that they get a particular interface (Job) as a result of calling the factory's load method. </p>
<p>Some Jobs may require a database connection, so I want to inject a PDO instance. Others may require something else, and I don't want to give all Jobs a PDO instance regardless of whether they need it.</p>
<p>This is what I've ended up with:</p>
<p>IoC class:</p>
<pre><code>use Queue\Job\MeterData;
use PDO;
class IoC
{
const DATABASE = 'db';
const METER_DATA_JOB = 'job_meterData';
public function get($item)
{
switch ($item) {
case self::DATABASE:
return new PDO('');
case self::METER_DATA_JOB:
return new MeterData($this->get(self::DATABASE));
}
}
}
</code></pre>
<p>Resulting Queue Factory class:</p>
<pre><code>namespace Queue\Job;
use IoC;
class Factory
{
const METER_DATA = 'meter-data';
private $ioc;
public function __construct(IoC $ioc)
{
$this->ioc = $ioc;
}
public function load($job)
{
switch ($job) {
case self::METER_DATA:
return $this->ioc->get(IoC::METER_DATA_JOB);
default:
throw new \Exception('No job class found for ' . $job);
}
}
}
</code></pre>
<p>In my mind having the Factory isn't strictly necessary but is advantageous, as I can doc-comment the load method and it will ensure that consuming code knows what type of object it is dealing with. It'll also keep all queue jobs together neatly, rather than having the consuming code access the IoC container directly instead of the more specific Queue Factory.</p>
<p>The problem is, if we assume that IoC container is going to be one class for a full application, isn't it going to get very messy very quickly, with a ton of import statements and such?</p>
<p>Is that really such an issue, because at least it will be limited to just the IoC container and it will keep the rest of the application clear?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:14:16.847",
"Id": "71502",
"Score": "0",
"body": "Are you... attempting to implement you own IoC container?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:17:03.577",
"Id": "71504",
"Score": "0",
"body": "Probably not. This is just a learning exercise rather than production code. If production it'd be ZF2 or Laravel's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:37:11.523",
"Id": "80342",
"Score": "1",
"body": "How would you be able to tell what host, and with which credentials this particular `PDO` instance is supposed to be created? I mean: `get` produces an instance, but I can't pass arguments (like other dependencies I already have created) to this IoC container class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:04:35.727",
"Id": "80359",
"Score": "0",
"body": "You'd name it under a different key, assuming it was for a different purpose. The question wasn't really about this simple IoC container example though, but the way in which one is used."
}
] |
[
{
"body": "<p>No. What you are doing is called <strong>The Service Locator Antipattern</strong>. And it's a bad thing.</p>\n\n<p>The basic rule of thumb: <strong>Don't inject the container!</strong>.</p>\n\n<p>The IoC container is supposed to be some sort of overseer, wiring your objects together at the bootstrap and configuration level. It isn't an object that's supposed to be injected into other objects, to create objects there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-28T15:32:37.033",
"Id": "89844",
"Score": "0",
"body": "Thanks for your answer. What would be a good alternative?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-28T15:54:35.743",
"Id": "89847",
"Score": "0",
"body": "@bcmcfc: Like I said, the basic rule of thumb is **Don't inject the container**. The DIC or IoC (or whatever you'd like to call it) sits outside of your application object tree, it oversees everything and wires things together. For a good IoC example in PHP, see [Auryn](https://github.com/rdlowrey/Auryn)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T12:14:41.210",
"Id": "51818",
"ParentId": "41587",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "51818",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:02:35.243",
"Id": "41587",
"Score": "7",
"Tags": [
"php",
"design-patterns",
"dependency-injection"
],
"Title": "Is this a sensible way of using an IoC container?"
}
|
41587
|
<p>This is an implementation of Bloom filter with <code>add</code> and <code>contain</code> functionality. I'm looking for code review, best practices, optimizations etc.</p>
<p>I'm also verifying complexity: \$O(1)\$</p>
<pre><code>public class BloomFilter<E> {
private final BitSet bitSet;
private final int hashFunctionCount;
private final MessageDigest md5Digest;
/**
* Constructs an empty Bloom filter. The optimal number of hash functions (k) is estimated from the total size of
* the Bloom and the number of expected elements.
*
* @param bitSetSize
* defines how many bits should be used in total for the filter.
* @param expectedNumberOfElements
* defines the maximum number of elements the filter is expected to contain.
* @throws NoSuchAlgorithmException
*/
public BloomFilter(int bitSetSize, int expectedNumberOfElements) throws NoSuchAlgorithmException {
bitSet = new BitSet(bitSetSize);
/*
* The natural logarithm is the logarithm to the base e, where e is an irrational and
* transcendental constant approximately equal to 2.718281828.
*/
hashFunctionCount = (int) Math.round((bitSetSize / (double)expectedNumberOfElements) * Math.log(2.0));
md5Digest = java.security.MessageDigest.getInstance("MD5");
}
/**
* Generates digests based on the contents of an array of bytes and splits the result into 4-byte int's and store them in an array. The
* digest function is called until the required number of int's are produced. For each call to digest a salt
* is prepended to the data. The salt is increased by 1 for each call.
*
* @param data specifies input data.
* @param hashes number of hashes/int's to produce.
* @return array of int-sized hashes
*/
private int[] createHashes(byte[] data) {
int[] result = new int[hashFunctionCount];
int k = 0;
byte salt = 0;
while (k < hashFunctionCount) {
byte[] digest;
synchronized (md5Digest) {
md5Digest.update(salt);
salt++;
digest = md5Digest.digest(data);
}
/*
* we divide an array into blocks of 4 for example:
* - 100 length digest array is broken into pieces of 25
*
* But i advances by 4, not by 25.
*/
for (int i = 0; i < digest.length/4 && k < hashFunctionCount; i++) {
int h = 0;
// 4 bits are consumed for a single hash.
for (int j = (i*4); j < (i*4)+4; j++) {
h <<= 8;
h |= ((int) digest[j]) & 0xFF;
}
result[k] = h;
k++;
}
}
return result;
}
private int getBitIndex(int hash) {
return Math.abs(hash % bitSet.size());
}
/**
* Adds all elements from a Collection to the Bloom filter.
* @param c Collection of elements.
*/
public void addAll(Collection<? extends E> c) {
for (E element : c)
add(element);
}
/**
* Adds an object to the Bloom filter. The output from the object's
* toString() method is used as input to the hash functions.
*
* @param element is an element to register in the Bloom filter.
*/
public void add(E element) {
add(element.toString().getBytes());
}
private void add(byte[] bytes) {
int[] hashes = createHashes(bytes);
for (int hash : hashes)
bitSet.set(getBitIndex(hash), true);
}
/**
* Returns true if all the elements of a Collection could have been inserted
* into the Bloom filter.
* @param c elements to check.
* @return true if all the elements in c could have been inserted into the Bloom filter.
*/
public boolean containsAll(Collection<? extends E> c) {
for (E element : c)
if (!contains(element))
return false;
return true;
}
/**
* Returns true if the array of bytes could have been inserted into the Bloom filter.
*
* @param bytes array of bytes to check.
* @return true if the array could have been inserted into the Bloom filter.
*/
public boolean contains(E element) {
return contains(element.toString().getBytes());
}
private boolean contains(byte[] bytes) {
for (int hash : createHashes(bytes)) {
if (!bitSet.get(getBitIndex(hash))) {
return false;
}
}
return true;
}
/**
* Sets all bits to false in the Bloom filter.
*/
public void clear() {
bitSet.clear();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
BloomFilter<String> bloomFilter = new BloomFilter<String>(10, 2);
bloomFilter.add("sachin");
bloomFilter.add("tendulkar");
System.out.println(bloomFilter.contains("sachin"));
System.out.println(bloomFilter.contains("tendulkar"));
System.out.println(bloomFilter.contains("rahul"));
System.out.println(bloomFilter.contains("dravid"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:16:15.097",
"Id": "71528",
"Score": "1",
"body": "Instead of a comment telling us what `e` is, why not indicate why it is important? Why are setting it to `(int) Math.round((bitSetSize / (double)expectedNumberOfElements) * Math.log(2.0));` and not to `(int)Math.sqrt(bitSetSize * bitSetSize + expectedNumberOfElements * expectedNumberOfElements)` ?"
}
] |
[
{
"body": "<ol>\n<li><p>Where's the class-level documentation?</p></li>\n<li><p> </p>\n\n<pre><code>private final MessageDigest md5Digest;\n</code></pre>\n\n<p>will need renaming if you change your hash function. Better to call it <code>hasher</code>?</p></li>\n<li><p> </p>\n\n<pre><code> * Constructs an empty Bloom filter. The optimal number of hash functions (k) is estimated from the total size of\n * the Bloom and the number of expected elements.\n</code></pre>\n\n<p>Great, but would it be useful to have a function to estimate an optimal filter size?</p></li>\n<li><p> </p>\n\n<pre><code> * @throws NoSuchAlgorithmException \n</code></pre>\n\n<p>isn't very useful. You could say under what conditions it will throw that exception, but basically the conditions come down to \"the JRE violates the spec, which says that MD5 will be supported\", so it would be more sensible to catch the <code>NoSuchAlgorithmException</code> and rethrow it wrapped in a <code>RuntimeException</code>. Then just include a unit test to make sure you haven't typoed <code>\"MD5\"</code>.</p></li>\n<li><p> </p>\n\n<pre><code> /*\n * The natural logarithm is the logarithm to the base e, where e is an irrational and \n * transcendental constant approximately equal to 2.718281828. \n */\n</code></pre>\n\n<p>As rolfl commented, this is a useless comment. Logarithms and <code>e</code> are far more basic concepts than Bloom filters, but you haven't tried to define Bloom filters anywhere. A useful comment here would be a literature reference to justify the estimate.</p></li>\n<li><p> </p>\n\n<pre><code> * Generates digests based on the contents of an array of bytes and splits the result into 4-byte int's and store them in an array. The\n * digest function is called until the required number of int's are produced. For each call to digest a salt\n * is prepended to the data. The salt is increased by 1 for each call.\n</code></pre>\n\n<p>seems like a lot of implementation detail for the javadoc. I would be inclined to inline <code>getBitIndex</code> into this method, rename it <code>getBuckets</code>, and simplify the javadoc to something like</p>\n\n<pre><code> * Hashes the data to generate a set of filter buckets.\n</code></pre>\n\n<p>(on the assumption that the use of buckets is documented at the class level, either directly or via literature reference).</p></li>\n<li><p> </p>\n\n<pre><code> * @param hashes number of hashes/int's to produce.\n</code></pre>\n\n<p>doesn't seem to correspond to a parameter of the method.</p></li>\n<li><p> </p>\n\n<pre><code> * we divide an array into blocks of 4 for example:\n * - 100 length digest array is broken into pieces of 25 \n * \n * But i advances by 4, not by 25.\n</code></pre>\n\n<p>confused me. I had to read the code to understand the comment, which rather defeats the purpose. <em>Why</em> are you splitting it?</p>\n\n<pre><code> * The MessageDigest output has far more entropy than we need, so\n * we break it into 4-byte chunks and use each chunk to compute a\n * bucket index.\n</code></pre></li>\n<li><p> </p>\n\n<pre><code> int h = 0;\n // 4 bits are consumed for a single hash.\n for (int j = (i*4); j < (i*4)+4; j++) {\n h <<= 8;\n h |= ((int) digest[j]) & 0xFF;\n }\n</code></pre>\n\n<p>is something which could be pulled out into a general-purpose bit bashing library, as a function <code>toIntBigEndian(byte[] buf, int off)</code>. Also, that cast is unnecessary: <code>byte</code>s and <code>short</code>s are automatically promoted to <code>int</code> by any arithmetic or bitwise operation.</p></li>\n<li><p> </p>\n\n<pre><code> for (int i = 0; i < digest.length/4 && k < hashFunctionCount; i++) {\n</code></pre>\n\n<p>seems more complicated to me than</p>\n\n<pre><code> for (int i = 0; i + 3 < digest.length && k < hashFunctionCount; i += 4) {\n</code></pre>\n\n<p>and frankly you can safely use</p>\n\n<pre><code> for (int i = 0; i < digest.length && k < hashFunctionCount; i += 4) {\n</code></pre>\n\n<p>because there's no widely used MessageDigest whose output isn't a multiple of 32 bits.</p></li>\n<li><p> </p>\n\n<pre><code> * Adds an object to the Bloom filter. The output from the object's\n * toString() method is used as input to the hash functions.\n</code></pre>\n\n<p>Two things: firstly, the fact that it uses the object's <code>toString()</code> as its identity is something that should be mentioned at the class level. Secondly, it strikes me as a bad idea anyway. If you're only working with strings, make that explicit by taking strings instead of genericising the class. Alternatively, add a field for a \"serialiser\" object which converts <code>E</code> to <code>byte[]</code>, with the default being one that works via <code>toString()</code>.</p></li>\n<li><p> </p>\n\n<pre><code>element.toString().getBytes()\n</code></pre>\n\n<p>is a bit suspect. You could get different results with the same test case on different machines, or even on the same machine in different locales.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:21:25.950",
"Id": "41646",
"ParentId": "41589",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41646",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:09:25.290",
"Id": "41589",
"Score": "4",
"Tags": [
"java",
"algorithm",
"bloom-filter"
],
"Title": "Bloom filter implementation"
}
|
41589
|
<blockquote>
<p>Rewrite the routines <code>day_of_year</code> and <code>month_day</code> with pointers instead of indexing.</p>
</blockquote>
<p>The exercise is quite simple, this is the solution:</p>
<pre><code>int day_of_year(unsigned int year, int month, int day) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((month >= 1 && month <= 12) && ((day >= 1) && (day <= *(*(daytab + leap) + month)))) {
for(i = 1; i < month; i++) {
day += *(*(daytab + leap) + i);
}
return day;
}
return -1;
}
int month_day(unsigned int year, int yearday, int *pmonth, int *pday) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 365))) {
for(i = 1; yearday > *(*(daytab + leap) + i); i++) {
yearday -= *(*(daytab + leap) + i);
}
*pday = yearday;
*pmonth = i;
return 1;
}
return -1;
}
</code></pre>
<p>The expression <code>(daytab + leap)</code> is a pointer to the <code>leap</code>-th row and <code>(*(daytab + leap) + i)</code> is a pointer to the <code>i</code>-th element of the <code>leap</code>-th row.</p>
|
[] |
[
{
"body": "<p>It would have been nice to see your <code>daytab</code> definition as well. I'll just assume that you're satisfied with the way it's defined, and that the functions work as intended.</p>\n\n<p>I find this condition in <code>month_day()</code> a bit monstrous:</p>\n\n<pre><code>if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 365)))\n</code></pre>\n\n<p>I would shorten it to the following. Also, I've inverted the check, so that the function returns early if the parameters fail validation. Returning early is a better habit, as it reduces indentation, and reduces mental load when reading the code by getting the simpler branch out of the way.</p>\n\n<pre><code>int leap = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));\nif (yearday < 1 || yearday > 365 + leap) {\n return -1;\n}\nfor (…) {\n …\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:31:27.213",
"Id": "71735",
"Score": "0",
"body": "But in this case I have to declare the variable `i` after the `if`. Is it recommended to declare variables in other places than the beginning of a routine?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:01:33.780",
"Id": "41609",
"ParentId": "41590",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41609",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:15:01.043",
"Id": "41590",
"Score": "4",
"Tags": [
"c",
"beginner",
"array",
"datetime",
"pointers"
],
"Title": "Writting day_of_month and month_day with pointers instead of array indexing"
}
|
41590
|
<p>The following code is helpful to anyone who uses websockets in general... and is probably good template for anyone getting started in this area. I'd like to flesh this out into something that is more general purpose, and reusable, since the assumptions and questions I have will apply to many different situations. </p>
<p>Assumptions:</p>
<ol>
<li><p>The Timespan "Delay" is used to tell the server my client is OK and refreshes the subscription. Issuing this to the server too often is a waste of resources, and issuing it too late may cause a server-defined timeout.</p></li>
<li><p>The receive chunksize is only how my client is talking to a network buffer. Delays in this do not affect the server. (unsure of this)</p></li>
<li><p>The <code>WebSocketStatus</code> can be other values, such as closed, opening, etc., and this code isn't production ready since I don't handle those events.</p></li>
</ol>
<p><strong>Questions</strong></p>
<ol>
<li><p>What must be done to make this code production ready?</p></li>
<li><p>How do I determine the optimal chunk size for send and receive? </p></li>
<li><p>How should I recover from an error in the code, the network, or a server error?</p></li>
<li><p>How do I ensure that the data I'm getting is complete, and not just a fragment of data, cut off in mid-transition simply because the rest of the data is stuck in the buffer?</p></li>
</ol>
<p>Code</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BlockchainInfoWebSockets
{
class Client
{
private static object consoleLock = new object();
private const int sendChunkSize = 256;
private const int receiveChunkSize = 256;
private const bool verbose = true;
private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(30000);
static void Main(string[] args)
{
Thread.Sleep(1000);
Connect("ws://ws.blockchain.info:8335/inv").Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
await Task.WhenAll(Receive(webSocket), Send(webSocket));
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
finally
{
if (webSocket != null)
webSocket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
static UTF8Encoding encoder = new UTF8Encoding();
private static async Task Send(ClientWebSocket webSocket)
{
//byte[] buffer = encoder.GetBytes("{\"op\":\"blocks_sub\"}"); //"{\"op\":\"unconfirmed_sub\"}");
byte[] buffer = encoder.GetBytes("{\"op\":\"unconfirmed_sub\"}");
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
while (webSocket.State == WebSocketState.Open)
{
LogStatus(false, buffer, buffer.Length);
await Task.Delay(delay);
}
}
private static async Task Receive(ClientWebSocket webSocket)
{
byte[] buffer = new byte[receiveChunkSize];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
LogStatus(true, buffer, result.Count);
}
}
}
private static void LogStatus(bool receiving, byte[] buffer, int length)
{
lock (consoleLock)
{
Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
//Console.WriteLine("{0} ", receiving ? "Received" : "Sent");
if (verbose)
Console.WriteLine(encoder.GetString(buffer));
Console.ResetColor();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-13T09:41:07.113",
"Id": "264583",
"Score": "0",
"body": "in Receive()\n\nwe could add support for handling fragmentation - happens when the sent message is large ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-13T16:42:41.240",
"Id": "264665",
"Score": "0",
"body": "working on this myself right now ....\n\nspecifically, we should check the return value from ReceiveAsync()\nclass type:\nSystem.Net.WebSockets.WebSocketReceiveResult\n\nit has a flag to say whether this is the 'end' message OR is it a fragment:\n\nEndOfMessage [bool]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-13T17:20:48.833",
"Id": "264671",
"Score": "0",
"body": "@Sean I'm not close to this code now, but please make edits for the greater good"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T05:09:16.070",
"Id": "446725",
"Score": "0",
"body": "In `Receive` method, shouldn't the `byte[] buffer = new byte[receiveChunkSize];` be present inside the while loop ?"
}
] |
[
{
"body": "<ol>\n<li>You may want to be using <code>CancellationToken</code>s via the overload for the async methods of the <code>ClientWebSocket</code> class to properly cleanup tasks on exit.</li>\n<li>1024 is usually the value I like to use for web connectivity, the MTU (Maximum Transmission Unit)1 for Ethernet is 1500 bytes, and I like to round that down to a near exponent of 2, in this case 2^10.</li>\n<li>I'm not all sure about the <code>ClientWebSocket</code> class, but you will either get a <code>WebException</code> e.g. 404, I think in the StatusCode, or else it may be that <code>WebSocketStatus</code> you were talking about. Logging these exceptions may be the only thing you can do.</li>\n<li>Unless you have access to the source code of the server on the otherside and are able to make changes to it, unless the server implements some way to tell how much data it is sending, there's no way to be sure. An example would be the first 4 bytes of the transmission is the length of the data.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:23:37.740",
"Id": "42562",
"ParentId": "41591",
"Score": "5"
}
},
{
"body": "<p>It's best practice to create thread synchronization objects using <code>System.Threading.Interlocked.CompareEx</code>. So something like:</p>\n\n<pre><code>private static object consoleLock\nprivate static object GetLock() \n{ \n System.Threading.Interlocked.CompareExchange(ref consoleLock, new object(), null); \n return consoleLock; \n}\n</code></pre>\n\n<p>And I'd write an overload of <code>LogStatus</code> that accepts a string and a Color so you can clean up the socket close logging in your Connect method finally block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-04T18:45:05.370",
"Id": "189599",
"Score": "2",
"body": "Would you mind to provide a link or describe a value of using CompareExchange instead of relying on Framework initialization order?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-20T09:53:18.547",
"Id": "63425",
"ParentId": "41591",
"Score": "1"
}
},
{
"body": "<p>The wrapper sends and receives exactly one message before closing the connection. If you're just doing that, you can simply use HTTP. WebSockets is useful when there is a sequences of reads and/or writes with gaps of inactivity in between.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T12:28:23.483",
"Id": "203342",
"ParentId": "41591",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T21:21:16.630",
"Id": "41591",
"Score": "28",
"Tags": [
"c#",
"task-parallel-library",
"websocket"
],
"Title": "Websockets client code and making it production-ready"
}
|
41591
|
<p>I am currently in a data-structures class. The professor will be providing a singly linked list. I wanted to make a doubly linked list to "learn" how to do it. I tested it and I think it works. After making it, I did compare it to other doubly linked lists but I still want to see if there is anything I am missing. Are there any other problems with it?</p>
<p><strong><code>LinkNode</code> Class:</strong></p>
<pre><code>#ifndef LINKNODE_H_
#define LINKNODE_H_
#include <iostream>
template<class E>
class LinkNode {
public:
E data;
LinkNode<E> *leftNode;
LinkNode<E> *rightNode;
LinkNode() {
}
LinkNode(E e) {
this->data = e;
}
~LinkNode() {
}
E getData() {
return data;
}
void setData(E e) {
this->data = e;
}
LinkNode<E> getLeftNode() {
return leftNode;
}
void setLeftNode(LinkNode<E> node) {
this->leftNode = node;
}
LinkNode<E> getRightNode() {
return rightNode;
}
void setRightNode(LinkNode<E> node) {
this->rightNode = node;
}
};
#endif /* LINKNODE_H_ */
</code></pre>
<p><strong><code>LinkedList</code> Class:</strong></p>
<pre><code> #ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "LinkNode.h"
template<class T>
class LinkedList {
private:
int size;
LinkNode<T> *firstNode;
LinkNode<T> *lastNode;
public:
LinkedList() {
firstNode = new LinkNode<T>();
lastNode = firstNode;
size = 0;
}
~LinkedList() {
}
void pushFront(T t) {
if (size == 0) {
pushBack(t);
return;
}
LinkNode<T> *linkNode = new LinkNode<T>(t);
linkNode->rightNode = firstNode;
firstNode->leftNode = linkNode;
firstNode = linkNode;
size++;
}
void pushBack(T t) {
LinkNode<T> *linkNode = new LinkNode<T>(t);
linkNode->leftNode = lastNode;
lastNode->rightNode = linkNode;
lastNode = linkNode;
if (size == 0) {
firstNode = lastNode;
}
size++;
}
T pollFirst() {
T t = firstNode->data;
firstNode = firstNode->rightNode;
size--;
return t;
}
T pollLast() {
T t = lastNode->data;
lastNode = lastNode->leftNode;
size--;
return t;
}
LinkNode<T> getFirstNode() {
return firstNode;
}
LinkNode<T> getLastNode() {
return lastNode;
}
T searchNode(T t) {
return t;
}
int Size() {
return size;
}
void printLinkedList() {
LinkNode<T> *temp = firstNode;
while (temp != NULL) {
std::cout << temp->data << "\t";
temp = temp->rightNode;
}
}
};
#endif /* LINKEDLIST_H_ */
</code></pre>
<p><strong>New <code>LinkedList</code> Class:</strong></p>
<pre><code>#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
template<class T>
class LinkedList {
/**
* Private inner node class
*/
//Have to use new template. Does not run if I try to use T
template<class E>
class LinkNode {
public:
E data;
LinkNode<E> *leftNode;
LinkNode<E> *rightNode;
LinkNode() {
}
LinkNode(E e) {
this->data = e;
}
~LinkNode() {
}
};
private:
int size;
LinkNode<T> *firstNode;
LinkNode<T> *lastNode;
public:
LinkedList() {
firstNode = new LinkNode<T>();
/*
* Init left and right node to null to prevent exception.
*/
firstNode->leftNode = NULL;
firstNode->rightNode = NULL;
lastNode = firstNode;
size = 0;
}
~LinkedList() {
LinkNode<T> *linkNode = firstNode->rightNode;
while (linkNode != NULL) {
delete linkNode->leftNode;
linkNode = linkNode->rightNode;
}
}
void pushFront(T t) {
//the size is zero therefore we are really justing pushing to the back of the linked list
if (size == 0) {
pushBack(t);
return;
}
LinkNode<T> *linkNode = new LinkNode<T>(t);
linkNode->rightNode = firstNode;
firstNode->leftNode = linkNode;
firstNode = linkNode;
size++;
}
void pushBack(T t) {
LinkNode<T> *linkNode = new LinkNode<T>(t);
linkNode->leftNode = lastNode;
lastNode->rightNode = linkNode;
lastNode = linkNode;
if (size == 0) {
firstNode = lastNode;
}
size++;
}
T pollFirst() {
LinkNode<T> *temp = firstNode;
T t = firstNode->data;
firstNode = firstNode->rightNode;
delete temp;
size--;
return t;
}
T pollLast() {
LinkNode<T> *temp = lastNode;
T t = lastNode->data;
lastNode = lastNode->leftNode;
delete temp;
size--;
return t;
}
LinkNode<T> getFirstNode() {
return *firstNode;
}
LinkNode<T> getLastNode() {
return *lastNode;
}
int const Size() {
return size;
}
void const printLinkedList() {
LinkNode<T> *temp = firstNode;
while (temp != NULL) {
std::cout << temp->data << "\t";
temp = temp->rightNode;
}
}
};
#endif /* LINKEDLIST_H_ */
</code></pre>
<ul>
<li>Xubuntu 13.10</li>
<li>GCC Compiler installed with sudo apt-get install g++</li>
</ul>
|
[] |
[
{
"body": "<p><strong>LinkNode</strong></p>\n\n<p>Assuming this is not an internal class:</p>\n\n<p>A huge problem (probably the biggest) with this is that <em>everything</em> is <code>public</code>. The three data members should be <code>private</code>. Data members should <em>always</em> be <code>private</code>, otherwise any outside code can access them. This defeats the purpose of using a <code>class</code> as opposed to a <code>struct</code>.</p>\n\n<p>You should also not have any accessors (\"getters\") and mutators (\"setters\"). The node should belong <em>only</em> to the class, and none of its implementation should be exposed to the public. The list itself should use the nodes, and it should be able to access the node's members directly.</p>\n\n<p>An implementation of a node includes its pointers (<code>next</code> for a singly list, or <code>previous</code> and <code>next</code> nodes for a doubly list) and its data. That can either be a <code>struct</code> or a <code>class</code>, <em>inside</em> the list class as a <code>private</code> data member.</p>\n\n<p>An example of a templated node implementation as a <code>class</code>:</p>\n\n<pre><code>template <typename T>\nclass Node\n{\n T data;\n Node<T>* previous;\n Node<T>* next;\n};\n</code></pre>\n\n<p><strong>LinkedList</strong></p>\n\n<ul>\n<li><p><em>Huge problem: no destructor!</em> You <em>need</em> a destructor for a linked list so that its allocated nodes will be deleted after use. Without this, you'll have <em>memory leaks</em>. The destructor should go through each node, using <code>delete</code> on each node until the list is empty.</p></li>\n<li><p>You should define a copy constructor and assignment operator (<code>operator=</code>). The default copy constructor performs a <a href=\"https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy\">shallow copy versus a deep copy</a>, and a shallow copy is bad to use with pointers as members. Copying <em>can</em> still compile (the default is used), but it won't be done properly.</p></li>\n<li><p><code>size()</code> should be <code>const</code> since it's not modifying any data members:</p>\n\n<pre><code>int Size() const { return size; }\n</code></pre>\n\n<p>On another note, <code>Size()</code> should be lowercase to match your other functions. It shouldn't need to have different naming.</p></li>\n<li><p><code>printLinkedList()</code> should also be <code>const</code> as it's not modifying any data members. This applies to display functions in general, due to their nature.</p></li>\n<li><p><code>searchNode()</code> just returns its argument instead of conducting an actual search, so it's obsolete and should be removed.</p></li>\n<li><p>What are <code>pollFirst()</code> and <code>pollLast()</code> used for? The names aren't very clear. If they're short for something, write them out entirely.</p></li>\n<li><p>Get rid of <code>getFirstNode()</code> and <code>getLastNode()</code>. You should not expose the nodes to the public, which is bad for encapsulation. Keep the node functionality within the list.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T00:04:05.923",
"Id": "71521",
"Score": "0",
"body": "I am a java developer and \"their\" linked list contains pollFirst() and pollLast(). It returns the first or last nodes data and then removes them from the linked list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T00:06:36.793",
"Id": "71522",
"Score": "0",
"body": "@horvste: Okay. I'm a C++ reviewer (and no Java experience), so I wasn't aware of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:02:52.627",
"Id": "71551",
"Score": "2",
"body": "@horvste These methods are to satisfy the `(De)Queue` interface."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:18:25.677",
"Id": "41598",
"ParentId": "41596",
"Score": "40"
}
},
{
"body": "<p>When I run your test code on my machine, it crashes.</p>\n\n<ul>\n<li>1st node on the list contains '10'</li>\n<li>2nd node on the list contains '0'</li>\n<li>3rd node on the list contains '2'</li>\n<li>rightNode element of the 3rd node contains a garbage address => exception when trying to dereference the 4th node</li>\n</ul>\n\n<p>So I'll try to clean this up.</p>\n\n<p>Following from Jamal's answer, the following reworks your code to implement his suggestions.</p>\n\n<p>First, the only change is that I made LinkNode a private nested class of LinkList.</p>\n\n<p>Second, we don't need two separate template parameters anymore: so get rid of <code>E</code> and have only <code>T</code>. LinkNode is no longer a template class: it's a nested class of a template class.</p>\n\n<pre><code>#include <iostream>\ntemplate<class T>\nclass LinkedList {\nprivate:\n class LinkNode {\n\n public:\n T data;\n LinkNode *leftNode;\n LinkNode *rightNode;\n LinkNode() {\n }\n LinkNode(T e) {\n this->data = e;\n }\n ~LinkNode() {\n }\n T getData() {\n return data;\n }\n void setData(T e) {\n this->data = e;\n }\n LinkNode getLeftNode() {\n return leftNode;\n }\n void setLeftNode(LinkNode node) {\n this->leftNode = node;\n }\n LinkNode getRightNode() {\n return rightNode;\n }\n void setRightNode(LinkNode node) {\n this->rightNode = node;\n }\n\n };\n int size;\n LinkNode *firstNode;\n LinkNode *lastNode;\npublic:\n\n LinkedList() {\n firstNode = new LinkNode();\n lastNode = firstNode;\n size = 0;\n }\n\n ~LinkedList() {\n }\n\n void pushFront(T t) {\n if (size == 0) {\n pushBack(t);\n return;\n }\n LinkNode *linkNode = new LinkNode(t);\n linkNode->rightNode = firstNode;\n firstNode->leftNode = linkNode;\n firstNode = linkNode;\n size++;\n }\n\n void pushBack(T t) {\n LinkNode *linkNode = new LinkNode(t);\n linkNode->leftNode = lastNode;\n lastNode->rightNode = linkNode;\n lastNode = linkNode;\n if (size == 0) {\n firstNode = lastNode;\n }\n size++;\n }\n\n T pollFirst() {\n T t = firstNode->data;\n firstNode = firstNode->rightNode;\n size--;\n return t;\n }\n\n T pollLast() {\n T t = lastNode->data;\n lastNode = lastNode->leftNode;\n size--;\n return t;\n }\n\n LinkNode getFirstNode() {\n return firstNode;\n }\n\n LinkNode getLastNode() {\n return lastNode;\n }\n\n T searchNode(T t) {\n return t;\n }\n int Size() {\n return size;\n }\n\n void printLinkedList() {\n LinkNode *temp = firstNode;\n while (temp != NULL) {\n std::cout << temp->data << \"\\t\";\n temp = temp->rightNode;\n }\n }\n\n};\n</code></pre>\n\n<p>Next, I tried to invoke one of those methods which returns a LinkNode. Adding a <code>linked.getFirstNode();</code> statement to the test program gives me the following compiler error:</p>\n\n<pre><code>'LinkedList<T>::LinkNode::LinkNode(T)' : cannot convert parameter 1 from 'LinkedList<T>::LinkNode *' to 'int'\n</code></pre>\n\n<p>The problem with the getFirstNode() method is that it promises to return a LinkNode and then tries to return <code>firstNode</code> which is a LinkNode* pointer (which is illegal). With C++ templates the compiler doesn't try to instantiate the method unless you use it; you hadn't tried to use it so the compiler didn't notice that coding error.</p>\n\n<p>Fortunately you shouldn't be trying to use it: LinkNode should be a private implementation detail of LinkedList. So I'll just remove the getFirstNode and getLastNode methods.</p>\n\n<p>It's not clear what your searchNode method is doing too, and you're not testing it, so I'll remove that too.</p>\n\n<p>And I'll remove most of the LinkNode methods, because LinkedList accesses its data members directly, and because classes other than LinkedList cannot access any of its members at all.</p>\n\n<pre><code>#pragma once\n#include <iostream>\ntemplate<class T>\nclass LinkedList {\nprivate:\n class LinkNode {\n\n public:\n T data;\n LinkNode *leftNode;\n LinkNode *rightNode;\n LinkNode() {\n }\n LinkNode(T e) {\n this->data = e;\n }\n ~LinkNode() {\n }\n };\n int size;\n LinkNode *firstNode;\n LinkNode *lastNode;\npublic:\n\n LinkedList() {\n firstNode = new LinkNode();\n lastNode = firstNode;\n size = 0;\n }\n\n ~LinkedList() {\n }\n\n void pushFront(T t) {\n if (size == 0) {\n pushBack(t);\n return;\n }\n LinkNode *linkNode = new LinkNode(t);\n linkNode->rightNode = firstNode;\n firstNode->leftNode = linkNode;\n firstNode = linkNode;\n size++;\n }\n\n void pushBack(T t) {\n LinkNode *linkNode = new LinkNode(t);\n linkNode->leftNode = lastNode;\n lastNode->rightNode = linkNode;\n lastNode = linkNode;\n if (size == 0) {\n firstNode = lastNode;\n }\n size++;\n }\n\n T pollFirst() {\n T t = firstNode->data;\n firstNode = firstNode->rightNode;\n size--;\n return t;\n }\n\n T pollLast() {\n T t = lastNode->data;\n lastNode = lastNode->leftNode;\n size--;\n return t;\n }\n\n int Size() const {\n return size;\n }\n\n void printLinkedList() const {\n LinkNode *temp = firstNode;\n while (temp != NULL) {\n std::cout << temp->data << \"\\t\";\n temp = temp->rightNode;\n }\n }\n\n};\n</code></pre>\n\n<hr>\n\n<p>The next problem is with your use of a sentinel node when the list is empty.</p>\n\n<p>The following method creates an initial empty node ...</p>\n\n<pre><code>LinkedList() {\n firstNode = new LinkNode();\n lastNode = firstNode;\n size = 0;\n}\n</code></pre>\n\n<p>... but doesn't initialize the node's leftNode and rightNode elements (which causes the crash later on).</p>\n\n<p>Also I'm confused by the idea of having an empty node in the list: how will you make sure that printLinkedList will not try to print the contents of the empty node?</p>\n\n<p>So I change the code as follows to get rid of the empty node:</p>\n\n<ul>\n<li>Remove the default constructor from LinkNode (so it can only be instantiated when there is data)</li>\n<li>Initialize the pointer elements of LinkNode to null in the LinkNode constructor</li>\n<li>Initialize the pointer elements of LinkedList to null in the LinkedList constructor</li>\n<li>Special case in pushFront and pushBack to handle inserting into an empty list</li>\n<li>Special case in pollFirst and pollLast to handle removing the last node from the list</li>\n</ul>\n\n<p>After these changes the code looks like this:</p>\n\n<pre><code>#pragma once\n#include <iostream>\ntemplate<class T>\nclass LinkedList {\nprivate:\n class LinkNode {\n\n public:\n T data;\n LinkNode *leftNode;\n LinkNode *rightNode;\n LinkNode(T e) {\n this->data = e;\n leftNode = 0;\n rightNode = 0;\n }\n ~LinkNode() {\n }\n };\n int size;\n LinkNode *firstNode;\n LinkNode *lastNode;\npublic:\n\n LinkedList() {\n firstNode = 0;\n lastNode = 0;\n size = 0;\n }\n\n ~LinkedList() {\n }\n\n void pushFront(T t) {\n LinkNode *linkNode = new LinkNode(t);\n ++size;\n if (size == 1) {\n firstNode = lastNode = linkNode;\n return;\n }\n linkNode->rightNode = firstNode;\n firstNode->leftNode = linkNode;\n firstNode = linkNode;\n }\n\n void pushBack(T t) {\n LinkNode *linkNode = new LinkNode(t);\n ++size;\n if (size == 1) {\n firstNode = lastNode = linkNode;\n return;\n }\n linkNode->leftNode = lastNode;\n lastNode->rightNode = linkNode;\n lastNode = linkNode;\n }\n\n T pollFirst() {\n T t = firstNode->data;\n firstNode = firstNode->rightNode;\n if (firstNode)\n firstNode->leftNode = NULL;\n --size;\n return t;\n }\n\n T pollLast() {\n T t = lastNode->data;\n lastNode = lastNode->leftNode;\n if (lastNode)\n lastNode->rightNode = NULL;\n --size;\n return t;\n }\n\n int Size() const {\n return size;\n }\n\n void printLinkedList() const {\n LinkNode *temp = firstNode;\n while (temp != NULL) {\n std::cout << temp->data << \"\\t\";\n temp = temp->rightNode;\n }\n }\n};\n</code></pre>\n\n<p>Also the test output looks like this (which is the correct result, and it's not crashing any longer):</p>\n\n<pre><code>10 0 2\n</code></pre>\n\n<p>A remaining problem is that you don't delete the nodes which you create. I change the code as follows:</p>\n\n<ul>\n<li>Add a delete statement to the poll methods (to delete the node they remove from the list)</li>\n<li>Invoke delete statements from the LinkedList destructor (to delete nodes on the list when the list is destroyed)</li>\n</ul>\n\n<p>After these changes the code is as follows:</p>\n\n<pre><code>#pragma once\n#include <iostream>\n#include <assert.h>\ntemplate<class T>\nclass LinkedList {\nprivate:\n class LinkNode {\n public:\n T data;\n LinkNode *leftNode;\n LinkNode *rightNode;\n LinkNode(T e) {\n this->data = e;\n leftNode = 0;\n rightNode = 0;\n }\n ~LinkNode() {\n }\n };\n int size;\n LinkNode *firstNode;\n LinkNode *lastNode;\npublic:\n\n LinkedList() {\n firstNode = 0;\n lastNode = 0;\n size = 0;\n }\n\n ~LinkedList() {\n LinkNode *temp = firstNode;\n while (temp != NULL) {\n LinkNode *next = temp->rightNode;\n delete temp;\n temp = next;\n }\n }\n\n void pushFront(T t) {\n LinkNode *linkNode = new LinkNode(t);\n ++size;\n if (size == 1) {\n firstNode = lastNode = linkNode;\n return;\n }\n linkNode->rightNode = firstNode;\n firstNode->leftNode = linkNode;\n firstNode = linkNode;\n }\n\n void pushBack(T t) {\n LinkNode *linkNode = new LinkNode(t);\n ++size;\n if (size == 1) {\n firstNode = lastNode = linkNode;\n return;\n }\n linkNode->leftNode = lastNode;\n lastNode->rightNode = linkNode;\n lastNode = linkNode;\n }\n\n T pollFirst() {\n LinkNode *found = firstNode;\n T t = found->data;\n firstNode = found->rightNode;\n if (firstNode)\n firstNode->leftNode = NULL;\n else {\n assert(size == 1);\n lastNode = 0;\n }\n delete found;\n --size;\n return t;\n }\n\n T pollLast() {\n LinkNode *found = lastNode;\n T t = found->data;\n lastNode = found->leftNode;\n if (lastNode)\n lastNode->rightNode = NULL;\n else {\n assert(size == 1);\n firstNode = 0;\n }\n delete found;\n --size;\n return t;\n }\n\n int Size() const {\n return size;\n }\n\n void printLinkedList() const {\n LinkNode *temp = firstNode;\n while (temp != NULL) {\n std::cout << temp->data << \"\\t\";\n temp = temp->rightNode;\n }\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:09:21.453",
"Id": "71544",
"Score": "1",
"body": "Now THAT is some *seriously* **EPIC** answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:14:43.457",
"Id": "71545",
"Score": "2",
"body": "@lol.upvote: It did need a lot of cleaning. :-) Such implementations are taken quite seriously."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:55:01.363",
"Id": "71663",
"Score": "0",
"body": "Mine doesn't crash. Could it be a compiler difference? I am using gcc compiler. Regardless, I will take your advice do some clean up and repost the code for further inspection. I am trying to learn it so I read your advice but did not look at the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:00:53.160",
"Id": "71665",
"Score": "1",
"body": "@horvste Yes it could be a compiler difference. Notice when you call `firstNode = new LinkNode<T>();` you don't initialize the `leftValue` and `rightValue` fields of that first node. Possibly/probably with your compiler, those field values happen to be `0` which causes your `while (temp != NULL)` in `printLinkedList` to exit when it finds them. In my compiler running in debug mode, uninitialized fields are initialized to a value like 0xadadadad (which, by crashing, makes it easier to detect trying to use an uninitialized pointer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:15:06.417",
"Id": "71667",
"Score": "0",
"body": "I still do not understand why the constructor is wrong. My new test code runs as expected (please see edit on orig question)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:00:56.617",
"Id": "71672",
"Score": "1",
"body": "@horvste What was wrong is that in C++ (unlike in Java) if you don't initialize a field in a constructor then the field contains a pseudo-random value (possibly but not necessarily `0`). So your `LinkNode() { }` constructor should probably initialize its leftField and rightField elements to 0 explicitly: `LinkNode() { leftField = 0; rightField = 0; data = ???; }`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:37:03.873",
"Id": "41602",
"ParentId": "41596",
"Score": "27"
}
},
{
"body": "<p>One quite important thing to do when you work with linked lists is to link and unlink the previous/next nodes as you add/remove nodes.</p>\n\n<p>If you can only add at the end, that's good, but if you can insert a node anywhere you have to be careful. The same goes with removing nodes.</p>\n\n<pre><code> +--------+ +--------+ +--------+\n | A | | B | | C |\n | A.n |--->| B.n |--->| C.n |---> null\nnull <---| A.p |<---| B.p |<---| C.p |\n +--------+ +--------+ +--------+\n</code></pre>\n\n<p>In this representation, removing B from the list means making A.n point to C instead of B, and C.p point to A instead of B. And setting B.n and B.p to <code>nullptr</code>.</p>\n\n<p>Similarly, if you only had A and C and wanted to add B, now you need to set B.p to A and A.n to B. Then C.p to B and B.n to C.</p>\n\n<p>It seems you only want to offer a push and a pop, so it makes it simpler, but that's something to keep in mind.</p>\n\n<p>Two other notes:</p>\n\n<ol>\n<li><p>I see that you use <code>this-></code>... within the class; that's not necessary.</p></li>\n<li><p>You may want to consider using <code>std::shared_ptr<>()</code> so that way multiple people can own a node and it doesn't get deleted until all are done with it.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:00:23.517",
"Id": "41619",
"ParentId": "41596",
"Score": "16"
}
},
{
"body": "<blockquote>\n <p>New Linked List Class</p>\n</blockquote>\n\n<p>This is a review of the new \"New Linked List Class\".</p>\n\n<hr>\n\n<p>Here you wrote:</p>\n\n<pre><code>//Have to use new template. Does not run if I try to use T\ntemplate<class E>\nclass LinkNode {\npublic:\n E data;\n LinkNode<E> *leftNode;\n LinkNode<E> *rightNode;\n LinkNode() {\n\n }\n LinkNode(E e) {\n this->data = e;\n }\n ~LinkNode() {\n }\n};\n</code></pre>\n\n<p>I said, \"LinkNode is no longer a template class: it's a nested class of a template class.\"</p>\n\n<p>You said you don't want to read my code, but here's my code ahead:</p>\n\n<pre><code> // Not a template class.\n // template<class E>\n class LinkNode {\n public:\n E data;\n LinkNode *leftNode;\n LinkNode *rightNode;\n LinkNode() {\n\n }\n LinkNode(E e) {\n this->data = e;\n }\n ~LinkNode() {\n }\n };\nprivate:\n int size;\n LinkNode *firstNode;\n LinkNode *lastNode;\n</code></pre>\n\n<hr>\n\n<p>In C++, unlike in Java, members are not auto-initialized to 0. Maybe your compiler leaves them initialized to 0, but mine doesn't. Your compiler is probably leaving you with uninitialized memory, which happened to be zero-filled, but which would no longer be zero-filled if your program had been running for longer with lots of previous <code>new</code>s and <code>delete</code>s.</p>\n\n<p>If I do printLinkedList after the first push, it crashes. That's because your push method is like this:</p>\n\n<pre><code>void pushBack(T t) {\n LinkNode<T> *linkNode = new LinkNode<T>(t);\n linkNode->leftNode = lastNode;\n lastNode->rightNode = linkNode;\n lastNode = linkNode;\n if (size == 0) {\n firstNode = lastNode;\n }\n size++;\n}\n</code></pre>\n\n<p>It doesn't initialize the rightNode member of the new linkNode.</p>\n\n<p>You probably want to initialize everything in your LinkNode constructor: set leftNode and rightNode to 0.</p>\n\n<hr>\n\n<p>Before the first push, firstNode and lastNode point to your initial, empty, 'sentinel' node.</p>\n\n<p>After the first push, firstNode and lastNode point to the new node, and the new node's leftNode points to your sentinel node.</p>\n\n<p>Then after the next pushFront, nothing is pointing to your sentinel node. If you're going to lose your sentinel node from the list, I don't see any good reason for creating it in the first place. (The solution I proposed in my other answer doesn't create an initial sentinel node, and instead sets and expects firstNode and lastNode to be NULL when the list is empty).</p>\n\n<hr>\n\n<p>If I call printLinkedList before I push anything onto the list, it prints the value (possibly 0, possibly something else) contained in your initial, empty, sentinel node.</p>\n\n<hr>\n\n<p>If I run the following test code then it prints an infinite number of <code>2</code>s:</p>\n\n<pre><code>LinkedList<int> linked;\nlinked.printLinkedList();\nlinked.pushFront(10);\nlinked.printLinkedList();\nlinked.pollFirst();\nlinked.printLinkedList();\nlinked.pushBack(2);\nlinked.printLinkedList();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T09:36:24.270",
"Id": "41723",
"ParentId": "41596",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "41723",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T22:55:16.040",
"Id": "41596",
"Score": "30",
"Tags": [
"c++",
"linked-list"
],
"Title": "Validity of doubly linked list"
}
|
41596
|
<p>I have been playing around with some improvements to some sort algorithms like Selection Sort and Merge Sort and I ended up needing some sort of measurement to check if my versions were any faster than the original algorithm form. I also had a need to implement some sort of time measurement before but never did it, so here came the chance. And so I ended up coding the following measurement method:</p>
<pre><code>public static double Measure(Action action, bool print = true)
{
Stopwatch watch = new Stopwatch();
const int precision = 1; //estimated precision of 1 milisecond on my machine
const int error = 1; //max error
const int times = 10;
double min = double.MaxValue;
for (int i = 0; i < times; ++i)
{
int iterations = 0;
watch.Restart();
while (watch.Elapsed.Milliseconds < precision*(100-error))
{
action();
++iterations;
}
watch.Stop();
min = Math.Min(min, watch.Elapsed.Milliseconds*1000.0/iterations);
}
if(print)
Debug.WriteLine("The action takes {0:N4} nanos to complete", min);
return min;
}
</code></pre>
<p>Is this a well conducted measurement algorithm? Any suggestions or improvements that I could apply?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:56:50.833",
"Id": "71621",
"Score": "0",
"body": "Can you explain what you are checking with `watch.Elapsed.Milliseconds < precision*(100-error)` condition?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:49:06.673",
"Id": "71624",
"Score": "0",
"body": "I found that the stopWatch has a precision of about a milisecond. And so to only have a error of 1% i need to run a method at least during about 100 milliseconds, although this only applies to the methods that take only some nanoseconds to run. That's also why ChrisW suggested his approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:32:24.453",
"Id": "71634",
"Score": "0",
"body": "So if my precision decreases (meaning that it would be bigger for example 2 milliseconds) I would need to test the method for about 200 milliseconds to have a 1% error."
}
] |
[
{
"body": "<p>The thing you're timing is:</p>\n\n<pre><code>while (watch.Elapsed.Milliseconds < precision*(100-error))\n{\n action();\n ++iterations;\n}\n</code></pre>\n\n<p>The problem is that if action takes a very short time, then most of what you're timing is the time it takes to call the <code>watch.Elapsed.Milliseconds</code> property.</p>\n\n<p>A more accurate timer would be something like:</p>\n\n<pre><code>int iterations = 1000;\nwatch.Restart();\nwhile (iterations--)\n{\n action();\n}\nwatch.Stop();\n</code></pre>\n\n<p>You would then need to do something to ensure you pick a suitable number of iterations (e.g. try again with 10 times as many iterations if the measured time is too short to be accurate).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:26:19.850",
"Id": "71541",
"Score": "0",
"body": "You made a point there. I think that I could mix my code with yours. So I would find the number of iterations on 100 milliseconds and than measure the time again using your way. Hopefully will save some precious nanoseconds in measurament."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:02:33.740",
"Id": "41605",
"ParentId": "41597",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41605",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:16:56.367",
"Id": "41597",
"Score": "7",
"Tags": [
"c#",
"performance",
"unit-testing"
],
"Title": "Measuring a given method's execution time"
}
|
41597
|
<p>Because I was spoiled with C# and the .NET framework, whenever I have to work with VB6 I feel like something's missing in the language. A little while ago I implemented a <code>List<T></code> for VB6 (<a href="https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba">here</a>), and before that I implemented <code>String.Format()</code> and a number of string-helper functions (<a href="https://codereview.stackexchange.com/questions/30817/how-can-i-get-rid-of-select-case-and-goto-in-this-string-formatting-helper-fun?lq=1">here</a>). Don't go looking for a <code>StringFormat</code> method in the VB6 language specs, that method is the one I've written.</p>
<p>Today I would have liked to be able to declare a <code>Nullable<bool></code> in VB6, so I implemented a class that allowed me to do that. I named this class <code>Nullable</code> and it goes like this:</p>
<pre><code>Private Type tNullable
Value As Variant
IsNull As Boolean
TItem As String
End Type
Private this As tNullable
Option Explicit
Private Sub Class_Initialize()
this.IsNull = True
End Sub
</code></pre>
<p>Now before I go any further I have to mention that I have used "procedure attributes" in the <code>Value</code> property, making it the type's <em>default member</em>:</p>
<pre><code>Public Property Get Value() As Variant
'default member
Value = this.Value
End Property
Public Property Let Value(val As Variant) 'damn case-insensitivity...
'default member
If ValidateItemType(val) Then
this.Value = val
this.IsNull = False
End If
End Property
Public Property Set Value(val As Variant)
'used for assigning Nothing.
'Must be explicitly specified (e.g. Set MyNullable.Value = Nothing; Set MyNullable = Nothing will not call this setter)
Dim emptyValue As Variant
If val Is Nothing Then
this.IsNull = True
this.Value = emptyValue
Else
Err.Raise vbObjectError + 911, "Nullable<T>", "Invalid argument."
End If
End Property
</code></pre>
<p>The <code>ValidateItemType</code> private method determines whether the type of a value is "ok" to be assigned as the instance's <code>Value</code>:</p>
<pre><code>Private Function ValidateItemType(val As Variant) As Boolean
Dim result As Boolean
If Not IsObject(val) Then
If this.TItem = vbNullString Then this.TItem = TypeName(val)
result = IsTypeSafe(val)
If Not result Then Err.Raise vbObjectError + 911, "Nullable<T>", StringFormat("Type mismatch. Expected '{0}', '{1}' was supplied.", this.TItem, TypeName(val))
Else
Err.Raise vbObjectError + 911, "Nullable<T>", "Value type required. T cannot be an object."
result = False
End If
ValidateItemType = result
End Function
Private Function IsTypeSafe(val As Variant) As Boolean
IsTypeSafe = this.TItem = vbNullString Or this.TItem = TypeName(val)
End Function
</code></pre>
<p>That mechanism is borrowed from the <code>List<T></code> implementation I wrote before, and proved to be working fine. Shortly put, an instance of the <code>Nullable</code> class is a <code>Nullable<Variant></code> until it's assigned a value - if that value is a <code>Integer</code> then the instance becomes a <code>Nullable<Integer></code> and remains of that type - so the <code>Value</code> can only be assigned an <code>Integer</code>. <a href="https://codereview.stackexchange.com/questions/33035/revisited-istypesafe-method-implementation-for-type-safe-list">The mechanism can be refined as shown here</a>, to be more flexible (i.e. more VB-like), but for now I only wanted something that works.</p>
<p>The remaining members are <code>HasValue()</code> and <code>ToString()</code>:</p>
<pre><code>Public Property Get HasValue() As Boolean
HasValue = Not this.IsNull
End Property
Public Function ToString() As String
ToString = StringFormat("Nullable<{0}>", IIf(this.TItem = vbNullString, "Variant", this.TItem))
End Function
</code></pre>
<hr />
<h3>Usage</h3>
<p>Here's some test code that shows how the class can be used:</p>
<pre><code>Public Sub TestNullable()
Dim n As New Nullable
Debug.Print StringFormat("{0} | HasValue: {1} | Value: {2}", n.ToString, n.HasValue, n)
n = False
Debug.Print StringFormat("{0} | HasValue: {1} | Value: {2}", n.ToString, n.HasValue, n)
n = True
Debug.Print StringFormat("{0} | HasValue: {1} | Value: {2}", n.ToString, n.HasValue, n)
Set n.Value = Nothing
Debug.Print StringFormat("{0} | HasValue: {1} | Value: {2}", n.ToString, n.HasValue, n)
On Error Resume Next
n = "test" 'expected "Type mismatch. Expected 'T', 'x' was supplied." error
Debug.Print Err.Description
n = New List 'expected "Value type required. T cannot be an object." error
Debug.Print Err.Description
On Error GoTo 0
End Sub
</code></pre>
<p>When called from the <em>immediate pane</em>, this method outputs the following:</p>
<pre><code>TestNullable
Nullable<Variant> | HasValue: False | Value:
Nullable<Boolean> | HasValue: True | Value: False
Nullable<Boolean> | HasValue: True | Value: True
Nullable<Boolean> | HasValue: False | Value:
Type mismatch. Expected 'Boolean', 'String' was supplied.
Value type required. T cannot be an object.
</code></pre>
<p>Did I miss anything or this is a perfectly acceptable implementation?</p>
<p>One thing did surprise me: if I do <code>Set n.Value = Nothing</code>, the instance remains a <code>Nullable<Boolean></code> as expected. However if I do <code>Set n = Nothing</code>, not only <code>Debug.Print n Is Nothing</code> will print <code>False</code>, the instance gets reset to a <code>Nullable<Variant></code> and ...the setter (<code>Public Property Set Value</code>) does <strong>not</strong> get called - as a result, I wonder if I have written a class with a built-in bug that makes it un-<em>Nothing</em>-able?</p>
<hr />
<h3>Bonus</h3>
<p>After further testing, I have found that this:</p>
<pre><code>Dim n As New Nullable
Set n = Nothing
Debug.Print n Is Nothing
</code></pre>
<p>Outputs <code>False</code>. However this:</p>
<pre><code>Dim n As Nullable
Set n = New Nullable
Set n = Nothing
Debug.Print n Is Nothing
</code></pre>
<p>Outputs <code>True</code> (both snippets never hit a breakpoint in the <code>Set</code> accessor).</p>
<p>All these years I thought <code>Dim n As New SomeClass</code> was the exact same thing as doing <code>Dim n As SomeClass</code> followed by <code>Set n = New SomeClass</code>. Did I miss the memo?</p>
<hr />
<h1>UPDATE</h1>
<h3>Don't do this at home.</h3>
<p>After a thorough review, it appears an <code>Emptyable<T></code> in VB6 is absolutely moot. All the class is buying, is a <code>HasValue</code> member, which VB6 already takes care of, with its <code>IsEmpty()</code> function.</p>
<p>Basically, instead of having a <code>Nullable<Boolean></code> and doing <code>MyNullable.HasValue</code>, just declare a <code>Boolean</code> and assign it to <code>Empty</code>, and verify "emptiness" with <code>IsEmpty(MyBoolean)</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:31:37.830",
"Id": "71529",
"Score": "1",
"body": "VB6 has the nasty habit of instantiating a new object if a method is called on something that is Nothing. I'm curious to see your test function for the Set n = Nothing bit. I suspect the surprising behavior is there, not in the class itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:33:02.453",
"Id": "71530",
"Score": "0",
"body": "@Comintern I've edited with my latest findings (although that's starting to be more on StackOverflow's grounds)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:11:46.247",
"Id": "71535",
"Score": "0",
"body": "I thought this deserved a longer-winded explanation. See below. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:13:53.727",
"Id": "71536",
"Score": "1",
"body": "`Dim n As New SomeClass` *is* the exact same thing as doing `Dim n As SomeClass` followed by `Set n = New SomeClass`. Unfortunately both are the same as `Dim n As SomeClass` followed by `Debug.Print (n)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-15T16:50:57.457",
"Id": "197620",
"Score": "0",
"body": "I think that what you suggest in your \"UPDATE\" section only works if you make `MyBoolean` a `Variant` rather than a `Boolean`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-15T17:17:00.820",
"Id": "197623",
"Score": "0",
"body": "@JeffRoe blast from the past! ...and damn, you're right!"
}
] |
[
{
"body": "<p>I think the itself class might be mis-named, because it is really 'Empty-able' not Nullable or 'Nothing-able'.</p>\n\n<p>You have to keep in mind that Empty, Null, and Nothing are very different concepts in VB6. Setting and object to Nothing is basically just syntactic sugar for releasing the pointer to the Object. This is the same as asking for ObjPtr() to return Null for that instance (although there is no way to <em>test</em> this in VB6 - see the code and explanation below).</p>\n\n<p>Null is actually better to conceptualize in VB6 as a type rather than an uninitialized variable, as the code below demonstrates:</p>\n\n<pre><code>Dim temp As Variant\n\n'This will return \"True\"\nDebug.Print (temp = Empty)\n\n'This will return \"False\"\nDebug.Print (IsNull(temp))\n\ntemp = Null\n'This will return \"True\"\nDebug.Print (IsNull(temp))\n\n'This will return \"Null\"\nDebug.Print (TypeName(temp))\n</code></pre>\n\n<p>This brings me to the explanation of why your class should really be referred to as 'Empty-able'. A Variant is best thought of as an object with 2 properties - a type and a pointer. If it is uninitialized, it basically has a pointer to Nothing and a type of Empty. But is isn't Null, because the Variant itself still exists with its default \"properties\". </p>\n\n<blockquote>\n <p>However if I do Set n = Nothing, not only Debug.Print n Is Nothing\n will print False, the instance gets reset to a Nullable and\n ...the setter (Public Property Set Value) does not get called</p>\n</blockquote>\n\n<p>This is because of VB6's obnoxious default behavior when you use a reference to an object that was set to nothing. It \"helpfully\" creates a new object for you as can be verified by the code below - before the second call to ObjPtr(temp), it implicitly runs <code>Set temp = New Test</code>. You should be able to verify this with a Debug.Print in Class_Initialize().</p>\n\n<pre><code>Private Sub Testing()\n\n Dim temp As New Test\n\n Debug.Print (ObjPtr(temp))\n\n Set temp = Nothing\n\n 'The code below instantiates a new Test object, because it is used after being released.\n Debug.Print (ObjPtr(temp))\n\nEnd Sub\n</code></pre>\n\n<p>VB6 treats setting an Object equal to Nothing as a special case, so it never calls the Property Set. What is it basically doing is: <code>AddressOf(n) = AddressOf(Nothing)</code>.</p>\n\n<p>EDIT:\nExcellent explanation of how Variants work under the hood <a href=\"https://stackoverflow.com/questions/10096040/vb6-object-and-data-types\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:15:07.553",
"Id": "71537",
"Score": "0",
"body": "+1 I was just coming to the same conclusions! Wow I *did* miss the memo... or .NET has successfully \"corrupted\" my VB6 mind!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:16:31.177",
"Id": "71539",
"Score": "1",
"body": "More accurate to say that .NET \"uncorrupted\" VB6."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:21:04.047",
"Id": "71540",
"Score": "1",
"body": "You seem to know your VB6.. I'd be curious to read your input on my `List<T>` class :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:26:42.487",
"Id": "71542",
"Score": "0",
"body": "It's where I cut my teeth in programming. I'll take a look at it tonight. You can do some wild stuff with VB6 like in-line assembly and opening files as memory mapped arrays. The wheels really came off when they introduced AddressOf, it lets you break out of the walls of the runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:01:30.217",
"Id": "71543",
"Score": "1",
"body": "Building on your answer I added my own, feel free to comment ;) and PS - feel free to join us (CR regulars) anytime in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T14:25:15.040",
"Id": "71629",
"Score": "0",
"body": "hmm... so all this class is buying me is really a `HasValue` member... which `IsEmpty` already addresses, the VB6-way... Right? Basically a `Nullabe<T>`/`Emptyable<T>` has little use in VB6 then, since **any value type can already be assigned to `Empty`**!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:10:42.307",
"Id": "41607",
"ParentId": "41601",
"Score": "10"
}
},
{
"body": "<p>Adding to @Comintern's excellent answer, the private type doesn't need an <code>IsNull</code> member, since the class only accepts value types, the correct semantics for \"null\" values is <code>vbEmpty</code>.</p>\n\n<p>The <code>Set</code> accessor is therefore not only wrong, it's also ambiguous - not only in attempting to assign <code>Nothing</code> to a value type, but also because <code>Value</code> being the default member, it's not immediately obvious what this does:</p>\n\n<pre><code>Set MyNullable = Nothing\n</code></pre>\n\n<p>The solution is simple: get rid of the <code>Set</code> accessor altogether:</p>\n\n<pre><code>Private Type tNullable\n Value As Variant\n TItem As String\nEnd Type\n\nPrivate this As tNullable\nOption Explicit\n\nPublic Property Get Value() As Variant\n Value = this.Value\nEnd Property\n\nPublic Property Let Value(val As Variant)\n If ValidateItemType(val) Then this.Value = val\nEnd Property \n</code></pre>\n\n<p><code>HasValue</code> can then be rewritten like this:</p>\n\n<pre><code>Public Property Get HasValue() As Boolean\n HasValue = Not IsEmpty(this.Value)\nEnd Property\n</code></pre>\n\n<p>And <code>IsTypeSafe</code> should accept type name \"Empty\":</p>\n\n<pre><code>Private Function IsTypeSafe(val As Variant) As Boolean\n IsTypeSafe = this.TItem = vbNullString _\n Or this.TItem = TypeName(val) _\n Or TypeName(val) = \"Empty\"\nEnd Function\n</code></pre>\n\n<p>As a result we can now do this:</p>\n\n<pre><code>Dim n As New Nullable\nn = False 'n.ToString returns \"Nullable<Boolean>\"; n.HasValue returns True\nn = Empty 'n.ToString returns \"Nullable<Boolean>\"; n.HasValue returns False\nSet n = Nothing 'n.ToString returns \"Nullable<Variant>\"; n.HasValue returns False\n</code></pre>\n\n<p>And now the bad naming for the class becomes more than just obvious.</p>\n\n<p>The <code>ToString</code> method should therefore be tweaked to no longer hard-code the type's name:</p>\n\n<pre><code>Public Function ToString() As String\n ToString = StringFormat(\"{0}<{1}>\", TypeName(Me), IIf(this.TItem = vbNullString, \"Variant\", this.TItem))\nEnd Function\n</code></pre>\n\n<p>And the class should be renamed to <code>Emptyable</code>... regardless of how ugly that is: VB6 just isn't .NET.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:07:40.477",
"Id": "71598",
"Score": "1",
"body": "Value is not always the default member though. It's the [**runtime that decides**](http://stackoverflow.com/questions/21386768/why-am-i-having-issues-assigning-a-range-to-an-array-of-variants) which type is the *most appropriate*. Other than that a definite +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:14:35.633",
"Id": "71615",
"Score": "0",
"body": "I see i see :) only recently I have found out that Value is not a default member if there is a _Default property defined in a class. It is the runtime that decides what the default property is going to be. You explicitly use `.Value` so it should not affect anything which is GOOD but I thought it was worth mentioning :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T02:58:02.700",
"Id": "41608",
"ParentId": "41601",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41607",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T00:49:00.190",
"Id": "41601",
"Score": "11",
"Tags": [
"vba",
"type-safety",
"vb6",
"null"
],
"Title": "Nullable<T> Implementation for VB6/VBA"
}
|
41601
|
<p>Is this the correct way to implement a thread-safe concurrent FIFO queue in C++? It requires passing <code>unsigned char*</code> arrays of binary data.</p>
<p><strong>Thread Safe Concurrent Queue</strong></p>
<pre><code>#include <queue>
#include <pthread.h>
class concurrent_queue
{
private:
std::queue<unsigned char*> _queue_;
pthread_mutex_t push_mutex;
pthread_mutex_t pop_mutex;
pthread_cond_t cond;
public:
concurrent_queue()
{
pthread_mutex_init(&push_mutex, NULL);
pthread_mutex_init(&pop_mutex, NULL);
pthread_cond_init(&cond, NULL);
}
void push(unsigned char* data)
{
pthread_mutex_lock(&push_mutex);
_queue_.push(data);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&push_mutex);
}
void pop(unsigned char** popped_data)
{
pthread_mutex_lock(&pop_mutex);
while (_queue_.empty() == true)
{
pthread_cond_wait(&cond, &pop_mutex);
}
*popped_data = _queue_.front();
_queue_.pop();
pthread_mutex_unlock(&pop_mutex);
}
};
</code></pre>
<p><strong>CONSUMER TEST:</strong></p>
<pre><code>void *consumer_thread(void *arguments)
{
concurrent_queue *cq = static_cast<concurrent_queue*>(arguments);
while (true)
{
unsigned char* data = NULL;
cq->pop(&data);
if (data != NULL)
{
// Eureka! Received from the other thread!!!
// Delete it so memory keeps free.
// NOTE: In the real scenario for which I need
// this class, the data received are bitmap pixels
// and at this point it would be processed
delete[] data;
}
}
return 0;
}
</code></pre>
<p><strong>PRODUCER TEST:</strong></p>
<pre><code>void main()
{
concurrent_queue cq;
// Create the consumer
pthread_t consumer;
pthread_create(&consumer, NULL, consumer_thread, &cq));
// Start producing
while(true)
{
// Push data.
// Expected behaviour: memory should never run out, as the
// consumer should receive the data and delete it.
// NOTE: test_data in the real purpose scenario for which I
// need this class would hold bitmap pixels, so it's meant to
// hold binary data and not a string
unsigned char* test_data = new unsigned char [8192];
cq.push(test_data);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:10:46.147",
"Id": "71622",
"Score": "1",
"body": "Please read [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/q/1482/34757)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:09:10.443",
"Id": "83638",
"Score": "0",
"body": "Zhenya - editing the question to incorporate suggested changes, 'invalidates' the answers that have been given. Please read the meta-post/link that ChrisW posted above, [and I repeat here....](http://meta.codereview.stackexchange.com/q/1482/34757)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-09T19:57:03.283",
"Id": "183421",
"Score": "0",
"body": "I see you're deleting the char * in consumer Thread. Isn't that a bug ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-09T20:00:30.290",
"Id": "183422",
"Score": "0",
"body": "The consumer is just a test. In the comment right before the delete, on the second line, is explained why is deleted. In a real scenario you will not delete it until you have used for your own purposes, but after using it you will need to delete it to avoid memory leaks."
}
] |
[
{
"body": "<p>You are guarding the state of one variable</p>\n\n<pre><code>std::queue<unsigned char*> _queue_;\n</code></pre>\n\n<p>So you only have one mutex.</p>\n\n<pre><code>pthread_mutex_t push_mutex;\npthread_mutex_t pop_mutex;\n</code></pre>\n\n<p>If you have two then push and pop can modify queue at the same time.</p>\n\n<p>Make sure your mutex locking is exception safe by using RAII. Note all operations were you do start operation stop should be done by using RAII. This is the most important concept in C++ look it up.</p>\n\n<p>Don't use pointers in C++. They do not convey ownership symantics (which means you don't know who should delete it (or when it should be deleted)). In this case use std::string it solves all the problems.</p>\n\n<p>I see calls <code>pthread_XXX_init</code> but not the equivalent destroy.</p>\n\n<p>Because you have not defined them the default copy constructor and assignment operator will be created. Since your object contains resources (mutext and conditional) you probably don't want the default behavior. Either define them or disable them.</p>\n\n<p>C++11 has a better set of threading constructs use those rather than the C pthread library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:42:30.083",
"Id": "71560",
"Score": "1",
"body": "I find std::vector easier to deal with when handling binary data (assuming the unsigned char * pointer is for binary data.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:47:29.143",
"Id": "71573",
"Score": "0",
"body": "@AlexisWilke: Me too. I was assuming a string. But for binary data I would use a vector."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:27:32.870",
"Id": "41614",
"ParentId": "41604",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T01:46:35.913",
"Id": "41604",
"Score": "22",
"Tags": [
"c++",
"thread-safety",
"queue",
"pthreads"
],
"Title": "Thread-safe concurrent FIFO queue in C++"
}
|
41604
|
<p>I always add an exception handler when a new method is created, and I don't know if it is a good or bad practice. I thought it may be a bit of an annoyance when viewing the source code.</p>
<p>Is it a good practice to put logging functions in the exception block?</p>
<pre><code>def insert_new_camera(self, camera, records, file_hdlr):
try:
pass
except BaseException as e:
traceback.print_exc(file=sys.stdout)
raise e
</code></pre>
|
[] |
[
{
"body": "<p>Don't do that.</p>\n\n<p>If you log your exceptions at every function, you'll print the same exception over and over and over again. Its only useful the first time, after that its a pain.</p>\n\n<p>It will also make your code much harder to read and write.</p>\n\n<p>You should log the exception when you would otherwise lose it. At some point, your exception has to be caught and not rethrown. This may happen in the default exception handler. That's where you should log. Don't log exceptions that you just rethrow. Trust whoever catches them to log them. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T07:30:23.363",
"Id": "71594",
"Score": "10",
"body": "Also, he'll end up with a stack trace that goes no higher then one function, and he should just do `raise` instead of `raise e`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:16:59.657",
"Id": "41611",
"ParentId": "41610",
"Score": "35"
}
},
{
"body": "<p>It's not recommended nor economical to put <code>try-catch</code> in every function and block code. Instead, create a separate class for exception handling and log exceptions here, then show or handle these exceptions. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T11:09:59.520",
"Id": "41641",
"ParentId": "41610",
"Score": "2"
}
},
{
"body": "<p>In general, with most languages, it's better not to handle exceptions until you absolutely need to. That could be just before the page crashes, you want to log the error and redirect the user to an error page.</p>\n\n<p>Exceptions, by definition, are exceptional. If you can consistently expect them, you can usually code away from having to deal with them at all, and if you don't know what to do with the exception when it happens, it's best not to do anything at all, and just let it bubble up to the top of the application. As Winston said \"At some point, your exception has to be caught and not rethrown\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:24:43.790",
"Id": "41651",
"ParentId": "41610",
"Score": "4"
}
},
{
"body": "<p>There are times when you can't do anything with exceptions. Running out of memory is one example.</p>\n\n<p>In the programming languages I've used, for private non-exposed methods/functions I don't put any, unless there is a good reason (like its critical I track this problem, or provide a more helpful error to improve the existing error message). In these cases, I blindly assume that the cleansing has already been applied to any data passed in to it.</p>\n\n<p>Public methods/functions usually have some form of checking for invalid inputs, as they are the public API into your system. This would be the place to have them, as all input is evil.</p>\n\n<p>Also exception handling is more to do with dealing with the system in an inconsistent state. Is it recoverable? This is where I personally draw the line. If there is a threat of internal state being corrupted, throw it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:16:29.387",
"Id": "41687",
"ParentId": "41610",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41611",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:09:04.857",
"Id": "41610",
"Score": "23",
"Tags": [
"python",
"exception"
],
"Title": "Is it a good practice to put an exception handler in every method?"
}
|
41610
|
<p>A user must query a large database for information repeatedly. This query may take up to ~7 seconds. This must be done asynchronously. Only one query will be running at a time.</p>
<p>I did not create a new thread for each query as the code would be less clean, less maintable, etc.</p>
<p>I did not use ThreadPool.QueueUserWorkItem as this will tie up a ThreadPool thread. I'd rather not increase the minimum ThreadPool threads for this via ThreadPool.SetMinThreads as this won't be used by every user.</p>
<p>Considering the above, and that this problem seems to come up in this project often, I decided to create my own single thread "ThreadPool" which just processes items. No new threads created, no ThreadPool thread occupied, reusable elsewhere...</p>
<p>Should I have avoided the built-in .net ThreadPool? Is there a better approach I've missed?</p>
<p>I've included source for clarity. I'm not looking for code critique as much as I am advice on what to do in this scenario. I do not have access to <code>async/await</code>, for those who want to critique source.</p>
<p><strong>SingleThreadPool</strong></p>
<pre><code>public class SingleThreadPool : IThreadPool
{
private readonly Thread thread;
private readonly Queue<CallbackTask> queue;
private readonly AutoResetEvent resetEvent;
public SingleThreadPool()
{
this.queue = new Queue<CallbackTask>();
this.resetEvent = new AutoResetEvent(false);
this.IsDisposed = false;
this.thread = new Thread(Run);
this.thread.IsBackground = true;
this.thread.Name = "SingleThreadPool";
this.thread.Start();
}
~SingleThreadPool()
{
this.Dispose(true);
}
public void Dispose()
{
this.Dispose(false);
//keeps destructor from executing.
GC.SuppressFinalize(this);
}
private void Dispose(bool calledFromFinalizer)
{
if (!this.IsDisposed)
{
CallbackTask[] cpy = null;
lock (this.queue)
{
cpy = this.queue.ToArray();
queue.Clear();
}
//do not call cancel within locked block.
foreach (var item in cpy)
{
item.TaskItem.Cancel();
}
this.IsDisposed = true;
this.resetEvent.Set();
//DO NOT JOIN IF CALLED FROM FINALIZER! CAN CAUSE DEADLOCK!
//the GC may put other threads to sleep while calling finalizer.
//if it puts this.thread to sleep, we may deadlock.
if (!calledFromFinalizer)
{
this.thread.Join();
}
}
}
public void QueueUserWorkItem(ITaskItem item,
Action<TaskResult> taskFinishedCallback)
{
if (item == null)
throw new ArgumentNullException("Item cannot be null");
lock (this.queue)
{
CallbackTask callbackTask = new CallbackTask(item, taskFinishedCallback);
this.queue.Enqueue(callbackTask);
}
this.resetEvent.Set();
}
protected bool IsDisposed { get; private set; }
private void Run()
{
while (!this.IsDisposed)
{
CallbackTask item = null;
lock (this.queue)
{
if (this.queue.Count > 0)
{
item = this.queue.Dequeue();
}
}
if (item != null)
{
this.ExecuteItem(item);
}
this.resetEvent.WaitOne();
}
}
private void ExecuteItem(CallbackTask item)
{
try
{
item.TaskItem.AsyncProcessTask();
item.FireFinishedCallback(null);
}
catch (Exception e)
{
string msg = "Exception executing task " + item + ", Exception: " + e;
Console.WriteLine(msg);
item.FireFinishedCallback(e);
}
}
private class CallbackTask
{
public ITaskItem TaskItem { get; private set; }
private readonly Action<TaskResult> finishedCallback;
public CallbackTask(ITaskItem item, Action<TaskResult> finishedCallback)
{
if (item == null)
throw new ArgumentNullException("Item cannot be null");
this.TaskItem = item;
this.finishedCallback = finishedCallback;
}
public void FireFinishedCallback(Exception e)
{
if (this.finishedCallback != null)
{
this.finishedCallback(new TaskResult(this.TaskItem, e));
}
}
}
}
</code></pre>
<p><strong>ITaskItem</strong></p>
<pre><code>public interface ITaskItem
{
/// <summary>
/// Item should end execution if in process.
/// </summary>
void Cancel();
/// <summary>
/// Perform some task, if not cancelled.
/// </summary>
void AsyncProcessTask();
}
</code></pre>
<p><strong>TaskResult</strong></p>
<pre><code>public class TaskResult
{
private readonly Exception exception;
private readonly ITaskItem item;
public TaskResult(ITaskItem item, Exception e)
{
this.item = item;
this.exception = e;
}
public ITaskItem Finish()
{
if (this.exception != null)
{
throw this.exception;
}
return this.item;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:44:40.953",
"Id": "71549",
"Score": "1",
"body": "What advice are you seeking? You are either wasting a thread if these requests are infrequent or slowing users making these if frequent. Neither of these will be terrible, but you could instead build an executor service that would use up to *N* threads from the main pool at a time. This minimizes unused threads and improves performance when several users perform these queries at once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:21:01.507",
"Id": "71555",
"Score": "0",
"body": "You suggest using the threadpool, but limiting the number of concurrent queries correct? Not good, as one or more threadpool threads will be tied up for ~7 seconds. If I tie them all up, no one else can use the threadpool for that time period."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:27:08.847",
"Id": "71557",
"Score": "0",
"body": "The point of a thread pool is to provide concurrent access without overloading the CPUs. Allocating up to four threads would only block up to four clients, but they would only for the next quick call to complete. Extra service calls for this (slow) method would sit in their own segregated queue while other calls would sit in the main pool's queue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:37:31.183",
"Id": "71558",
"Score": "0",
"body": "Please post an answer. I can't tell if you're saying this is a built in feature of .net's threadpool, or your suggesting some class I've never heard of or that I build my own or what..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:46:45.203",
"Id": "71561",
"Score": "0",
"body": "I do not know C#, but that it has a thread pool and queue tells me this is possible. I will post some psuedocode tomorrow when I'm not on my phone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:48:09.393",
"Id": "71563",
"Score": "0",
"body": "I'm not too sure I understand your question. You say \"Only one query will be running at a time\" then you say you want to create a thread pool to run \"as many requests as possible in parallel.\" Which is correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:59:29.090",
"Id": "71565",
"Score": "0",
"body": "@Alexis I never said that second quote.\n\nDavid, if you're suggesting I write my own threadpool, I took the approach you're suggesting. That's precisely what all that code is, just with one thread, as only one query will be running at a time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:02:26.463",
"Id": "71566",
"Score": "0",
"body": "You do not need a Pool if you're going to have 1 thread. That would explain why your question seems difficult to answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:19:24.597",
"Id": "71570",
"Score": "0",
"body": "I got the term from Java. They have a single-threaded ExecutorService (which is a threadpool) for tasks like this. My \"threadpool\" is just an object which processes one item at a time on a single thread. I'm asking if I was right to avoid the .net threadpool, or if there's some .net class I'm missing for a solution here. I'm surprised I've not found one."
}
] |
[
{
"body": "<p>As it stands, I do not really see any problem. You are using the thread as I would think it should be used.</p>\n\n<p>One note, you could add a priority to the queue so someone could be added at the top of the queue instead of the bottom. That way that someone is next in line and won't have to wait for all the other queries to end before he can run his own (that's good for the boss... but seriously, if you have say 5 people who use that feature all the time, they should probably have higher priority than the 20 others who can wait 30 seconds once for their one query a day.)</p>\n\n<p>The one other possibility, although you seem to already have had it tested and not viewed as a good solution, is to have 2 threads running in parallel. When compiling, using -J 4 or -J 8 will improve the compilation process because it can make use of multiple processors and while compiler A reads a file, compiler B can compile what it read earlier. If that applies to your database, one thread does some work with the CPU, then another thread can access the database by itself.</p>\n\n<p>You could also go further where you allow many threads, but any query to the database in regard to these jobs are serialized (you use a lock() and only one of the threads can access the database at a time). This is quite useful if you have much work to do with the data read before writing it back to the database. It is useless if the SQL database does all the work itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:26:18.193",
"Id": "41621",
"ParentId": "41612",
"Score": "1"
}
},
{
"body": "<p>If you are using .Net 4.0 you can use <a href=\"http://msdn.microsoft.com/en-us/library/ee789351%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Tasks</code></a>:</p>\n\n<pre><code> // Create a scheduler that uses two threads. \n LimitedConcurrencyLevelTaskScheduler lcts = \n new LimitedConcurrencyLevelTaskScheduler(1);\n List<Task> tasks = new List<Task>();\n\n // Create a TaskFactory and pass it our custom scheduler. \n TaskFactory factory = new TaskFactory(lcts);\n\n //...\n\n public void InitiateNewTask() {\n Task t = factory.StartNew(() => {\n // your code here\n }, cts.Token);\n tasks.Add(t); \n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:52:30.827",
"Id": "41631",
"ParentId": "41612",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I did not use ThreadPool.QueueUserWorkItem as this will tie up a ThreadPool thread.</p>\n</blockquote>\n\n<p>But that's pretty much what the ThreadPool is for: for you to submit your jobs to it and tie it up for some time. The ThreadPool is smart, so if it detects that some of its threads are blocking, it will create new threads faster. This means that your submitting of this job to the ThreadPool shouldn't block other code that also uses it (or at least not for long).</p>\n\n<p>But there are also some ways to do this than just <code>QueueUserWorkItem()</code>:</p>\n\n<ol>\n<li>Use the <code>Task</code> type from .Net 4.0, specifically <code>Task.Run()</code> if you're using .Net 4.5 or <code>Task.Factory.StartNew()</code> on .Net 4.0.</li>\n<li>Make your code truly asynchronous (which won't tie up a thread at all). This assumes your database code supports it. But, this is probably not worth it if you can't use <code>async</code>-<code>await</code>. (Note: you <em>can</em> use it even if you target .Net 4.0, but it requires VS 2012 and <a href=\"http://www.nuget.org/packages/Microsoft.Bcl.Async\" rel=\"nofollow\">Microsoft.Bcl.Async</a>.)</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:58:18.720",
"Id": "73415",
"Score": "0",
"body": "Thanks, I didnt realize the threadpool allowed so many maximum active threads. Its silly to worry about tying one up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:06:58.200",
"Id": "42516",
"ParentId": "41612",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42516",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T03:24:41.587",
"Id": "41612",
"Score": "11",
"Tags": [
"c#",
"multithreading"
],
"Title": "Long running, frequent async advice?"
}
|
41612
|
<p>I need a little help in finding a better solution. In the screen shot below any change to the forecast line I need to find the value in column B. The screen shot is only a sample in my production sheet the row count is currently 4200.</p>
<pre><code> Column A Col B Col C Col D Col E
Row 5 January
Row 6 Prg Desc SD FG GH DF
Row 7 Forecast 1 2 3 4
Row 8 Actual
Row 9 Compare
</code></pre>
<p>My current code does what I need it to, however, I'm sure there is a better method of accomplish my goal. In my production sheet the value in B is in row 5.</p>
<pre><code>CurMonth = target.Offset(5 - target.Row).Value
If CurMonth = "" Then
CurMonth = target.Offset((5 - target.Row), -1).Value
If CurMonth = "" Then
CurMonth = target.Offset((5 - target.Row), -2).Value
If CurMonth = "" Then
CurMonth = target.Offset((5 - target.Row), -3).Value
End If
End If
End If
Debug.Print CurMonth
</code></pre>
<p>Any suggestions would be very appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:46:50.280",
"Id": "71562",
"Score": "3",
"body": "It isn't exactly clear what you are trying to accomplish here. Is the code you posted in a Worksheet event, a custom defined function, a macro, or something else? Can you post some more of the code to give more context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:56:08.590",
"Id": "71564",
"Score": "1",
"body": "Thought that was an awesome screenshot!\nThe code is part of a worksheet change event. The desire was when a user changes the value in the forecast line it will return the value in B5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:10:18.857",
"Id": "71567",
"Score": "0",
"body": "Is the month in a merged cell? It's hard to tell from the \"screenshot\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:14:04.223",
"Id": "71569",
"Score": "0",
"body": "No the month is centered across the selection of row 5 columns b, c, d & e"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:23:36.313",
"Id": "71571",
"Score": "0",
"body": "@RL76 this posts needed a better title - feel free to edit yourself, rollback, or whatever :)"
}
] |
[
{
"body": "<p>Not relevant to your algo, but you shouldn't be using <code>\"\"</code> like this; use the <code>vbNullString</code> language constant instead, which consumes 0 memory (as opposed to <code>\"\"</code> which has the overhead of a <code>string</code>).</p>\n\n<p>As for suggestions, in order to find a better way to do something, it's important to first understand what's going on. And <em>proper indentation</em> greatly helps for that:</p>\n\n<pre><code>CurMonth = target.Offset(5 - target.Row).Value\nIf CurMonth = vbNullString Then\n CurMonth = target.Offset((5 - target.Row), -1).Value\n If CurMonth = vbNullString Then\n CurMonth = target.Offset((5 - target.Row), -2).Value\n If CurMonth = vbNullString Then\n CurMonth = target.Offset((5 - target.Row), -3).Value\n End If\n End If\nEnd If\nDebug.Print CurMonth\n</code></pre>\n\n<p>Something sticks out right away - every new nested level seems to increment the offset, so what you really have is this:</p>\n\n<pre><code>CurMonth = target.Offset((5 - target.Row), n).Value\nIf CurMonth = vbNullString Then\n n = n - 1\n [and do that again while n > -3]\n</code></pre>\n\n<p>This looks like a recursive logic - something like this:</p>\n\n<pre><code>Private Function GetCurMonth(ByVal n As Long) As String\n Dim result As String\n\n result = target.Offset((5 - target.Row), n).Value\n If result = vbNullString And n > -3 Then\n n = n - 1\n result = GetCurMonth(n) 'recursive call\n End If\n\n GetCurMonth = result\nEnd Sub\n</code></pre>\n\n<p>Also <code>CurMonth</code> has no reason not to be called <code>CurrentMonth</code> I guess. As Comintern mentioned, it would be easier to give a better review with more [code] context.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:28:21.407",
"Id": "71602",
"Score": "1",
"body": "Can't you write it with a `WHILE` instead of recursion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:55:26.223",
"Id": "71647",
"Score": "0",
"body": "@abuzittin probably. That was just a quickie :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:58:34.410",
"Id": "41617",
"ParentId": "41615",
"Score": "7"
}
},
{
"body": "<p>OK, I'll make a couple of assumptions here. First is that you are mainly looking for changes to individual cells or only changes in a specific row. The reason I am making that assumption is that if it <em>isn't</em> true, you aren't handling the cases where changes occur in multiple months at the same time. Remember, the Target object that you get as a parameter to Worksheet_Change is a Range - not a Row or a Cell. When you call Target.Row, it returns the top row in the passed Range making <em>no guarantees</em> that only 1 Row was altered. A good way to check to see if your final code handles this robustly is to select a 5x5 or 10x10 array of cells and clear them. Does this give you the desire behavior? If not, you may have to re-think your approach to the problem.</p>\n\n<p>Now, going on the assumption that you only care about single cell or single row edits, you need to test for that in your code. My general rule is to always try to resolve a Range into something more useful. The .Offset method is typically asking for trouble, as it gives a value that is relative to the Range as opposed to having a hard location on the Worksheet. You can always get your location on the Worksheet from a Range by getting the Row and Column of the upper-left most Cell:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\n Debug.Print Target.Cells(1, 1).Row\n Debug.Print Target.Cells(1, 1).Column\n\nEnd Sub\n</code></pre>\n\n<p>Once you have an absolute Row and Column relative to the <em>Worksheet</em>, it makes your calculations a lot simpler. For example: you can test to see if the Row you returned if one that you care about, and then use that knowledge to directly address the other cells you care about without fumbling around with the Offset.</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\n Dim CurrentRow As Integer\n CurrentRow = Target.Cells(1, 1).Row\n\n If Me.Cells(CurrentRow, 1).Value = \"Forecast\" Then\n 'In the correct row.\n CurrentMonth = Me.Cells(CurrentRow - 2, 2)\n Else\n 'Must not have been on the Forecast row.\n End If\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:38:12.970",
"Id": "41623",
"ParentId": "41615",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41617",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:34:48.153",
"Id": "41615",
"Score": "12",
"Tags": [
"vba",
"excel"
],
"Title": "Suspiciously redundant Excel macro code"
}
|
41615
|
<p>This code lists the permutations of the string, and eliminates duplicates if any. I'm looking for code review, best practices, optimizations etc.</p>
<p>I'm also verifying complexity: \$O(n! * n)\$ as time complexity and \$O(n * n)\$ as space complexity, where \$n\$ is length of the input string.</p>
<pre><code>public final class Permutation {
private Permutation() {
};
/**
* Return permutation of a given string.
* But, if the string contains duplicate characters, it
* takes care to eradicate duplicate permutations.
*
* @param string the string whose permutation needs to be found out.
* @return a list with permuted values.
*/
public static List<String> permutation(String string) {
final List<String> stringPermutations = new ArrayList<String>();
permute(string, 0, stringPermutations);
return stringPermutations;
}
private static void permute(String s, int currIndex, List<String> stringPermutations) {
if (currIndex == s.length() - 1) {
stringPermutations.add(s);
return;
}
// prints the string without permuting characters from currIndex onwards.
permute(s, currIndex + 1, stringPermutations);
// prints the strings on permuting the characters from currIndex onwards.
for (int i = currIndex + 1; i < s.length(); i++) {
if (s.charAt(currIndex) == s.charAt(i)) continue;
s = swap(s, currIndex, i);
permute(s, currIndex + 1, stringPermutations);
}
}
private static String swap(String s, int i, int j) {
char[] ch = s.toCharArray();
char tmp = ch[i];
ch[i] = ch[j];
ch[j] = tmp;
return new String(ch);
}
public static void main(String[] args) {
for (String str : permutation("abc")) {
System.out.println(str);
}
System.out.println("------------");
for (String str : permutation("aabb")) {
System.out.println(str);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:43:51.483",
"Id": "71599",
"Score": "2",
"body": "Your space complexity is definitely not O(n*n). And cannot be less than O(n*n!) (for n distinct chars) because you have n! different arrays with n chars each. This program fills 2GB heap and hits `OutOfMemoryError` in few minutes if not seconds. Just try it with about a dozen different characters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-06T16:01:29.730",
"Id": "195687",
"Score": "0",
"body": "different approach: http://javabypatel.blogspot.in/2015/08/program-to-print-permutations-of-string-without-repetition.html"
}
] |
[
{
"body": "<ol>\n<li>Best beginner's code I've seen. Possibly ever. Admittedly, I haven't reviewed too many beginner's programmes, but this one was definitely an easy review.</li>\n<li>Only style change I'd suggest is to avoid the single-line <code>if (s.charAt(currIndex) == s.charAt(i)) continue;</code>. It's totally valid, but easy to miss. At least put the <code>continue</code> on a new line; many people prefer to put it in braces, too.</li>\n<li>Since your main() method is obviously a way to test the rest of the code, I'd suggest pulling the loops that are currently in there into a self-documenting method like <code>testPermutation(String arg)</code> and call that from <code>main()</code>.</li>\n<li>Now that your main method is so simple (it just contains <code>testPermutation(\"abc\");</code> and <code>testPermutation(\"aabb\");</code>), change it to either\n<ol>\n<li>loop over the arguments to main(), so you can call your program like <code>java yourpackage.Permutation abc aabb</code>, or</li>\n<li>read strings from stdin until user exits.</li>\n</ol></li>\n<li>To measure time complexity, you can maintain a counter that gets incremented inside <code>swap()</code>, and infer from that result. I think you'll find that it's much less than n! * n.</li>\n<li>Space complexity is the same as time complexity, since you create a new String every time you swap. Or depending on how you define \"space complexity\", I suppose it might be n * time complexity, since each time you swap, you create a String of length n.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T06:34:39.417",
"Id": "41627",
"ParentId": "41618",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>When you have potentially very large number of return values. You can return return an <code>Iterable<T></code> which lazily generates the results one by one. That way you will not keep GC from collecting the values you no longer need. For example you do not need a particular permutation of the string after you printed it. You can use <code>guava</code> library which has useful utilities to work with <code>Iterable</code>s and <code>Iterator</code>s for this.</p></li>\n<li><p>Do not make you class <code>final</code> or disable the default constructor. It allows you nothing and makes the work of people that <em>may have to</em> use it in the future harder, by making your code hard or impossible to use with byte-code manipulation and reflection where most testing, ORM, DI, AOP tooling depend on. This is particularly useless with classes that have no virtual methods or any fields, no one would want to extend them anyway, let alone accidentally.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:17:57.423",
"Id": "41632",
"ParentId": "41618",
"Score": "1"
}
},
{
"body": "<p>It does not eliminate the duplicates. In permute method you check only two consecutive char elements. If you change the ordering of duplicate elements in your second input for the test such as \"abab\" then it will print duplicate permutations. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-04T05:06:35.760",
"Id": "195139",
"Score": "2",
"body": "Very well spotted, nice answer, welcome to Code Review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-04T04:13:42.063",
"Id": "106498",
"ParentId": "41618",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41627",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T04:59:02.570",
"Id": "41618",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"combinatorics"
],
"Title": "Permutation of a string eliminating duplicates"
}
|
41618
|
<p>I've written an Erlang implementation of the genetic algorithm for a "Hello World" program as described <a href="http://www.puremango.co.uk/2010/12/genetic-algorithm-for-hello-world/">here</a>.</p>
<p>This is my first time writing any code in Erlang and also my first time writing code in a functional language, so I'd really like some feedback on whether I'm doing things the "functional" way, whether I'm doing things the Erlang way, and what useful functional/Erlang features could make this code better. I'm not interested in general programming style feedback or whether there are bugs in this implementation (I'm sure there are). I'm slightly interested in efficiency, but not too much.</p>
<p>Let me describe the basic algorithm for those of you who aren't planning on reading the article (I don't think you need to understand all the details to be able to review the code). The idea is to "breed" strings that closer and closer to the target string.</p>
<ol>
<li>Create a large pool of random strings of the target length.</li>
<li>Choose four strings and pick the "fittest" two to breed (fit is defined later).</li>
<li>Breed the two strings by either doing nothing, or by picking a point in both strings, and swapping substrings at that point.</li>
<li>With the resulting two strings, either insert them directly into the pool of strings, or mutate them by moving a random character in the string up or down a bit, and then insert them.</li>
</ol>
<p>With this process, eventually one of the strings will be the target string you are searching for. This depends on having a good fitness function, which I define as the sum of the difference of each character in a candidate string with the respective characters in the target string. So if a candidate string is "abc" and the target string was "acd", the first character has a difference of 0, second a difference of 1, and third a difference of one so its fitness score is 2. A lower fitness score is better.</p>
<pre><code>-module(genetic).
-author("Gulshan Singh").
-export([run_genetic/1]).
-define(PoolSize, 400).
-define(CrossoverProb, 0.9).
-define(MutateProb, 0.2).
-define(MinChar, 65). %% 'A'
-define(MaxChar, 90). %% 'Z'
%% Main entry point. Produces the Target string from a pool of random strings
%% using a genetic algorithm
run_genetic(Target) ->
random:seed(now()),
FirstGen = create_pool(length(Target), ?PoolSize),
io:format("Starting iteration 1~n"),
run_genetic(FirstGen, [], Target, ?PoolSize, 0, 1).
run_genetic(_, CurrentGen, Target, ?PoolSize, ?PoolSize, Iteration) ->
io:format("Starting iteration ~B~n", [Iteration + 1]),
run_genetic(CurrentGen, [], Target, ?PoolSize, 0, Iteration + 1);
run_genetic(LastGen, CurrentGen, Target, ?PoolSize, Size, Iteration) ->
{P1, P2} = choose_parents(LastGen, Target),
io:format("Breeding ~s (~B) and ~s (~B)~n",
[P1, fitness(P1, Target), P2, fitness(P2, Target)]),
CrossoverProb = random:uniform(),
if CrossoverProb =< ?CrossoverProb ->
{Result1, Result2} = crossover(P1, P2);
CrossoverProb > ?CrossoverProb ->
{Result1, Result2} = {P1, P2}
end,
io:format("Result strings are ~s (~B) and ~s (~B)~n",
[Result1, fitness(Result1, Target),
Result2, fitness(Result2, Target)]),
Finished = check_result(Result1, Target) or check_result(Result2, Target),
case Finished of
true -> io:format("Found result at iteration ~B~n", [Iteration]);
false -> case MutateProb = random:uniform() of
MutateProb when MutateProb =< ?MutateProb ->
mutate(Result1),
mutate(Result2);
MutateProb when MutateProb > ?MutateProb ->
no_mutation
end,
run_genetic(LastGen, [Result1, Result2|CurrentGen], Target,
?PoolSize, Size + 2, Iteration)
end.
%% Returns a list of Num random strings, each of length Len
create_pool(Len, Num) ->
create_pool(Len, Num, [], 0).
create_pool(_, Num, Pool, Num) ->
Pool;
create_pool(Len, Num, Pool, X) ->
S = rand_string(Len),
create_pool(Len, Num, [S|Pool], X + 1).
%% Returns a random string of length Len
rand_string(Len) ->
rand_string(Len, [], 0).
rand_string(Len, String, Len) ->
String;
rand_string(Len, String, SoFar) ->
C = random:uniform(?MaxChar - ?MinChar + 1) + ?MinChar - 1,
rand_string(Len, [C|String], SoFar + 1).
%% Return two parents for breeding
choose_parents(Pool, Target) ->
P1 = choose_parent(Pool, Target),
P2 = choose_parent(Pool, Target),
case P1 =:= P2 of
true ->
choose_parents(Pool, Target);
false -> {P1, P2}
end.
%% Chooses a single parent for breeding. This is done by choosing two candidates
%% and then choosing the fittest of the two
choose_parent(Pool, Target) ->
P1 = lists:nth(random:uniform(length(Pool)), Pool),
P2 = lists:nth(random:uniform(length(Pool)), Pool),
F1 = fitness(P1, Target),
F2 = fitness(P2, Target),
if P1 =:= P2 -> choose_parent(Pool, Target);
F1 > F2 -> P2;
F1 < F2 -> P1;
F1 == F2 -> P1
end.
%% Return the fitness of the Candidate. This is calculated as the sum of the
%% distances of each letter from Candidate to the corresponding letter in Target
fitness(Candidate, Target) ->
fitness(Candidate, Target, 0).
fitness([C1|Rest1], [C2|Rest2], Sum) ->
fitness(Rest1, Rest2, Sum + abs(C1 - C2));
fitness([], [], Sum) ->
Sum.
%% Cross S1 with S2. Choose a random position and swap S1 and S2 at this
%% position
crossover(S1, S2) ->
R = random:uniform(length(S1)),
{lists:sublist(S1, R) ++ lists:nthtail(R, S2),
lists:sublist(S2, R) ++ lists:nthtail(R, S1)}.
%% Returns true when Result equals Target
check_result(Result, Target) ->
fitness(Result, Target) =:= 0.
%% Mutates S by modifying the value of one character by +5/-5
mutate(S) ->
R = random:uniform(length(S)) - 1, %% [0, length - 1]
Char = lists:nth(R + 1, S),
%% Randomly mutate a single character, but don't go out of the character range
case X = random:uniform() of
X when X =< 0.5 ->
Offset = min(random:uniform(5) * -1, ?MinChar - Char);
X when X > 0.5 ->
Offset = min(random:uniform(5), ?MaxChar - Char)
end,
lists:sublist(S, R) ++ [Char + Offset] ++ lists:nthtail(R + 1, S).
</code></pre>
<p>You would run this with <code>genetic:run_genetic("HELLO")</code> and it would usually finish within 20 iterations. 10% of the time it loops forever, but I'm not too concerned about that.</p>
|
[] |
[
{
"body": "<h1>General Remarks</h1>\n\n<ul>\n<li>Give your constants all uppercase names <a href=\"http://erlang.org/doc/reference_manual/macros.html\">see Style in reference manual</a>.</li>\n<li>If you make the pool size a parameter in the <code>run_genetic</code> function, you should match it with an unbound variable. If you always match it only with the constant, you could omit this parameter and only use the constant.</li>\n</ul>\n\n<h1>run_genetic</h1>\n\n<ul>\n<li><code>run_genetic</code> currently does three different jobs which should be split in functions with different names:\n<ul>\n<li>main entry point and initialization</li>\n<li>runs over all generations</li>\n<li>genetic algorithm steps for one generation (test fitness, mutation, crossover)</li>\n</ul></li>\n<li><p>When compute a possible crossover, you can compute the result and store the result of the if as value. </p></li>\n<li><p>When you perform mutation, you don't store the result of the call of the <code>mutate(Result1)</code></p></li>\n<li><p>As you should check also if the mutated string matches your target, this should be split in another function</p></li>\n</ul>\n\n<h1>check_pool / rand_string</h1>\n\n<p>You could write those simpler as</p>\n\n<pre><code>create_pool(Len, Num) ->\n [rand_string(Len) || _ <- lists:seq(1,Num)].\n</code></pre>\n\n<p>But this solution is potentially not as fast as you create a list from 1 to N first.</p>\n\n<h1>crossover</h1>\n\n<p>You could create the sublists with <code>lists:split</code></p>\n\n<h1>mutate</h1>\n\n<p>You want if your calculated offset is negative probably do not go under <code>MinChar</code> so exchange <code>min</code> with <code>max</code></p>\n\n<h1>My changed version of run_genetic</h1>\n\n<pre><code>run_genetic(Target) ->\n random:seed(now()),\n FirstGen = create_pool(length(Target), ?POOLSIZE),\n produce_generations(FirstGen, Target, ?POOLSIZE, 1).\n\nproduce_generations(CurrentGen, Target, PoolSize, Iteration) ->\n io:format(\"Starting iteration ~B~n\", [Iteration]),\n case populate(CurrentGen,[],Target, PoolSize) of \n {not_found,NextGen} ->\n produce_generations(NextGen,Target,PoolSize,Iteration+1);\n _->\n io:format(\"Found result at iteration ~B~n\", [Iteration])\n end.\n\npopulate(_LastGen,CurrentGen,_Target,0)->\n {not_found,CurrentGen}; \npopulate(LastGen,CurrentGen,Target,NumberMissingInPopulation) ->\n {P1, P2} = choose_parents(LastGen, Target),\n io:format(\"Breeding ~s (~B) and ~s (~B)~n\",\n [P1, fitness(P1, Target), P2, fitness(P2, Target)]),\n CrossoverProb = random:uniform(),\n if CrossoverProb =< ?CROSSOVERPROB ->\n {Result1, Result2} = crossover(P1, P2);\n CrossoverProb > ?CROSSOVERPROB ->\n {Result1, Result2} = {P1, P2}\n end,\n io:format(\"Result strings are ~s (~B) and ~s (~B)~n\",\n [Result1, fitness(Result1, Target),\n Result2, fitness(Result2, Target)]),\n Result=case check_add_and_continue(Result1,Result2,CurrentGen,Target) of\n R={not_found,_Gen} -> \n case MutateProb = random:uniform() of\n MutateProb when MutateProb =< ?MutateProb ->\n MutatedResult1=mutate(Result1),\n MutatedResult2=mutate(Result2),\n check_add_and_continue(MutatedResult1,MutatedResult2,CurrentGen,Target); \n _-> R\n end;\n Found -> Found \n end,\n case Result of \n %%include min here if population size can be uneven\n {not_found,NewCurrentGen}-> \n populate(LastGen,NewCurrentGen,Target,NumberMissingInPopulation-2);\n _-> Result\n end.\n\n\ncheck_add_and_continue(Child1,Child2,Generation,Target)->\n NewCurrentGen=[Child1, Child2|Generation],\n Found=case check_result(Child1, Target) or check_result(Child2, Target) of\n true -> found;\n false ->not_found\n end,\n {Found,NewCurrentGen}.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-17T12:06:53.883",
"Id": "140881",
"Score": "3",
"body": "Welcome to Code Review! Your answer looks good, so I'll just leave you to enjoy your stay here. (Your answer came up in the review queue because the question is from about a year ago, maybe don't expect it to be accepted.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-16T18:15:23.247",
"Id": "77747",
"ParentId": "41622",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:27:04.077",
"Id": "41622",
"Score": "11",
"Tags": [
"beginner",
"algorithm",
"functional-programming",
"erlang",
"genetic-algorithm"
],
"Title": "Genetic algorithm for \"Hello World\""
}
|
41622
|
<p>I created a Java Trie as part of a project someone challenged me to do. I'm not sure that this is the most efficient way to go about producing a Trie, I know that this works but I was hoping someone with some professional experience could enlighten me on anything I might be doing fundamentally wrong.</p>
<p>I'm studying computer science in college and have no professional experience with development.</p>
<p>I'm mainly curious to know what you think about this with respect to:</p>
<ol>
<li><p>My use of methods, some are static while others are not. For the scope of the methods, I feel like I might have been better off putting the entire search function or <code>getWords</code> function inside the <code>Trie</code> class and not the <code>TrieNode</code> class, but I was unable to figure out how to do that logically.</p></li>
<li><p>The use of comments or the logical flow of the code. Would this be a nightmare in an office or is this about what you would hope for?</p></li>
<li><p>Efficiency of the code. I know recursion can be demanding, but I think that the nature of the way this is created has made it more efficient than lets say a massive list of words. I would need a giant library.txt file to test that theory, though and I don't really have one to work with.</p></li>
</ol>
<p><strong>Trie class:</strong></p>
<pre><code>import java.util.List;
public class Trie {
private TrieNode root;
private List<String> wordList;
public Trie(){
root = new TrieNode();
}
public Trie(String word){
this();
this.addWord(word);
}
public void addWord(String word){
root.addWord(word.toLowerCase());
}
public List<String> getWords(){
wordList = root.getWords(root, "");
return wordList;
}
public boolean containsWord(String word){
return root.containsWord(root, word);
}
}
</code></pre>
<p><strong>TrieNode class:</strong></p>
<pre><code>import java.util.*;
class TrieNode {
//Variables used in addWords
private boolean isWord;
private boolean hasChildren;
private char character;
private Map<Character, TrieNode> children = new HashMap<>();
//Variables for search method
private static List<String> wordList = new ArrayList();;
public TrieNode(){
hasChildren = false;
isWord = false;
}
public TrieNode(String word){
this();
addWord(word);
}
/* Recursively add nodes to the tree. Each node contains a map with letters.
* If the next letter in a word is not inside the map, it is added.
* */
public void addWord(String word){
char firstChar = word.charAt(0);
//If current node has no more letters, add subsequent letters
if (children.get(firstChar) == null){
this.hasChildren = true;
// If word has more than 1 character left
if(word.length() > 1){
TrieNode tn = new TrieNode();
children.put(firstChar, tn);
children.get(firstChar).addWord(word.substring(1));
}
// If only 1 character remains in the word
else{
children.put(firstChar, new TrieNode());
children.get(firstChar).isWord = true;
}
// Once the node was added, set the character value for future reference
children.get(firstChar).character = firstChar;
}
// If first letter is already in the index, send subsequent characters into that node.
else
children.get(firstChar).addWord(word.substring(1));
}
// Static method starts with Root and blank values.
public static List<String> getWords(TrieNode node, String chars){
chars += node.character;
// Traverse trie adding characters to the string until a word is found
if(node.isWord){
wordList.add(chars.trim());
}
// If more letters still remain, continue traversing
if(node.hasChildren){
for(Character c: node.children.keySet()){
getWords(node.children.get(c), chars);
}
}
// If the end of a branch is reached, reset the string
else{
chars = "";
}
// Sort and return the list of words
Collections.sort(wordList);
return wordList;
}
static boolean hasWord = false;
public static boolean containsWord(TrieNode node, String word){
char letter = word.charAt(0);
// If current node does not contain next letter, word isn't in list
if(node.children.get(letter) == null)
hasWord = false;
// If the former if passed, and 1 character remains, check to see if last char node is a word
else if(word.length() == 1){
if(node.children.get(letter).isWord == true)
hasWord = true;
else
hasWord = false;
}
// If more letters remain, recursively call this method with a substring
else{
containsWord(node.children.get(letter), word.substring(1));
}
return hasWord;
}
}
</code></pre>
<p>And lastly the class that calls this:</p>
<pre><code>public class TrieProject {
public static Trie t;
public static void main(String[] args) {
t = new Trie();
t.addWord("h");
t.addWord("ha");
t.addWord("hhha");
t.addWord("samsung");
t.addWord("sampson");
t.addWord("Double Vision");
for(String s: t.getWords()){
System.out.println(s);
}
System.out.println(t.containsWord("samsun"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:35:41.807",
"Id": "71604",
"Score": "2",
"body": "also small note, while you are lowercasing the words you are saving the contains function is not lowered, so it will always return false. especially surprising seeing as the word added will not match the same word when checked again!"
}
] |
[
{
"body": "<p>Your <code>Trie</code> class looks fine.</p>\n\n<p>In <code>TrieNode</code> I can see a few problems with you algorithm:</p>\n\n<p><strong><code>addWord</code></strong></p>\n\n<ol>\n<li>You do not properly check for the edge conditions, i.e. when <code>word</code> is <code>null</code> or empty.</li>\n<li>You are setting <code>private</code> members of your child's instances in the parent - you should move that to your constructor.</li>\n<li>Your code is not DRY, since you call <code>children.get(firstChar).addWord(word.substring(1))</code> twice.</li>\n</ol>\n\n<p>I would have re-written the method to something like this:</p>\n\n<pre><code>public TrieNode(char character) {\n this.character = character;\n}\n\npublic void addWord(String word){\n if (word == null) return;\n if (word.length() == 0) {\n isWord = true;\n return;\n }\n char firstChar = word.charAt(0);\n\n //If current node has no more letters, add subsequent letters\n if (children.get(firstChar) == null){\n this.hasChildren = true;\n children.put(firstChar, new TrieNode(firstChar));\n }\n\n children.get(firstChar).addWord(word.substring(1));\n}\n</code></pre>\n\n<p><strong><code>getWords</code></strong></p>\n\n<ol>\n<li>You use a <code>static</code> member to keep your <code>wordList</code>. This is problematic for a couple of reasons:\n<ul>\n<li>You cannot have more than one <code>Trie</code> in your program...</li>\n<li>Each time you call <code>getWords</code> you compound your new word structure on lists from previous calls, since you never clean it up...</li>\n</ul></li>\n<li>You use recursion, but treat your variables as in iteration - <code>chars = \"\";</code> is redundant, for example. </li>\n</ol>\n\n<p>I would have made the <code>getWords</code> method not static, and change the one in <code>Trie</code> as follows:</p>\n\n<p>Trie class:</p>\n\n<pre><code>public List<String> getWords() {\n return Collections.sort(root.getWords(new List<String>(), \"\"));\n}\n</code></pre>\n\n<p>TrieNode class:</p>\n\n<pre><code>public List<String> getWords(list, prefix) {\n if (node.isWord) {\n list.add(prefix);\n }\n\n prefix += this.character\n\n for(TrieNode child: children.values()) {\n child.getWords(list, prefix);\n }\n return wordList;\n}\n</code></pre>\n\n<p>Changes is <code>containsWord()</code> will be similar, I'm leaving this as an exercise for the OP.</p>\n\n<p>Another small observation - your <code>root</code> does not have a <code>character</code>, which might prove problematic...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:33:22.507",
"Id": "71606",
"Score": "0",
"body": "I left the root blank because I found it more problematic to have a root node with a character. How can you add the word \"sample\" to a tree whose root character is a 't'? The way it is, each level of the tree can have all 26 letters of the alphabet if necessary.\n\nGreat points, thank you for taking the time. In the improved `getWords()` method, you removed the `node` from the method signature. I'm assuming that should be `if(this.isWord)` instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:15:12.483",
"Id": "71616",
"Score": "0",
"body": "A blank root node is fine. No problem, and it allows you to store the 'empty string' \"\" as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:37:34.510",
"Id": "71642",
"Score": "0",
"body": "@rolfl, since `character` is a `char` - its default value is not a `null` (it is a primitive) or an empty string - it is a '\\u0000' which is not a printable character - all words will begin with a small rectangle..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:39:39.190",
"Id": "71643",
"Score": "0",
"body": "@leigero - I agree that the root node should not have a character, but it would need some special attention in the code. Maybe have an `isRoot` attribute to the class... Anyway, if you like my answer you can mark it as the correct answer :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:48:31.093",
"Id": "71644",
"Score": "0",
"body": "@leigero you are right about char being `\\u0000` and I never disputed that. All I said was that the root node can be 'blank'. If you have a look at the answer I gave, you will see it is very successful even with a null-char (`u0000`) in the root node."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:03:32.017",
"Id": "71648",
"Score": "1",
"body": "The nature of code review should warrant more than one correct answer. You've both been very helpful, although the answer @rolfl provided was almost exactly what I was looking for, so I went with his. You both deserved a +1 though."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:24:54.323",
"Id": "41635",
"ParentId": "41630",
"Score": "3"
}
},
{
"body": "<p>In general, with data structures containing nodes, it is common practice for the node class to be a simple container, and not a computational power house. You have reversed this concept, and made the Node the engine.... which is unexpected... and is why you feel your class is 'awkward' with the static methods, etc. Rearranging where the logic is will make a big difference.</p>\n\n<p>This is a big change, and going through your code as it is, while saying \"everything is in the wrong place\" is not productive.... it's better for me to show you what it will look like if the Node is a simple container, and the actual Trie does the heavy lifting.</p>\n\n<p>Things about this re-factor that are significant, and you should look for are:</p>\n\n<ul>\n<li>The TrieNode is an inner (nested) class, and it does not know anything about any other class (except it's own state).</li>\n<li>I use iteration to <code>add</code>, and 'contains' words, not recursion. This only works because the logic is outside the <code>TrieNode</code></li>\n<li>I use recursion to <code>getWords()</code>, with a 'stack' that contains the characters.</li>\n<li>I have added a <code>size()</code> method, and I also track the deepest point.</li>\n<li>there is no static content at all, except for EMPTYNODES</li>\n<li>I thought it would be 'cute' to return the words in alphabetical order.</li>\n<li>it supports the empty-string.</li>\n</ul>\n\n<p>So, the point of my answer is to say you chose the less-appropriate code structure. Nodes should be containers (and private, and light-weight). The Trie itself contains the state data, and is what does the heavy lifting. This is the opposite of what you have.</p>\n\n<p>I have left the data structures similar to what you have. If I were doing this myself, I would probably be using a large data set, and I would find a way to get rid of the <code>children</code> Map, and replace it with a more space-saving primitive array structure of some sort.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n\npublic class Trie {\n\n private static final TrieNode[] EMPTYNODES = new TrieNode[0];\n\n private static final class TrieNode implements Comparable<TrieNode> {\n\n private final char character;\n private boolean isWord = false;\n private Map<Character, TrieNode> children = null;\n\n public TrieNode(char ch) {\n character = ch;\n }\n\n public TrieNode getOrCreateChild(char ch) {\n if (children == null) {\n children = new HashMap<>();\n }\n TrieNode kid = children.get(ch);\n if (kid == null) {\n kid = new TrieNode(ch);\n children.put(ch, kid);\n }\n return kid;\n }\n\n public TrieNode get(char ch) {\n return children != null ? children.get(ch) : null;\n }\n\n public void setWord() {\n isWord = true;\n }\n\n public boolean isWord() {\n return isWord;\n }\n\n public char getChar() {\n return character;\n }\n\n public TrieNode[] getChildNodes() {\n if (children == null) {\n return EMPTYNODES;\n }\n TrieNode[] result = children.values().toArray(new TrieNode[children.size()]);\n Arrays.sort(result);\n return result;\n }\n\n @Override\n public int compareTo(TrieNode o) {\n // cheap way to sort alphabetically.\n return (int)character - o.character;\n }\n\n }\n\n\n\n private final TrieNode root; // fix - make root final.\n private int size = 0; // how many words\n private int depth = 0; // longest word\n\n public Trie(){\n // root has null character.\n root = new TrieNode((char)0);\n }\n\n public void addWord(String word){\n TrieNode node = root;\n int wdepth = 0;\n for (char ch : word.toLowerCase().toCharArray()) {\n node = node.getOrCreateChild(ch);\n wdepth++;\n }\n if (!node.isWord()) { // fix - only add new words....\n node.setWord();\n size++;\n if (wdepth > depth) {\n depth = wdepth;\n }\n }\n }\n\n public boolean containsWord(String word){\n TrieNode node = root;\n for (char ch : word.toLowerCase().toCharArray()) {\n node = node.get(ch);\n if (node == null) {\n break;\n }\n }\n return node != null && node.isWord();\n }\n\n public int size() {\n return size;\n }\n\n public List<String> getWords() {\n // set up a recursion call.\n List<String> result = new ArrayList<>(size);\n char[] charstack = new char[depth];\n getWords(root, charstack, 0, result);\n return result;\n }\n\n private void getWords(final TrieNode node, final char[] charstack, final int stackdepth, final List<String> result) {\n if (node == null) {\n return;\n }\n if (node.isWord()) {\n result.add(new String(charstack, 0, stackdepth));\n }\n for (TrieNode kid : node.getChildNodes()) {\n charstack[stackdepth] = kid.getChar();\n getWords(kid, charstack, stackdepth + 1, result);\n }\n }\n\n public static void main(String[] args) {\n Trie t = new Trie();\n t.addWord(\"h\");\n t.addWord(\"ha\");\n t.addWord(\"hhha\");\n t.addWord(\"samsung\");\n t.addWord(\"sampson\");\n t.addWord(\"Double Vision\");\n\n List<String> words = t.getWords();\n\n for(String s : words){\n System.out.println(s);\n }\n System.out.println(t.containsWord(\"samsun\"));\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:21:30.817",
"Id": "71651",
"Score": "0",
"body": "Just re-reading my answer, there's one change, and one bug to consider.... I will edit the answer, but `root` could/should be `final`, and `size` should only increase if it is a new word... I have marked the code with `// fix`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:17:26.167",
"Id": "72693",
"Score": "1",
"body": "I wanted to add that I just had an interview for a Java position, and they really didn't like recursive solutions to anything. They preferred the stack implementation because it is more efficient. So again, good answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:30:04.430",
"Id": "72695",
"Score": "0",
"body": "You're welcome, and I wish you success in your hunt!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:00:50.627",
"Id": "41649",
"ParentId": "41630",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41649",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:44:49.150",
"Id": "41630",
"Score": "6",
"Tags": [
"java",
"trie"
],
"Title": "Trie (tree form) in Java"
}
|
41630
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.